Monday, April 29, 2013

Prevent the browser from caching the ASPX page

​use this code to prevent the browser from caching the ASPX page.

By default browser cache the page. sometimes we don't require the page to be cached.

It will work for IE, Mozilla, and Chrome. I didn't checked the below code for other browsers.

<%@ Page language="c#" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>HttpCachePolicy - SetNoStore - C# Example</title>
    <script runat="server">
      void Page_Load(Object sender, EventArgs e) 
      {
        // Prevent the browser from caching the ASPX page
        Response.Cache.SetNoStore();

        // Display the DateTime value.
        Label1.Text = DateTime.Now.ToLongTimeString();
      }
    </script>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">
      <h3>HttpCachePolicy - SetNoStore - C# Example</h3>

      <p>Click the Submit button a few times, and then click the Browser's Back button.<br />
      You should get a "Warning: Page has Expired" error message.</p>

      <p>Time:  <asp:Label id="Label1" runat="server" Font-Bold="True" ForeColor="Red" /></p>

      <asp:Button id="Button1" runat="server" Text="Submit" />
    </form>
  </body>
</html>

Happy Coding !!

Paging and sorting in sql server


Suppose you have to implement Paging and sorting then following code snippet will help you.

create table #Student(id int identity(1,1), name nvarchar(100), birthdate datetime)
declare @PageSize int=5
declare @MinRowNumber int=1
declare @MaxRowNumber int= @MinRowNumber + @PageSize-1
declare @SortExpression nvarchar(100)='Name' ---'birthdate' Pass here column name.
declare @SortOrder nvarchar(100)='D' --'A' pass here sort order D- for descending and A for ascending.
insert #Student
select 'Viru','1986-12-07'
union all
select 'Sachin','1960-01-31'
union all
select 'Gambhir','1950-06-23'
union all
select 'Shreekant','1983-10-04'
union all
select 'Kapil','1981-03-17'
union all
select 'Yuvi','1986-03-02'
union all
select 'Dhoni','1987-12-05'
union all
select 'Zak','1975-08-17'
union all
select 'Bhajji','2007-08-06'
union all
select 'Ashwin','2010-04-22'
union all
select 'Ojha','2012-02-26'
union all
select 'Ravindra','2012-10-04'
SELECT RowNumber, name, birthdate,id FROM
(select *,ROW_NUMBER() OVER (ORDER BY
CASE WHEN @SortExpression = 'Name' AND @SortOrder='D' THEN Name END DESC,
CASE WHEN @SortExpression = 'Name' AND @SortOrder='A' THEN Name END ASC,
CASE WHEN @SortExpression = 'birthdate' AND @SortOrder='D' THEN birthdate END DESC,
CASE WHEN @SortExpression = 'birthdate' AND @SortOrder='A' THEN birthdate END ASC
) AS RowNumber from #Student) AS Student
WHERE RowNumber BETWEEN @MinRowNumber AND @MaxRowNumber
drop table #student


Happy Coding!!

Monday, March 18, 2013

Get users information through active directory

If you have an requirement where you have to read users information from active directory then dot net has provided a dll named "System.DirectoryServices dll ".

Get users information through active directory.

1.You need to add System.DirectoryServices dll reference in your asp.net project.

2.Add following code in default.aspx page.
        it automatically finds user name from Page.User.Identity.Name. We have added some properties like: sAMAccountName it only load those properties which we have mentioned in our code.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.DirectoryServices;
using System.Runtime.InteropServices;
using System.Security.Authentication;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SearchResultCollection users;
        string loginUserName = "";
        if (string.IsNullOrEmpty(Page.User.Identity.Name) == false)
        {
            loginUserName = Page.User.Identity.Name.ToString().Substring(Page.User.Identity.Name.ToString().LastIndexOf("\\") + 1);
        }
        using (DirectoryEntry Root = new DirectoryEntry())
        {
            //Establish connection to current loged on users Active Directory
            using (DirectorySearcher Searcher = new DirectorySearcher(Root))
            {
                //Start at the top              
                Searcher.Filter = "(&(objectCategory=person)(anr=" + loginUserName.ToUpper().Trim() + "))";
                Searcher.SearchScope = SearchScope.Subtree;
                //Start at the top and keep drilling down
                Searcher.PropertiesToLoad.Add("sAMAccountName");
                //Load User ID
                Searcher.PropertiesToLoad.Add("displayName");
                //Load Display Name
                Searcher.PropertiesToLoad.Add("givenName");
                //Load Users first name
                Searcher.PropertiesToLoad.Add("sn");
                //Load Users last name
                Searcher.PropertiesToLoad.Add("distinguishedName");
                //Users Distinguished name
                Searcher.PropertiesToLoad.Add("telephoneNumber");
                //Ext. Number
                Searcher.PropertiesToLoad.Add("ipPhone");
                //7D Phone Number
                Searcher.PropertiesToLoad.Add("mobile");
                //Cell Phone Number
                Searcher.PropertiesToLoad.Add("mail");
                //Cell Phone Number
                Searcher.Sort.PropertyName = "sn";
                //Sort by last name
                Searcher.Sort.Direction = System.DirectoryServices.SortDirection.Ascending;
                //A-Z
                users = Searcher.FindAll();
                {
                    //Users contains our searh results
                    //MsgBox(users.Count)
                    //If it's zero then no matches were found
                    if (users.Count > 0)
                    {
                        //goes throug each user in the search results
                        foreach (SearchResult User in users)
                        {
                           // ResultPropertyCollection rcol = User.Properties;
                            ResultPropertyCollection props = User.Properties;
                            foreach (string prop in props.PropertyNames )
                            {
                                ResultPropertyValueCollection values = props[prop];
                                foreach (string val in values)
                                {
                                    //if (prop=="mail")
                                    //    Response.Write(val);
                                    Response.Write("<br>"+prop + "= " + val);
                                }
                            }  
                        }
                    }
                    else
                    {
                        // Store the DataTable in ViewState.
                        return;
                    }
                }
            }
        }
    }
}
Active directory can provide a lot of information for a user. I have collected some of information which i required for my task.

Happy Coding!!

Tables without Primary Key in Database


Some times you are analyzing the database to check which tables don't have primary keys then  in that case follwing query will help you to find out the tables:

Below SQL will give you the list of table in you Database not having Primary Keys.
SELECT SCHEMA_NAME(schema_id) AS SchemaName,name AS TableName
FROM sys.tables
WHERE OBJECTPROPERTY(OBJECT_ID,'TableHasPrimaryKey') = 0
ORDER BY SchemaName, TableName;

Happy Coding!! 

Saturday, March 16, 2013

Custom errors in web.config

Some times after hosting web application on the server, we get unexpected error. But we did not get the detailed message for the unexpected error or if we added defaultredirect="error.htm".

<customErrors defaultRedirect="error.htm" mode="On" />

  how can we get detailed message for the unexpected error. Unexpected error may occur on remote or on local server. We can find out exact error message by doing some changes in web.config. Just change Custom error  mode to off.

<customErrors defaultRedirect="error.htm" mode="Off" />
There are three error modes in which an ASP.NET application can work:
1) Off Mode
2) On Mode
3) RemoteOnly Mode


The Error mode attribute determines whether or not an ASP.NET error message is displayed. By default, the mode value is set to "RemoteOnly".

Off Mode

When the error attribute is set to "Off", ASP.NET uses its default error page for both local and remote users in case of an error.

On Mode

In case of "On" Mode, ASP.NET uses user-defined custom error page instead of its default error page for both local and remote users. If a custom error page is not specified, ASP.NET shows the error page describing how to enable remote viewing of errors.

RemoteOnly

ASP.NET error page is shown only to local users. Remote requests will first check the configuration settings for the custom error page or finally show an IIS error. 

Happy Coding!!

Saturday, January 12, 2013

Grid view Column- Apply Word wrap to work in all browser

Sometimes in gridview we have a column which has too much information so it is not shown properly on page.

We can achieve with the help of CSS.
.word_wrap
{
    white-space: pre; /* CSS 2.0 */
    white-space: pre-wrap; /* CSS 2.1 */
    white-space: pre-line; /* CSS 3.0 */
    white-space: -pre-wrap; /* Opera 4-6 */
    white-space: -o-pre-wrap; /* Opera 7 */
    white-space: -moz-pre-wrap; /* Mozilla */
    white-space: -hp-pre-wrap; /* HP Printers */
    word-wrap: break-word; /* IE 5+ */
}
We have defined a css class, and we can assign this cssclass to column which has too much information.

<asp:TemplateField HeaderText="Name On Document" meta:resourcekey="HeaderText_NameOnResource1">
    <HeaderStyle Width="100px" Font-Bold="true" />
        <ItemTemplate>
            <div style="word-wrap: break-word; width: 100px;">
                 <%# Eval("NameOnDocument")%>
            </div>
        </ItemTemplate>
        <ItemStyle Width="100px" CssClass="word_wrap" Wrap="true" />
</asp:TemplateField>

Happy Coding!!

Wednesday, January 9, 2013

Encrypt connection string in web.config file

This time we have written a generalize function which will encrypt an decrypt connection strings.

Following code snippet will help to encrypt connection string in web.config file.

  protected void encryptConfi(bool bencrypt)
        {
            string webconfigfilepath = "~/";
            Configuration config = WebConfigurationManager.OpenWebConfiguration(webconfigfilepath);
            ConfigurationSection configsec = config.GetSection("connectionStrings");
            if (bencrypt)
            {
                configsec.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
            }
            else
            {
                configsec.SectionInformation.UnprotectSection();
            }
            config.Save();
        }

Happy Coding!!