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.

Thursday 19 September 2013

You can check Database Status using SQL query.

Below are the possible status of database.
  • ONLINE : Database is available for access.
  • RESTORING : Primary file group and secondary files are being restored.
  • RECOVERING : Database is being recovered.
  • RECOVERY PENDING : Resource-related error occurred during recovery.
  • OFFLINE : Database is unavailable to access.
  • SUSPECT : One or many primary file group is suspect and may be damaged.
  • EMERGENCY : User has changed the database and set the status to EMERGENCY.

Here is query for this.

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 :

Monday 9 September 2013

Click Here to Download UploadAndDownloadFileInMVC.zip Example.
 
In many software application uploading and downloading files are required. There are very easy way to upload and download file in ASP.Net MVC framework.

Here is step by step example of how to implement upload and download functionality in MVC.

In this example we will also demonstrate how to change encoding type of form, how to apply CSS class to "Button" and "ActionLink" control and also How to apply style attribute with value.

STEP 1 : Add Upload View
Here is HTML of Uplod view file.

@using (Html.BeginForm("Index", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
    @Html.AntiForgeryToken() 
     <fieldset>
         <legend>Upload a file</legend>
        @Html.Raw(ViewBag.Message)
            <div class="editor-field">
                    @Html.TextBox("file", "", new { type = "file" }) 

            </div>
            <div class="editor-field">
                <input type="submit" value="Upload File" class="button_example" />
            </div>
         @Html.ActionLink("Go To Download Page","Index","Download",null, new {@class = "button_example",style="float:right"})
    </fieldset> 
} 


Monday 26 August 2013

You can get Parent element from child element using LINQ method. Some times there are situations when you traverse XML file and you reach at child node and you want to get details of Parent node at that time you can use "Parent" method which will give you parent node as XElement object.

Here is example for this.
In this example we took one "BooksList.xml" file. Now we traverse to child node "Title" and after that, we get its parent node using "Parent" property.

Monday 19 August 2013

Click Here to MVC_Regular_Expression_ValidationUsingAnnotations.zip Example.

We can do Regular Expression or REGEX validation using Annotations in MVC. We can use "RegularExpression" attribute for validation. In this attribute we specify Regular Expression string.

We can also specify our custom error messages for that we need to set "ErrorMessage" Property in "RegularExpression" attribute.

Here is example for this.

Monday 12 August 2013

Download AbstractFactoryDesignPatternExampleWithCSharp.zip C# Example.
Download AbstractFactoryDesignPatternExampleWithVB.Net.zip VB.Net Example.


Abstract factory pattern is expanded version of basic factory pattern. In Abstract factory pattern we unite similar type of factory pattern classes in to one unique interface.

Factory classes helps to centralize the creation of classes and types. Abstract factory help bring equability between related factory patterns classes. Which create more simplified interface for the client.

Now let's understand basic details of how to implement abstract factory patterns. We have the factory pattern classes which integrate to a common abstract factory classes through inheritance. Factory classes lay over concrete classes which are derived from common interface.
For instance in below figure we demonstrate "Implementation of abstract factory".

Abstract  Factory Design Pattern
(To view original image , click on image)


Both the concrete classes "ConcreateClass1" and "ConcreateClass2" inherits from one common interface. The client has to only interact with the abstract factory and the common interface from which the concrete classes inherit.

Monday 29 July 2013

There are situations where some time we want to get root element of XML file or document. We can get this root element and root element name very easily. We are using "Root" property of "XDocument" class.

Here is example for this.
In this example we take on "BooksList.xml" file and we display its root element name.

C#. Net Example :
        XElement objRootElement = XDocument.Load(Server.MapPath("BooksList.xml")).Root;
        Response.Write("<b>Name of root element is : </b>" + objRootElement.Name);

VB.Net Examples :
        Dim objRootElement As XElement = XDocument.Load(Server.MapPath("BooksList.xml")).Root
        Response.Write("<b>Name of root element is : </b>" & objRootElement.Name.ToString())

Output :


Below are the books that you would like :

Tuesday 23 July 2013

Click Here to Download MVC_String_Length_ValidationUsingAnnotations.zip Example.

We can do string length validation using Annotations in MVC. We are using "StringLength" attribute for validation in this attribute we can specify how many characters we want to allow for particular field. In this, we can specify Maximum Length and Minimum Length. Minimum Length is an optional.

We can use more than one attribute on field.

Here is example for this.

Monday 15 July 2013

We can get specific attributes values from XML file or document or object using LINQ. We are using "Elements" and "Attributes" methods of XML document object to get attributes values.

Here is example for this.
In this example we take one "BooksList.xml" file. This file contains books related details and each book has ISBN number which appears as attribute in "<book>" node. We retrieve this attribute using LINQ and display on screen.

Tuesday 9 July 2013

Click Here to Download MVCValidationUsingAnnotations.zip Example.
 
Data annotations are uses for validation purposes. We can use annotations attribute on a model property. You can find data annotations in System.ComponentModel.DataAnnotations namespace. But there are attributes also available outside this namespace.

These attributes provide server-side validation and client-side validation. Here we are demonstrating "Required" attribute. This is a basic validation in each and every project or application we need required field validation.

Here is example for this.

Saturday 29 June 2013

 Click Here to Download FactoryPatternSampleWithCSharp.zip C# Example.
 Click Here to Download FactoryPatternSampleWithVBNET.zip VB.Net Example.

Factory Design Pattern is type of creational patterns. We can architect software with the help of factory design pattern. With the help of factory pattern we can centralize creations of objects and also reduce object creation logic at the client side.

Let's see some example on this.
We take booklet display example. You have functionality like display booklet on screen in two ways one is with header and footer and other is plain without header and footer.

In traditional approach you might take two classes "BookletWithHeaderFooter" and "BookletPlain" and create objects depending on your requirement on client side like below code.

Tuesday 18 June 2013

We can Create or Generate XML file or document programmatically using XDocument, XElement and XAttribute class. We can use infinite level of XML element. We can also create "web.config" file programmatically.

Here is example for this.
In this example we create sample "web.config" file using XElement and XAttribute class and display that generated XML in textbox. We are using ".ToString" method of XDocument object to get XML string.

ASPX Code :
    <asp:TextBox runat="server" ID="txtXML" TextMode="MultiLine" Rows="20" Columns="110"></asp:TextBox>


C#. Net Example :
        XDocument myDocument = new XDocument(
                                  new XElement("configuration",
                                    new XElement("system.web",
                                      new XElement("membership",
                                        new XElement("providers",
                                          new XElement("add",
                                            new XAttribute("name","WebAdminMembershipProvider"),
                                            new XAttribute("type","System.Web.Administration.WebAdminMembershipProvider")))),
                                      new XElement("httpModules",
                                        new XElement("add",
                                          new XAttribute("name","WebAdminModule"),
                                          new XAttribute("type","System.Web.Administration.WebAdminModule"))),
                                      new XElement("authentication",
                                        new XAttribute("mode", "Windows")),
                                      new XElement("authorization",
                                        new XElement("deny",
                                          new XAttribute("users", "?"))),
                                      new XElement("identity",
                                        new XAttribute("impersonate", "true")),
                                      new XElement("trust",
                                        new XAttribute("level", "full")),
                                      new XElement("pages",
                                        new XAttribute("validationRequest", "true")))));

        txtXML.Text = myDocument.ToString();

VB.Net Examples :
        Dim myDocument As New XDocument(
            New XElement("configuration",
                                    New XElement("system.web",
                                        New XElement("membership",
                                        New XElement("providers",
                                            New XElement("add",
                                            New XAttribute("name", "WebAdminMembershipProvider"),
                                            New XAttribute("type", "System.Web.Administration.WebAdminMembershipProvider")))),
                                        New XElement("httpModules",
                                        New XElement("add",
                                            New XAttribute("name", "WebAdminModule"),
                                            New XAttribute("type", "System.Web.Administration.WebAdminModule"))),
                                        New XElement("authentication",
                                        New XAttribute("mode", "Windows")),
                                        New XElement("authorization",
                                        New XElement("deny",
                                            New XAttribute("users", "?"))),
                                        New XElement("identity",
                                        New XAttribute("impersonate", "true")),
                                        New XElement("trust",
                                        New XAttribute("level", "full")),
                                        New XElement("pages",
                                        New XAttribute("validationRequest", "true")))))

        txtXML.Text = myDocument.ToString()

Output :
Create or Generate XML file programmatically using XElement and XAttribute class
(To view original image , click on image)

Tuesday 11 June 2013

XML declaration of a XML document or file is very important. We can add XML declaration and create XML element programmatically .
We are using "XDocument" and "XDeclaration" class to add declaration.

Here is example for this.
In this example we create XML document with specified XML declaration and save it into the StringWriter object. You can see in the debug time screenshot.

C#. Net Example :
        XDocument doc = new XDocument(new XDeclaration("1.0", "UTF-16", "Yes"),new XElement("Products"));
        StringWriter sw = new StringWriter();
        doc.Save(sw);
        Response.Write(sw.ToString());

VB.Net Examples :
        Dim doc As New XDocument(New XDeclaration("1.0", "UTF-16", "Yes"), New XElement("Products"))
        Dim sw As New StringWriter()
        doc.Save(sw)
        Response.Write(sw.ToString())

Output :
Add XML declaration programmatically
(To view original image , click on image)



Wednesday 5 June 2013

We can construct or create XML or XElement from string. There are situations in applications where we receive some XML data in form of string and we need to convert that string back into the XML for our need and easy to handle that XML document for querying and other manipulation.
We are using "XElement.Parse" method to get XElement.

Here is example for this.
In this example we take one string xml and then we converted that in to XElement using "Parse" method of "System.Xml.Linq.XElement" Class.
You can see in output image that after parse that object we watch this object in "Text Visualizer" window and able to see that that string is converted in to XElement.

C#. Net Example :
        string strXML = "<Products>" +
                        "<Product id='1' price='5000'>CPU</Product>" +
                        "<Product id='2' price='500'>Monitor</Product>" +
                        "<Product id='2' price='100'>Mouse</Product>" +
                        "</Products>";
        System.Xml.Linq.XElement objXElement = System.Xml.Linq.XElement.Parse(strXML);
        Response.Write(objXElement);

VB.Net Examples :
        Dim strXML As String = "<Products>" & _
                                "<Product id='1' price='5000'>CPU</Product>" & _
                                "<Product id='2' price='500'>Monitor</Product>" & _
                                "<Product id='2' price='100'>Mouse</Product>" & "</Products>"
        Dim objXElement As System.Xml.Linq.XElement = System.Xml.Linq.XElement.Parse(strXML)
        Response.Write(objXElement)

Output : 
Create XElement or XML from string
(To view original image , click on image)

Friday 31 May 2013

SkipWhile LINQ method to get the elements of the array starting from our given condition matched.

Here is LINQ "SkipWhile" Method example.
In this example we take one integer array "arrayNumbers" which contains integer values. Now we use "SkipWhile" method to get all elements starting from first element divisible by 3. In the lambda expression, "n" is the input parameter that identifies each element in the collection in succession. It is inferred to be of type int because numbers is an int array.

C#. Net Example :
        int[] arrayNumbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

        
        var objResult = arrayNumbers.SkipWhile(n => n % 3 != 0);

        Response.Write("<b>All elements starting from first element divisible by 3 : </b>");
        Response.Write("<br/>");
        foreach (var n in objResult)
        {
            Response.Write(n);
            Response.Write("<br/>");
        }

VB.Net Examples :
        Dim arrayNumbers As Integer() = {4, 5, 0, 3, 9, 8, 6, 7, 1, 2, 0}

        Dim objResult = arrayNumbers.SkipWhile(Function(n) n Mod 3 <> 0)

        Response.Write("<b>All elements starting from first element divisible by 3 : </b>")
        Response.Write("<br/>")

        For Each num As Integer In objResult
            Response.Write(num)
            Response.Write("<br/>")
        Next

Output :
LINQ SkipWhile Method Example

To view "TakeWhile" LINQ method example Click Here...


Thursday 23 May 2013

You can get element from array until your given condition is satisfied.
TakeWhile LINQ method to return elements starting from the beginning of the array until a number is read whose value satisfied according to our given criteria.


Here is LINQ "TakeWhile" Method example.

Wednesday 22 May 2013

Using LINQ we can check sequence match on all elements in same order for two different array.
We are using "SequenceEqual" LINQ method to check. This method returns "true" if sequence match else return "false".

Here is LINQ "SequenceEqual" Method example.

Tuesday 14 May 2013

There are situations were we have string array which contains many value and we want to check that particular word or string part exist in all values.
We want to avoid iteration of array at that time we can use LINQ's "Any" method. Using one line code we can check.

Here is example for this :
In this example we take on string array "ProductArray" and insert some values. Now we want to check that "er" word is contain any values of this array or not using "Contains" method. You can check output below.

C#. Net Example :
        string[] ProductArray = { "CPU", "Computer", "DVD", ".Net" };

        bool isExist = ProductArray.Any(o => o.Contains("er"));

        Response.Write("There is a word in the list that contains 'er': <b>" + isExist + "</b>");

VB.Net Examples :
        Dim ProductArray As String() = {"CPU", "Computer", "DVD", ".Net"}

        Dim isExist As Boolean = ProductArray.Any(Function(o) o.Contains("er"))

        Response.Write("There is a word in the list that contains 'er': <b>" & isExist & "</b>")

Output :

Wednesday 8 May 2013

Using LINQ we can convert array in to dictionary object. We can use "ToDictionary" LINQ method to get dictionary object from array.
But we need to make sure that the key value should be unique in array, otherwise it will generate error "An item with the same key has already been added.".

Here is example for that.
In this example we take one two dimensional array "CustomerDetails". This array contains ID and Name of customer. Now using "ToDictionary" method of this array we can get dictionary object of type "Dictionary<int, string>". You can get your desirable type of Dictionary object.

Thursday 2 May 2013

Using LINQ we can get specific type of object from Object Type array which contains many types of object. We are using "OfType" generic method to return only the elements of the array that  we specified.

Here is example for this.
In this example we take one array whose type is object and which contains many types of object, i.e. string, integer, double, Dictionary etc...
Now we get only doubles value using LINQ and display, after that, we get Dictionary object using LINQ and display. You can see the output for that.


Saturday 13 April 2013

You can easily do date time conversion in ASP.Net. You can convert date time from one format to other format.

In real application when data comes from external sources at that time chances increase for date time conversion error because both sender and receiver of data has different local date format setting.

May be you want to display or store date time in different format. If you know that date format that come from outside and you need in different format at that time your task become easy.

Here is example for this.
In this, we have one date in string variable in "MM/dd/yyyy" format. Now we convert this date in "dd/MM/yyyy" format. We are using "TryParseExact" method to parse and create DateTime object from date string after that, we convert in our desire format using "ToString" method. You can convert in any date time format.

Saturday 6 April 2013

Click Here to Download Autocomplete And Fancy Dropdown boxes.zip
Also Download From this Link : Download Autocomplete And Fancy Dropdown boxes.zip

There is a situation where you have a large amount of value in dropdown list and you want to make that dropdown user-friendly. You want auto search functionality in ASP.Net Dropdownlist control.

You want one textbox inside dropdown list and when user type something in that textbox dropdown list become searchable and it will display only those records which were matched within textbox without doing any postback.

We can do this using Javascript and JQuery. We are using one JQuery plug-in for that. Plug-in name is "Chosen".

Here is example for ASP.NET Autocomplete DropDown.

In this example we take ASP.Net dropdown control and fill countries name into that, after that when user click on that combobox by default dropdown list is open and on first position you can see the textbox when you type in textbox dropdown list control become search-able and this list if automatically filter.

You can also get selected value in server side code using "SelectedValue" property of comobox. In this example when user click on "GetSelected" button at that time server side button click event called and display selected value in label. You can see that in below output screens.

ASPX Code :
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FnacyDropdownlist.aspx.cs" Inherits="FnacyDropdownlist" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <style>
        a img{border: none;}
        ol li{list-style: decimal outside;}
        div#container{width: 780px;margin: 0 auto;padding: 1em 0;}
        div.side-by-side{width: 100%;margin-bottom: 1em;}
        div.side-by-side > div{float: left;width: 50%;}
        div.side-by-side > div > em{margin-bottom: 10px;display: block;}
        .clearfix:after{content: "\0020";display: block;height: 0;clear: both;overflow: hidden;visibility: hidden;}
        
    </style>
    <link rel="stylesheet" href="Style/chosen.css" />
</head>
<body>
    <form runat="server" id="form1">
        <div id="container">
            <h2>Selected Value :
                <asp:Label runat="server" ID="lblSelectedValue" Style="color: red"></asp:Label></h2>
            <div class="side-by-side clearfix">

                <div>

                    <asp:DropDownList data-placeholder="Choose a Country..." runat="server" ID="cboCountry" class="chzn-select" Style="width: 350px;">
                        <asp:ListItem Text="" Value=""></asp:ListItem>
                        <asp:ListItem Text="United States" Value="United States"></asp:ListItem>
                        <asp:ListItem Text="United Kingdom" Value="United Kingdom"></asp:ListItem>
                        <asp:ListItem Text="Albania" Value="Albania"></asp:ListItem>
                        <asp:ListItem Text="Algeria" Value="Algeria"></asp:ListItem>
                        <asp:ListItem Text="Angola" Value="Angola"></asp:ListItem>
                        <asp:ListItem Text="Bahamas" Value="Bahamas">Bahamas</asp:ListItem>
                        <asp:ListItem Text="Bahrain" Value="Bahrain"></asp:ListItem>
                        <asp:ListItem Text="Brazil" Value="Brazil"></asp:ListItem>
                        <asp:ListItem Text="Czech Republic" Value="Czech Republic"></asp:ListItem>
                        <asp:ListItem Text="Denmark" Value="Denmark"></asp:ListItem>
                        <asp:ListItem Text="Djibouti" Value="Djibouti"></asp:ListItem>
                        <asp:ListItem Text="Dominica" Value="Dominica"></asp:ListItem>
                        <asp:ListItem Text="Dominican Republic" Value="Dominican Republic"></asp:ListItem>

                    </asp:DropDownList><asp:Button runat="server" ID="btnSelect" Text="Get Selected" OnClick="btnSelect_Click" />

                </div>
            </div>

        </div>
        <script src="Scripts/jquery.min.js" type="text/javascript"></script>
        <script src="Scripts/chosen.jquery.js" type="text/javascript"></script>
        <script type="text/javascript"> $(".chzn-select").chosen(); $(".chzn-select-deselect").chosen({ allow_single_deselect: true }); </script>
    </form>
</body>
</html>

C#. Net Example :
    protected void btnSelect_Click(object sender, EventArgs e)
    {
        lblSelectedValue.Text = cboCountry.SelectedValue;
        
    }

Output (Default Screen) : 

Auto Search Functionality in ASP.Net Dropdownlist control
(To view original image , click on image)


Output (Auto search screen) : 

Auto Search Functionality in ASP.Net Dropdownlist control
(To view original image , click on image)

Output (Selected Value Screen) :  

Auto Search Functionality in ASP.Net Dropdownlist control
(To view original image , click on image)
 

You can download complete running source code from above link.

Note : There are other lots of functionality of this "Chosen" plug-in. We will post those functionality in next
blogs.

Saturday 30 March 2013

Click Here to Download WebAPICRUDOperation.zip


In this article we are demonstrating how Insert, Update, View and Delete operation works in Output using HTTP service.
We can also call as CRUD (Create, Read, Update, Delete) Operation.

In this WebAPI example we are using following HTTP Methods for CURD Operations.

  • GET method retrieves the data or resources at a specified URI.
  • PUT method updates the data or resource at a specified URI.
  • POST method send data to the specified URI.
  • DELETE method deletes a resource at a specified URI.

Now we are creating project step by step.

STEP 1 :

Create a Web API Project.

Saturday 16 March 2013

There are situations where we had date in string format in string variable and want to check that this string contains specific date format or not and if this date is in pacific format, then convert it to date time object.

By checking this, we can avoid any date time conversion run time errors. We can do this using "TryParseExact" method of "DateTime" Class.

Here is an Example for this.

Friday 8 March 2013

Click Here to Download WebAPIProject_First.zip


ASP.NET Web API is a framework for developing web APIs on top of the .NET Framework. Web API serves data on HTTP. HTTP service is so powerful and compatible with various clients and platform.

Web API uses in Mobile devices, various browsers and in desktop applications to get or post data.

In this project or tutorial, we will use ASP.NET Web API to create a web API that returns a list of customers and depend on parameters we provide. We are getting results direct on browser and also display in web page with use of jQuery.

As we are developing this project in new framework following are the prerequisite:
Following is the requirement :

This example requires Visual Studio with ASP.NET MVC 4.

We can use any following:
    Visual Studio 2012
    Visual Studio Express 2012 for Web
    Visual Studio 2010 with ASP.NET MVC 4 installed.
    Visual Web Developer 2010 Express with ASP.NET MVC 4 installed.

If you are using Visual Studio 2010 or Visual Web Developer 2010 Express, you will need to install ASP.NET MVC 4 separately.


This project we developed in Visual Studio 2012.

Here is the step-by-step explanation of how to create Web API Project.

STEP 1 : 

Wednesday 27 February 2013

There are situations where we want date time values in different formats like dd/MM/yy, MM/dd/yy, dd/MMM/yyyy etc.


We are using .ToString() method of date time object to get formatted date time string. In this .ToString() method we need to provide string format in which we want to format date. You can also get time in various format like AM, PM and also get Time Zone like +5:30 etc...

Here is example for this.
In this example we provide various different date time formats. You can also change that accordingly your need. You can also use other symbol than "/".

C#. Net Example :

        DateTime objDateTime = new DateTime(2013, 2, 25, 5, 40, 10);
        Response.Write("<b>dd/MM/yy Date Format :</b>" + objDateTime.ToString("dd/MM/yy"));
        Response.Write("<br/>");
        Response.Write("<b>MM/dd/yy Date Format :</b>" + objDateTime.ToString("MM/dd/yy"));
        Response.Write("<br/>");
        Response.Write("<b>dd/MM/yyyy Date Format :</b>" + objDateTime.ToString("dd/MM/yyyy"));
        Response.Write("<br/>");
        Response.Write("<b>dd-MMM-yyyy Format :</b>" + objDateTime.ToString("dd-MMM-yyyy"));
        Response.Write("<br/>");
        Response.Write("<b>dd/MM/yyyy HH:mm:ss Date And Time Format :</b>" + objDateTime.ToString("dd/MM/yyyy HH:mm:ss"));
        Response.Write("<br/>");
        Response.Write("<b>dd/MM/yyyy HH:mm:ss zzz Date And Time Format with time zone :</b>" + objDateTime.ToString("dd/MM/yyyy HH:mm:ss zzz"));
        Response.Write("<br/>");
        Response.Write("<b>dd/MM/yyyy HH:mm:ss tt Date And Time Format :</b>" + objDateTime.ToString("dd/MM/yyyy HH:mm:ss tt"));
        Response.Write("<br/>");
        Response.Write("<br/>");

VB.Net Example :

            Dim objDateTime As New DateTime(2013, 2, 25, 5, 40, 10)
            Response.Write("<b>dd/MM/yy Date Format : </b>" & objDateTime.ToString("dd/MM/yy"))
            Response.Write("<br/>")
            Response.Write("<b>MM/dd/yy Date Format : </b>" & objDateTime.ToString("MM/dd/yy"))
            Response.Write("<br/>")
            Response.Write("<b>dd/MM/yyyy Date Format : </b>" & objDateTime.ToString("dd/MM/yyyy"))
            Response.Write("<br/>")
            Response.Write("<b>dd-MMM-yyyy Format : </b>" & objDateTime.ToString("dd-MMM-yyyy"))
            Response.Write("<br/>")
            Response.Write("<b>dd/MM/yyyy HH:mm:ss Date And Time Format : </b>" & objDateTime.ToString("dd/MM/yyyy HH:mm:ss"))
            Response.Write("<br/>")
            Response.Write("<b>dd/MM/yyyy HH:mm:ss zzz Date And Time Format with time zone : </b>" & objDateTime.ToString("dd/MM/yyyy HH:mm:ss zzz"))
            Response.Write("<br/>")
            Response.Write("<b>dd/MM/yyyy HH:mm:ss tt Date And Time Format : </b>" & objDateTime.ToString("dd/MM/yyyy HH:mm:ss tt"))
            Response.Write("<br/>")
            Response.Write("<br/>")

Output :
Formatted Date Time In Asp.Net
(To view original image , click on image)


Note : Give us your valuable feedback in comments. Give your suggestions in this article so we can update our articles according to that.


Friday 22 February 2013

There are many situations where in past we did some useful functionality in some stored procedures after that as time goes we forgot that how exactly we had done that functionality and now we want implement that functionality somewhere else and we do not remember where we used, but we know some important keyword or string that we used at that place. At that time this query is useful.

This query searches in all Stored Procedures in database according to given search criteria and give use the search results. In this query we are using sys.sql_modules and sys.objects system tables.

SQL Query : 

SELECT 
        so.[name] AS SP_NAME ,
        so.type_desc AS ROUTINE_TYPE,
        sm.definition AS SP_DEFINITION
FROM sys.sql_modules AS sm
INNER JOIN sys.objects AS so
    ON sm.object_id = so.object_id
WHERE sm.definition LIKE '%Quantity%'
and type='P'

Output :
Sql Query for Search in Stored Procedures
(To view original image , click on image)

This is the very useful SQL Server Scripts.

Note : Give us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.



Tuesday 19 February 2013

Click Here to Download JQueryCyclePuginDemo.zip

Now a day image slide show is very popular in websites. Earlier we are using Flash for image slide show. But now a days we are using Javascript for making lite weight image slide show. Using JQuery we can make image slide shows with a many variations in slide show.

We are using JQuery Cycle plugin. This plugin provide many options for slide show. You can download cycle plugin here. Download "jquery.cycle.all.js". You can also check it's Functional documentation and FAQs on this link.

Here is example for this.

Wednesday 13 February 2013

We can create date time object by supplying day , month , year , hour , minute and second values. After creating this date time object we can get datetime in our desire format. like short date , long date etc... We are using "ToShortDateString" , "ToLongDateString" , "ToShortTimeString" and "ToLongTimeString" methods.

This is example for this.
In this example we create date time object with day , month , year , hour , minute and second values and print that generated date time on screen.

C#. Net Example :

        DateTime objDateTime = new DateTime(2013, 2, 13, 5, 40, 10);
        Response.Write("<b>Short Date :</b>" + objDateTime.ToShortDateString());
        Response.Write("<br/>");
        Response.Write("<b>Long Date :</b>" + objDateTime.ToLongDateString());
        Response.Write("<br/>");
        Response.Write("<b>Short Time :</b>" + objDateTime.ToShortTimeString());
        Response.Write("<br/>");
        Response.Write("<b>Long Time :</b>" + objDateTime.ToLongTimeString());

VB.Net Examples :

        Dim objDateTime As New DateTime(2013, 2, 13, 5, 40, 10)
        Response.Write("<b>Short Date :</b>" + objDateTime.ToShortDateString())
        Response.Write("<br/>")
        Response.Write("<b>Long Date :</b>" + objDateTime.ToLongDateString())
        Response.Write("<br/>")
        Response.Write("<b>Short Time :</b>" + objDateTime.ToShortTimeString())
        Response.Write("<br/>")
        Response.Write("<b>Long Time :</b>" + objDateTime.ToLongTimeString())

Output :
Create Date Time Object

For more Beginning .Net articles visit this link.  Click Here...

Note : Give us your valuable feedback in comments. Give your suggestions in this article so we can update our articles according to that.


Thursday 7 February 2013

New feature in ASP.Net 4.5. HTML5 introduces new data types which also support by ASP.NET 4.5 textbox control. For email validation you do not require any validation controls. We need to just set property of textbox and input type control.

Your browser must support HTML5 if you want to use this feature.

Now ASP.Net supports new attributes in TextMode property. We are going to use "Email" attribute. There are different way to do this email validation in ASP.NET 4.5 and HTML5. But ASP.NET 4.5 Utlimetly converting to HTML5 at a time of rendering.

Here is example for this.

Friday 1 February 2013

Click to Download C# Example ImageMappedHandlerInCSharp.zip
Click to Download VB.NET Example ImageMappedHandlerInVBNET.zip


Http Handler using ".ashx" file extension and this is very convenient and understandable to all of us. But we can also custom this file extension with our requirement. To make customization in file extension we need to do add class file in "App_Code" folder and this class file implement "IHttpHandler" interface. And also mapping file extension in IIS and add settings in "web.config" file.

This configuration tell the application to show which file extension this handler serves. We can You do this by adding an <httpHandlers> section to the web.config file.
Here is configuration setting :
    <system.web>
      <httpHandlers>
        <add verb="*" path="ImageHandler.img" type="ImageMappedHandler, App_Code"/>
      </httpHandlers>
    </system.web>

This settings direct the application to use the "ImageMappedHandler" class to process incoming requests for ImageHandler.img. We can also specify wildcards for the path. By specifying *.img for the path which indicates that we want the application to use the ImageMappedHandler class to process any request with the
.img file extension. By specifying * indicates that we want all requests to the application to be processed using the handler.

Additional Configuration for IIS 7 :
If we run out web application on IIS 7 then we also must add the <handlers> configuration section to the <system.webServer> configuration section in our application’s config file. When adding the handler configuration in this section, we must also include the name attribute.

Configuration for IIS 7 :
  <system.webServer>
    <handlers>
      <add name="ImageHandler" verb="*" path="ImageHandler.img" type="ImageMappedHandler, App_Code" />
    </handlers>
  </system.webServer>

Now after doing this settings we can directly call ImageHandler.img from browser and we can get image from that.

Here is example for this.

Tuesday 29 January 2013

This Image shows how an HTTP request flows through the Web API pipeline, and how the HTTP response arrive back. It has also shows extensibility points, where we can add custom code or even replace the default behavior entirely.

This Image is used by web developers who want to understand the Web API pipeline. You can download that image from below link. This image is available in PDF file.

For printing purpose it's size is 24"X30". There are two version of that image one is full color and other is a gray-scale version.

Image : 
Lifecycle of an HTTP message in ASP.NET Web API


Click To Download full color Image.
Click To Download gray scale Image.

Source : http://www.microsoft.com

Friday 25 January 2013

Click to Download C# Example StronglyTypedDataControlsInCSharp.zip
Click to Download VB.NET StronglyTypedDataControlsInVBNET.zip


Strongly Typed Data Controls features newly introduce in vNext series. New ItemType Property for controls who has "template" Concept like Repeater, Grid, Form View etc.. Strongly typed data-controls is a small, but very good feature that makes work with data bound expressions easier and cleaner.

ASP.NET Web Forms introduced the concept of  "templates" starting with the very first release. Templates allow you to customize (or override) the markup of server controls, and are typically used with data binding expressions.

When using data binding within a template we used late bound expressions to bind to the data. For example, we are using the Eval() helper method for binding data. the "customer_id" and "customer_name" properties from a list of objects data bound to a repeater control like this :

        <asp:Repeater runat="server" ID="Repeater1">
            <ItemTemplate>
                ID : <%# Eval("customer_id") %>
                <br />
                Name : <%# Eval("customer_name") %>
                <br />
                <hr>
                <br />
            </ItemTemplate>
        </asp:Repeater>
      
In .Net 4.5 there is new strongly-typed data templates in that new "ItemType" property introduce on data controls. With the help of this property we declare that what type of data is going to be bound to data control.

Where you set "ItemType" property to object at that time there are two new typed variables to be generated in the scope of the data bound template. These variables are "Item" and "BindItem".

We can use these variables in data binding expressions and get Intellisense and compile time checking support.

IntelliSense Display : 

Strongly Typed Data Controls IntelliSense Display
(To view original image , click on image)



If we make any mistake while typing the field name we will receive error message from IntelliSense engine.

IntelliSense Error :
Strongly Typed Data Controls IntelliSense Display
(To view original image , click on image)



Here is example for this.