Thursday 17 January 2013

Highlight current page link on asp.net

How to highlight current page or link in asp.net.

Let's see it.

I have a site.master page like below.
-------------------------

<head runat="server">

    <title></title>
    <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
    </asp:ContentPlaceHolder>
</head>

<body>
    <form id="form1" runat="server">
    <table><tr>
            <td><asp:LinkButton ID="LinkButton2" runat="server" PostBackUrl="~/WebForm1.aspx">Page2</asp:LinkButton></td>
           <td><asp:LinkButton ID="LinkButton3" runat="server" PostBackUrl="~/WebForm2.aspx">Page3</asp:LinkButton></td>
        </tr></table>
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server">
        </asp:ContentPlaceHolder>
     
       
    </div>
    </form>
</body>
------------------------------------------------------------
Now on site.master.cs file write following code.


  public partial class Site1 : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        public void changecolor(Page obj)
        {
            if (obj is WebForm1)
            {
                LinkButton2.ForeColor = Color.Green;
                LinkButton3.ForeColor = Color.Empty;

            }
            if (obj is WebForm2)
            {
                LinkButton2.ForeColor = Color.Empty;
                LinkButton3.ForeColor = Color.Green;

            }
        }
    }
---------------------------------------------------------
Now on each page load event write just following code.


 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Site1 myMasterPage = (Site1)Page.Master;
                myMasterPage.changecolor(this.Page);
            }
        }
--------


Done..

Disable previous dates in calendar

How to disable the past dates in calendar control.

For this you need to write following simple code on DayRender event of calendar.


 protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
        {
            if (e.Day.Date<System.DateTime.Today)
            {
                e.Cell.BackColor = System.Drawing.Color.LightGray;
                e.Day.IsSelectable = false;
            }
        }

---------------------------------------------------------------------




Wednesday 16 January 2013

How to check trust level for sharepoint 2010 custom application

Go to path:

C:\inetpub\wwwroot\wss\VirtualDirectories\10000  (10000 is your application port no)

Go to Web (config file)

and search for trust

You can see there Full/Custom/minimal kind of options.

How to create WSP from solution file visual studio

Often we need to create wsp(work solution package) from Solution file.

What we do

Step1: In Release mode Clean solution.
Step2:Check in bin folder of solution
bin>Release

Delete craeted wsp file from there.

Step3: Now Go to Build->Package

Now go to bin>Release

Your wsp file is created.you can check CAS policy there in solution file.

Go to package then.

Under Package.Template.xml

You can check CAS policy.

Select/Deselect all listbox items by checkbox

Simple code for executing this is

protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{

foreach (ListItem item in ListBox1.Items)   {
item.Selected = CheckBox1.Checked;
   }
}

Populate Gridview based on listbox selection

Often we need to populate grid based on listbox selections.

For this we have a listbox,one button and grid.

On button click event write following code.
-------------------------------------------
protected void Button2_Click(object sender, EventArgs e)
        {
          
            string Seperator = ""; 
            StringBuilder Builder = new StringBuilder();
            foreach (ListItem li in ListBox1.Items)
            {
                if(li.Selected)
                {
                Builder.Append(Seperator).Append("'"+li.Value+"'");
                Seperator = ",";
                }
            }
            string conStr = @"Server=DEVVM5;Database=Sales;Integrated Security=true";
            SqlConnection conn = new SqlConnection(conStr);
            conn.Open();
            string query = "select * from Product where Name in (" + Builder + ")";
            SqlDataAdapter adp = new SqlDataAdapter(query, conn);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            Gridview1.DataSource = ds;
            Gridview1.AllowPaging = false;
            Gridview1.AllowSorting = false;
            Gridview1.DataBind();
            ViewState["Dataset"] = ds;
            Button1.Visible = true;
          

        }

---------------------------------------

Create sharepoint list programmatically

I have written a sample code showing how to create custom sharepoint list programmatically .

-------------------------------------
            SPSite site = new SPSite("URL");
            SPWeb web = site.OpenWeb();
            SPListCollection lists = web.Lists;
            lists.Add("Programmatically List", "Here the list is being created programmatically", SPListTemplateType.GenericList);
            SPList newList = web.Lists["Programmatically List"];
            newList.Fields.Add("My Column", SPFieldType.Text, true);
            newList.Fields.Add("DOB", SPFieldType.DateTime, true);
           
           // Lookup from another list and adding that column along with the fileds present
            SPList targetList = web.Lists["InfoValidation"];
            newList.Fields.AddLookup("Message", targetList.ID, false);
            SPFieldLookup lkp = (SPFieldLookup)newList.Fields["Message"];
            lkp.LookupField = targetList.Fields["Message"].InternalName;
            lkp.Update();

            SPView view = newList.DefaultView;
            view.ViewFields.Add("My Column");
            view.ViewFields.Add("DOB");
            view.ViewFields.Add("Message");
            view.Update();
            Console.WriteLine("List Created Successfully");
            Console.Read();
            site.Dispose();
            web.Dispose();

Run this as a console application.

Create sharepoint document library programatically

This is how we can craete document library programatically.


             SPSite site = new SPSite("URL");
             SPWeb web = site.OpenWeb();
             web.AllowUnsafeUpdates = true;
             web.Lists.Add("Document Programmatically", "Doc programmatically", SPListTemplateType.DocumentLibrary);
             web.AllowUnsafeUpdates = false;
             web.Dispose();
             site.Dispose();

-------------------
Run this by creating console application.

Sharepoint Folder creation programmatically

I am showing you how we can create folder programmatically.

namespace FolderCreation
{
    class Program
    {
        static void Main(string[] args)
        {
         //   SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPSite site = new SPSite("URL");
                site.AllowUnsafeUpdates = true;
                SPWeb web = site.OpenWeb();
                web.AllowUnsafeUpdates = true;
                SPList list = web.Lists.TryGetList("YOUR-LIST");
                SPListItem folderColl = list.Items.Add(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder);
                folderColl["Title"] = "NewFolder";
                folderColl.Update();
                list.Update();
                web.AllowUnsafeUpdates = false;
                site.AllowUnsafeUpdates = false;
            }
        }
    }
}

Please add Microsoft.Sharepoint namespace.
 

Assign Permission to sharepoint groups programmatically

In this post I am showing you how to assign custom permissions to sharepoint groups.

Add following namespaces:
---------------------------
using Microsoft.SharePoint;
using System.Resources;
using System.Reflection;
----------------------------

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            SPSite site = new SPSite("URL");
            SPWeb web = site.OpenWeb();
            ResourceManager rm = new ResourceManager("DemoFolder.Resource1", Assembly.GetExecutingAssembly());     //We are creating resource file and taking info from there.
            string MUFolder = rm.GetString("MUFolder");
            string[] grpmu = MUFolder.Split(',');
            string CntryFolder = rm.GetString("CntryFolder");
            string[] grpCntry = CntryFolder.Split(',');
            string CCfolder = rm.GetString("CCfolder");
            string[] grpcc = CCfolder.Split(',');
            string fold = rm.GetString("Folder");
            string[] grpList = fold.Split(',');

          for (int i = 0; i < grpList.Length; i++)
            {
                SPList list = web.Lists["CustomList"];
                SPQuery query = new SPQuery();
                query.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + grpList[i] + "</Value></Eq></Where>";
                SPListItemCollection items = list.GetItems(query);
                foreach (SPListItem item in items)
                {
                    SPFolder folder = web.GetFolder(item.Url);
                    folder.Item.BreakRoleInheritance(true);
                    SPGroupCollection spc = web.SiteGroups;
                    foreach (SPGroup oGroup in spc)
                    {
                        folder.Item.RoleAssignments.Remove((SPPrincipal)oGroup);
                    }
                    Console.WriteLine("All existing groups are removed");
                    SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)web.SiteGroups[grpmu[i]]);
                    roleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions["Country"]);
                    folder.Item.RoleAssignments.Add(roleAssignment);
                    Console.WriteLine("Assigned " + grpmu[i] + " to " + grpList[i]);
                    SPRoleAssignment roleAssignment1 = new SPRoleAssignment((SPPrincipal)web.SiteGroups[grpcc[i]]);
                    roleAssignment1.RoleDefinitionBindings.Add(web.RoleDefinitions["Country"]);
                    folder.Item.RoleAssignments.Add(roleAssignment1);
                    Console.WriteLine("Assigned " + grpcc[i] + " to " + grpList[i]);
                    SPRoleAssignment roleAssignment2 = new SPRoleAssignment((SPPrincipal)web.SiteGroups[grpCntry[i]]);
                    roleAssignment2.RoleDefinitionBindings.Add(web.RoleDefinitions["Country"]);
                    folder.Item.RoleAssignments.Add(roleAssignment2);
                    Console.WriteLine("Assigned " + grpCntry[i] + " to " + grpList[i]);
                    SPRoleAssignment roleAssignment3 = new SPRoleAssignment((SPPrincipal)web.SiteGroups["Custom"]);
                    roleAssignment3.RoleDefinitionBindings.Add(web.RoleDefinitions["Custom"]);
                    folder.Item.RoleAssignments.Add(roleAssignment3);
                    Console.WriteLine("Assigned Custom to " + grpList[i]);
                    SPRoleAssignment roleAssignment4 = new SPRoleAssignment((SPPrincipal)web.SiteGroups["ReadOnlyUser"]);
                    roleAssignment4.RoleDefinitionBindings.Add(web.RoleDefinitions["ReadOnlyUser"]);
                    folder.Item.RoleAssignments.Add(roleAssignment4);
                    Console.WriteLine("Assigned ReadOnlyUser to " + grpList[i]);
                    web.Update();
                }
            }
            site.Dispose();
}
}
}
--------------------------------------------
This way we can assign permissions programmatically.

Monday 14 January 2013

Site collection backup and restore in Sharepoint 2013

Hi in sharepoint 2013 or 2010 by using these following commands we can take back up of site collection:

Open powershell in Run as Admin mode.

Backup-SPSite -Identity <SiteCollectionURL> -Path <BackupFile>

<SiteCollectionURL> your site collection url which you want to back up.
<BackupFile> path where .bak will be created.

For Restore we do:
Restore-SPSite -Identity <SiteCollectionURL> -Path <BackupFile>  -Force


Remember Force parameter is absolutely required as you are overwriting one existing site collection.

Sliding panel in asp.net with jquery

Sometimes we need a beautiful panel which slides up and down for better look.

Let's see how can we achieve it with simple jquery.

<script>
    function slideUp(){
            $("#<%= myPanel.ClienID %>").slideUp(); //myPanel is panel ID in aspx page.
    }
    function slideDown(){
            $("#<%= myPanel.ClienID %>").slideDown();
    }
</script>

Sunday 13 January 2013

Parent-Child Gridview/nested Gridview

Often We need nested gridview.



Like showing parent-child relationship in gridview.

I created 2 tables Customer(CustomerID as int,CustomerName as varchar(50)) and Order(Orderid as int,description as varchar(50),CustomerId as Foreign key to Customer).

Enter code into HTML source:
----------------------------------


        <asp:GridView ID="GridParent" runat="server" AutoGenerateColumns="False"
            OnRowDataBound="GridParent_RowDataBound" CellPadding="4" ForeColor="#333333"
            GridLines="None" Width="384px" Height="183px">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <Columns>
                <asp:TemplateField HeaderText="ID">
                    <ItemTemplate>
                        <asp:Label ID="lblID" Text='<%# Eval("CustomerID") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Customer Name">
                    <ItemTemplate>
                        <asp:Label ID="lblName" Text='<%# Eval("CustomerName") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Orders">
                    <ItemTemplate>
                        <asp:Label ID="lbltoggel" runat="server" >+Orders</asp:Label>
                        <asp:HiddenField ID="lblCustomerID" value='<%# Eval("CustomerID") %>' runat="server"></asp:HiddenField>
                        <asp:GridView ID="GridChild" runat="server" style="display:block" AutoGenerateColumns="false">
                         <Columns>
                                <asp:TemplateField HeaderText="Order No">
                                    <ItemTemplate>
                                        <asp:Label ID="lblOrderID" Text='<%# Eval("Orderid") %>' runat="server"></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Description">
                                    <ItemTemplate>
                                        <asp:Label ID="lblTotal" Text='<%# Eval("description") %>' runat="server"></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                        </asp:GridView>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
</asp:gridview>
----------------------------------
Now create this javascript :(It is for expanding Show or Hide child grid/Order Details)
----------------------------------

 <script type="text/javascript" language="javascript">
         function toggle(toggeldivid, toggeltext)
          {
             var divelement = document.getElementById(toggeldivid);
             var lbltext = document.getElementById(toggeltext);
             if (divelement.style.display == "block")
             {
                 divelement.style.display = "none";
                 lbltext.innerHTML = "+ Show Orders";
             }
             else
             {
                 divelement.style.display = "block";
                 lbltext.innerHTML = "- Hide Orders";
             }
         }
</script>
--------------------------------------

Now write following code on server side:
--------------------------------------

namespace nestedGrid
{
    public partial class Form1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                LoadParentGrid();
            }

        }

        private void LoadParentGrid()
        {
     
                DataSet ds = GetDataSet("Select * from Customer");
                GridParent.DataSource = ds;
                GridParent.DataBind();
        }

        private DataSet GetDataSet(string query)
        {
            DataSet Ds = new DataSet();
            try
            {
                string strCon = @"Data Source=User-PC\SQLEXPRESS;Initial Catalog=Student;Integrated Security=True;";
                SqlConnection Con = new SqlConnection(strCon);
                SqlDataAdapter Da = new SqlDataAdapter(query, Con);
                Da.Fill(Ds);
            }
            catch (Exception) { }
            return Ds;
        }

        protected void GridParent_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                HiddenField custID = (HiddenField)e.Row.FindControl("lblCustomerID");
                Label lblToggle = (Label)e.Row.FindControl("lbltoggel");
                GridView gvChild = (GridView)e.Row.FindControl("GridChild");
                int customerid = Convert.ToInt32(custID.Value);
                LoadChildGrid(customerid, gvChild);
                lblToggle.Attributes.Add("onClick", "toggle('" + gvChild.ClientID + "' ,'" + lblToggle.ClientID + "');");
            }
        }

        private void LoadChildGrid(int custId, GridView gvChild)
        {
            try
            {
                DataSet Ds = GetDataSet("SELECT *  FROM [student].[dbo].[Order] where CustomerId=" + custId);
                gvChild.DataSource = Ds;
                gvChild.DataSourceID = null;
                gvChild.DataBind();
            }
            catch (Exception) { }
        }
    }
}






Bulk insert into Sql Server table with XML input


Let's say I have a table named User

Create stored procedure "addtodb".
-------------------------------------
Create Procedure addtodb @exml xml
as
begin
Insert into [student].[dbo].[User](UserId,UserName)
Select p.value('@UserId','integer')as Id,p.value('@UserName','varchar(50)')as Name
from @exml.nodes('/employeeData/employee') as abc(p)
end
--------------------------------------

Now execute it :
------------------
Exec addtodb @exml = '<employeeData>
                  <employee UserId="1" UserName="Rsu"/>
                  <employee UserId="2" UserName="PSU"/>
                  <employee UserId="3" UserName="Nsu"/>
                  <employee UserId="4" UserName="Ksu"/>
                  <employee UserId="5" UserName="Dsu"/>
               </employeeData>'



Check for duplicate data in database

I will show you how to check duplicate in database table before inserting into database.

For that follow database design from my previous example (display image in gridview).

Now Write a function which will return true/false.(bool value)
-------------------------------------------------

 private bool IsPictureExists(string name)
        {
            string constring = @"Server=User-PC\SQLEXPRESS;initial catalog=Student;Integrated Security=true";
            SqlConnection conn = new SqlConnection(constring);
            conn.Open();
            string query="Select count(ImageName) from  [student].[dbo].[ImageTable] where ImageName= '" + name.Text +"'";
            SqlCommand cmd = new SqlCommand(query, conn);
            int i = (int)cmd.ExecuteScalar();
            if (i ==0)
            {
                return true;
            }
            return false;
        }
------------------------------------------------------
Now call this function on button click like


 protected void Button1_Click(object sender, EventArgs e)
        {
           if(IsPictureExists(name).Equals(true))
           {
       //Insert Logic goes here
           }
         else
      //Show message - Duplictaed..
That's it.

Upload and Display Images in Gridview




I created one table ImageTable which has 3 fields ID(int),ImageName(varchar) and TheImage(image).

Now I have created 3 stored procedues as follows:
SP1:-

ALTER Procedure [dbo].[InsertImage]
 
    @Name  varchar(50),
    @theImage  Image
AS
Begin

Insert into [student].[dbo].[ImageTable] values(@Name,@theImage)
END
SP2:-

ALTER Procedure [dbo].[SelectImage]
As

Select ImageName,ID from [student].[dbo].[ImageTable]
SP3:-

ALTER Procedure [dbo].[SelectImageByID]
@ID int
AS
Select TheImage from [student].[dbo].[ImageTable] where ID=@ID
------------------------------
Now on html I took one textbox,one fileupload control and one button.


<form id="form1" runat="server">
    <div style="height: 247px">
        <asp:Panel ID="Panel1" Visible="false" runat="server">
       
      <asp:Label ID="lblErr" runat="server" Text="Please select One file" BackColor="#FFFF66" ForeColor="Red"></asp:Label><br />
       
        </asp:Panel>
        &nbsp;&nbsp;Image Name:
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
&nbsp; Upload Image
        <asp:FileUpload ID="FileUpload1" runat="server" />
&nbsp;<asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click" />
        <br />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            onrowcommand="GridView1_RowCommand" onrowdeleting="GridView1_RowDeleting">
        <Columns>
         <asp:TemplateField HeaderText="ID" Visible="false">
        <EditItemTemplate>
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        </EditItemTemplate>
        <ItemTemplate>
        <asp:Label ID="lblID" runat="server" Text='<%# Bind("ID") %>' />
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Name">
        <EditItemTemplate>
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        </EditItemTemplate>
        <ItemTemplate>
        <asp:Label ID="lblName" runat="server" Text='<%# Bind("ImageName") %>' />
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField  HeaderText="Image">
        <EditItemTemplate>
        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
        </EditItemTemplate>
        <ItemTemplate>
            <asp:Image ID="Image1" Height="100px" Width="250px" runat="server" ImageUrl='<%# "ImageHandler.ashx?ID=" +Eval("ID") %>' />
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Select">
     <ItemTemplate>
       <asp:LinkButton ID="LinkButton1" OnClientClick="return confirm('Do you want to delete')"
         CommandArgument='<%# Eval("ID") %>'
         CommandName="Delete" runat="server">
         Delete</asp:LinkButton>
     </ItemTemplate>
   </asp:TemplateField>
        </Columns>
        </asp:GridView>
   
    </div>
    </form>
-----------------------------------------------------
Now on server side create one "Linq to Sql" .dbml file.
Drag database table and 3 stored procedures there and save it.
In my case it is ClassicDataContext.dbml.

Next step I took one Generic Handler. in my case it is ImageHandler.ashx

Enter following code:(This is for processing ID)

 public void ProcessRequest(HttpContext context)
        {
            string imageId = context.Request.QueryString["ID"];
            context.Response.ContentType = "image/jpeg";
            Stream stm = ImageLoading(imageId);
            byte[] buffer = new byte[4096];
            int byteSeq = stm.Read(buffer, 0, 4096);
            while (byteSeq > 0)
            {
                context.Response.OutputStream.Write(buffer, 0, byteSeq);
                byteSeq = stm.Read(buffer, 0, 4096);
            }
        }

        private Stream ImageLoading(string imageId)
        {
            int obj = Convert.ToInt32(imageId);
            ClassicDataContext db = new ClassicDataContext();
            var x = db.SelectImageByID(obj).First();
            return new MemoryStream(x.TheImage.ToArray());
        }
----------------------------------------------------------------


Now put following code on cs file.



namespace ImageGrid
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        ClassicDataContext db;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.LoadGrid();
            }

        }

        private void LoadGrid()
        {
            db = new ClassicDataContext();
            GridView1.DataSource = db.SelectImage();
            GridView1.DataBind();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
           if(IsPictureExists(TextBox1).Equals(true))
           {
               if (FileUpload1.HasFile)
                {

                    byte[] Imagesize = new byte[FileUpload1.PostedFile.ContentLength];
                    HttpPostedFile myImg = FileUpload1.PostedFile;
                    myImg.InputStream.Read(Imagesize, 0, FileUpload1.PostedFile.ContentLength);
                    db = new ClassicDataContext();
                    db.InsertImage(TextBox1.Text, Imagesize);
                    db.SubmitChanges();
                    this.LoadGrid();
                }
           
            else
            {
                Panel1.Visible = true;

            }
           }
           else
           {
               Panel1.Visible = true;
               lblErr.Text = "Name already Exists";
           }
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                int imageID = Convert.ToInt32(e.CommandArgument);
                string constring = @"Server=User-PC\SQLEXPRESS;initial catalog=Student;Integrated Security=true";
                SqlConnection conn = new SqlConnection(constring);
                conn.Open();
                string query="Delete from [student].[dbo].[ImageTable] where ID=" +imageID;
                SqlCommand cmd = new SqlCommand(query, conn);
                cmd.ExecuteNonQuery();
                this.LoadGrid();
                conn.Close();
               
            }
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
        }
       
    }
}