Showing posts with label c# tips. Show all posts
Showing posts with label c# tips. Show all posts

Wednesday, 2 July 2014

It is very easy to remove string's leading and trailing white spaces using Regex.

 The Regex is "^\s+|\s+$".

Here is example of this.

In this example we are taking on string which has leading and trailing white spaces. We can remove this spaces using Regex.

C#. Net Example :
string strData = "            This string contains leading and trailing white spaces             ";
strData = Regex.Replace(strData, @"^\s+|\s+$", "");
Response.Write(strData);

VB.Net Examples :
Dim strData As String = "            This string contains leading and trailing white spaces             "
strData = Regex.Replace(strData, "^\s+|\s+$", "")
Response.Write(strData)

  
Click here for other post regarding Remove only leading white spaces from string using Regex with C#.Net and VB.Net example


Click here for other post regarding Remove only trailing white spaces from string using Regex with C#.Net and VB.Net example


Wednesday, 25 June 2014

It is very easy to remove string's trailing white space.

We can achieve using Regex. The Regex is "[ \t]+$".

Here is example of this.

In this example we are taking on string which has trailing white space. We can remove this spaces using Regex.

C#. Net Example :
string strData = "This string contains trailing white spaces             ";
strData = Regex.Replace(strData, "[ \t]+$", "");
Response.Write(strData);

VB.Net Examples :
Dim strData As String = "This string contains trailing white spaces             "
strData = Regex.Replace(strData, "[ \t]+$", "")
Response.Write(strData)


Click here for other post regarding Remove only leading white spaces from string using Regex with C#.Net and VB.Net example

Click here for other post regarding Remove leading and trailing white spaces from string using Regex with C#.Net and VB.Net example.  


Wednesday, 18 June 2014

It is very easy to remove string's leading white space.

We can achieve using Regex. The Regex is "^[ \t]+".

Here is example of this.
In this example we are taking on string which has leading white space. We can remove this spaces using Regex.

C#. Net Example :
string strData = "   This string contains leading white spaces";
strData=Regex.Replace(strData, "^[ \t]+", "");
Response.Write(strData);

VB.Net Examples :
Dim strData As String = "   This string contains leading white spaces"
strData = Regex.Replace(strData, "^[ \t]+", "")
Response.Write(strData)


Click here for other post regarding Remove only trailing white spaces from string using Regex with C#.Net and VB.Net example

Click here for other post regarding Remove leading and trailing white spaces from string using Regex with C#.Net and VB.Net example.  
 

Tuesday, 13 May 2014

Click Here to Download CustomRazorHelperClass.zip

It is very easy to write custom razor helper class. After creating custom razor helper class, we can use these classes anywhere in MVC Application.

Here is step by step explanation of creation of razor helper class.

STEP 1 :
First create MVC web application if you do not have MVC Web Application

STEP 2 :
Now Add new "App_Code" folder. In this folder add MVC Razor View page (MVC 4 View Page (Razor)).

To do this, you need to do right click on 'App_Code' folder and click on "Add New Item" menu. It will display dialog box to add new item. After that add 'MVC 4 View Page (Razor)' Page. Give it named like 'CustomRazorHelper.cshtml'.

Now we add one method name 'ToTitleCase', this method makes first character upper case of given statement and make rest of the characters lower case.

Wednesday, 23 April 2014

Click Here to Download PlayVideoInMVC.zip

It is very easy to play or display video in ASP.NET MVC using HTML5. We can do this using custom action filter in MVC. We can play various files like MP4, Ogg, WebM, etc. format.

Here are step by step tutorial to play video in ASP.NET MVC using HTML5.

Here is example for this.

Wednesday, 26 March 2014

You can fill DataTable from another DataTable using LINQ after doing LINQ operation.

This would be useful in condition like you need to perform some operation on DataTable using LINQ and get back result into another 'DataTable'. Means, you can filter and projection on one DataTable and get result in another DataTable.

We can achieve this by using 'CopyToDataTable' method of LINQ query result variable.

Here is example for this.
In this example we are taking one DataTable which contains product information like ID, name, etc. Now we get only those products which ID is greater than one by LINQ operation on this table and get result in another table using 'CopyToDataTable' method of LINQ query result variable.

Tuesday, 4 March 2014

You can create XML file from another file with selected elements from source XML file using LINQ. In this, we query the source XML file using LINQ and write or create new XML file.

Here is example for this. 
In this example we take one "Book.xml" file. In this file we have element like Title, Pages, ISBN and Auther. Now we are querying the "Book.xml" file to get only Title and ISBN of book and create another XML with data that contains only Title and ISBN element.

Wednesday, 12 February 2014

You can fill List of object from DataTable using LINQ. There are many situations where you need to get data from DB into data table and after that from data table to proper class object. We can do this easily with LINQ.

Here is example for this.
In this example we take one DataTable object which contains two columns 'product_id' and 'product_name'. This DataTable has many rows. Now we want to convert DataTable object into list of class object. We have one Class 'clsProduct' which has two property 'product_id' and 'product_name'. Now we transform DataTable object data in to list of clsProduct class object using LINQ.

Friday, 24 January 2014

Click Here to Download ImplementIValidateObjectInterfaceInMVC.zip Example.

We can validate model itself by implementing IValidatableObject Interface. For validation you need to implement 'Validate' method of IValidatableObject Interface.

Here is some difference from the attribute validation version.
  • In this for validation method is 'Validate' instead of 'IsValid' and also return type and parameter is different.
  • The return type for Validate is an IEnumerable<ValidationResult>, because the logic inside this method is validating the entire model and might need to return more than a single validation error.
  • No parameter is passed to Validate because you  can directly access model properties because this Validate method is inside model.

Here is example for this.

Thursday, 16 January 2014

You can attach events like 'onChanging' and 'onChanged' events on XML document object. These events raise when you 'ADD' or 'REMOVE' XML element from XML Document object.

First 'onChanging' event raise after that 'onChanged' event raise. In this event we get 'XObjectChangeEventArgs' class object. This object give us property like 'ObjectChange'. In this property we can know that which method is performed.

When we call 'Add' method we get 'Add' value in 'ObjectChange' property and when we call 'Remove' method we get 'Remove' value in 'ObjectChange' property.

Here is example on this.

Wednesday, 1 January 2014

Click Here to Download CustomAnnotationInMVC.zip Example.

You can write your own custom annotations in MVC 4.
Here we can do custom validation using custom annotations. Custom annotations validation derive from the ValidationAttribute base class. This base class available in 'System.ComponentModel.DataAnnotations' namespace. ValidationAttribute class is abstract class.

For custom validation you need to write your own class and inherit ValidationAttribute class. After that, you need to override IsValid Method. IsValid Method has two parameters 'Value' and 'ValidationContext'.

  • Value : Which contains your data, which is going to validate.
  • ValidationContext : This parameter is very important. This content information like model object instance, model type friendly display name and other information
In this method you write your own logic for validate data and return result. If value is validate at that time you need to return this 'ValidationResult.Success' else you return result like 'return new ValidationResult(your custom error message)'

Friday, 20 December 2013

You can validate the data of XML file and identify XML elements which are failed to validate. We can easily achieve this using LINQ.

Here is example for this.
In this example we take one 'customer.xml' file. In this file we have 'name' and 'phone' element. We need to validate phone number with REGEX and display it's validate result either it is true or false.

Wednesday, 11 December 2013

Using LINQ you can check that attribute exist in element or not. There is property called "HasAttributes" of XElement class to check existence of attribute.

Here is example for this.

In this example we take one 'customers.xml' file which contains customers information like name, id, etc. Now we check that does "customer" element has 'id' attribute or not. In XML there is one customer 'David' which does not have 'id' attribute. Now we iterate each 'customer' element and display that it element has attribute or not.

Wednesday, 20 November 2013


 XML file contains various types of data like string, integer, date, etc. Now if we want to get data from XML file order by some attribute which contains dates at that time we need to do some special things if we are not doing that at that time data is not sorted date wise it will treat as normal string sorting. We can do date wise sorting. 

Here are examples for this.
In this example we are taking on 'Books.xml' file which contains books details in this XML file for each book element we are one "ReleaseDate" element which contains date value. Now we take that XML file in XMLDocument object and sort on "ReleaseDate" attribute by converting that string date into date datatype.

Monday, 4 November 2013

Click Here to Download SetDefaultActionInMVC Example.

You can set default action name for controller in MVC. By providing default action name you did not type action name in controller. It will automatically call default action.

We can configure Route in 'App_Start/RouteConfig.cs' file using this 'routes.MapRoute' method, where 'routes' is the object of 'RouteCollection' class. In 'MapRoute' method we can set Default values. Code is something like below :

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { id = UrlParameter.Optional,Action="List" }
    );

Here is example for this.

Monday, 28 October 2013

Click Here to Download SetDefaultRouteInMVC.zip Example.

You can set Default route value for URL in MVC. Traditional our route pattern is like '{controller}/{action}/{id}'. This is going to fail if we pass URL like '{controller}/{action}'.

There are many scenarios in our day to day software application we require both pattern. For that you can set 'Id' as default parameter so that if we did not pass 'id' in query string it will not raise errors and execute our desired 'action'.

We can configure Route in 'App_Start/RouteConfig.cs' file using this 'routes.MapRoute' method, where 'routes' is the object of 'RouteCollection' class. In 'MapRoute' method we can set Default values. Code is something like below :
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { id = UrlParameter.Optional }
    );

Here is example for this. 

Wednesday, 16 October 2013

You can query objects using SelectMany LINQ method and get result according to your given criteria. You can also query more than one criteria.

Here is example for this.

In this example we take "books.xml". Now we query on element "author" whose sub element is 'firstname' and 'lastname' and we only want list of authors whose name is either 'Pratik' or 'David'.

Tuesday, 8 October 2013

We can do Range validation using annotations in MVC for that we are using 'Range' attribute. In the Range attribute we could specifies minimum and maximum value for a numerical value.

The first parameter to the attribute is the minimum value, and the second parameter is the maximum value. The values are inclusive. The Range attribute can work with integers, doubles, dates, etc. We can specify Type in overloaded version constructor.

Here is example for this.

Thursday, 26 September 2013

We can get or retrieve full path of the given XML Node or Element. Means from root element to the given XML Node. We can achieve this  LINQ's extensions methods. We are using 'Descendants', 'AncestorsAndSelf' and 'Reverse' methods.

  • Descendants : Returns filtered collections of the given elements from document or element. For more details Click Here.
  • AncestorsAndSelf : Returns collection of elements that contain this element. For more details Click Here.

Here is C#.Net example and VB.Net example.

Wednesday, 11 September 2013

You can directly get element of particular position or query that element using LINQ's 'Descendants' and 'ElementAt' method.

  • 'Descendants' is a method of XDocument class which accept name of element as string.
  • 'ElementAt' is a method of 'XElement' class which accept integer value of index.

Means you can query the 2nd book element in the XML document or file. You can also call that as positional predicate.

Here is example for this.
In this example we took one XML file 'BooksList.xml'. Now we use 'Descendants' method of 'XDocument' and pass 'book' element and after that, we use 'ElementAt' method and pass '1' so that we can get 2nd element of 'book' from that XML file.


C#. Net Example :
XDocument objDoc = XDocument.Load(Server.MapPath("BooksList.xml"));
XElement objElement = objDoc.Descendants("book").ElementAt(1);

Response.Write("<b>Title Element Value : </b>" + objElement.Element("Title").Value);
Response.Write("<br/>");
Response.Write("<b>ReleaseDate Element Value : </b>" + objElement.Element("ReleaseDate").Value);
Response.Write("<br/>");
Response.Write("<b>Pages Element Value : </b>" + objElement.Element("Pages").Value);

VB.Net Examples :
Dim objDoc As XDocument = XDocument.Load(Server.MapPath("BooksList.xml"))
Dim objElement As XElement = objDoc.Descendants("book").ElementAt(1)

Response.Write("<b>Title Element Value : </b>" + objElement.Element("Title").Value)
Response.Write("<br/>")
Response.Write("<b>ReleaseDate Element Value : </b>" + objElement.Element("ReleaseDate").Value)
Response.Write("<br/>")
Response.Write("<b>Pages Element Value : </b>" + objElement.Element("Pages").Value)

BooksList.xml
<?xml version="1.0" encoding="utf-16"?>
<books>
  <book ISBN="asp1">
    <Title>ASP.NET</Title>
    <ReleaseDate>11/11/2010</ReleaseDate>
    <Pages>200</Pages>
  </book>
  <book ISBN="c#2">
    <Title>C#.NET</Title>
    <ReleaseDate>10/11/2010</ReleaseDate>
    <Pages>500</Pages>
  </book>
</books>


Output :
LINQ positional predicate


Below are the books that you would like :