Friday 29 November 2013

Programmatically Create Subsite in SharePoint using c#



 private void CreateSubSites(string parentSiteURL, string siteURLRequested, string siteTitle, string siteTemplateName)
        {
            const Int32 LOCALE_ID_ENGLISH = 1033;
            string newSiteURL = string.Empty;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite siteCollection = new SPSite(parentSiteURL))
                {
                    using (SPSite site = new SPSite(parentSiteURL))
                    {
                        using (SPWeb parentWeb = site.OpenWeb())
                        {
                            SPWebTemplateCollection Templates = parentWeb.GetAvailableWebTemplates(Convert.ToUInt32(LOCALE_ID_ENGLISH));
                            SPWebTemplate siteTemplate = Templates[siteTemplateName];
                            //create subsite
                            using (SPWeb newSite = parentWeb.Webs.Add(siteURLRequested, siteTitle, "", Convert.ToUInt32(LOCALE_ID_ENGLISH), siteTemplate, false, false))
                            {
                                if (!string.IsNullOrEmpty(newSite.Url))
                                    newSiteURL = newSite.Url.ToString();
                            }
                        }
                    }
                }
            });
        }

Example:-
            CreateSubSites(SPContext.Current.Site.Url, "Services", "Services", "STS#0");
Continue Reading...

programmatically reterive item from sharepointlist using caml query in sharepoint


            SPSite mySite = new SPSite(SPContext.Current.Site.ID);
            SPWeb myWeb = mySite.OpenWeb();
            SPList myList = myWeb.Lists["ListName"];
            SPQuery query = new SPQuery();
            string CurrentDate = DateTime.Now.ToString("yyyy-MM-dd");
            query.Query = "<Where><Eq><FieldRef Name=\"DOB\" /><Value IncludeTimeValue=\"FALSE\" Type=\"DateTime\">" + CurrentDate + "</Value></Eq></Where>";
            query.RowLimit = 10;
            SPListItemCollection items = myList.GetItems(query);
            DataTable dt = items.GetDataTable();
Continue Reading...

get last list item id in sharepoint list using c#


            SPSite oSPsite = new SPSite(SPContext.Current.Site.ID);
            SPWeb oSPWeb = oSPsite.OpenWeb();
            SPList list = oSPWeb.Lists["ListName"];
             SPQuery query = new SPQuery();
                    query.RowLimit = 1;
                    query.Query = "<OrderBy><FieldRef Name='ID' Ascending='FALSE'/></OrderBy>";
                    SPListItem maxItem = list.GetItems(query).Cast<SPListItem>().FirstOrDefault();
                    int lastItemId = -1;
                    if (maxItem != null)
                    {
                        lastItemId = maxItem.ID;
                    }

Continue Reading...

Programmaticaly Add user in sharepoint list using c#

           SPSite oSPsite = new SPSite(SPContext.Current.Site.ID);
            SPWeb oSPWeb = oSPsite.OpenWeb();
            SPList list = oSPWeb.Lists["user"];
            SPListItem oSPListItem = list.Items.Add();
            SPFieldUserValueCollection userCollection = new SPFieldUserValueCollection();
            userCollection = UserValidation(oSPWeb, "DomainName/UserName");
            oSPListItem["Title"] = "Mohamed sithik";
            oSPListItem["UserName"] = userCollection;
            oSPListItem.Update();


  private SPFieldUserValueCollection UserValidation(SPWeb web, string Users)
        {
            SPFieldUserValueCollection userCollection = new SPFieldUserValueCollection();
            string FormatedUsers = string.Empty;
            string[] UserArray = Users.Split(';');
            foreach (string sUser in UserArray)
            {
                SPUser user = null;
                try
                {
                    user = web.AllUsers[sUser];
                }
                catch { }
                if (user == null)
                {
                    try
                    {
                        web.AllUsers.Add(sUser, "", sUser, "");
                        web.Update();
                        user = web.AllUsers[sUser];
                    }
                    catch { }
                }
                if (user != null)
                {
                    userCollection.Add(new SPFieldUserValue(web, user.ID, user.LoginName));
                }
            }
            return userCollection;
        }
Continue Reading...

Programmaticaly Add multi user in sharepoint list using c#


 DataTable table = new DataTable();
            table.Columns.Add("Title", typeof(string));
            table.Columns.Add("UserName", typeof(string));
            table.Rows.Add( "Mohamedsithik","User1");
            table.Rows.Add("Raja", "User2");
            table.Rows.Add("Uthaya", "User3");
            table.Rows.Add("Elamaran", "User4");
            SPSite mySite = new SPSite(SPContext.Current.Site.ID);
            SPWeb myWeb = mySite.OpenWeb();
            SPList myList = myWeb.Lists["User"];
            string MultiUser = string.Empty;
            for (int i = 0; i < table.Rows.Count; i++)
            {
                DataRow row = table.Rows[i];
                string Mem = Convert.ToString(row["UserName"]);
                if (MultiUser != string.Empty)
                {
                    MultiUser = MultiUser + "," + Mem;
                }
                else
                {
                    MultiUser = Mem;
                }
            }
            SPListItem oSPListItem = myList.Items.Add();
            SPFieldUserValueCollection usercollection = new SPFieldUserValueCollection();
            string[] userarray = MultiUser.Split(',');
            for (int i = 0; i < userarray.Length; i++)
            {
                SPFieldUserValue usertoadd = ConvertLoginName(userarray[i]);
                usercollection.Add(usertoadd);
            }
            oSPListItem["Title"] = "Add MultiUser";
            oSPListItem["UserName"] = usercollection;
            oSPListItem.Update();

public SPFieldUserValue ConvertLoginName(string userid)
        {
            SPSite oSPsite = new SPSite(SPContext.Current.Site.ID);
            SPWeb oSPWeb = oSPsite.OpenWeb();
            SPUser requireduser = oSPWeb.EnsureUser(userid);
            SPFieldUserValue uservalue = new SPFieldUserValue(oSPWeb, requireduser.ID, requireduser.LoginName);
            return uservalue;
        }
Continue Reading...

Wednesday 27 November 2013

Programmatically get people picker value from sharepoint list using C#


                   
string users = string.Empty;
SPFieldUserValueCollection userCol = new SPFieldUserValueCollection(SPContext.Current.Web, listItem["SiteOwner"].ToString());
foreach (SPFieldUserValue usrItm in userCol)
  {
  users += usrItm.User.ToString() + ",";
  }
   this.spPeoplePicker.CommaSeparatedAccounts = users.Remove(users.LastIndexOf(","), 1);
Continue Reading...

programmatically upload document library file in SharePoint 2013 with meta data using c#

string fileNameonly = Fileupload1.FileName;  // Only file name.

 private byte[] ToByteArray(Stream inputStream)
        {
            using (MemoryStream ms = new MemoryStream())
            {

                inputStream.CopyTo(ms);
                return ms.ToArray();
            }

        }

private void AddFileToDocumentLibrary(string documentLibraryUrl, string filename, string Title)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(documentLibraryUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        Stream StreamImage = null;
                        if (Fileupload1.HasFile)
                        {
                            StreamImage = Fileupload1.PostedFile.InputStream;
                        }
                        byte[] file_bytes = ToByteArray(StreamImage);
                        web.AllowUnsafeUpdates = true;
                        SPDocumentLibrary documentLibrary = (SPDocumentLibrary)web.Lists["DocumentLibraryName"];
                        SPFileCollection files = documentLibrary.RootFolder.Files;
                        SPFile newFile = files.Add(documentLibrary.RootFolder.Url + "/" + filename, file_bytes, true);
                        SPList documentLibraryAsList = web.Lists["DocumentLibraryName"];
                        SPListItem itemJustAdded = documentLibraryAsList.GetItemById(newFile.ListItemAllFields.ID);
                        SPContentType documentContentType = documentLibraryAsList.ContentTypes["Document"]; //amend with your document-derived custom Content Type
                        itemJustAdded["ContentTypeId"] = documentContentType.Id;
                        itemJustAdded["Title"] = Title;
                        itemJustAdded.Update();
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });
        }
Continue Reading...

Thursday 21 November 2013

sharepoint custom attachement upload control with example

                        sharepoint custom attachement upload control with example 

Design Code:-

<table> <tr><td>
<asp:HiddenField Value="hDeleteAttachs" ID="hHiddenFields" runat="server" />
</td></tr>
<tr>
<td><span id="part1">
<SharePoint:AttachmentButton runat="server" ID="btnAttach" ControlMode="new" Text="Add Attachment">
</SharePoint:AttachmentButton> </span></td></tr>
<tr><td id='idAttachmentsRow'>
<SharePoint:AttachmentUpload runat="server" ID="uploadAttach" ControlMode="New">
</SharePoint:AttachmentUpload></td></tr>

<tr><td><SharePoint:AttachmentsField runat="server" ID="fieldAttach" ControlMode="new" FieldName="Attachments">
</SharePoint:AttachmentsField></td></tr>
</table>
<asp:Button ID="submitButton" runat="server" Text="Submit" OnClick="submitButton_Click" />
Cs Code:-

SPSite Objsite = null;
SPWeb Objweb = null;
SPSite noprevsite = null;
SPWeb noprevweb = null;
SPList Olist = null;
SPListItem Osplistitem = null;
protected void Page_Load(object sender, EventArgs e)
{
noprevsite = SPContext.Current.Site;
noprevweb = noprevsite.OpenWeb();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
Objsite = new SPSite(noprevsite.ID);
Objweb = Objsite.OpenWeb(noprevweb.ID);
Objweb.AllowUnsafeUpdates = true;
Olist = Objweb.Lists["Users"];
btnAttach.ListId = Olist.ID;
uploadAttach.ListId = Olist.ID;
fieldAttach.ListId = Olist.ID;
Osplistitem = Olist.Items.Add();
});
}
protected void submitButton_Click(object sender, EventArgs e)
{

SPWeb mySite = SPContext.Current.Web;
SPList myList = mySite.Lists["Users"];
SPListItem myListItem = myList.Items.Add();
myListItem["Title"] = "myTitle";
if (HttpContext.Current.Request.Files.Count > 0)
{
HttpFileCollection uploads = HttpContext.Current.Request.Files;
SPAttachmentCollection attachments;
for (int i = 0; i < uploads.Count; i++)
{
Stream fs = uploads[i].InputStream;
byte[] fileContents = new byte[fs.Length];
fs.Read(fileContents, 0, (int)fs.Length);
fs.Close();
attachments = myListItem.Attachments;
string fileName = Path.GetFileName(uploads[i].FileName);
attachments.Add(fileName, fileContents);
}
myListItem.Update();
}
}

Continue Reading...

Select Insert update delete SharePoint custom list data using CSOM C# Example

public class EmpInfo
        {
            public EmpInfo(string Name, string Age)
            {
                _Name = Name;
                _Age = Age;
            }
            private string _Name;
            private string _Age;
            public string Name
            {
                get { return _Name; }
                set { _Name = value; }
            }
            public string Age
            {
                get { return _Age; }
                set { _Age = value; }
            }
        }
public void getdata()
        {
            NetworkCredential credentials = new NetworkCredential("UserName", "Pwd ", "DomainName");
            List<EmpInfo> lsts = new List<EmpInfo>();
            ClientContext cc = new ClientContext("http://Abc:4000/sites/Rsite1/");
            cc.Credentials = credentials;
            Web web = cc.Web;
            List list = web.Lists.GetByTitle("Users");
            CamlQuery caml = new CamlQuery();
            ListItemCollection items = list.GetItems(caml);
            cc.Load<List>(list);
            cc.Load<ListItemCollection>(items);
            cc.ExecuteQuery();
            foreach (Microsoft.SharePoint.Client.ListItem item in items)
            {
                string Name = Convert.ToString(item.FieldValues["Name"]);
                string Age = Convert.ToString(item.FieldValues["Age"]);
                lsts.Add(new EmpInfo(Name, Age));
            }
            GridView1.DataSource = lsts;
            GridView1.DataBind();
        }
Insert item:-
            NetworkCredential credentials = new NetworkCredential("UserName", "Pwd ", "DomainName");
            ClientContext context = new ClientContext("http://Abc:4000/sites/Rsite1/");
            context.Credentials = credentials;
            Web web = context.Web;
            List list = web.Lists.GetByTitle("Users");
            ListItemCreationInformation newItem = new ListItemCreationInformation();
            ListItem listItem = list.AddItem(newItem);
            listItem["Name"] = "Mohamed";
            listItem["Age"] = "27";
            listItem.Update();
            context.ExecuteQuery();
Update Item:-
            NetworkCredential credentials = new NetworkCredential("UserName", "Pwd", "DomainName");
            ClientContext context = new ClientContext("http://Abc:4000/sites/Rsite1/");
            context.Credentials = credentials;
            List list = context.Web.Lists.GetByTitle("Users");
            CamlQuery query = new CamlQuery();
            query.ViewXml = "<View/>";
            ListItemCollection listItems = list.GetItems(query);
            context.Load(listItems);
            context.ExecuteQuery();
            ListItem item = listItems[0];
            item["Name"] = "Mohamed sithik...";
            item["Age"] = "26";
            item.Update();
            context.ExecuteQuery();
Delete Item:-
            NetworkCredential credentials = new NetworkCredential("UserName", "Pwd ", "DomainName");
            ClientContext context = new ClientContext("http://Abc:4000/sites/Rsite1/");
            context.Credentials = credentials;
            List list = context.Web.Lists.GetByTitle("Users");
            ListItemCollection listItems = list.GetItems(new CamlQuery() { ViewXml = "<View/>" });
            context.Load(listItems);
            context.ExecuteQuery();
            listItems[2].DeleteObject();
            context.ExecuteQuery();
Continue Reading...

the remote server returned an error 401 unauthorized sharepoint client object model

Solution:-

NetworkCredential credentials = new NetworkCredential("username", "pwd", "domain");
ClientContext context = new ClientContext("http://site-url");
context.Credentials = credentials;

Continue Reading...

Tuesday 19 November 2013

visual studio 2012 sharepoint 2013 templates missing

Continue Reading...

Excel data to DataTable using c#

  DataTable dt = new DataTable();
            string line = null;
            int i = 0;

            using (StreamReader sr = File.OpenText(@"E:\Sample.csv"))
            {
                while ((line = sr.ReadLine()) != null)
                {
                    string[] data = line.Split(',');
                    if (data.Length > 0)
                    {
                        if (i == 0)
                        {
                            foreach (var item in data)
                            {
                                dt.Columns.Add(new DataColumn());
                            }
                            i++;
                        }
                        DataRow row = dt.NewRow();
                        row.ItemArray = data;
                        dt.Rows.Add(row);
                    }
                }
            }
Continue Reading...

SharePoint 2013 Content Deployment Source feature

SharePoint 2013 Content Deployment Source feature

Site settings
Site Collection Features 
Content Deployment Source Feature ----->  Activate features

site settings
Site Collection Administration section
click Content Deployment Source Status


Continue Reading...

An object of the type Microsoft.SharePoint.Administration.SPIisWebServiceApplicationPool named











                                           
Sorry, something went wrong
An unhandled exception occurred in the user interface.Exception Information: An object of the type Microsoft.SharePoint.Administration.SPIisWebServiceApplicationPool named "NewAppPool" already exists under the parent Microsoft.SharePoint.Administration.SPIisWebServiceSettings named "SharePoint Web Services".  Rename your object or delete the existing object.


Solution:-


Try with different Application Pool Name , Try with some random number.
Continue Reading...

programmatically Insert,update,delete in sharepoint list using c#

Add New Item :-
                   public void AddNewItem()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList listEmpInsert = web.Lists["Employee"];
                        web.AllowUnsafeUpdates = true;
                        SPListItem EmpInsert = listEmpInsert.Items.Add();
                        EmpInsert["EmpName"] = "Mohamed";
                        EmpInsert["Age"] = "28";
                        EmpInsert["Address"] = "Chennnai";
                        EmpInsert.Update();
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });
        }  
Update the Item:-
                        public void updateExistingItem()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList lstupdate = web.Lists["Employee"];
                        web.AllowUnsafeUpdates = true;
                        int listItemId = 1;
                        SPListItem itemToUpdate = lstupdate.GetItemById(listItemId);
                        itemToUpdate["EmpName"] = "Mohamed sithik";
                        itemToUpdate["Age"] = "30";
                        itemToUpdate["Address"] = "Bangalore";
                        itemToUpdate.Update();
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });
        }
Delete the Item
                           public void DelteItem() 
        {
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList lstdelete = web.Lists["Employee"]; 
                        web.AllowUnsafeUpdates = true;
                        int listItemId = 1;
                        SPListItem itemToDelete = lstdelete.GetItemById(listItemId);
                        itemToDelete.Delete();
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });
        }
Get all the Item:-
              public void ReteriveallItem()  
        {
            SPSite mySite = new SPSite(SPContext.Current.Site.ID);
            SPWeb myWeb = mySite.OpenWeb();
            SPList myList = myWeb.Lists["Employee"];
            DataTable dt = ConvertSPListToDataTable(myList); 
           
        }
        private static DataTable ConvertSPListToDataTable(SPList oList)
        {
            DataTable dt = new DataTable();
            try
            {
                dt = oList.Items.GetDataTable();
                foreach (DataColumn c in dt.Columns)
                    c.ColumnName = System.Xml.XmlConvert.DecodeName(c.ColumnName);
                return (dt);
            }
            catch
            {
                return (dt);
            }
        }
Continue Reading...

we are having a problem opening this location in file explorer sharepoint 2013

Solution:-
            Just add the Desktop Experience

Refer the below link

http://www.win2012workstation.com/desktop-experience/

Continue Reading...

open with explorer sharepoint disabled


Solution:-

Just open the same Document in Internet Explorer(IE)










Continue Reading...

sign in different user missing in sharepoint 2013

1.Just open the following file

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\CONTROLTEMPLATES\Welcome.ascx

2.Add the below line inside the file

<SharePoint:MenuItemTemplate runat="server" ID="ID_LoginAsDifferentUser"  
Text="<%$Resources:wss,personalactions_loginasdifferentuser%>"   
Description="<%$Resources:wss,personalactions_loginasdifferentuserdescription%>"   
MenuGroupId="100"   Sequence="100"   UseShortId="true"   />

3. save it








Continue Reading...

Rename ContentDataBaseName in SharePoint Using SQLQuery

Alter ContentDb Name
USE MASTER;
GO
ALTER DATABASE [WSS_Content_fdc3317e5897456ab294ef998ec46420]
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE [WSS_Content_fdc3317e5897456ab294ef998ec46420]
MODIFY NAME= WSS_Content4;
GO
ALTER DATABASE WSS_Content4
SET MULTI_USER
GO
Continue Reading...

Delete SharePoint Content DataBase using PowerShell

Syntax:-

Remove-SPWebApplication http://sitename -Confirm -DeleteIISSite -RemoveContentDatabases

Example:-

Remove-SPWebApplication http://abcd01:1111/ -Confirm -DeleteIISSite -RemoveContentDatabases
Continue Reading...

move site collection from one web application to another web application using powershell

Example Script:-


#Get the from Site Collection URL
$fromURL = "http://Abcd:5000/sites/Fromsite"
#Get the to Site Collection URL 
$toURL = "http://sfs01:4000/sites/Rsite3/"

#Location to the backup file directory to store Site Collection backup files
$backupPath = "C:\\SiteBK.bak"

#Backing up Site Collection prior to moving
Write-Host "Backing Up Site Collection…."
Backup-SPSite $fromURL -Path C:\SiteBK.bak -force

#Removing Site Collection from old web application path
Write-Host "Removing Site Collection from old managed path location…"
Remove-SPSite -Identity $fromURL -Confirm:$false

#Restoring Site Collection to new Managed Path
Write-Host "Restoring Site Collection to new managed path location…"
Restore-SPSite -Identity $toURL -Path c:\SiteBK.bak -Confirm:$false

#Remove backup files from the backup dirctory
Remove-Item c:\SiteBK.bak
Continue Reading...

Followers

Follow The Author