0

Configure Unique Document IDs Feature In SharePoint 2010

This post explains how to Enable Activate Or Configure Unique Document IDs Feature In SharePoint 2010 For better Document Management.

Open your site collection in browser and login with administrator account

Click on Site Actions > Site Settings

Unique Document ID In SharePoint 2010


Select Site collection features from Site Collection Administration section
sharepoint 2010 document id

Activate Document ID Service
After activation it will look like shown in image 

Now go back to Site Actions > Site Settings and select Document ID Settings 

Document ID Settings
Here you can customize the document ID to begin with characters you want 


Now you can see the document ID by selecting the document and clicking on View Properties icon on top ribbon 



Alternatively you can add document id column to be displayed 

check the document, Click on Library > Modify View and check the Document ID Checkbox and finish it 





Hope this helps

1

Asp.Net Bind Populate DropDownList With JQuery And XML

In this example i'm explaining How To Populate Or Bind DropDownList With JQuery And XML In Asp.Net.
bind populate dropdownlist with jquery and xml

Add jquery library reference in head section and place one dropdown on the page.

Add one list item with select as it's value.

   1:  <asp:DropDownList ID="DropDownList1" runat="server">
   2:  <asp:ListItem>Select</asp:ListItem>
   3:  </asp:DropDownList>
   4:   
   5:  <asp:Label ID="Label1" runat="server" Text=""/>


Following is the Cities.xml file i'm using to bind dropdownlist using jquery.


  
    Mumbai
    1
  
    
    Delhi
      2
  
  
    Banglore
    3
  
  
    Chennai
    4
  

Add this script in head section of page.

  

Build and run the code.

0

AjaxFileUpload AsyncFileUpload In ModalPopUp Extender Asp.Net

This example shows how to use AjaxFileUpload Control Or AsyncFileUpload In ModalPopUp Extender Using C# VB Asp.Net.

Place ToolkitScriptManager and a button inside UpdatePanel on the page, we will open ModalPopup in click event of this button to upload files.

Create one panel on the page and add AjaxFileUpload or Ajax AsyncFileUpload in it.

Async Ajax FileUpload In ModalPopUp Extender


HTML Source
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="btnUpload" runat="server" 
            Text="Upload File" onclick="btnUpload_Click"/>
            
<asp:ModalPopupExtender runat="server" 
                        ID="modelPopupExtender1" 
                        TargetControlID="btnUpload"
                        PopupControlID="popUpPanel" 
                        OkControlID="btOK" 
                        BackgroundCssClass="modalBackground">
</asp:ModalPopupExtender>
 
 <asp:Panel ID="popUpPanel" runat="server" CssClass="pnl">
 <div style="font-weight: bold; border: Solid 3px Aqua; 
                                background-color: AliceBlue">
 
 <asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server" 
                     OnUploadComplete="UploadComplete" 
                     OnClientUploadComplete="Success" 
                     ThrobberID="loader" Width="400px"/>
 <asp:Image ID="loader" runat="server" 
            ImageUrl ="~/loading.gif" 
            Style="display:None"/>
 </div><br /><br />
 <asp:Label ID="lblMessage" runat="server"/><br /><br />
 <asp:Button ID="btOK" runat="server" Text="OK" />
 <asp:LinkButton ID="LinkButton1" runat="server" CssClass="close" 
 OnClientClick="$find('modelPopupExtender1').hide(); return false;"/>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>


If you are using AsyncFileUpload Control then don't forget to set UploaderStyle property to Traditional, other wise it will throw invalid argument error.

<ajax:AsyncFileUpload ID="AsyncFileUpload1" runat="server" 
                      UploadingBackColor="Blue" 
                      CompleteBackColor="WhiteSmoke"
                      OnUploadedComplete="SaveUploadedFile" 
                      OnClientUploadComplete="Success" 
                      OnClientUploadError="Error"
                      UploaderStyle="Traditional"/>


Add following Javascript and CSS in head section of page.



Write following code in OnUploadComplete event to save file on server.

protected void UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string path = Server.MapPath("~/Uploads/") + e.FileName;
        AjaxFileUpload1.SaveAs(path);
    }


Build and run the code.

Download Sample Code


0

Allow Enable Anonymous Access In SharePoint 2010 Sites

This Post explains How To Allow Or Enable Anonymous Access In SharePoint 2010 Sites Collections.

1. Open SharePoint 2010 Central Administration, Go to Manage Web Applications

Allow Anonymous Access In SharePoint 2010 SItes


Select Your Site and click on Authentication Providers icon in the top ribbon bar 

SharePoint 2010 Enable Anonymous Access


Click on Default Zone and Check the Enable Anonymous Access CheckBox and save it

Anonymous Access



2. Select your site and click on Anonymous Policy Icon In ribbon

Anonymous Policy


Select Default Zone from dropdown and select the permissions option you want to grant to anonymous users Selecting None - No Policy is recommended )



3. Close Central Administration and open your site collection in browser with administrator account (Site for which you just had set anonymous access)

Click on Site Actions and select Site Permissions

Site Permissions


Click on Anonymous Access Icon on the top ribbon



Select Entire Web Site Option and click on OK



Now you can browse your site Anonymously without login.



Hope this helps.

4

Ajax AutoCompleteExtender In Master Page Asp.Net

This Example shows How To Use Ajax AutoCompleteExtender TextBox In Master Page In Asp.Net.

Open Visual Studio and create new website, add master page in it and design it as you want.

Create a BIN folder in application and add AjaxControlToolkit.dll in it.

I have use Northwind database to fetch names for AutoCompletion list.

Add Connection String in web.config file

<connectionStrings>
<add name="NorthwindConnectionString" 
     connectionString="Data Source=AMITJAIN\SQL;
                       Initial Catalog=Northwind;
                       User ID=amit;Password=password"
providerName="System.Data.SqlClient"/>
</connectionStrings>


Place ToolkitScriptManager on Master Page inside form tag, one textbox and Add Ajax AutoComplete Extender from Toolbox.

HTML SOURCE OF MASTER PAGE
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!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 runat="server">
<title></title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>
 
<asp:TextBox ID="txtAutoComplete" runat="server"/>
                               
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" 
                          runat="server" 
                          DelimiterCharacters="" 
                          Enabled="True" 
                          ServicePath="~/AutoComplete.asmx" 
                          ServiceMethod="GetCompletionList"
                          TargetControlID="txtAutoComplete"
                          MinimumPrefixLength="1" 
                          CompletionInterval="10" 
                          EnableCaching="true"
                          CompletionSetCount="12">
</asp:AutoCompleteExtender>
                
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
 
</form>
</body>
</html>


We can set CompletionList WIdth and styles using CSS or use AutoCompleteExtender In GridView or Windows Forms Application.

Add new webservice, name it AutoComplete.asmx and write following code in it's code behind.

C#
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : System.Web.Services.WebService {

    public AutoComplete () 
    {
    }

    [WebMethod]
    public string[] GetCompletionList(string prefixText, int count)
    {
        if (count == 0)
        {
            count = 10;
        }
        DataTable dt = GetRecords(prefixText);
        List items = new List(count);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            string strName = dt.Rows[i][0].ToString();
            items.Add(strName);
        }
        return items.ToArray();
    }

    public DataTable GetRecords(string strName)
    {
        string strConn = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConn);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Parameters.AddWithValue("@Name", strName);
        cmd.CommandText = "Select FirstName from Employees where FirstName like '%'+@Name+'%'";
        DataSet objDs = new DataSet();
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd;
        con.Open();
        dAdapter.Fill(objDs);
        con.Close();
        return objDs.Tables[0];
    }
}

VB.NET
Imports System.Collections.Generic
Imports System.Web.Services
Imports System.Data.SqlClient
Imports System.Data
Imports System.Configuration

 _
 _
 _
Public Class AutoComplete
 Inherits System.Web.Services.WebService

 Public Sub New()
 End Sub

  _
 Public Function GetCompletionList(prefixText As String, count As Integer) As String()
  If count = 0 Then
   count = 10
  End If
  Dim dt As DataTable = GetRecords(prefixText)
  Dim items As New List(Of String)(count)

  For i As Integer = 0 To dt.Rows.Count - 1
   Dim strName As String = dt.Rows(i)(0).ToString()
   items.Add(strName)
  Next
  Return items.ToArray()
 End Function

 Public Function GetRecords(strName As String) As DataTable
  Dim strConn As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString
  Dim con As New SqlConnection(strConn)
  Dim cmd As New SqlCommand()
  cmd.Connection = con
  cmd.CommandType = System.Data.CommandType.Text
  cmd.Parameters.AddWithValue("@Name", strName)
  cmd.CommandText = "Select FirstName from Employees where FirstName like '%'+@Name+'%'"
  Dim objDs As New DataSet()
  Dim dAdapter As New SqlDataAdapter()
  dAdapter.SelectCommand = cmd
  con.Open()
  dAdapter.Fill(objDs)
  con.Close()
  Return objDs.Tables(0)
 End Function
End Class


Build and run the application.

1

Validation Of ViewState MAC Failed Error Asp.Net

If you are receiving Validation Of ViewState MAC Failed Error In Asp.Net web application.

This occurs if you are using controls like Gridview or Detailsview with DataKeyNames on the page and page takes long time in loading.

This issue has been fixed in .Net framework 2.0 SP2 and .Net framework 3.5 SP1. so upgrading to service packs is best option to fix validation of viewstate mac failed error.

Other workarounds can be

1. Set enableEventValidation to false and viewStateEncryptionMode to Never in web.config.
   1:  <pages enableeventvalidation="false" 
   2:         viewstateencryptionmode="Never">


5

Custom Login Web Part In SharePoint 2010 Forms Based

This post explains How To Create Custom Login Web Part In SharePoint 2010 For Forms Based Authentication FBA.

Before creating Login WebPart we need to setup and configure Membership Provider Database and Forms Based Authentication(FBA) In SharePoint 2010 and can optionally Allow Anonymous Access to sharepoint web application and sites collection.

1. Create Visual Web Part In Visual Studio 2010
Open VS 2010 and create new project by selecting New > Project from File Menu

Create Custom Login WebPart In SharePoint 2010 For Forms Based Authentication FBA


Choose SharePoint 2010 in left pane and select Empty SharePoint Project, name it LoginWebPart.

Select Deploy as a farm solution option from next screen and click on finish

Right click on solution explorer and select Add > New Item

Visual Web Part For Login In SharePoint 2010


Choose Visual Web Part from the list and name it LoginWebPart

2. Add Reference To Assemblies
2a. Add reference to Microsoft.SharePoint.IdentityModel.dll
Right click on Refrences in solution explorer, select add reference and browse to
C:\Windows\assembly\GAC_MSIL\Microsoft.SharePoint.IdentityModel\14.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.IdentityModel.dll 

2b. Add reference to Microsoft.IdentityModel.dll
Select add reference and browse to
C:\Program Files\Reference Assemblies\Microsoft\Windows Identity Foundation\v3.5\Microsoft.IdentityModel.dll

2c. Add reference toSystem.IdentityModel.dll
Browse to C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0\System.IdentityModel.dll

2d. Add Microsoft.SharePoint.IdentityModel assembly reference in Page Directive of LoginWebPartUserControl.ascx

Assembly reference to Microsoft.IdentityModel.dll


3. Place Login Control on the LoginWebPartUserControl

HTML SOURCE
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
 
<%@ Assembly Name="Microsoft.SharePoint.IdentityModel, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
 
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
 
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" 
             Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
 
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" 
             Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
 
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" 
             Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
 
<%@ Import Namespace="Microsoft.SharePoint" %> 
 
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" 
             Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
 
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="LoginWebPartUserControl.ascx.cs" 
            Inherits="LoginWebPart.LoginWebPart.LoginWebPartUserControl" %>
 
 
<asp:Login ID="Login1" runat="server" 
           FailureText="<%$ Resources:wss,login_pageFailureText %>" 
           onauthenticate="Login1_Authenticate">
</asp:Login>


4. Go to Code behind of user control and add following reference
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.IdentityModel;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.IdentityModel.Tokens;


Write following code in Login1_Authenticate Event of Login Control

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
        {
            string membership = "MembershipProvider";
            string role = "RoleProvider";

            e.Authenticated = SPClaimsUtility.AuthenticateFormsUser(new Uri(SPContext.Current.Web.Url),Login1.UserName,Login1.Password);

            if (!e.Authenticated) return;

            SecurityToken token = SPSecurityContext.SecurityTokenForFormsAuthentication(new Uri(SPContext.Current.Web.Url), membership, role, Login1.UserName, Login1.Password);
            if (token == null)
            {

                e.Authenticated = false;
                return;
            }
            else
            {

                SPFederationAuthenticationModule module = SPFederationAuthenticationModule.Current;
                module.SetPrincipalAndWriteSessionToken(token);
                e.Authenticated = true;

                SPUtility.Redirect(SPContext.Current.Web.Url, SPRedirectFlags.Trusted, this.Context);

            }
        }


Build and Deploy Solution by clicking on Build Menu and select Deploy Solution From Visual Studio

5. Open SharePoint site in browser and login with administrator account

Click on Site Actions and Select Edit Page



Click on Insert and select Web Part from the top ribbon



Select Custom from Categories And select LoginWebPart, Click on Add and Save And Close





Hope this helps

7

Asp.Net AjaxFileUpload Control With Drag Drop And Progress Bar

This Example explains how to use AjaxFileUpload Control With Drag Drop And Progress Bar Functionality In Asp.Net 2.0 3.5 4.0 C# And VB.NET.

May 2012 release of AjaxControlToolkit includes a new AjaxFileUpload Control which supports Multiple File Upload, Progress Bar and Drag And Drop functionality.

These new features are supported by Google Chrome version 16+, Firefox 8+ , Safari 5+ and Internet explorer 10 + , IE9 or earlier does not support this feature.

AjaxFileUpload Control Example with Drag Drop And Progress Bar

To start with it, download and put latest AjaxControlToolkit.dll in Bin folder of application, Place ToolkitScriptManager and AjaxFileUpload on the page.

HTML SOURCE
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>
          
<asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server" 
                    OnUploadComplete="UploadComplete" 
                    ThrobberID="loader"/>
 
<asp:Image ID="loader" runat="server" 
           ImageUrl ="~/loading.gif" Style="display:None"/>


ThrobberID is used to display loading image instead of progress bar in unsupported browsers.

Type of files uploaded can be restricted by using AllowedFileTypes property with comma separated list such as "zip,doc,pdf".

Write following code in OnUploadComplete event to save the file.

C#
protected void UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string path = Server.MapPath("~/Uploads/") + e.FileName;
        AjaxFileUpload1.SaveAs(path);
    }
VB.NET
protected void UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string path = Server.MapPath("~/Uploads/") + e.FileName;
        AjaxFileUpload1.SaveAs(path);
    }
Build and run the code.

Download Sample Code


0

Ajax ConfirmButtonExtender With ModalPopUp In GridView Asp.Net

This example implements Ajax ConfirmButtonExtender With ModalPopUp Extender In Asp.Net GridView to show Delete Confirmation before deleting records.

Populate GridView using SqlDataSource and add one LinkButton inside TemplateField in Columns.

   1:  <asp:TemplateField HeaderText="Delete">
   2:  <ItemTemplate>
   3:  <asp:LinkButton ID="lnkDel" runat="server" 
   4:                  CommandName="Delete" Text="Delete"/>


Place ToolkitScriptManager and UpdatePanel on the page and add ConfirmButton, ModalPopUpExtender and Panel to pop inside Template field we added earlier.

HTML SOURCE
<div>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
        
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataKeyNames="ProductID" 
              DataSourceID="SqlDataSource1"
              onrowdeleted="GridView1_RowDeleted">
<Columns>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="lnkDel" runat="server" 
                CommandName="Delete" Text="Delete"/>
                
<asp:ConfirmButtonExtender ID="ConfirmButtonExtender1" 
                           runat="server" 
                           TargetControlID="lnkDel"
                           DisplayModalPopupID="ModalPopupExtender1"/>
                                        
<asp:ModalPopupExtender ID="ModalPopupExtender1" 
                        runat="server"
                        TargetControlID="lnkDel"
                        PopupControlID="pnlModal"
                        BackgroundCssClass="Background"
                        OkControlID="btnYes"
                        CancelControlID="btnNo"
                        X="80"
                        Y="80"/>
 
<asp:Panel runat="Server" ID="pnlModal" CssClass="Pnl">
<br />         
Do you want to delete this record
<br /><br />
<asp:Button ID="btnYes" runat="server" Text="Yes"/>
<asp:Button ID="btnNo" runat="server" Text="No"/>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
 
<asp:BoundField DataField="ProductID" HeaderText="ProductID"/>
<asp:BoundField DataField="ProductName" HeaderText="ProductName"/> 
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice"/> 
<asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock"/> 
</Columns>
</asp:GridView>
 
<asp:Label ID="lblMessage" runat="server" Text=""/>
</ContentTemplate>
</asp:UpdatePanel>
 
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" 
DeleteCommand="DELETE FROM [Products] 
               WHERE [ProductID] = @ProductID" 
SelectCommand="SELECT [ProductID], [ProductName], 
              [UnitPrice], [UnitsInStock] FROM [Products]" 
        
<DeleteParameters>
<asp:Parameter Name="ProductID" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
</div>


Add following CSS style in Head section of the page.
  

Build and run the code

AJax ConfirmButtonExtender With ModalPopUp In GridView Asp.Net

Download Sample Code




1

Populate Bind DropDownList From XML File In Asp.Net

This Example explains how to Populate Or Bind DropDownList With XML File Data In Asp.Net In 3/n Tier Architecture Using C# And VB.

Populate Bind DropDownList From XML File
Place one DropdownList on the page.

<asp:DropDownList ID="DropDownList1" 
                  runat="server" 
                  onselectedindexchanged
  ="DropDownList1_SelectedIndexChanged">


XML Data Can be in various formats, i'll use 3 different ones shown below.


Sample 1.
   1:  <?xml version="1.0" encoding="utf-8" ?>
   2:  <Employees>
   3:    <Detail>
   4:      <ID>1</ID>
   5:      <Name>Csharp</Name>
   6:    </Detail>
   7:    <Detail>
   8:      <ID>2</ID>
   9:      <Name>AspNet</Name>
  10:    </Detail>
  11:    <Detail>
  12:      <ID>3</ID>
  13:      <Name>Articles</Name>
  14:    </Detail>
  15:  </Employees>

Another format can be
   1:  <?xml version="1.0" encoding="utf-8" ?>
   2:  <Employees>
   3:    <Detail ID="1" Name="Csharp"></Detail>
   4:    <Detail ID="2" Name="AspNet"></Detail>
   5:    <Detail ID="3" Name="Articles"></Detail>
   6:  </Employees>

Writing following code in Page_Load event is enough to bind dropdownlist from these types of XML data.

C#
using System.Data;
using System.Xml;
protected void Page_Load(object sender, EventArgs e)
{
        DataSet dsXml = new DataSet();
        dsXml.ReadXml(Server.MapPath("~/XMLFile2.xml"));
        DropDownList1.DataSource = dsXml;
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "ID";
        DropDownList1.DataBind();
        DropDownList1.AutoPostBack = true;
}

VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
 Dim dsXml As New DataSet()
 dsXml.ReadXml(Server.MapPath("~/XMLFile2.xml"))
 DropDownList1.DataSource = dsXml
 DropDownList1.DataTextField = "Name"
 DropDownList1.DataValueField = "ID"
 DropDownList1.DataBind()
 DropDownList1.AutoPostBack = True
End Sub


If XML format is mix of above two.
   1:  <?xml version="1.0" encoding="utf-8" ?>
   2:  <Details>
   3:    <Name ID="1">Amit</Name>
   4:    <Name ID="2">Jain</Name>
   5:    <Name ID="3">Csharp</Name>
   6:    <Name ID="4">AspNet</Name>
   7:    <Name ID="5">Articles</Name>
   8:  </Details>

We need to loop through nodes to fine value of ID attribute.

C#
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Server.MapPath("~/XMLFile.xml"));
            XmlNodeList list = doc.GetElementsByTagName("Name");
            foreach (XmlNode node in list)
            {
                ListItem lItem = new ListItem(node.InnerText, node.Attributes["ID"].Value);
                DropDownList1.Items.Add(lItem);
            }
            DropDownList1.Items.Insert(0, "--Select--");
            DropDownList1.SelectedIndex = 0;
            DropDownList1.AutoPostBack = true;
        }
    }

VB
Protected Sub Page_Load(sender As Object, e As EventArgs)
 If Not IsPostBack Then
  Dim doc As New XmlDocument()
  doc.Load(Server.MapPath("~/XMLFile.xml"))
  Dim list As XmlNodeList = doc.GetElementsByTagName("Name")
  For Each node As XmlNode In list
   Dim lItem As New ListItem(node.InnerText, node.Attributes("ID").Value)
   DropDownList1.Items.Add(lItem)
  Next
  DropDownList1.Items.Insert(0, "--Select--")
  DropDownList1.SelectedIndex = 0
  DropDownList1.AutoPostBack = True
 End If
End Sub


To Bind DropDownList in 3 tier architecture environment, add to new class files in App_Code folder of application and name them DataLayer.cs and BusinessLayer.cs

Write Following code in these class respectively.

Data Access Layer (DAL)
using System.Web;
using System.Xml;
public class DataLayer
{
 public DataLayer()
 {
 }
    public XmlDocument GetXmlData()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(HttpContext.Current.Server.MapPath("~/XMLFile.xml"));
        return doc;
    }
}

Business Access Layer (BAL)
using System.Web.UI.WebControls;
using System.Xml;
public class BusinessLayer
{
 public BusinessLayer()
 {
    }
    public ListItemCollection BindDropDownList()
    {
        ListItemCollection ddlItems = new ListItemCollection();
        DataLayer objDAL = new DataLayer();
        XmlNodeList list = objDAL.GetXmlData().GetElementsByTagName("Name");
        foreach (XmlNode node in list)
        {
           ListItem item = new ListItem(node.InnerText, node.Attributes["ID"].Value);
           ddlItems.Add(item);
            
        }
        return ddlItems;
    }
}

Write code in Page_Load event of aspx page (Presentation Layer)
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BusinessLayer objBAL = new BusinessLayer();
            DropDownList1.DataSource = objBAL.BindDropDownList();
            DropDownList1.DataBind();
            DropDownList1.Items.Insert(0, "--Select--");
            DropDownList1.SelectedIndex = 0;
            DropDownList1.AutoPostBack = true;
        }
    }


2

Auto Refresh Update GridView In Asp.Net Ajax With Timer

This Example describes How To Auto Refresh Or Update GridView Automatically At Regular Interval In Asp.Net Using Ajax And Timer.

Add GridView And Timer control inside UpdatePanel on the page and set Interval property to desired value in miliseconds. I have set it to 5000 (5 Seconds).

HTML SOURCE
   1:  <asp:ScriptManager ID="ScriptManager1" runat="server"/>
   2:  <asp:UpdatePanel ID="UpdatePanel1" runat="server">
   3:  <ContentTemplate>
   4:   
   5:  <asp:Timer ID="AutoRefreshTimer" runat="server" 
   6:             Interval="5000" 
   7:             ontick="AutoRefreshTimer_Tick"/>
   8:                              
   9:  <asp:GridView ID="GridView1" runat="server" 
  10:                AutoGenerateColumns="False" 
  11:                DataSourceID="SqlDataSource1">
  12:  <Columns>
  13:  <asp:BoundField DataField="FirstName" HeaderText="FirstName"/>
  14:  <asp:BoundField DataField="LastName" HeaderText="LastName"/>
  15:  <asp:BoundField DataField="Location" HeaderText="Location"/>
  16:  </Columns>
  17:  </asp:GridView>
  18:   
  19:  <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
  20:  ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
  21:  SelectCommand="SELECT [FirstName], [LastName], [Location] 
  22:                 FROM [Details]">
  23:  </asp:SqlDataSource>
  24:   
  25:  <asp:Label ID="lblMsg" runat="server"/>
  26:  </ContentTemplate>
  27:  </asp:UpdatePanel>


Rebind GridView In Tick Event of Timer to refresh.

C#
protected void AutoRefreshTimer_Tick(object sender, EventArgs e)
    {
        GridView1.DataBind();
        lblMsg.Text = "Last Updated at " + DateTime.Now;
    }


Image below shows the implementation.

Automatically Refresh Update Asp.Net GridView with Ajax Timer

Hope this helps.

0

SharePoint 2010 Custom Login Page For FBA

This post explains How To Create Custom Login Page In SharePoint 2010 For Forms Based Authentication FBA.

Open Visual Studio 2010 and click on File > New Project


Select SharePoint 2010 from installed templates in left pane and select Empty SharePoint Project 

SharePoint 2010 Custom Login Page FBA

Name this project CustomLogin 


In the next window of SharePoint Customization Wizard, select the sharepoint site you want to create custom login page for and click on validate to test the connection.

Forms Based Authentication SharePoint


Select Deploy as farm solution option and click on finish


Right click on project name in solution explorer and add new item

Login Page

Select Application Page and name it Login.aspx

Before going to next step we need to add reference to IdentityModel dll to use it

Right click on Refrences and select add new reference
Click on Browse tab
Navigate to C:\Windows\assembly\GAC_MSIL\Microsoft.SharePoint.IdentityModel\14.0.0.0__71e9bce111e9429c

Microsoft.SharePoint.IdentityModel.dll

Select Microsoft.SharePoint.IdentityModel.dll and click on ok to add it's reference


Delete DynamicMasterPageFile="~masterurl/default.master" attribute from page directive in html source of page since we won't use master page for login page

It should look like shown below

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="CustomLogin.Layouts.CustomLogin.Login"%>


Make sure html source of page have all the following assembly references and directives


Delete all the ContentPlaceHolder html source from the page and design your login page with html as mentioned below 
<html>
<head id="Head1" runat="server">
 <title>Login </title>
 </head>
<body>
<form id="form1" runat="server">
 
<asp:Label ID="Name" runat="server" Text="UserName:"/>
<br/>
<asp:TextBox ID="txtUserName" runat="server" Height="22px"/>
<br />
<asp:Label ID="lblPwd" runat="server" Text="Password:"/>
<br/>
<asp:TextBox ID="txtPwd" runat="server" TextMode="Password" 
                                        Height="22px"/>
<br />
 
<asp:Button ID="btnLogIn" runat="server" Text="Sign In" 
                          onclick="btnLogIn_Click"/>
                    
<br /><br />
<asp:Label ID="lblMsg" runat="server" Text=""/>
</form>
</body>
</html>


I have placed two textbox on the page for username, password and one button for login

Change inharitance of Login class to System.Web.UI.Page  (it might be LayoutsPageBase)



Write following code in Click event of button in code behind of page 


using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.IdentityModel;
using Microsoft.SharePoint.IdentityModel.Pages;
namespace CustomLogin.Layouts.CustomLogin
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void btnLogIn_Click(object sender, EventArgs e)
        {
            if ((txtUserName.Text.Length > 0 && txtPwd.Text.Length > 0))
            {
                bool authenticated = SPClaimsUtility.AuthenticateFormsUser(Context.Request.UrlReferrer, txtUserName.Text, txtPwd.Text);
                if (!authenticated) 
                {
                    lblMsg.Text = "Invalid Username or Password";

                }
                else 
                {
                    Response.Redirect(Context.Request.QueryString["ReturnUrl"].ToString());

                }

            }
            else
            {
                lblMsg.Text = "Username or Password can't be empty";
            }
        }

    }
}
Build the solution and then Select Deploy Solution from Build menu to deploy it.

Deploy SharePoint SIte


It should create a CustomLogin folder inside _layouts folder in SharePoint site application in IIS Server 

Open SharePoint Central Administration, Click on Manage Web Applications


Select your site and click on Authentication Providers from ribbon bar at top




Click on default zone and scroll to Sign In Page URL section


Select Custom Sign In Page option and provide the url to the Login page we just created and deployed
It should be ~/_layouts/CustomLogin/Login.aspx

Click on save and open the SharePoint site to see new custom login page for Forms Based Authentication





Find More Articles