Showing posts with label Web development. Show all posts
Showing posts with label Web development. Show all posts

Saturday, January 18, 2014

How do I enable HTTP PUT and DELETE for ASP.NET MVC

  1. GO to Handler Mappings in your IIS Manager
  2. Find ExtensionlessUrlHandler-Integrated-4.0
  3. double click it. 
  4. Click Request Restrictions... button and on Verbs tab, add both DELETE and PUT


Remove WebDav from "Modules" and from "Handler Mappings"


Modules:
                WebDAVModule, %windir%\System32\inetsrv\webdav.dll, Native, Inherited

Handler Mappings:

                WebDAV, *, Enabled, Unspecified, WebDAVModule, Inherited

Then Restart IIS

It results in a Web.Config change of:

  <system.webServer>
        <modules>
            <remove name="WebDAVModule" />
        </modules>
        <handlers>
            <remove name="WebDAV" />
        </handlers>
  </system.webServer>

 
Submit this story to DotNetKicks

Read more...

Wednesday, January 9, 2013

ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized

ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized

While using transaction in Asp.net/C# I got above error.

To solve this error I simply added Transaction object in SqlCommand like below
SqlTransaction Transaction;
conn.Open();
Transaction = conn.BeginTransaction(); 
SqlCommand cmd = new SqlCommand(sql, conn, Transaction);

Submit this story to DotNetKicks

Read more...

Monday, October 29, 2012

Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException

While working on Asp.Net application with Master Pages, Child pages and web user controls getting following error is very common. Which is related to Events related to Web user controls, e.g. Button click event...

Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: Invalid postback or callback argument.  Event validation is enabled using  in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

In such cases as error says we simply have to disable EventValidation in @Page directive and error disappears.

<%@ Page EnableEventValidation="false" %>
OR enable it for whole application by modifying it in web.config file

<%@pages enableeventvalidation="false">
<%@/pages>
Submit this story to DotNetKicks

Read more...

Thursday, August 9, 2012

Auto Generate Serial Number in GridView

To auto generate serial number in Gridview, which we can use only for display purpose and has nothing to do with database and data related operations.

  • Add Following Column in Grid View at first position

       
       <%# ((GridViewRow)Container).RowIndex + 1%>
   
 

Above code will simply autogenerate serial number in Gridview
Submit this story to DotNetKicks

Read more...

Wednesday, August 1, 2012

Textbox with background image using CSS

We can use CSS To make stylish textboxes like rounded corner textbox or textbox with some image inside. Rounded corner text box is like following image.


To make rounded corner textbox we use following logic. We will put textbox in some wrapper layer i.e. div tag and apply style to wrapper layer.
Now style applied to wrapper div tag is as follows
.tt-wrapper
 {
 background-image:url('images/user_box.png');
 margin:0;
 width:255px;
 height:35px; 
  }
In above style user_box.png is a background image (check following image.)


 Then we apply style to fit the textbox with in wrapper div class.
.tt{
 width:240px;
 height:25px;
 margin:5px 0 0 8px;
 border:none;
 background:none;
 }
And we are done with Textbox with rounded corner. To display some image inside textbox we simply need to add background image in the class applied to textbox
Submit this story to DotNetKicks

Read more...

Logout User In Asp.net Membership

While developing usermanagement based web application using Membership provider, many times we come across some trivial issues or queries as follows
  • formsauthentication.signout not working
  • Using formsauthentication.signout
  • logout user programmatically
  • Check user date subscription and log out if user is not valid.
  • programmatically logout in asp net
  • Logout user in asp.net Membership
Solution for all above queries is as follows
FormsAuthentication.SignOut();
  Session.Abandon();

 // clear authentication cookie
 HttpCookie frmcookie = new HttpCookie(FormsAuthentication.FormsCookieName, "");
 frmcookie.Expires = DateTime.Now.AddYears(-1);
 Response.Cookies.Add(frmcookie);

 // clear session cookie if we use any
 HttpCookie sessioncookie = new HttpCookie("ASP.NET_SessionId", "");
 sessioncookie.Expires = DateTime.Now.AddYears(-1);
 Response.Cookies.Add(sessioncookie);

 FormsAuthentication.RedirectToLoginPage("v=SubscriptionExpired");
Above code signout the user, remove all the Cookies set. Forms Authentication.RedirectToLoginPage uses settings in web.config file. We can pass Querystring to the function so that we can show proper Messages.
Submit this story to DotNetKicks

Read more...

Display rupee symbol website

To display Rupee Symbol to website use following code.
Ruppee Symbol

  1. Add a stylesheet link in the head section of your webpage:


  • Add the following code enclosing your "Rs."
    Rs. 1000
    
  • OR Just include the following javascript and it will update all the "Rs" / "Rs." for you
    
    
    This is how we can display indian rupee symbol in website/blog. If Unicode is supported then we can use rupee symbol positioned at U+20B9.
    Submit this story to DotNetKicks

    Read more...

    Tuesday, July 31, 2012

    Form Authentication Is Not Working

    Form Authentication Is Not Working in IE 8. I am working on one web based project where I started with user management and struggled to make Form Authentication work... :( without testing it on other browsers. I had following settings in web.config...
    
          
        
    
    
    After struggling for the day on "Form Authentication Is Not Working" and to Make it work... I tested it in Firefox and Google Crome and it did work very well :(, without any error. What I realized is, there is some Issue with IE 8 and Cookies we are using for Form authentication, so I made following change in Web.Config Setting.
    
          
        
    
    
    Which in turn changed URL for IE 8 by adding some encoded information as a part of URL (going cookie-less), and in other browsers it allowed cookies and URL was without any Encoding added i.e. it was using Cookies. I hope this piece of Information will be Useful.
    Submit this story to DotNetKicks

    Read more...

    Getting session state in httphandlers - ashx files

    To do session state handling in Generic handlers or ashx files, there are two possibilities Readonly session state: we need to implement IReadOnlySessionsState interface, usefollowing demo code.
    using System;
    using System;
    using System.Web;
    using System.Web.SessionState;
    
    public class Handler : IHttpHandler, IReadOnlySessionState
    {
    
        public void ProcessRequest(HttpContext context)
        {
        if (HttpContext.Current.Session["SessionsName"] != null)
         {
          context.Response.Write(HttpContext.Current.Session["SessionsName"]);
         }
        }
    
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    
    }
    
    Read and Write Access to state: we need to implement IRequiresSessionState interface, usefollowing demo code.
    using System;
    using System.Web;
    using System.Web.SessionState;
    
    public class Handler : IHttpHandler, IRequiresSessionState
    {
    
     public void ProcessRequest(HttpContext context)
      {
       if (HttpContext.Current.Session["SessionsName"] != null)
        {
          HttpContext.Current.Session["SessionsName"] = "Demo Session";
         }
       }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    
    }
    
    Submit this story to DotNetKicks

    Read more...

    Tuesday, January 3, 2012

    Drop All Functions in SQL SERVER

    To DROP All function in SQL SERVER Database use following lines of codes, use it in Query window for particular database.

    This code will save lots of time as DROPing All functions in SQL Server database is not a manual process, if we use this

    DECLARE @name VARCHAR(128)
    DECLARE @SQL VARCHAR(254)
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects 
    WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') 
    AND category = 0 ORDER BY [name]) 
     
    WHILE @name IS NOT NULL
    BEGIN
        SELECT @SQL = 'DROP FUNCTION [dbo].[' + RTRIM(@name) +']'
        EXEC (@SQL)
        PRINT 'Dropped Function: ' + @name
        SELECT @name = (SELECT TOP 1 [name] FROM sysobjects 
    WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND 
    category = 0 AND [name] > @name ORDER BY [name])
    END
    GO
    





    Submit this story to DotNetKicks

    Read more...

    Drop All Views in SQL SERVER

    This is a very common scenario while updating or replacing database in SQL SERVER, we might need to delete all the views in SQL SERVER database. But to delete one view at a times is a time consuming process if database is huge with lots of Views.

    To Drop all views in SQL SERVER database use following

    DECLARE @name VARCHAR(128)
    DECLARE @SQL VARCHAR(254)
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects 
    WHERE [type] = 'V' AND category = 0 ORDER BY [name])
    WHILE @name IS NOT NULL
    BEGIN
        SELECT @SQL = 'DROP VIEW [dbo].[' + RTRIM(@name) +']'
        EXEC (@SQL)
        PRINT 'Dropped View: ' + @name
        SELECT @name = (SELECT TOP 1 [name] FROM sysobjects 
    WHERE [type] = 'V' AND category = 0 AND [name] > @name 
    ORDER BY [name])
    END
    GO
    






    Submit this story to DotNetKicks

    Read more...

    Delete All Store Procedures in SQL SERVER

    While working on SQL Server 2008, there was a situation when I had to delete one Store Procedure at a time :(.
    After doing some research to delete all store procedures with some query, I succeeded to save 2-3 hours or labour work :P

    To delete all store procedures in single we can use following code in SQL Query.

    DECLARE @procedureName varchar(500)
    DECLARE cur CURSOR
          FOR SELECT [name] FROM sys.objects WHERE type = 'p'
          OPEN cur
    
          FETCH NEXT FROM cur INTO @procedureName
          WHILE @@fetch_status = 0
          BEGIN
                EXEC('DROP PROCEDURE ' + @procedureName)
                FETCH NEXT FROM cur INTO @procedureName
          END
          CLOSE cur
          DEALLOCATE cur
    
    This will surely save time, required to Delete All Store Procedures in SQL SERVER Database
    Submit this story to DotNetKicks

    Read more...

    Tuesday, November 22, 2011

    Delete All Tables MSSQL

    While working on ASP.Net application, I came across a situation where I had to delete all the Tables of the MSSQL 2008 database, and it was really painful process. 

    In this case I had to delete all the SPs and all views as well. As I started searching like "Truncate database Sql 2008" or "Delete all tables in MSSQL" I came across two things and it worked for me.

    (I am really not sure whether it works in all the cases but for Deleting all tables in SQL, this worked for me.) 
    Firstly we need to remove all indexs from SQL table, I found following code when I Google the term 


    DECLARE @indexName NVARCHAR(128)
    DECLARE @dropIndexSql NVARCHAR(4000)
    
    DECLARE tableIndexes CURSOR FOR
    SELECT name FROM sysindexes
    WHERE id = OBJECT_ID(N'tableName') AND
      indid > 0 AND indid < 255 AND
      INDEXPROPERTY(id, name, 'IsStatistics') = 0
    ORDER BY indid DESC
    
    OPEN tableIndexes
    FETCH NEXT FROM tableIndexes INTO @indexName
    WHILE @@fetch_status = 0
    BEGIN
      SET @dropIndexSql = N'DROP INDEX tableName.' + @indexName
      EXEC sp_executesql @dropIndexSql
    
      FETCH NEXT FROM tableIndexes INTO @indexName
    END
    
    CLOSE tableIndexes
    DEALLOCATE tableIndexes

    After this we need to delete all the tables in SQL, for this I used following SP
    EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"
    

    It seems that this is a HIDDEN stored procedure in MSSQL.
    Submit this story to DotNetKicks

    Read more...

    Sunday, November 20, 2011

    Access userName asp.net-membership without using Membership.getUser()

    While I was working on Membership and User Management in Asp.Net 2010
    Following Scenario
    • After creating user, admin sets subscribtion for the user.
    • User logs in with id and password, after validating user, I check for subscription details.
    • If user is logging in with subscription period he/she has access to the application else he/she will be redirected to Subscription Expired page.
    To check subscription, I had requirement to get username and check it in Subscription table.
    I did not want to use getUser function, as I just wanted to get user name of currently logged in user.

    To get user name I used following line of code

    System.Web.HttpContext.Current.User.Identity.Name
    


    Submit this story to DotNetKicks

    Read more...

    Friday, November 18, 2011

    Error : Could not find any resources appropriate for the specified culture or the neutral culture

    Just recieved this error:
    Could not find any resources appropriate for the specified culture or the neutral culture.  Make sure "AjaxControlToolkit.Properties.Resources.NET4.resources" was correctly embedded or linked into assembly "AjaxControlToolkit" at compile time, or that all the satellite assemblies required are loadable and fully signed. 

    Could not find any resources appropriate for the specified culture or 
    the neutral culture.  Make sure 
    "AjaxControlToolkit.Properties.Resources.NET4.resources" 
    was correctly embedded or linked into assembly "AjaxControlToolkit" 
    at compile time, or that all the satellite assemblies required are
    loadable and fully signed.
    

    Ajax Tool kit realted .Net errors look a lot more worse than they really are.
    What we have to do is simply add scriptManager ;)
     
    <ajax:ToolkitScriptManager 
    ID="ToolkitScriptManager1" 
    runat="server" />
    Submit this story to DotNetKicks

    Read more...

    Tuesday, November 8, 2011

    Use Membership for user management - Basics

    In this article we shall discuss the membership feature in ASP.NET applications. Asp.net has reduced the development drastically by introducing this. Membership feature of Asp.Net drastically reduces the amount of code we have to write to authenticate users at our Web site. In this article we are going to develop User Management system membership class, and SqlMembershipProvider.

    Membership feature of Asp.net provides a membership API that simplifies the task of validating user credentials. SqlMembershipProvider uses SQL Database for storing membership details.

    Step1: Install Membership Database for SQLMembershipProvider.
    To install Membership Database we have to log on to our server with an account that has authority to administer SQL server. After this open Visual Studio 2010 Command prompt.


    Run following command
    aspnet_regsql.exe -E -S localhost -A m

    Where:
        -E indicates authenticate using the Windows credentials of the currently logged on user.
        -S (server) indicates the name of the server where the database will be installed or is already installed.
        -A m indicates add membership support. This creates the tables and stored procedures required by the membership provider.

    Above command mainly generates database naming "aspnetdb" with following  schema structure and related stored procedures


    * Please Note that Related stored procedures also get created with above command. These stored procedures get called internally from Membership provider. 

    Step2: Configure Forms Authentication
    Set following authentication mode in Web.config file
    <authentication mode="Forms">
        <forms loginUrl="Login.aspx" 
               protection="All" 
               timeout="30" 
               name="AppNameCookie" 
               path="/FormsAuth" 
               requireSSL="false" 
               slidingExpiration="true" 
               defaultUrl="default.aspx"
               cookieless="UseCookies"
               enableCrossAppRedirects="false"/>
    </authentication>

    If so many options are not required we can simply use following Tag for authentication

    <authentication mode="Forms">
          <forms loginUrl="Login.aspx" timeout="2880" />
        </authentication>
    

    Add the following <authorization> element after the element. This will allow only authenticated users to access the application. The previously established loginUrl attribute of the <authentication> element will redirect unauthenticated requests to the Login.aspx page.


    <authorization> 
       <deny users="?" />
       <allow users="*" />
    </authorization>
      
    Step 3: Configuring SQLMembership Provider
    In Step 1, we created SQL Database for Membership Provider, in this step we will configure SQLMembership Provider in Web.config file.


    <connectionStrings>
      <add name="MyConnectionString" connectionString="Data Source=MySqlServer;Initial Catalog=aspnetdb;Integrated Security=SSPI;" />
    </connectionStrings>
    <system.web>
    ...
      <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
        <providers>
          <clear />
          <add 
            name="SqlProvider" 
            type="System.Web.Security.SqlMembershipProvider" 
            connectionStringName="MyConnectionString"
            applicationName="/"
            enablePasswordRetrieval="false"
            enablePasswordReset="true"
            requiresQuestionAndAnswer="true"
            requiresUniqueEmail="true"
            passwordFormat="Hashed" />
        </providers>
      </membership>

    Default passwordFormat is "Hashed", if we remove it from Configuration then by default Passwords are stored in Hashed format. We can change passwordFormat to Encrypted. (This is not the scope of this Article; I shall put another article for it.)

    Step 4: Start using Membership class
    Upto step 3 we were only doing configuration for using Membership class. After we done with step 3; whenever we use Membership class, if by default uses Database structure generated in Step 1. It internally manages all the Database calls.
    e.g.
    Membership.CreateUser("UserName","Password");
    //This will create user in Database.
    
    Check out following Membership APIs for user management in Asp.net.
    MethodParametersNotes
    CreateUserstring username–User name to create.

    string password–Password for new user


    string email–E-mail for new user.

    string passwordQuestion

    string passwordAnswer

    bool IsApproved

    object providerUserKey
    Used to create a new user.
    DeleteUserstring username–User to delete.

    bool removeAllRelatedData
    Used to immediately remove a user identified by the supplied username. Returns true if the user was deleted or false if not found.
    FindUsersByNamestring usernameToMatch

    int pageIndex

    int pageSize
    Returns a collection of users where the string parameter passed matches part of the username.

    Wildcard support depends on how each data store handles characters such as "*", "%" and "_".
    FindUsersByEmailstring emailToMatch

    int pageIndex

    int pageSize
    Returns a collection of users whose e-mail addreses matches any part of the string parameter passed.

    Wildcard support depends on how each data store handles characters such as "*", "%" and "_"
    GeneratePasswordint length

    Int numberOfNonAlpha

    NumericCharacters
    Returns a password of the specified length that contains the specified number of non-alphanumeric characters.
    GetAllUsersint pageIndex

    int pageSize
    Returns a subset of users from the collection of all users. The subset is based on the pageIndex and pageSize methods.
    GetNumberOfUsersOnlineNoneReturns a count of all the users who are currently online

    The Active Directory provider does not implement this functionality
    GetUsernameByEmailstring email–Email of user to lookup.Return a member's username.
    UpdateUserMembershipUser user–Membership user to updateUpdates a member's properties; for example, an e-mail address.
    ValidateUserstring username–User name to validate.

    string password–User password to validate.
    Validates a user's credentials. Returns true if the credentials are valid and false if they are not.


    With Active Directory, regardless of the configured connection credentials, the provider connects to the directory with the username and password parameter as the connection credentials.
    (Note: Above table is picked up from MSDN)

    This is how we can use Membership class for User management in Asp.net using SQLMembershipProvider.

    Submit this story to DotNetKicks

    Read more...

    Saturday, August 6, 2011

    Facebook like Autosuggest in Asp.net

    This article is about using AjaxToolKit AutoCompleteExtender, to make Facebook like Autosuggest in asp.net. To use AutoCompleteExtender is simple, but we can modify the code little bit and make it more user friendly. Check out following Image. (Download Demo code for better understanding.)

    Note: Democode is developed in VS2010 and .net framework 4.0

    AutoComplete extender can be used to extend behaviour of any ASP.NET TextBox control. Ajaxtoolkit autocomplete extender associates textbox control with a popup panel to display words which begins with the prefix that is entered into the text box. We can define the minimum length of charachters, after which extender displays a popup containing words or phrases that start with that value.

    </div> </div><h2> AutoComplete Demonstration</h2> Type some characters in this textbox. The web service returns names which contains text you have typed. <table> <tbody> <tr> <td> <asp:textbox autocomplete="off" id="txtAutoComplete" runat="server" width="300"></asp:textbox></td> <td><div id="divLoading" style="display: none;"> Loading...</div> </td> </tr> </tbody></table> <ajaxtoolkit:autocompleteextender behaviorid="AutoCompleteEx" completioninterval="500" completionlistcssclass="completionListClass" completionlisthighlighteditemcssclass="CompletionListHighlightedItemClass" completionlistitemcssclass="completionlistItemClass" completionsetcount="0" delimitercharacters=";, :" enablecaching="true" id="autoComplete1" minimumprefixlength="2" onclienthidden="ListPopulated" onclientitemselected="onSelection" onclientpopulated="ItemSelected" onclientpopulating="ListPopulating" runat="server" servicemethod="GetCompletionList" servicepath="AutoComplete.asmx" showonlycurrentwordincompletionlistitem="true" targetcontrolid="txtAutoComplete"> <animations> <onshow> <sequence> <%-- Make the completion list transparent and then show it --%> <opacityaction opacity="0"> <hideaction visible="true"> <%--Cache the original size of the completion list the first time the animation is played and then set it to zero --%> <scriptaction script=" // Cache the size and setup the initial size var behavior = $find('AutoCompleteEx'); if (!behavior._height) { var target = behavior.get_completionList(); behavior._height = target.offsetHeight - 2; target.style.height = '0px'; }"> <%-- Expand from 0px to the appropriate size while fading in --%> <parallel duration=".4"> <fadein> <length endvaluescript="$find('AutoCompleteEx')._height" propertykey="height" startvalue="0"> </length></fadein></parallel> </scriptaction></hideaction></opacityaction></sequence> </onshow> <onhide> <;%-- Collapse down to 0px and fade out --%>; <parallel duration=".4"> <fadeout> <length endvalue="0" propertykey="height" startvaluescript="$find('AutoCompleteEx')._height"> </length></fadeout></parallel> </onhide> </animations> </ajaxtoolkit:autocompleteextender> <%-- Prevent enter in textbox from causing the collapsible panel from operating --%> <input style="display: none;" type="submit" /> <div id="divAddressDetails"> </div> </div>

    To Make AutoExtender work, we need to define certain properties.
    1. TargetControlID: The TextBox control where the user types content to be automatically completed.
    2. ServicePath: The path to the web service that the extender will pull the word\sentence completions from. If this is not provided, the service method should be a page method.
    3. ServiceMethod - The web service method to be called. The signature of this method must match the following:
      [System.Web.Services.WebMethod]
      [System.Web.Script.Services.ScriptMethod]
      public string[] YourFunctionName(string prefixText,int count)
      

      Syntax of the function should remain same.
    4. CompletionListCssClass - Css Class that will be used to style the completion list flyout.
    5. CompletionListItemCssClass - Css Class that will be used to style an item in the AutoComplete list flyout.
    6. CompletionListHighlightedItemCssClass - Css Class that will be used to style a highlighted item in the AutoComplete list flyout.
    (Refer DEMO CODE for better Understanding...)

    In above HTML Autocompletete extender; we can display loading image; this will make user understand that something is happening behind the screen. We have used three properties to display & Hide loading image and to display YELLOW background for the text as in above screen shot...
    1. OnClientPopulating: This adds event handler to Client side populating event. In our demo we have used ListPopulating function as event handler, we use this handler to display loading image, which is as follows.

      function ListPopulating(source, e) {
         window.document.getElementById('divLoading').style.display = "";
        
         var textboxControl = window.document.getElementById(source.get_element().id);
         // Get the textbox control.
        
         textboxControl.style.background = "url(Images/loader.gif) no-repeat right";
        //Above code displays loading image inside text box...
                      }
      
    2. OnClientHidden: This adds event handler to Client side hidden event of AutoExtentender. This handler gets fired when Autocomplete popup goes hidden. We have used ListPopulated function to handle this event. We use this event to hide loading image.

      function ListPopulated(source, e) {
      
        window.document.getElementById('divLoading').style.display = "none";
                          
        var textboxControl = window.document.getElementById(source.get_element().id); 
        // Get the textbox control.
                          
        textboxControl.style.background = "";
        }


    3. OnClientPopulated: This event handler can be used when Autosuggest list is populated. We have used this event handler to display YELLOW background in typed text. Check out above screenshot. Function name for this event is ItemSelected, this JavaScript function is as follows.

      function ItemSelected(source, e) {
         window.document.getElementById('divLoading').style.display = "none";
         var customers = source.get_completionList().childNodes;
         var searchText = source.get_element().value;
      
         for (var i = 0; i < customers.length; i++) {
      
         var customer;//  eval('(' + customers[i]._value + ')');
      
         customers[i].innerHTML = customers[i].innerHTML.replace(new RegExp('(' + searchText + ')', 'gi'), "$1");
      
         //We can modify the innerHTML if we want to display more information.
         // e.g. some logo or image
              }  
         }
      

    Apart from HTML and javascript we used a webmethod naming GetCompletionList which is as follows


    [WebMethod]
        public string[] GetCompletionList(string prefixText, int count)
        {
    
            //string sql = "WRITE SQL QUERY with Like Statement and use prefix text e.g. PartnerName like '%" + prefixText + "%'";
    
            //SqlDataAdapter da = new SqlDataAdapter(sql, "ConnectionString");
           
            DataTable dt = DT;// new DataTable();
            DataRow [] dr = dt.Select("Name LIKE '%" + prefixText + "%'");
            //    da.Fill(dt);
            //    da.Dispose();
            
            if (count == 0)
            {
                count = dr.Length;
                //count = dt.Rows.Count;
            }
    
           
            List items = new List(count);
            for (int i = 0; i < count; i++)
            {
                string value = dr[i]["City"].ToString() + "|" + dr[i]["State"].ToString() + "|" + dr[i]["Country"].ToString() + "|" + dr[i]["PostalCode"].ToString();
                var Items = AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr[i]["Name"].ToString(), value);
                //Using this we can send Name, Value pair client side. 
                //Value can be used to display related data of selected Name.
    
                //string value = dt.Rows[i]["City"].ToString() + "|" + dt.Rows[i]["State"].ToString() + "|" + dt.Rows[i]["Country"].ToString() + "|" + dt.Rows[i]["PostalCode"].ToString();
                //var items1 = AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dt.Rows[i]["Name"].ToString(), value);
    
                items.Add(Items);
            }
            
    
            return items.ToArray();
        }
    
    //Ignore above string string tag it is coming due to some editor issue of auto completing tags, some syntax issue.
    

    Check out follwing screen shot, on selection of User we are displaying his/her information. (Note that we have created Name-Value pair in above code to display the information in following screen shot format.)


    Now to display Selected User related address information as in the Screen shot, we used event handler of AutoCompleteExtender naming OnClientItemSelected
    • OnClientItemSelected: Handler to attach to the client-side itemSelected event. We used function naming onSelection to display Address details, this JavaScript function is as follows
    function onSelection(source, e) {
    
    var htmlString = "
    Address Details " + "
    City" + e._value.split("|")[0] + "
    State" + e._value.split("|")[1] + "
    Country" + e._value.split("|")[2] + "
    Postal Code" + e._value.split("|")[3] + "
    "; // Above alignement might disorder due to HTML rules of blogger, make sure in coding you handle it. window.document.getElementById('divAddressDetails').innerHTML = htmlString; var customers = source.get_completionList().childNodes; //Following is used to put value in Textbox, as we are overriding it to display address. if (document.all) { window.document.getElementById(source.get_element().id).value = e._item.innerText; } else window.document.getElementById(source.get_element().id).value = e._item.textContent; }

    We are done with development of Facebook Like Autosuggest in Asp.net.
    Donwload demo code here --> Facebook Like AutoSuggest in Asp.net.zip
    Submit this story to DotNetKicks

    Read more...

    Tuesday, July 19, 2011

    Send Email In Asp.net Using Gmail

    We can use Gmail smtp server to send email, using Asp.Net. Before we start developing Asp.net code, make sure POP is enabled in your Gmail's mail setting.






    Once you done with this step SAVE your Gmail settings....

    To do Email sending in Asp.net we need "System.Net.Mail" namespace.

    public static Boolean SendEmail()
    {
      MailMessage mail = new MailMessage();
    
    mail.From = new MailAddress("YOUR FROM EMAIL ADDRESS");
    mail.To.Add(new MailAddress("YOUR TO EMAIL ADDRESS"));            
    mail.Bcc.Add(new MailAddress("YOUR BCC EMAIL"));
                
      mail.Subject = "Email using Gmail";
    
      string Body = "Put your Email Body TEXT here"; 
    // Here you can put HTML string if you want email to be sent in HTML format.
      mail.Body = Body;
    
      mail.IsBodyHtml = true;
      SmtpClient smtp = new SmtpClient();
      smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
      smtp.Credentials = new System.Net.NetworkCredential
           ("Username@gmail.com","GmailPassword");
    //Or your Smtp Email ID and Password
      smtp.EnableSsl = true;
      smtp.Send(mail);
    }
    

    This is simple function to send email in Asp.net using Gmail account.
    You can also find Copy of this email in Your SENT items. Submit this story to DotNetKicks

    Read more...

    Thursday, May 5, 2011

    Disable Text Selection using Javascript

    In the web development cycle, at times we come to a requirement where we need to disable text selection for some HTML Tags i.e. "Do not allow to select text present in some particular Div tag, or span tag or text present in some table" in that case we can use following function. Actually this JavaScript function can be used to Disable Text selection for whole body of the HTML.

    function disableSelection(target) {
            if (typeof target.onselectstart != "undefined") //IE route
                target.onselectstart = function () { return false }
            else if (typeof target.style.MozUserSelect != "undefined") //Firefox route
                target.style.MozUserSelect = "none"
            else //All other route (ie: Opera)
                target.onmousedown = function () { return false }
            target.style.cursor = "default"
        }
    
    

    Define above function in HEAD tag and call this function either on some form event or directly at the bottom of the HTML page.

    //disableSelection(document.body) //Disable text selection on entire body
    
    disableSelection(document.getElementById("mydiv")) //Disable text selection on element with id="mydiv"
    

    This is very small function but it was very useful for one of my project.
    Submit this story to DotNetKicks

    Read more...

    Saturday, April 30, 2011

    Add Update Delete in Gridview Asp.net

    This article is about simple way to Add Update and Delete records using asp.net GridView using Dataset or Datatable. We shall update the database table naming (Download Demo)

    "UserTable".

    Schema for UserTable is as follows
    Note:I have used SqlServer 2008
    For this article we are going to fill GridView by data from database.
    We are going to make perform following operations on data using GridView
    1. Add New record into database; here data will directly be added into database table
    2. Update Records into database, using edit link.
    3. Delete Records using delete link
    To make Add Update Delete in Gridview more user friendly; make sure your website is Ajax Enabled and Gridview is put under UpdatePanel. This will avoid unnecessary

    postback and Gridview control will look smart.

    Before we develop GridView, lets work out main functions for database operations. Create a Class File naming "ManageUsers" and add following functions one by one

    Fetch Data from Database.
    public DataTable Fetch()
        {
            string sql = "Select * From UserTable";
            SqlDataAdapter da = new SqlDataAdapter(sql, cnstr);
            DataTable dt = new DataTable();
            da.Fill(dt);
            return dt;
            // Write your own Logic for fetching data, this method should return a DataTable
        }
    


    Update Data into Database
    public void Update(int id, string FirstName, string LastName, string EmailAddress, string LoginId, string Password, string StartDate, string EndDate)
        {
            string sql = "UPDATE UserTable SET [First Name] = '"+ FirstName + "',[Last Name] = '" + LastName + "',[Login Id] = '" + LoginId +"' ,[Password] = '" + Password 
    
    + "'";
                 sql += ",[Start Date] = '" + StartDate +"',[End Date] = '" + EndDate +"',[Email Address] = '" + EmailAddress + "' WHERE Id=" + id;
    
            SqlConnection conn = new SqlConnection(cnstr);
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.ExecuteNonQuery();
            conn.Close();
            conn.Dispose();
    
        }
    


    Insert new records into Database
    public void Insert(string FirstName, string LastName, string EmailAddress, string LoginId, string Password, string StartDate, string EndDate)
        {
           string sql = "INSERT INTO UserTable ([First Name],[Last Name],[Login Id],[Password],[Start Date],[End Date],[Email Address]) ";
           sql +=" VALUES ('"+ FirstName +"','" + LastName + "','" + LoginId +"','" + Password + "','" + StartDate + "','" + EndDate + "','" + EmailAddress + "')";
               
            SqlConnection conn = new SqlConnection(cnstr);
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.ExecuteNonQuery();
            conn.Close();
            conn.Dispose();
        }
    

    Delete records from Database

    public void Delete(int id)
        {
            string sql = "DELETE FROM UserTable WHERE Id=" + id;
            SqlConnection conn = new SqlConnection(cnstr);
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.ExecuteNonQuery();
            conn.Close();
            conn.Dispose();
            // Write your own Delete statement blocks.
        }
    

    In above code cnstr is the connection string for our

    database.

    Now we shall make changes in GridView (Note: Make sure GridView is added on page and under updatepanel) (Download Demo)

    Once we add gridview inside updatepanel, do following things
    1. set AutoGenerateColumns as False.
    2. Change the ShowFooter Flag to True
    3. set the DataKeyNames your column name for Id. (This field can have multiple values depending on requirement, we are going to use Id, as it is primary key of our datatable. These values are available in GridView events. We can access them using. GridView.DataKeys[e.RowIndex].Values[0]
    4. Smart Navigation Tag of the GridView control, choose Add New Column
      Now add 8 BoundField columns with DataField values as "Id","First Name","Last Name","Email Address", "Login Id", "Password", "Start Date", "End Date"; also add 2 CommandField columns with one for Edit/Update and another for Delete functions. Now we can see our Grid View control is ready. Above data fields are column names of the DataTable we are using. (To bind correct columns, our datatable column names and gridview bound column's "DataField" should match.
    5. We shall also give facility to add new records, for that we will put controls in Footer row. To do this we need to convert all above BoundField columns to template field columns. Click on the Smart Navigation Tag on the GridView choose Edit Columns, the Field’s property window will open.  Select column by column from Id, include also Edit column, and select ‘Convert this field into a TemplateField’
      Except "delete" column all the BoundField columns are converted in to Template Field Column.
    6. Now one by one we will controls to Footer of the GridView. Right click on the GridView control, select Edit Template.
      Column[0] – Id: select Edit Template, choose column[0] – Id, you can view a label placed in the ItemTemplate section and a TextBox placed in the EditItemTemplate section (Id is our Primary key and it should not be editable). In edit Item Section template, put Label. Do not add anything in Footer Template.

      Column[1] - First Name
      Now again select Edit Template, choose column[1] - First Name, Add another TextBox in the FooterTemplate section and name it as NewFirstName. 

      Column[2] - Last Name
      Choose column[2] - Last Name, Add another TextBox in the FooterTemplate section and name it as NewLastName. 

      Column[3] - Email Address
      Choose column[3] - Email Address, Add another TextBox in the FooterTemplate section and name it as NewEmailAddress. 

      Column[4] - Login Id
      Choose column[4] - Login Id, Add another TextBox in the FooterTemplate section and name it as NewLoginId. 

      Column[5] - Password
      Choose column[5] - Password, Add another TextBox in the FooterTemplate section and name it as NewPassword. 

      Column[6] - Start Date
      Choose column[6] - Start Date, Add another TextBox in the FooterTemplate section and name it as NewStartDate. (Check following source view, we have added, Calender Extender of Ajax Toolkit)

      Column[7] - End Date
      Choose column[7] - End Date, Add another TextBox in the FooterTemplate section and name it as NewEndDate.  (Check following source view, we have added, Calender Extender of Ajax Toolkit)

      Column[8] - Edit
      Just add a link button into the FooterTemplate section, specify its CommandName property as ‘AddNew’.

    7. Source of the Gridview control changes to following, check we have added Calender Extender for date selection. (Download Demo)

      
              
                  
                      
                          
                      
                      
                          
                      
                  
                  
                      
                          
                      
                      
                          
                      
                      
                          
                      
                  
                  
                      
                          
                      
                      
                          
                      
                      
                          
                      
                  
                  
                      
                          
                      
                      
                          
                      
                      
                          
                      
                  
                  
                      
                          
                      
                      
                          
                      
                      
                          
                      
                  
                  
                      
                          
                      
                      
                          
                      
                      
                          
                      
                  
                  
                      
                          
                          
                      
                      
                          
                          
                      
                      
                          
                      
                  
                  
                      
                          
                          
                      
                      
                          
                          
                      
                      
                          
                      
                  
                  
                      
                          
                           
                      
                      
                          Add New
                      
                      
                          
                      
                  
                  
              
              
      
    8. Now we shall develop code in code behind of web page i.e. in C#. We have already developed ManageUsers Class in start. We will develop code for handing Edit,Update and Insert operations of GridView. Add events as shown in following image.


      Now check out following code for each event we have added for GridView.

      Create object of the Class "ManageUsers"; and write function to Bind Customer details to the GridView.
      private void BindCustomers()
          {
              DataTable CustomerTable = customer.Fetch();
      
              if (CustomerTable.Rows.Count > 0)
              {
                  gridUserManagement.DataSource = CustomerTable;
                  gridUserManagement.DataBind();
              }
              else
              {
                  CustomerTable.Rows.Add(CustomerTable.NewRow());
                  gridUserManagement.DataSource = CustomerTable;
                  gridUserManagement.DataBind();
      
                  int TotalColumns = gridUserManagement.Rows[0].Cells.Count;
                  gridUserManagement.Rows[0].Cells.Clear();
                  gridUserManagement.Rows[0].Cells.Add(new TableCell());
                  gridUserManagement.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                  gridUserManagement.Rows[0].Cells[0].Text = "No Record Found";
              }
          }
      

      Initializing the GridView control on Page load:
      protected void Page_Load(object sender, EventArgs e)
          {
              if (!IsPostBack)
              {
                  BindCustomers();
              }
          }
      

      GridView RowEditing Event
      protected void gridUserManagement_RowEditing(object sender, GridViewEditEventArgs e)
          {
              gridUserManagement.EditIndex = e.NewEditIndex;
              BindCustomers(); 
          }
      

      GridView RowCancelingEdit Event
      protected void gridUserManagement_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
          {
              gridUserManagement.EditIndex = -1;
              BindCustomers(); 
          }
      

      Updating Records (GridView RowUpdating Event): Update the data to the UserTable, by adding the following lines of code in the GridView’s RowUpdating event
      protected void gridUserManagement_RowUpdating(object sender, GridViewUpdateEventArgs e)
          {
              TextBox txtNewFirstName = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox2");
              TextBox txtNewLastName = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox3");
              TextBox txtNewEmailAddress = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox4");
              TextBox txtNewLoginId = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox5");
              TextBox txtNewPassword = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox6");
              TextBox txtNewStartDate = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox8");
              TextBox txtNewEndDate = (TextBox)gridUserManagement.Rows[e.RowIndex].FindControl("TextBox9");
      
              customer.Update(Convert.ToInt32(gridUserManagement.DataKeys[e.RowIndex].Values[0].ToString()), txtNewFirstName.Text, txtNewLastName.Text, txtNewEmailAddress.Text, txtNewLoginId.Text, txtNewPassword.Text, txtNewStartDate.Text, txtNewEndDate.Text);
              gridUserManagement.EditIndex = -1;
              BindCustomers(); 
          }
      
      The above block of codes in RowUpdating event, finds the control in the GridView, takes those values in pass it to the ManageUsers class Update method. The first parameter GridView1.DataKeys[e.RowIndex].Values[0].ToString() will return the Id of the Customer. That is the unique id for each customer to perform update function.

      Delete In GridView:
      protected void gridUserManagement_RowDeleting(object sender, GridViewDeleteEventArgs e)
          {
              customer.Delete(Convert.ToInt32(gridUserManagement.DataKeys[e.RowIndex].Values[0].ToString()));
              BindCustomers(); 
          }
      

      Add New Records from GridView control

      protected void gridUserManagement_RowCommand(object sender, GridViewCommandEventArgs e)
          {
              if (e.CommandName.Equals("AddNew"))
              {
                  TextBox txtNewFirstName = (TextBox)gridUserManagement.FooterRow.FindControl("NewFirstName");
                  TextBox txtNewLastName = (TextBox)gridUserManagement.FooterRow.FindControl("NewLastName");
                  TextBox txtNewEmailAddress = (TextBox)gridUserManagement.FooterRow.FindControl("NewEmailAddress");
                  TextBox txtNewLoginId = (TextBox)gridUserManagement.FooterRow.FindControl("NewLoginId");
                  TextBox txtNewPassword = (TextBox)gridUserManagement.FooterRow.FindControl("NewPassword");
                  TextBox txtNewStartDate = (TextBox)gridUserManagement.FooterRow.FindControl("NewStartDate");
                  TextBox txtNewEndDate = (TextBox)gridUserManagement.FooterRow.FindControl("NewEndDate");
      
                  customer.Insert(txtNewFirstName.Text, txtNewLastName.Text, txtNewEmailAddress.Text, txtNewLoginId.Text, txtNewPassword.Text, txtNewStartDate.Text, txtNewEndDate.Text);
                  BindCustomers();
              } 
          }
      


    This is how we can develop a simple GridView control in Asp.Net with Add Update Delete functionality.

    Download Demo Code here --> Add Update Delete in Gridview Asp.net
    Submit this story to DotNetKicks

    Read more...