Showing posts with label programmatically. Show all posts
Showing posts with label programmatically. Show all posts

Friday, 13 February 2015

Programmatically Get items from sharepoint list in sharepoint apps using Napa office 365 tool

1.Create a Custom List Name as "Emp" and Create a below Column Name





2.Paste the below code in Default.aspx

<%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>
<%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>

<!-- Add your CSS styles to the following file -->
<link rel="Stylesheet" type="text/css" href="../Content/App.css" />
<style type="text/css">
.myOtherTable { background-color:#FFFFE0;border-collapse:collapse;color:#000;font-size:18px; }
.myOtherTable th { background-color:#BDB76B;color:white;width:32%; }
.myOtherTable td, .myOtherTable th { padding:5px;border:0; }
.myOtherTable td { border-bottom:1px dotted #BDB76B; }

</style>

<!-- Add your JavaScript to the following file -->
<script type="text/javascript" src="../Scripts/App.js"></script>
</asp:Content>

<%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
Page Title
</asp:Content>

<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">

<h2>Get Items</h2>
<div class="EmpInfo" style="margin-top:10px;">
</div>

</asp:Content>

3.Paste the below code in  App.js 

'use strict';
    var hostweburl;
    var appweburl;
var sFullHtml = '';
    $(document).ready(function () {
     
        hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
        appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
      
        var scriptbase = hostweburl + "/_layouts/15/";
       
        $.getScript(scriptbase + "SP.RequestExecutor.js", loadPage);
    });
   
    function getQueryStringParameter(paramToRetrieve) {
        var params = document.URL.split("?")[1].split("&");
        for (var i = 0; i < params.length; i = i + 1) {
            var singleParam = params[i].split("=");
            if (singleParam[0] == paramToRetrieve) return singleParam[1];
        }
    }
    function loadPage() {
       getListItems();
}

    //Retrieve all of the list items
    function getListItems() {
        var executor;
      
        executor = new SP.RequestExecutor(appweburl);
        executor.executeAsync({
            url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('Emp')/items?@target='" + hostweburl + "'",
            method: "GET",
            headers: {
                "Accept": "application/json; odata=verbose"
            },
            success: getListItemsSuccessHandler,
            error: getListItemsErrorHandler
        });
    }
    //Populate the selectListItems control after retrieving all of the list items.
    function getListItemsSuccessHandler(data) {
        var jsonObject = JSON.parse(data.body);
   var results = jsonObject.d.results;
sFullHtml += '<table id="TblEmpInfo" class="myOtherTable" >';
sFullHtml += ' <tr >';
sFullHtml += ' <th>First Name</th>';
sFullHtml += ' <th>Last Name</th>';
sFullHtml += ' <th>Location</th>';
sFullHtml += ' </tr>';
        for (var i = 0; i < results.length; i++) {
           
var Title=results[i].Title;
var Fname=results[i].FirstName;
var Lname=results[i].LastName;
var Location=results[i].Location;
 
sFullHtml += '<tr>';
                    sFullHtml += '<td align="left" valign="top">'+ Fname +'</td>';
                    sFullHtml += '<td align="left" valign="top">'+ Lname  +'</td>';
                    sFullHtml += '<td align="left" valign="top">'+ Location  +'</td>';
sFullHtml += '</tr>';
            
          
        }
sFullHtml += '</table>';
$(".EmpInfo").html(sFullHtml);
    }
    function getListItemsErrorHandler(data, errorCode, errorMessage) {
        alert("Could not get list items: " + errorMessage);
    }


4.After Publishing the App the output will look like this 

Continue Reading...

Wednesday, 30 July 2014

Programmatically Check Current user in SharePoint Group using C#

 public void CheckcurrentuserinGroup()
        {
            SPGroup grp = SPContext.Current.Web.SiteGroups["GroupName"];
            if (grp != null)
            {
                if (grp.ContainsCurrentUser)
                {
                    //True
                }
                else
                {
                    //false
                    SPUtility.HandleAccessDenied(new Exception("You don’t have access rights to see this content. Contact Administrator"));
                }
            }
        }
Continue Reading...

get user profile properties programmatically using c#

 public void getuserprofilesyncCustomattributesvalues(string MysitecollectionUrl)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite siteCollection = new SPSite(MysitecollectionUrl))
                {
                    using (SPWeb site = siteCollection.OpenWeb())
                    {
                        ServerContext context = ServerContext.GetContext(siteCollection);
                        UserProfileManager profileManager = new UserProfileManager(context);
                        foreach (UserProfile profile in profileManager)
                        {
                            string PersonalSiteUrl = ((string)profile["PersonalSpace"].Value);
                            string AccountName = ((string)profile["AccountName"].Value);
                        }
                    }
                }
            });

        }
 
  public void getuserprofilesyncDefaultattributesvalues(string MysitecollectionUrl)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite site = new SPSite(MysitecollectionUrl))
                {
                    ServerContext context = ServerContext.GetContext(site);
                    UserProfileManager profileManager = new UserProfileManager(context);
                    foreach (UserProfile profile in profileManager)
                    {
                        string Department = Convert.ToString(profile[PropertyConstants.Department].Value);
                        string AccountName = Convert.ToString((profile[PropertyConstants.AccountName].Value));
                        string Name = Convert.ToString((profile[PropertyConstants.PreferredName].Value));
                    }
                }
            });
        }
 
Continue Reading...

Programmatically Delete all Item in SharePoint List using c#

       
        public static void DeleteAllItems(string list)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite spSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        spWeb.AllowUnsafeUpdates = true;
                        StringBuilder deletebuilder = BatchCommand(spWeb.Lists[list]);
                        spSite.RootWeb.ProcessBatchData(deletebuilder.ToString());
                        spWeb.AllowUnsafeUpdates = false;
                    }
                }
            });

        }
        private static StringBuilder BatchCommand(SPList spList)
        {
            StringBuilder deletebuilder = new StringBuilder();
            deletebuilder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
            string command = "<Method><SetList Scope=\"Request\">" + spList.ID +
                "</SetList><SetVar Name=\"ID\">{0}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar></Method>";

            foreach (SPListItem item in spList.Items)
            {
                deletebuilder.Append(string.Format(command, item.ID.ToString()));
            }
            deletebuilder.Append("</Batch>");
            return deletebuilder;
        }
   DeleteAllItems("Employee");
Continue Reading...

Friday, 29 November 2013

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

Tuesday, 19 November 2013

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