Sunday, November 11, 2012

Fetch Distinct Values From Datatable In c#

To Fetch distinct values from already fetched DataTable in Ado.net we can use following method.

DataTable temp = DT.DefaultView.ToTable(true, "ContractId");
//Note here I wanted to fetch Distinct ContractIds from DT
Use Above code to select Distinct values from the Datatable, or Use Above code to fetch distinct values from Ado.Net Datatable or datatable in c#. 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...

Install CSI files BlackBerry

I am using PhoneGap.com for BlackBerry development, after developing web app I came across a situation where I had to register my code signing key using  SignatureTool.jar, I used following line of code in Command prompt to register my key and password pair. C:\BBWP\bin>SignatureTool.jar client-RBB-YOURCSICODE.csi c:\BBWP\bin>SignatureTool.jar client-RCR-  YOURCSICODE.csi c:\BBWP\bin>SignatureTool.jar client-RRT-  YOURCSICODE.csi If you don't have a private key installed you need to create one. And use the pin number which you used during the registration process.
Submit this story to DotNetKicks

Read more...

Javascript Find Arguments Passed to a Function

While working on Javascript optimization we can always use some functions having variable number of arguments.
E.g. if we come across a situation where we have to use one function to toggle visibility of the objects, but depending on clients input number of objects which needs to hide/show varies. In this case we can write a function as below where number of parameters can any variable.
//Assumption 0th parameter is boolean 

 function toggle() {
        var args = toggle.arguments
        for (v = 1; v < args.length; v++) {
            obj = window.document.getElementById(args[v]);
            if (args[0]) obj.style.display = "";
            else obj.style.display = "none";
        }
    }
We can use this type of functions to minimize size of javascript before optimizing it.
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

    Check if the page is in iframe

    There is a common requirement while developing iframe based web application i.e. redirect if the page is not in iframe or redirect main page to login page or any default page if the page is not opened with in iframe.
    In such case; if some one tries to open page using URL; we need to check if the page is in iframe or not, if it is not in iframe we have to perform desired action. 
    We can use following javascript to perform this checking and if the page is not in iframe redirect it to default page.
    
    
    Submit this story to DotNetKicks

    Read more...

    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...