Showing posts with label SharePoint Code. Show all posts
Showing posts with label SharePoint Code. Show all posts

Thursday, 20 March 2014

Get the size of folder and Get Number Of Files In Folder in SharePoint


1. This method is used to get the size of folder in SharePoint


        private static long GetFolderSize(SPFolder folder)
        {
            long folderSize = 0;
            foreach (SPFile file in folder.Files)
            {
                folderSize += file.Length;
            }
            foreach (SPFolder subfolder in folder.SubFolders)
            {
                folderSize += GetFolderSize(subfolder);
            }
            return folderSize;
        }

2. This method is used to Get Number Of Files In Folder in SharePoint

        private static int GetNumberOfFilesInFolder(SPFolder folder)
        {
            int folderNum = 0;
            foreach (SPFile file in folder.Files)
            {
                folderNum += 1;
            }
            foreach (SPFolder subfolder in folder.SubFolders)
            {
                folderNum += GetNumberOfFilesInFolder(subfolder);
            }
            return folderNum;
        }

Tuesday, 28 January 2014

Show the loading message like (Please wait, Item is being launched for all active Employees .....) when click on button




<asp:Button runat="server" ID="btnLaunch" Text="Launch" Width="120px" OnClick="btnLaunch_Click" ValidationGroup="LaunchFields" CssClass="btnwidth" OnClientClick="OpenLoadingAlert();" />




<script type="text/javascript">
    function OpenLoadingAlert() {
        Page_ClientValidate();
        if (Page_IsValid) {
            SP.UI.ModalDialog.showWaitScreenWithNoClose('Loading...', 'Please wait, Item is being launched for all active Employees ..... ', 60, 270);
        }
    }
</script>



Tuesday, 24 December 2013

People Picker control

People Picker control below User Interface :


Add below CSS
 .ms-inputuserfield
{
font-size: 8pt;
font-family: Verdana,sans-serif;
border: 1px solid #a5a5a5;
}
div.ms-inputuserfield a
{
color: #000000;
text-decoration: none;
font-weight: normal;
font-style: normal;
}
div.ms-inputuserfield
{
padding-left: 1px;
padding-top: 2px;
}




Ascx controlCoding :à

<SharePoint:PeopleEditor ID="peopleEditorRelegationDetailsSharedBy" runat="server"
AllowEmpty="true" SelectionSet="User" Width="400px" MultiSelect="false" validationgroup="Tr"
ValidatorEnabled="true" BorderColor="Black" BorderWidth="0px" />


.cs Coding :à
if (peopleEditorRelegationDetailsSharedBy.ResolvedEntities.Count> 0)
                 {
peopleEditorRelegationDetailsSharedBy.Validate();

if (peopleEditorRelegationDetailsSharedBy.IsValid)
                     {
RelegationDetailsSharedBy = peoplePickerData();
peoplepickervalue = true;
                     }                 

                 }
else
                 {
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg", "alert('There are no recipients in Relegation Details SharedBy by')", true);
                 }



public string peoplePickerData()
        {
            #region Relegated By People Picker
stringSharedBy = string.Empty;
stringSharedByEmail = "";
if (peopleEditorRelegationDetailsSharedBy.Entities.Count> 0)
            {
for (inti = 0; i<peopleEditorRelegationDetailsSharedBy.ResolvedEntities.Count; i++)
                {
PickerEntity picker = (PickerEntity)peopleEditorRelegationDetailsSharedBy.ResolvedEntities[i];
if (peopleEditorRelegationDetailsSharedBy.Accounts[i].ToString().Contains("GOINDIGO"))
                    {
if (SharedBy == string.Empty)
SharedBy = peopleEditorRelegationDetailsSharedBy.Accounts[i].ToString().Split('\\')[1];
else
SharedBy = SharedBy + "," + peopleEditorRelegationDetailsSharedBy.Accounts[i].ToString().Split('\\')[1];
                    }                  
Hashtable hash = picker.EntityData;
stringstrRecEmail = Convert.ToString(hash["Email"]);
SharedByEmail += strRecEmail;
                }
            }
returnSharedByEmail;
            #endregion
        }

Sunday, 22 December 2013

Export To Excel in SharePoint 2010

SharePoint postback to work after clicking on export to excel button
<asp:ImageButton ID="imagbtnExportToExcel" runat="server" 
                                ImageUrl="~/_layouts/images/CrewRelegationTracker/Excel.PNG" Width="35px" 
                                onclick="imagbtnExportToExcel_Click"  />



  protected void Page_Load(object sender, EventArgs e)
        {
            imagbtnExportToExcel.OnClientClick = "_spFormOnSubmitCalled = false;_spSuppressFormOnSubmitWrapper=true;";
}
  OR

You can use below script code if above code not working for postback to work after clicking on export to excel in sharepoint 2010

<script type="text/javascript" language="javascript">
    //sharepoint postback to work after clicking on export to excel button
    if (typeof (_spBodyOnLoadFunctionNames) != 'undefined' &&
                                           _spBodyOnLoadFunctionNames != null) {
        _spBodyOnLoadFunctionNames.push("supressSubmitWraper");
    }
    function supressSubmitWraper() {
        _spSuppressFormOnSubmitWrapper = true;
    }
</script>



  protected void imagbtnExportToExcel_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                DataTable dtExportData = new DataTable();
                var btnIDFlag = ((ImageButton)sender).ID;
                if (btnIDFlag == "imagbtnExportToExcel")
                    dtExportData = (DataTable)ViewState["PageIndexData"];
                else
                    dtExportData = (DataTable)ViewState["FinalCrewEntitlmentDetails"];
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.ClearHeaders();
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.ContentType = "application/ms-excel";
                HttpContext.Current.Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");

                if (btnIDFlag == "imagbtnExportToExcel")

                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=CrewRelegationTracker.xls");
                else
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=CrewRelegationTracker.xls");

                HttpContext.Current.Response.Charset = "utf-8";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
                HttpContext.Current.Response.Write("<font style='font-size:10.0pt; font-family:Calibri;'>");
                HttpContext.Current.Response.Write("<BR><BR><BR>");
                HttpContext.Current.Response.Write("<Table border='1' bgColor='#ffffff' " +
                  "borderColor='#000000' cellSpacing='0' cellPadding='0' " +
                  "style='font-size:10.0pt; font-family:Calibri; background:white;'>");

                int columnscount = dtExportData.Columns.Count;
                HttpContext.Current.Response.Write("<TR>");
                for (int j = 0; j < columnscount; j++)
                {
                    HttpContext.Current.Response.Write("<Td style='background-color:#99CCCC'>");
                    HttpContext.Current.Response.Write("<B>" + dtExportData.Columns[j].ColumnName + "</B>");
                    HttpContext.Current.Response.Write("</Td>");
                }
                HttpContext.Current.Response.Write("</TR>");
                foreach (DataRow row in dtExportData.Rows)
                {
                    HttpContext.Current.Response.Write("<TR>");
                    for (int i = 0; i < dtExportData.Columns.Count; i++)
                    {
                        HttpContext.Current.Response.Write("<Td>");
                        HttpContext.Current.Response.Write(row[i].ToString());
                        HttpContext.Current.Response.Write("</Td>");
                    }
                    HttpContext.Current.Response.Write("</TR>");
                }
                HttpContext.Current.Response.Write("</Table>");
                HttpContext.Current.Response.Write("</font>");
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
            }
            catch (Exception ex)
            {
                objLogger.LogExceptions(ex, "btnSearch_Click");
                //Page.ClientScript.RegisterStartupScript(this.GetType(), "refresh", "ErrorMessage();", true);
            }
        }

Wednesday, 2 October 2013

SP.UI.ModalDailog on Client and Server side in SharePoint 2010

1.Open Alert with SharePoint ~ SP.UI.ModalDialog.showModalDialog


.ascx page

   function OpenWindow(title, url) {

        var html = document.createElement('h1');
        html.innerHTML = 'Thanks for your valuable suggestion.';
        var options = {
            html: html,
            title: title
        };
        SP.UI.ModalDialog.showModalDialog(options);
        //return false;
    }   


 <asp:ImageButton OnClick="imgbtnSend_Click" ID="imgbtnSend" runat="server" ImageUrl="~/_layouts/AlumniFBAPortal/images/proSend.jpg" />


Server side

  protected void imgbtnSend_Click(object sender, ImageClickEventArgs e)
        {

            StringBuilder sb = new StringBuilder(); 
            sb.Append("ExecuteOrDelayUntilScriptLoaded(function () {");
            sb.Append(string.Format("OpenWindow('Suggestion','{0}');", url)); 
            sb.Append("}, \"sp.js\");"); 

            Page.ClientScript.RegisterStartupScript(this.GetType(), "keyOpenMonPopUp", sb.ToString(), true); 
}   



2. open ModalPopUp Dialog on server side in SharePoint 2010

 <script type="text/javascript">
 function OpenWebPage(title, url) {
var options = {url: url,
title: title,
width: 600,
height: 400,
dialogReturnValueCallback: DialogCallback
};
SP.UI.ModalDialog.showModalDialog(options);
}

function DialogCallback(dialogResult, returnValue) {meesageId = SP.UI.Notify.addNotification(returnValue,
false);}

</script>

<table width="901px" border="0" align="left" cellpadding="0" cellspacing="0" style="background-color: White;"><tr><td colspan="5" align="left" style="height: 5px;"><input type="button" value="Open Modal Popup Dialog"id="btnAddVendors" onclientclick="return OpenModalPopupDialog('Growth Remarks Page','/_Layouts/GrowthApp/MyPage.aspx');"/><asp:Button ID="btnAddVendors" runat="server" Text="Add Vendors" CausesValidation="false"ToolTip="Click here to Add Vendor" />
</td></tr></table>

on the class.cs file 

btnAddVendors.Attributes.Add("onclick", "return OpenModalPopupDialog('Edit Vendor','/_Layouts/GrowthApp/MyPage.aspx'')");




3.Open model dialog onClientclick event i SharePoint 2010



4.Refresh parent page when model dialog page is opened

When you want to refresh the parent page when user clicks on OK button on dialog page that you open from the parent page then you can use SP.UI.ModalDialog.RefreshPage

Usually we write this code in dialogReturnCallBack function.


       dialogReturnValueCallback: function(dialogResult) 
        { 
          SP.UI.ModalDialog.RefreshPage(dialogResult) 
        }

Saturday, 31 August 2013

List Operation

Attach File/Document to List Item programmatically in SharePoint 2010 using C#

        public  int AddNewItemWithAttachment()
        {
             // Get name of the file 
            string _Str_File_Name = fuAttachment.PostedFile.FileName;
           //  Get stream data by following way
            byte[] contents = GetFileStream();

           // Declare variable which hold the newly created item id.
            int _Int_ID = 0;

           //  Follow the steps to insert new item into your sharepoint list with attachment. 
           //  Create new instance of site with your current application
            using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
            { 
            //  Create new web instance and open web for current application
                using (SPWeb web = site.OpenWeb())
                { 
                   //  Create new list object and get your list
                    SPList list = web.Lists["EmployeeList"]; 
                   //  Set allowunsafeupdates for web & site to true
                    site.AllowUnsafeUpdates = true;
                    web.AllowUnsafeUpdates = true; 
                   //  Create new list item object and add new item for newly created list object 
                    SPListItem item = list.Items.Add();
                    // Assign value for newly created item
                    item["Title"] = txtFirstName.Text.Trim();
                    item["FirstName"]  = txtFirstName.Text.Trim();
                    item["LastName"]  = txtLastName.Text.Trim();
                    item["Address"]  = txtAddress.Text.Trim();
                    item["Phone"]  = txtPhone.Text.Trim();
                    item["City"]  = txtCity.Text.Trim();
                    item["State"]  = txtState.Text.Trim();
                    item["Country"] = txtCountry.Text.Trim();     
                    //- Assign selected filename and stream data
                    if (!string.IsNullOrEmpty(_Str_File_Name) && (contents.Length > 0))
                    {
                    SPAttachmentCollection fileAttach = item.Attachments;
                    fileAttach.Add(_Str_File_Name, contents );
                    }
                   //  Update item which will add new item to list
                    item.Update();
                    // if you want to manipulate on newly created item then you can get id of the newly created item by following way
                  // return the ID
                   return  _Int_ID = item.ID;
                }
            }        

        }

Add  Attach File/Document to List Item By ListItemID programmatically in SharePoint 2010 using C#

        public void attachmentbylistid(int ItemId)
        {
            using (SPSite _site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb _web = _site.OpenWeb())
                {
                    // for testing Let's suppose your Item Id is 1
                  // int ItemId = 1;
                    SPList oList = _web.Lists["EmployeeList"];
                    SPListItem _item = oList.GetItemById(ItemId);
                    if (fileUpload.HasFile)
                    {
                        _web.AllowUnsafeUpdates = true;
                        Stream fs = fileUpload.PostedFile.InputStream;
                        byte[] _bytes = new byte[fs.Length];
                        fs.Position = 0;
                        fs.Read(_bytes, 0, (int)fs.Length);
                        fs.Close();
                        fs.Dispose();

                        _item.Attachments.Add(fileUpload.PostedFile.FileName, _bytes);
                        _item.Update();
                        _web.AllowUnsafeUpdates = false;
                    }
                }
            }

        }


Delete the Attach File/Document to List Item programmatically in SharePoint 2010 using C#

// pass ListItem ID , File name
        private void DeleteAttachment(int NodeID, String strFileName)
        {
            SPContext.Current.Web.AllowUnsafeUpdates = true;
            SPList List = SPContext.Current.Web.Lists["EmployeeList"];
            SPListItem delItem = List.GetItemById(NodeID);
            SPAttachmentCollection atCol = delItem.Attachments;
            foreach (string strDelfileName in atCol)
            {
                if (strDelfileName == strFileName)
                {
                    atCol.Delete(strDelfileName);
                    delItem.Update();
                    return;
                }
            }

        }


Add new Items into List programmatically in SharePoint 2010 using C#
        private void AddListItem()
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["EmployeeList"];
                    web.AllowUnsafeUpdates = true;
                    SPListItem item = list.Items.Add();
                    item["Title"] = txtFirstName.Text.Trim();
                    item["FirstName"] = txtFirstName.Text.Trim();
                    item["LastName"] = txtLastName.Text.Trim();
                    item["Address"] = txtAddress.Text.Trim();
                    item["Phone"] = txtPhone.Text.Trim();
                    item["City"] = txtCity.Text.Trim();
                    item["State"] = txtState.Text.Trim();
                    item["Country"] = txtCountry.Text.Trim();
                    item.Update();
                    web.AllowUnsafeUpdates = false;
                }
            }
        }


Update List Items By ListItemID  into List programmatically in SharePoint 2010 using C#

        public void UpdateListItem(int _ListItemID)
        {
            using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    SPList list = web.Lists["EmployeeList"];    
                    SPQuery _Query = new SPQuery();
                    _Query.Query = string.Format("<Where><Eq><FieldRef Name='ID' /><Value Type='Counter' >{0}</Value> </Eq> </Where>", _ListItemID); 
                    
                    //- Assign query to list and get item on the basis of the query build above
                    SPListItemCollection common = list.GetItems(_Query);
                    // Assign value for newly created item
                    if (common.Count > 0)
                    {
                        web.AllowUnsafeUpdates = true;
                        //Get first list item from the result list
                        SPListItem item = common[0];
                        item["Title"] = txtFirstName.Text.Trim();
                        item["FirstName"] = txtFirstName.Text.Trim();
                        item["LastName"] = txtLastName.Text.Trim();
                        item["Address"] = txtAddress.Text.Trim();
                        item["Phone"] = txtPhone.Text.Trim();
                        item["City"] = txtCity.Text.Trim();
                        item["State"] = txtState.Text.Trim();
                        item["Country"] = txtCountry.Text.Trim();
                        item.Update();
                        web.AllowUnsafeUpdates = false;
                    }                    
                }
            }
        }

Delete List Items By ListItemID into List programmatically in SharePoint 2010 using C#

        public void DeleteListItem(int _ListItemID)
        {
            using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    SPList list = web.Lists["EmployeeList"];
                    SPQuery _Query = new SPQuery();
                    _Query.Query = string.Format("<Where><Eq><FieldRef Name='ID' /><Value Type='Counter' >{0}</Value> </Eq> </Where>", _ListItemID);

                    //- Assign query to list and get item on the basis of the query build above
                    SPListItemCollection common = list.GetItems(_Query);
                    // Assign value for newly created item
                    if (common.Count > 0)
                    {
                        //- Set allowunsafeupdates for web to true
                        web.AllowUnsafeUpdates = true; 
                        //- Delete selected item from fetched list 
                        common[0].Delete(); 
                        //- Update item which will add new item to list
                        web.Update(); 
                    }
                }
            }

        }





      Get SharePoint List Item by ID

        private void GetListItembyID(int ItemID)
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["EmployeeList"];
SPListItem Item = list .GetItemById(ItemID);
Response.Write("Item Title: " + Item["Title"].ToString());
               }
          }
      }

Deleting Multiple Versions of a List Item

When you delete multiple versions of a list item, use the DeleteByID method; do not use the Delete method. You will experience performance problems if you delete each SPListItemVersion object from an SPListItemVersionCollection object. The recommended practice is to create an array that contains the ID properties of each version and then delete each version by using the SPFileVersionCollection.DeleteByID method. The following code examples demonstrate both the approach that is not recommended and the recommended approach to deleting all versions of the first item of a custom list.
Good Coding Practice
Deleting each version of a list item by using the SPFileVersionCollection.DeleteByID method
SPSite site = new SPSite("site url");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["custom list name"];
SPListItem item = list.GetItemById(1);
SPFile file = web.GetFile(item.Url);
SPFileVersionCollection collection = file.Versions;
ArrayList idList = new ArrayList();
foreach (SPFileVersion ver in collection)
{  idList.Add(ver.ID);
}foreach (int verID in idList)
{try{
  collection.DeleteByID(verID);
}catch (Exception ex)
{  MessageBox.Show(ex.Message); 
}}
If you are deleting versions of items in a document library, you can use a similar approach by retrieving the SPListItem.File.Versions property.