Tuesday, November 27, 2012

Export to excel of a asp.net data table or a Sharepoint List.

Here I am giving a way to export a Data table into an Excel Sheet. You need to add this class into your project and then call only this method with provided values in particular event firing where you want it to created :


ExcelHelper.ToExcel(DataTable dtInput, string filename, HttpResponse response)

I have used it in this way for a button click :

protected void btnExportToExcel_Click(object sender, Eventargs e)
{
//  objSPList is SharePoint List object.
//  objSPQuery is SPQuery object.

DataTable exportResult = objSPList.GetItems(objSPQuery).GetDataTable();
ExcelHelper.ToExcel(exportResult, "My Excel " + System.DateTime.Today.ToShortDateString(), this.Page.Response);
}

 
 Class code is like this:

 public class ExcelHelper
    {
        //Row limits older Excel version per sheet
        const int rowLimit = 65000;

        private static string getWorkbookTemplate()
        {
            var sb = new StringBuilder();
            sb.Append("<xml version>\r\n<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n");
            sb.Append(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n xmlns:x=\"urn:schemas- microsoft-com:office:excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">\r\n");
            sb.Append(" <Styles>\r\n <Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n <Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>");
            sb.Append("\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>\r\n    <Protection/>\r\n </Style>\r\n <Style ss:ID=\"BoldColumn\">\r\n <Font ");
            sb.Append("x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n <Style ss:ID=\"s62\">\r\n <NumberFormat");
            sb.Append(" ss:Format=\"@\"/>\r\n </Style>\r\n <Style ss:ID=\"Decimal\">\r\n <NumberFormat ss:Format=\"0.0000\"/>\r\n </Style>\r\n ");
            sb.Append("<Style ss:ID=\"Integer\">\r\n <NumberFormat ss:Format=\"0\"/>\r\n </Style>\r\n <Style ss:ID=\"DateLiteral\">\r\n <NumberFormat ");
            sb.Append("ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n <Style ss:ID=\"s28\">\r\n");
            sb.Append("<Alignment ss:Horizontal=\"Left\" ss:Vertical=\"Top\" ss:ReadingOrder=\"LeftToRight\" ss:WrapText=\"1\"/>\r\n");
            sb.Append("<Font x:CharSet=\"1\" ss:Size=\"9\" ss:Color=\"#808080\" ss:Underline=\"Single\"/>\r\n");
            sb.Append("<Interior ss:Color=\"#FFFFFF\" ss:Pattern=\"Solid\"/> </Style>\r\n</Styles>\r\n {0}</Workbook>");
            return sb.ToString();
        }

        private static string replaceXmlChar(string input)
        {
            input = input.Replace("&", "&");
            input = input.Replace("<", "<");
            input = input.Replace(">", ">");
            input = input.Replace("\"", "");
            input = input.Replace("'", "&apos;");
            return input;
        }

        private static string getWorksheets(DataSet source)
        {
            var sw = new StringWriter();
            if (source == null || source.Tables.Count == 0)
            {
                sw.Write("<Worksheet ss:Name=\"Sheet1\"><Table><Row><Cell  ss:StyleID=\"s62\"><Data ss:Type=\"String\"></Data></Cell></Row></Table></Worksheet>");
                return sw.ToString();
            }
            foreach (DataTable dt in source.Tables)
            {
                if (dt.Rows.Count == 0)
                    sw.Write("<Worksheet ss:Name=\"" + replaceXmlChar(dt.TableName) + "\"><Table><Row><Cell  ss:StyleID=\"s62\"><Data ss:Type=\"String\"></Data></Cell></Row></Table></Worksheet>");
                else
                {
                    //write each row data
                    var sheetCount = 0;
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if ((i % rowLimit) == 0)
                        {
                            //add close tags for previous sheet of the same data table
                            if ((i / rowLimit) > sheetCount)
                            {
                                sw.Write("</Table></Worksheet>");
                                sheetCount = (i / rowLimit);
                            }
                            sw.Write("<Worksheet ss:Name=\"" + replaceXmlChar(dt.TableName) + (((i / rowLimit) == 0) ? "" : Convert.ToString(i / rowLimit)) + "\"><Table>");
                            sw.Write("<Row>");
                            foreach (DataColumn dc in dt.Columns)
                                sw.Write(string.Format("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">{0}</Data></Cell>", replaceXmlChar(dc.ColumnName)));
                            sw.Write("</Row>\r\n");
                        }
                        sw.Write("<Row>\r\n");
                        foreach (DataColumn dc in dt.Columns)
                            sw.Write(string.Format("<Cell ss:StyleID=\"s62\"><Data ss:Type=\"String\">{0}</Data></Cell>", replaceXmlChar(dt.Rows[i][dc.ColumnName].ToString())));
                        sw.Write("</Row>\r\n");
                    }
                    sw.Write("</Table></Worksheet>");
                }
            }
            return sw.ToString();
        }
        public static string GetExcelXml(DataTable dtInput, string filename)
        {
            var excelTemplate = getWorkbookTemplate();
            var ds = new DataSet();
            ds.Tables.Add(dtInput.Copy());
            var worksheets = getWorksheets(ds);
            var excelXml = string.Format(excelTemplate, worksheets);
            return excelXml;
        }

        public static string GetExcelXml(DataSet dsInput, string filename)
        {
            var excelTemplate = getWorkbookTemplate();
            var worksheets = getWorksheets(dsInput);
            var excelXml = string.Format(excelTemplate, worksheets);
            return excelXml;
        }

        public static void ToExcel(DataSet dsInput, string filename, HttpResponse response)
        {
            var excelXml = GetExcelXml(dsInput, filename);
            response.Clear();
            response.AppendHeader("Content-Type", "application/vnd.ms-excel");
            response.AppendHeader("Content-disposition", "attachment; filename=" + filename + ".xls");
            response.Write(excelXml);
            response.Flush();
            response.End();
        }

        public static void ToExcel(DataTable dtInput, string filename, HttpResponse response)
        {
            var ds = new DataSet();
            ds.Tables.Add(dtInput.Copy());
            ToExcel(ds, filename, response);
        }
    }

Thursday, November 22, 2012

How to deploy a page in SharePoint File system and then set it acess url through module in SharePoint 2010.

Here I am going to add a page to a  and then configure it to access through SharePoint Site collection URL. This is the best way to add an application page with code behind. So here are the steps :

1.) Open Visual Studio 2010. Add a new project. Expand SharePoint button. Select 2010 and then choose  Module template in all provided templates. We need to deploy it as farm Solution because we need to write code behind that would be deployed in GAC and moreover we are adding a page into file system. I have given this project SharePointModulePOC. It will look like this now :

2.) Here we can see a feature is added to the solution we can expand feature node and select Feature1 and it would like this containing your module. In the very same way it contains any other element.

3.) Now we will add a aspx page to the module by right clicking on it select add a New Item and POCApplicationPage.aspx page with its default content. Now it will look like this :

4.) Now deploy this solution and you can access this page by adding this URL" /Module1/POCApplicationPage.aspx" to site URL. Suppose site URL is "http://servername:portnumber/sites/sitecollection" and then page URL will be "http://servername:portnumber/sites/sitecollection/Module1/POCApplicationPage.aspx".

5.) Suppose now you want to change access URL to without this module reference then you can click on this  "POCApplicationPage.aspx" page and press F4 and then select Deployment Location. and delete this module path. Now it will look like this :

Which was like this earlier :



Now you can access this page through this URL "http://minf-0091:33333/sites/TestPages/POCApplicationPage.aspx".

Wednesday, November 14, 2012

Printing content of a particular area of a page through Java Script function.

This is the way to print content of a particular div through this function. Very basic but important :

function PrintContent(ctrl) {
        var DocumentContainer = ctrl;
        var WindowObject = window.open('', "TrackHistoryData",
            "width=420,height=225,top=250,left=345,toolbars=no,scrollbars=yes,status=no,resizable=no");
        WindowObject.document.write(DocumentContainer.innerHTML);
        WindowObject.document.close();
        WindowObject.focus();
        WindowObject.print();
        WindowObject.close();
    }


You need to put this iframe for better preview..

<iframe id="ifmcontentstoprint" style="height: 0px; width: 0px; position: absolute">
</iframe>


This is function for whole Page :

 function printPage() {
        var content = document.getElementById("Your Div ID");
        var pri = document.getElementById("ifmcontentstoprint").contentWindow;
        pri.document.open();
        pri.document.write(content.innerHTML);
        pri.document.close();
        pri.focus();
        pri.print();
    }

Friday, November 2, 2012

How to query two or more columns of SharePoint list with multiple Values.

Here I am going to explain a you a way to create a dynamic query which deals with multiple values of two fields(Columns). There are other way of doing it to do it through LINQ but that would be heavy because you have to use for each loop for the purpose.

I will do it for two list of string values collection for two columns. I am considering AND operation between columns and OR between all values for columns. I will divide into three function for clarity. However I and II are same except its filed name, you can modify it as per your need. III function would be combine both these queries with an AND operator.

1. First we will create dynamic query for Column1:

 public StringBuilder GetQueryForColumn1(List<string> Values1)
        {
            StringBuilder stbQuery = new StringBuilder();
            if (Regions.Count > 0)
            {
                bool first = true;
                    foreach (string Value in Values1)
                    {

                        if (first)
                        {
                            stbQuery.Append("<Eq><FieldRef Name='Column1' /><Value Type='Text'>").Append(Value .Trim()).Append("</Value></Eq>");
                            first = false;
                        }
                        else
                        {
                            string formatedQuery = stbQuery.ToString();
                            StringBuilder objNew = new StringBuilder();
                            objNew.Append("<Or>");
                            objNew.Append("<Eq><FieldRef Name='Column1' /><Value Type='Text'>").Append(Value .Trim()).Append("</Value></Eq>");
                            objNew.Append(formatedQuery);
                            objNew.Append("</Or>");
                            stbQuery = objNew;
                        }
                }
            }
            return stbQuery;
        }


2. Now we will create dynamic query for Column2:

 public StringBuilder GetQueryForColumn2(List<string> Values2)
        {
            StringBuilder stbQuery = new StringBuilder();
            if (Regions.Count > 0)
            {
                bool first = true;
                    foreach (string Value in Values2)
                    {

                        if (first)
                        {
                            stbQuery.Append("<Eq><FieldRef Name='Column2' /><Value Type='Text'>").Append(Value .Trim()).Append("</Value></Eq>");
                            first = false;
                        }
                        else
                        {
                            string formatedQuery = stbQuery.ToString();
                            StringBuilder objNew = new StringBuilder();
                            objNew.Append("<Or>");
                            objNew.Append("<Eq><FieldRef Name='Column2' /><Value Type='Text'>").Append(Value .Trim()).Append("</Value></Eq>");
                            objNew.Append(formatedQuery);
                            objNew.Append("</Or>");
                            stbQuery = objNew;
                        }
                }
            }
            return stbQuery;
        }


3. Then we will put this into a common function and concatenate  it : 

 public StringBuilder GetQueryForBothColumn1AndColumn2(List<string> Regions, List<string> OfficerTitles)
        {
            StringBuilder stbAllQuery = new StringBuilder();
            stbAllQuery.Append("<Where><And>");
            stbAllQuery.Append( GetQueryForColumn1(Values1));
            stbAllQuery.Append( GetQueryForColumn2(Values2));
            stbAllQuery.Append("</And></Where>");
            return stbAllQuery;
        }

 
Now this query you can use to query on this on your chunk of selected choices in a single query to list. you can do it for more than two columns as well but that would need a bit effort and change in  GetQueryForBothColumn1AndColumn2 function.




Wednesday, October 31, 2012

How to manage and query items in folders of SharePoint Lists pro-grammatically in C#.

Here I am going to provide you very simple way of managing your SharePoint List Items in Folders. In this way we will first check that folder with this name exists or not. If it exists then it will insert item in that folder and if not then it will create a new folder of this name and put item inside this newly created folder. 

At first we need to include this method in our project to check that particular folder exists or not :

 public static bool FolderExists(string url, SPWeb web)
        {
            try
            {
                if (web.GetFolder(url).Exists)
                {
                    return true;
                }
                return false;
            }
            catch (ArgumentException ex)
            {
                Logger.Write(ex);
                return false;
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
                return false;
            }
        }


This methods will check that a folder with the supplied parameters exists or not. And then add item as per values given in corresponding folder OR if does not exists will create a new one  and then add item as per values given in corresponding folder.  

public void UpdateDemoFolderInListA(SPWeb objSPWeb, string strDemo)
        {
            if (objSPWeb != null)
            {
                SPList objSPListListA = objSPWeb.Lists.TryGetList("ListA");
                if (objSPListSavedSearch != null)
                {
                    SPFolder spFolder;
                    if (FolderExists(objSPWeb.ServerRelativeUrl + "/Lists/ListA/" + strDemo, spWeb))
                    {
                        spFolder = spWeb.GetFolder(objSPWeb.ServerRelativeUrl + "/Lists/ListA/" + strDemo);
                    }
                    else
                    {
                        SPListItem newFolder = objSPListSavedSearch.Items.Add(spWeb.ServerRelativeUrl + "/" + objSPListListA.RootFolder.Url, SPFileSystemObjectType.Folder, strDemo);
                        newFolder.Update();
                        spFolder = spWeb.GetFolder(spWeb.ServerRelativeUrl + "/Lists/ListA/" + strDemo);
                    }
                        SPListItem item = objSPListListA.Items.Add(spFolder.ServerRelativeUrl, SPFileSystemObjectType.File);
                        item["Column1"] = Value1;
                        item["Column2"] = Value2;
                        item["Column3"] = Value3;
                        item.Update();
                    }
                }
            }
        }


You can use this approach to extend functionality such as to add item in some restriction such as maximum no. of items in the folder or date wise folder or user logged in folder items update.Anyways querying for item inside a particular folder with defined URL will a performance boost.  Hope it will help.

Tuesday, October 30, 2012

How to add a border less poopup in an asp.net or SharePoint Page.

It is quite tedious to add popup in your page without any border. And more than that if you have to transfer a lot of information. Sometimes we need to add a new Page in our project just for adding a very simple popup which contains a text box only. However putting all theses you can not get rid of windows default close and minimize button. So I have done this through putting a div and then setting its z-index style. Through which It will look like a popup.

Here are the steps to integrate this solution into your page.

Code need to put into .aspx or .ascx file :-

Code to put add a panel and controls : 

 <asp:Panel runat="server" ID="pnlPopupContainer" CssClass="positionSetter">
        <table width="100%">
            <tr style="width: 100%">
                <td style="text-align: left; vertical-align: middle; width: 300px; padding-left: 10px;">
                    <asp:TextBox runat="server" ID="txtBox1" Width="275px"></asp:TextBox>
                </td>
                <td style="vertical-align: middle; width: 300px;">
                    <asp:LinkButton runat="server" Text="
Save Search" ID="lnkBtn1"                                  OnClientClick="HideMainPanel()" OnClick="lnkBtn1_Click"></asp:LinkButton>
                </td>
            </tr>
        </table>
    </asp:Panel>


 This is the link on which click popup will be opened. It can be a button or anything you want.
<a href='#' onclick='ShowPanel()'><b>Open Popup </b></a>

 Styles :  

      .positionSetter       
      {
            position: absolute;
            left: 275px;
            top: 425px;
            width: 400px !important;
            height: 35px !important;
            text-align: center;
            z-index: 1000;
            background-color: #4f81bc !important;
            visibility: hidden;
        }

This style class will play a very crucial role in its positioning.  Left and top attribute will set its horizontal position in page, z-index will position its over page and give a popup feel, width and height will decide popup width and height. 

JavaScript :
This java script functions will show and hide of our div(popup).

function HideMainPanel() {
            el = document.getElementById('<%=
pnlPopupContainer.ClientID%>');
            if (el != null) {
                el.style.visibility = "hidden";
            }
        }

        function ShowPanel() {
            el = document.getElementById('<%=
pnlPopupContainer.ClientID%>');
            if (el != null) {
                el.style.visibility = "visible";
            }

        }


Through this code you can view it in this way.



And you can customize it as per your requirement further.

Friday, October 19, 2012

How to bubble a user control event in its calling pages or webparts.

This is a user control which contains a Drop Down list and an event


UserControl.ascx contents will be like this : 

<%@ Control Language="C#" AutoEventWireup="true" Inherits="NameSpaceName.ClassName, NameSpaceName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=74a8568657e011e0" %>
.drp-color
{
    color:#7d99c1;
    font-family:Calibri;
    font-size: 8pt;
    width:150px;
}
</style>
<asp:Panel runat="server" ID="mainPanel">
 <asp:DropDownList ID="drpList" runat="server" AutoPostBack="true"  CssClass="drp-color" OnSelectedIndexChanged="drpList_SelectedIndexChanged">
</asp:DropDownList>
</asp:Panel>


UserControl.ascx.cs contents will be like this :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Web.UI;
using Microsoft.SharePoint;

namespace NameSpaceName
{
    public partial class ClassName: System.Web.UI.UserControl
    {
        public string TextColumnName { get; set; }
        public string IdColumnName { get; set; }
        public string ListName { get; set; }
     
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PopulateDropDown();
            }
          
        }

        public void PopulateDropDown()
        {
            try
            {
                DataTable dtResult;
                using (SPSite spSite = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        dtResult = GetListValues(spWeb);
                        drpList.DataSource = dtResult;
                        drpList.DataValueField = this.IdColumnName;
                        drpList.DataTextField = this.TextColumnName;
                        drpList.DataBind();
                        ListItem objItem = new ListItem("View All", "0");
                        drpList.Items.Insert(0, objItem);

                        //if (this.drpList.Items.Count > 0)
                        //{
                        //    this.drpList.Items[0].Selected = true;
                        //    this.OnDropDownListSelectionChanged();
                        //}
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public DataTable GetListValues(SPWeb spWeb)
        {
            SPList lstValues = GetList(this.ListName, spWeb);
            if (null != lstValues)
            {
                if (lstValues.ItemCount > 0)
                    return lstValues.Items.GetDataTable();
                else
                    return null;
            }

            return null;
        }

        public SPList GetList(string listName, SPWeb spWeb)
        {
            SPList spList = null;

            if (null != spWeb)
            {
                try
                {
                    spList = spWeb.Lists[listName];
                }
                catch (Exception)
                {
                    spList = null;
                }
            }

            return spList;
        }

        public void drpList_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.OnDropDownListSelectionChanged(sender,e);

        }

        # region Event Section
     
       public delegate void DropDownSelectionDelegate(object sender, EventArgs e);
       protected event DropDownSelectionDelegate drpListselectionChanged;

        public event DropDownSelectionDelegate DropDownListSelectionChanged
        {
            add
            {
                this.drpListselectionChanged += value;
            }
            remove
            {
                this.drpListselectionChanged -= value;
            }
        }
        public virtual void OnDropDownListSelectionChanged(object sender, EventArgs e)
        {
          
            if (this.drpListselectionChanged != null)
                this.drpListselectionChanged(sender,e);
        }
        # endregion
    }
}


Now in the Web part/Page in which you are using this control or want to trap this user control events. In this case its a visual web part (It will be inside another user control) will be like this :
 UserControlABC.ascx :

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ 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="UserControlA.ascx.cs"
    Inherits="NameSpace.ClassName.UserControlA" %>
<%@ Register Src="/_controltemplates/Project1/SPDropDownControl.ascx" TagPrefix="SAUserControl"
    TagName="SPDropDownList" %>
    <style type="text/css">
        .pnlHorizontal
        {
        width:100%           
        }
    </style>
<asp:Panel runat="server" ID="pnlHorizontal" Visible="false" CssClass="pnlHorizontal">
    <table width="100%">
        <tr>
            <td>
                <font style='font-family: Calibri !important; color: #C0C0C0 !important; font-size: 14pt!important; padding-left:50px; width:30%;'>
                    B :</font>
            </td>
            <td >
                <font style='font-family: Calibri !important; font-size: 8 !important; color: #58443B !important; width:30%;'>
                    D : </font></br>
                <SAUserControl:SPDropDownList runat="server" ID="uscH1" OnDropDownListSelectionChanged="ucListControl1_DropDownListSelectionChanged"
                    TextColumnName="Title" IdColumnName="ID" ListName="Channel" />
            </td>
            <td >
                <font style='font-family: Calibri !important; font-size: 8 !important; color: #58443B !important; width:30%;'>
                    H : </font></br><SAUserControl:SPDropDownList runat="server" ID="uscH2"
                        OnDropDownListSelectionChanged="ucListControl1_DropDownListSelectionChanged"
                        TextColumnName="Title" IdColumnName="ID" ListName="Topic" />
            </td>
            <td>
                <font style='font-family: Calibri !important; font-size: 8 !important; color: #58443B !important; width:30%; padding-right:100px;'>
                   I : </font></br><SAUserControl:SPDropDownList runat="server" ID="uscH3"
                        OnDropDownListSelectionChanged="ucListControl1_DropDownListSelectionChanged"
                        TextColumnName="Name" IdColumnName="ID" ListName="SMEProfile" />
            </td>
        </tr>
    </table>
</asp:Panel>
<asp:Panel runat="server" ID="pnlVertical" Visible="false">
    <table>
        <%--<tr>
            <td class='tc-VerticalSMEHeading'>
                Find eXpert Knowledge by:
            </td>
        </tr>--%>
        <tr>
            <td>
                <font style='font-family: Calibri !important; font-size: 8pt !important; color: black !important;'>
                    A:</font></br><SAUserControl:SPDropDownList runat="server" ID="uscV2" OnDropDownListSelectionChanged="ucListControl1_DropDownListSelectionChanged"
                    TextColumnName="Title" IdColumnName="ID" ListName="Channel" />
            </td>
            <td>
        </tr>
        <tr>
            <td>
                <font style='font-family: Calibri !important; font-size: 8pt !important; color: black !important;'>
                    F :</font></br><SAUserControl:SPDropDownList runat="server" ID="uscV1"
                        OnDropDownListSelectionChanged="ucListControl1_DropDownListSelectionChanged"
                        TextColumnName="Title" IdColumnName="ID" ListName="Topic" />
            </td>
        </tr>
        <tr>
            <td>
                <font style='font-family: Calibri !important; font-size: 8pt !important; color: black !important;'>
                    E : </font></br><SAUserControl:SPDropDownList runat="server" ID="uscV3"
                        OnDropDownListSelectionChanged="ucListControl1_DropDownListSelectionChanged"
                        TextColumnName="Name" IdColumnName="ID" ListName="SMEProfile" />
            </td>
        </tr>
    </table>
</asp:Panel>



UserControlABC.ascx.cs:

namespace NameSpace
{
    public partial class UserControlABC : UserControl
    {
        public bool Horizontal { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
          
        }

        protected void ucListControl1_DropDownListSelectionChanged(object sender, EventArgs e)
        {
            DropDownList ddlCurrent = (DropDownList)sender;
            string selectedID = ddlCurrent.SelectedValue;
            switch (((System.Web.UI.WebControls.ListControl)(sender)).Parent.Parent.ID)
            {
                case "A":
                    Response.Redirect(SPContext.Current.Web.Url + string.Format("/Pages/rets.aspx?ID={0}&Mode=Channel",selectedID));
                    break;
                case "B":
                    Response.Redirect(SPContext.Current.Web.Url + string.Format("/Pages/hyut.aspx?ID={0}&Mode=Topic", selectedID));
                    break;
                case "F":
                    Response.Redirect(SPContext.Current.Web.Url + string.Format("/Pages/kjil.aspx?ID={0}", selectedID));
                    break;
                case "C":
                    Response.Redirect(SPContext.Current.Web.Url + string.Format("/Pages/ghi.aspx?ID={0}&Mode=Channel",selectedID));
                    break;
                case "D":
                    Response.Redirect(SPContext.Current.Web.Url + string.Format("/Pages/mno.aspx?ID={0}&Mode=Topic", selectedID));
                    break;
                case "E":
                    Response.Redirect(SPContext.Current.Web.Url + string.Format("/Pages/abs.aspx?ID={0}", selectedID));
                    break;
            }
        }
    }
}




Now you can trap this event as per cases in which you have used it.
 

Thursday, October 18, 2012

How to insert an image, page, video or file in a SharePoint site Document Library through a feature.

Suppose you want to upload an image or any file on a site document library on feature activated. It will get uploaded on that gallery and then you can use this image path in your code. Now you can change image without changing its name and can change it. Steps are as follows:

Steps for adding an image in Document Library:

1.) First you need to open a SharePoint type project in Visual Studio 2010. Now add a new Module to project and name it as "SiteCollectionImages" and within it. Now add a new folder within this module and rename this folder as "Document Library Name". Put this image inside this folder.

2.) Now in Elements.xml file of module and made elements.xml file entry should be like this :

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module  Name="SiteCollectionImages" Url="SiteCollectionImages" >
      <File Path="
Document Library Name/Default.jpg" Url="Default.jpg" Type="GhostableInLibrary" />
  </Module>
</Elements>


Here SiteCollectionImages is the Module Name and document library name is name of the doc lib in which you want to keep this image or file.

3.) Now right click on this particular image and select properties and in properties select its Deployment Location. In deployment location path should be like this "Document Library Name/". Now save it.

4.) Now activate the feature added by default and this image will be uploaded into your doc library. You can upload any static file (which do cont contains code) like this and then use it across SharePoint site.



Wednesday, October 17, 2012

How to add all different type of columns to a sharepoint 2010/2007 list and views.

This post will tell that how to add different types of columns to a SharePoint List and its views 2007/2010 through code. It will tell how to add all  kinds of columns in an already existing list and also their views. You can put this code inside a feature or in whatever context you need it :

Adding a Single Line of Text column :


private static void AddSingleLineOfTextFieldToList(SPList objSPList, string FieldName)
        {
            if (objSPList != null)
            {
                if (!objSPList.Fields.ContainsField(FieldName))
                {
                    objSPList.Fields.Add(FieldName, SPFieldType.Text, false);
                }
            }
        }

Adding a Multiple Line of Text column : 

 private static void AddMultipleLineOfTextFieldToList(SPList objSPList, string FieldName)
        {
            if (objSPList != null)
            {
                if (!objSPList.Fields.ContainsField(FieldName))
                {
                    objSPList.Fields.Add(FieldName, SPFieldType.Note, false);
                }
            }
        }

Adding a Rich Text Type of  column :

private static void AddRichTextFieldToList(SPList objSPList, string FieldName)
        {
            if (objSPList != null)
            {
                if (!objSPList.Fields.ContainsField(FieldName))
                {
                    objSPList.Fields.Add(FieldName, SPFieldType.Note, true);
                    SPFieldMultiLineText field = (SPFieldMultiLineText)objSPList.Fields[FieldName];
                    field.RichText = true;
                    field.RichTextMode = SPRichTextMode.Compatible;
                    field.Update();
                }
            }
        }


Adding a Calculated Type of Column :

 private static void AddCalculatedFieldToList(SPList objSPList, string FieldName, string Formula, SPFieldType OutputType)
        {
            if (objSPList != null)
            {
                if (!objSPList.Fields.ContainsField(FieldName))
                {
                    objSPList.Fields.Add(FieldName, SPFieldType.Calculated, false);
                    SPFieldCalculated CalcField = (SPFieldCalculated)objSPList.Fields[FieldName];
                    CalcField.OutputType = OutputType;
                    CalcField.Formula = Formula;
                    CalcField.Update();
                }
            }
        }

Adding a DateTime Type column:

private static void AddDateTimeColumn(SPList objSPList, string columnName)
        {
            if (objSPList != null && columnName != null)
            {
                if (!objSPList.Fields.ContainsField(columnName))
                {
                    /* add a new choice field */
                    objSPList.Fields.Add(columnName, SPFieldType.DateTime, false);
                    objSPList.Update();
                    /* get the newly added choice field instance */
                    SPFieldDateTime objSPField = (SPFieldDateTime)objSPList.Fields[columnName];
                    objSPField.DisplayFormat = SPDateTimeFieldFormatType.DateTime;
                    objSPField.Update();
                    /* finally update list */
                    objSPList.Update();
                }
            }
        }

Adding a People and Group Type of Column :

private static void AddPeopleandGroupColumnToList(SPWeb objSPWeb, string listName, string columnName)
        {
            if (objSPWeb != null)
            {
                SPList objSPList = objSPWeb.Lists[listName];
                if (objSPList != null && (!string.IsNullOrEmpty(columnName)))
                {
                    if (!objSPList.Fields.ContainsField(columnName))
                    {
                        objSPList.Fields.Add(columnName, SPFieldType.User, false);
                        SPFieldUser userField = (SPFieldUser)objSPList.Fields[columnName];
                        userField.LookupField = "Name";
                        userField.Update();
                        objSPList.Update();
                        AddFieldToListDefaultView(objSPList, columnName);
                    }
                }
            }
        }

Adding a Choice Field Type of Columns:  

private static void AddChoiceColumn(SPList objSPList, string columnName, StringCollection strChoices, string defaultValue)
        {
            if (objSPList != null && columnName != null)
            {
                if (!objSPList.Fields.ContainsField(columnName))
                {
                    /* add a new choice field */
                    objSPList.Fields.Add(columnName, SPFieldType.Choice, false);
                    objSPList.Update();
                    /* get the newly added choice field instance */
                    SPFieldChoice objSPField = (SPFieldChoice)objSPList.Fields[columnName];
                    /* set field format type i.e. radio / dropdown */
                    objSPField.EditFormat = SPChoiceFormatType.Dropdown;
                    /* set the choice strings and update the field */
                    if (strChoices.Count > 0)
                    {
                        for (int iCounter = 0; iCounter < strChoices.Count; iCounter++)
                        {
                            objSPField.Choices.Add(strChoices[iCounter]);
                        }
                    }
                    objSPField.DefaultValue = defaultValue;
                    objSPField.Update();
                    /* finally update list */
                    objSPList.Update();
                }
            }
        }

Add a LookUp Type of column :

private static void AddLookUpColumn(SPWeb objSPWeb, SPList objSPList, string LookupSourceListName, string columnName, string sourceColumnName)
        {
            if (objSPWeb != null)
            {
                /*create lookup type new column called "Lookup Column"*/
                SPList objLookupSourceList = objSPWeb.Lists[LookupSourceListName];
                if (!objSPList.Fields.ContainsField(columnName))
                {
                    objSPList.Fields.AddLookup(columnName, objLookupSourceList.ID, false);
                    SPFieldLookup lkp = (SPFieldLookup)objSPList.Fields[columnName];
                    lkp.LookupField = objLookupSourceList.Fields[sourceColumnName].InternalName;
                    lkp.Update();
                }
            }
        }

Add a Column to particular List View

private static void AddColumnToView(SPList objSPList string ViewName, string columnName)
        {
            if (objSPList != null && columnName != null)
            {
                if (objSPList.Views[ViewName] != null)
                {
                    SPView objSPListCatalogView = objSPList.Views[ViewName];
                    if (!objSPListView.ViewFields.Exists(columnName))
                    {
                        objSPListView.ViewFields.Add(columnName);
                        objSPListView.Update();
                    }
                    objSPList.Update();
                }
            }
        }

In this way you will be able to add all type of columns and then them to view of a SharePoint List. All you need to do is to add these methods in your and pass asked parameter.

Wednesday, August 1, 2012

Batch Update and Delete in SharePoint List based on conditions.

Here I am going to give you an example that how can you use batch update and batch delete is SharePoint List programmatically. It deletes all selected items as per given query and list name. It is so time efficient in comparison to delete or update them one by them.

For Updating Items :

public void BatchUpdateOfColumn(SPWeb objSPWeb, string listName, string Query, string ValueToUpdate)
        {
            if (objSPWeb != null)
            {
                // Set up the variables to be used.
                StringBuilder methodBuilder = new StringBuilder();
                string batch = string.Empty;

                string batchFormat = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                  "<ows:Batch OnError=\"Return\">{0}</ows:Batch>";

                string methodFormat = "<Method ID=\"{0}\">" +
                 "<SetList>{1}</SetList>" +
                 "<SetVar Name=\"Cmd\">Save</SetVar>" +
                 "<SetVar Name=\"ID\">{2}</SetVar>" +
                 "<SetVar Name=\"urn:schemas-microsoft-com:office:office#Exclude\">{3}</SetVar>" +
                 "</Method>";

                // Get the list containing the items to update.
                if (listName != null)
                {
                    SPList list = objSPWeb.Lists[listName];
                    if (list != null)
                    {
                        string listGuid = list.ID.ToString();
                        // Query to get the unprocessed items.
                        SPQuery query = new SPQuery();
                        query.Query = Query;
                        query.ViewAttributes = "Scope='Recursive'";
                        SPListItemCollection unprocessedItems = list.GetItems(query);
                        // Build the CAML update commands.
                        for (int i = 0; i < unprocessedItems.Count; i++)
                        {
                            int itemID = unprocessedItems[i].ID;
                            methodBuilder.AppendFormat(methodFormat, itemID, listGuid, itemID, ValueToUpdate);
                         }

                        // Put the pieces together.
                        batch = string.Format(batchFormat, methodBuilder.ToString());

                        // Process the batch of commands.
                        string batchReturn = objSPWeb.ProcessBatchData(batch);
                    }
                }
            }
          }

For Deleting  Items:

 public static void DeleteItemUsingBatch(string strUrl)
        {
            using (SPSite site = new SPSite(strUrl))
            {
                SPWeb web = site.OpenWeb();
                web.AllowUnsafeUpdates = true;
                SPList list = web.Lists["List Name"];
                SPQuery query = new SPQuery();
                query.Query = "<Where><And><IsNull><FieldRef Name='Coulmn1' /></IsNull><IsNull><FieldRef Name='Coulmn2' /></IsNull></And></Where>"; // Query as per need.
                query.ViewAttributes = "Scope='Recursive'"; // Because items are within different folders.
                SPListItemCollection listItem = list.GetItems(query);
                StringBuilder sbDelete = new System.Text.StringBuilder();
                sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
                string command = "<Method><SetList Scope=\"Request\">" + list.ID + "</SetList>" +
                    "<SetVar Name=\"ID\">{0}</SetVar>" +
                    "<SetVar Name=\"Cmd\">Delete</SetVar></Method>";
                foreach (SPListItem item in listItem)
                {
                    sbDelete.Append(String.Format(command, Convert.ToString(item.ID)));
                }
                sbDelete.Append("</Batch>");
                web.ProcessBatchData(sbDelete.ToString());
            }
        }