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

Sunday, December 30, 2012

The Difference Between “Add Web Reference” and “Add Service Reference”


I was playing around with building a simple WCF ASP.NET client in Visual Studio 2008 and wanted to make a reference to my WCF service (that used basicHttpBinding).

I have built plenty of ASMX web services in the past so simply selected “Add Web Reference”, pointed to my .svc file hosted in IIS– everything worked as expected.
Then I checked the “Add Service Reference” menu option and thought – why this option is given?
In interview sometimes this question will be asked to check your understanding of web services.

Add Web Reference

It is a wrapper over wsdl.exe and can be used to create proxies for .NET 1.1 or 2.0 clients. Of course this means when you are pointing to a WCF service you have to be pointing to an endpoint that uses basicHttpBinding.

Add Service Reference 

It is a wrapper over svcutil.exe and also creates clients proxies (and additionally web.config entries). These proxies, however, can only be consumed by .NET 3.0+ clients.

Happy Coding!!

Wednesday, December 19, 2012

Download File in Asp.net

Following is a snippet required to download a file


    private void StartDownloadFile(string attachmentPath)
        {
            FileInfo file = new FileInfo(attachmentPath);
            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.AppendHeader("Content-Disposition", "attachment; filename = " + file.Name);
            Response.AppendHeader("Content-Length", file.Length.ToString());
            Response.ContentType = "application/download";
            Response.WriteFile(file.FullName);
            Response.Flush();
            Response.Close();
            Response.End();
        }

This is generalize function, you need to pass path of filename. With the help of above code snippet browser will popup download box where you need to give the path.

Happy Coding!!