Wednesday, 4 December 2013

Insert,update,delete in sharepoint list using Javascript


<input type="button" value="Submit"  onclick="createListItem();" style="width: 89px" />
<input type="button" value="Update"  onclick="updateListItem();" style="width: 89px" />
<input type="button" value="Delete"  onclick="deleteListItem();" style="width: 89px" />

<script type="text/javascript">
    var siteUrl = '/sites/TeamSite1';
    function createListItem() {
        var clientContext = new SP.ClientContext(siteUrl);
        var oList = clientContext.get_web().get_lists().getByTitle('Employee');
        var itemCreateInfo = new SP.ListItemCreationInformation();
        this.oListItem = oList.addItem(itemCreateInfo);
        oListItem.set_item('Title', '1');
        oListItem.set_item('EmpName', 'Mohamed sithik');
        oListItem.set_item('Age', '27');
        oListItem.set_item('Address', 'Chennai');
        oListItem.update();
        clientContext.load(oListItem);
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
    }
    function onQuerySucceeded() {
        alert('Item created: ' + oListItem.get_id());
    }
    function onQueryFailed(sender, args) {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }

</script>
<script>
    var siteUrl = '/sites/TeamSite1';
    function updateListItem() {
        var clientContext = new SP.ClientContext(siteUrl);
        var oList = clientContext.get_web().get_lists().getByTitle('Employee');
        this.oListItem = oList.getItemById(333);
        oListItem.set_item('Title', '4');
        oListItem.set_item('EmpName', 'sithik');
        oListItem.set_item('Age', '26');
        oListItem.set_item('Address', 'Bangalore');
        oListItem.update();
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
    }
    function onQuerySucceeded() {
        alert('Item updated!');
    }
    function onQueryFailed(sender, args) {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
</script>
<script>
     var siteUrl = '/sites/TeamSite1';

     function deleteListItem() {
         this.itemId = 333;
         var clientContext = new SP.ClientContext(siteUrl);
         var oList = clientContext.get_web().get_lists().getByTitle('Employee');
         this.oListItem = oList.getItemById(itemId);
         oListItem.deleteObject();
         clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
     }

     function onQuerySucceeded() {
         alert('Item deleted: ' + itemId);
     }

     function onQueryFailed(sender, args) {
         alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
     }


    </script>
Continue Reading...

Delete all SharePoint List Item using Powershell in SharePoint

Sytax:-

$SITEURL = "http://serverurl"

$site = new-object Microsoft.SharePoint.SPSite ( $SITEURL )
$web = $site.OpenWeb()
"Web is : " + $web.Title

$oList = $web.Lists["LIST NAME"];

"List is :" + $oList.Title + " with item count " + $oList.ItemCount

$collListItems = $oList.Items;
$count = $collListItems.Count - 1

for($intIndex = $count; $intIndex -gt -1; $intIndex--)
{
        "Deleting record: " + $intIndex
        $collListItems.Delete($intIndex);
}

Continue Reading...

Tuesday, 3 December 2013

join two sharepoint list using c#


1.Create a custom list name as "List1" with below column

2.Create a custom list name as "List2" with below column

3.paste the below code inside the webpart

public void GetEmployee()
        {
            SPWeb objweb = SPContext.Current.Web;
            SPList olist1 = objweb.Lists["list1"];
            SPListItemCollection collListItems = olist1.Items;
            SPQuery oQuery1 = new SPQuery();
            DataTable table1 = collListItems.GetDataTable();
            SPList olist2 = objweb.Lists["list2"];
            SPListItemCollection collListItems2 = olist2.Items;
            DataTable table2 = collListItems2.GetDataTable();
            DataTable dt = new DataTable();
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Age", typeof(string));
            dt.Columns.Add("Salary", typeof(string));
            dt.Columns.Add("Sex", typeof(string));
            dt.Columns.Add("Address", typeof(string));
            var Vout = from tbl1 in table1.AsEnumerable()
                       join tbl2 in table2.AsEnumerable() on tbl1["Name"] equals tbl2["Name"]
                       select new
                       {
                           Sex = tbl2["Sex"],
                           Address = tbl2["Address"],
                           Name = tbl1["Name"],
                           Age = tbl1["Age"],
                           Salary = tbl1["Salary"]
                       };
            foreach (var item in Vout)
            {
                DataRow dr = dt.NewRow();
                dr["Name"] = item.Name;
                dr["Age"] = item.Age;
                dr["Salary"] = item.Salary;
                dr["Sex"] = item.Sex;
                dr["Address"] = item.Address;
                dt.Rows.Add(dr);
            }
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
4.output



Continue Reading...

Timer Job Example in SharePoint 2013


1.open visual studio 2012
2.Add SharePoint2013-Empty Project named it "TimerJobExample"
3.Enter your site collection and choose Deploy as a Farm solution
4.Add class file in your solution named it "Employee"
5.paste the below code inside the Employee class

 public class Employee : SPJobDefinition
    {
        public Employee()
            : base()
        {
            Title = "Sithik Job";

        }

        public const string JobName = "Sithik Job";
        public Employee(SPWebApplication webApp) :
            base(JobName, webApp, null, SPJobLockType.Job) { }
        public override void Execute(Guid targetInstanceId)
        {
            AddNewItem();

        }
  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;
                    }
                }
            });
        }  

    }
6.Go to Features right click add one new features and rename it "Employee"
7.Right click the Employee Features  add one "Event receiver" paste the below code inside the receiver

 private void DeleteJob(Microsoft.SharePoint.Administration.SPJobDefinitionCollection jobs)
        {
            foreach (SPJobDefinition job in jobs)
            {
                if (job.Name.Equals(TimerJobExample.Employee.JobName,
                StringComparison.OrdinalIgnoreCase))
                {
                    job.Delete();
                }
            }
        }

   public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
            DeleteJob(webApp.JobDefinitions);


            TimerJobExample.Employee simpleJob = new TimerJobExample.Employee(webApp);

            SPMinuteSchedule schedule = new SPMinuteSchedule();
            schedule.BeginSecond = 0;
            schedule.EndSecond = 59;
            schedule.Interval = 1;

            simpleJob.Schedule = schedule;
            simpleJob.Update();
        }

      public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
            DeleteJob(webApp.JobDefinitions);
        }

8.click the "Employee Features" Change the scope to "WebApplication"
9.click the "properties windows" "Always Force to Install" to "True"
10.Deploy the project
11.Go "central administration" click "Monitoring"
12.under "Timer Jobs" click "Review Job definitions"
13.you will see your Timer job named "Sithik Job"



Continue Reading...

Create sharepoint list custom form via visual studio 2012

1.open visual studio 2012
2.Add Sharepoint 2013 Empty project Named it "Employee"
3.Create a custom list name as "Employee" and add the below columns

4.Right click the project add the layouts folder inside that add one Application page named it "EmpCustomForm"
5.Paste the below code inside the Content ID "Main"


      <p style="font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif">&nbsp; Employee Custom Form</p>
    <table>
                <tr>
                    <td class="auto-style1">
                        <asp:Label ID="LblTitle" runat="server" Text="Title: "></asp:Label>
                    </td>
                   
                    <td>
                         <asp:TextBox ID="Txttile" runat="server" Height="46px"  Width="470px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                         <asp:Label ID="LblName" runat="server" Text="Name : "></asp:Label>
                    </td>
                    
                    <td>
                         <asp:TextBox ID="TxtName" runat="server" Height="46px"  Width="470px"></asp:TextBox>
                    </td>
                </tr>
                 <tr>
                    <td>
                         <asp:Label ID="LblAge" runat="server" Text=" Age : "></asp:Label>
                    </td>

                    <td>
                           <asp:TextBox ID="TxtAge" runat="server" Height="46px"  Width="470px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                         <asp:Label ID="LblEmail" runat="server" Text=" Email : "></asp:Label>
                    </td>
                    
                    <td>
                        <asp:TextBox ID="TxtEmail" runat="server" Height="46px"   Width="470px"></asp:TextBox>
                    </td>
                </tr>
                       </table>
        <table>
            <tr>
                <td>
                    <asp:Button ID="BtnSave" runat="server" Text="Save" OnClick="BtnSave_Click" Width="94px" />
                </td>
                <td>
                    <asp:Button ID="BtnClear" runat="server" Text="Clear" OnClick="BtnClear_Click" Width="102px" />
                </td>
            </tr>
        </table>
6.Paste the below code inside the cs page

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                LoadData();
            }
        }
        private void LoadData()
        {
            var list = SPContext.Current.Web.Lists[new Guid(Request.QueryString["list"])];
            var itemId = 0;
          
            if (string.IsNullOrEmpty(Request.QueryString["id"]) == false)
            {
                int.TryParse(Request.QueryString["id"], out itemId);
            }
            if (itemId != 0)
            {
                var listItem = list.GetItemById(itemId);
                Txttile.Text = (listItem["Title"] == null) ? string.Empty : listItem["Title"].ToString();
                TxtName.Text = (listItem["EmpName"] == null) ? string.Empty : listItem["EmpName"].ToString();
                TxtAge.Text = (listItem["Age"] == null) ? string.Empty : listItem["Age"].ToString();
                TxtEmail.Text = (listItem["Email"] == null) ? string.Empty : listItem["Email"].ToString();
                SPSite sites = new SPSite(SPContext.Current.Site.ID);
                SPWeb webs = sites.OpenWeb();
                SPList lists = webs.Lists["Employee"];
                SPListItem item = listItem;
            }

        }
        protected void BtnSave_Click(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                var list = SPContext.Current.Web.Lists[new Guid(Request.QueryString["list"])];
                string ItemsID = string.Empty;
                var itemId = 0;
                if (string.IsNullOrEmpty(Request.QueryString["id"]) == false)
                {
                    int.TryParse(Request.QueryString["id"], out itemId);
                }
                SPListItem listItem = null;
                if (itemId == 0)
                {
                    listItem = list.AddItem();
                }
                else
                {
                    listItem = list.GetItemById(itemId);
                }
                ItemsID = Convert.ToString(itemId);
                listItem["Title"] = Txttile.Text;
                listItem["EmpName"] = TxtName.Text;
                listItem["Age"] = TxtAge.Text;
                listItem["Email"] = TxtEmail.Text;
                listItem.Update();
            });
            Txttile.Text = string.Empty;
            TxtAge.Text = string.Empty;
            TxtName.Text = string.Empty;
            TxtEmail.Text = string.Empty;
        }
        protected void BtnClear_Click(object sender, EventArgs e)
        {
            Txttile.Text = string.Empty;
            TxtAge.Text = string.Empty;
            TxtName.Text = string.Empty;
            TxtEmail.Text = string.Empty;

        }
7.Go to the Employee List click the Schema.xml add the below lines

        <XmlDocuments>
          <XmlDocument NamespaceURI="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms/url">
            <FormUrls xmlns="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms/url">
              <Display>/sites/Test1/_layouts/15/Employee/EmpCustomForm.aspx</Display>
              <Edit>/sites/Test1/_layouts/15/Employee/EmpCustomForm.aspx</Edit>
              <New>/sites/Test1/_layouts/15/Employee/EmpCustomForm.aspx</New>
            </FormUrls>
          </XmlDocument>
        </XmlDocuments>
8. ouput



Continue Reading...

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...

Followers

Follow The Author