Monday 21 December 2015

Displaying Alerts


1. Page.ClientScript.RegisterStartupScript(this.GetType(), "showSaveMessage", "<script language="'javascript'">alert('USER Deleted Sucessfully');</script>");

2. ScriptManager.RegisterStartupScript(this, this.GetType(), "@#$", "alert('No Items mapped with selected Party');", true);

Before or after this are you using any response.redirect..... 

Try ScriptManager.RegisterstartupScript.

Wednesday 28 October 2015

SharePoint 2013 – How to add SSL to a Web Application

SharePoint 2013 – How to add SSL to a Web Application

Here are some things that need to be done to make SSL work and to remove the ability to hit any sites via NON-SSL.  I recommend these settings if you guys plan to run SSL inside the corporate network for the 2013 instance of SharePoint.
Go to IIS on the WFE and do the following:
  • On the SharePoint – 80 site→ Edit Bindings
Step1SSL
  • In the Site Bindings dialogue, click Add → in the Type drop down, select https→ in the SSL Certificate drop down, select your cert.
Step2SSL
  • It should look like this when you’re done
Step3SSL
  • Next, on the SharePoint – 80 site, click on SSL settings
Step4SSL
  • Select the check box for Require SSL
Step5SSL
  • Launch the CA.  Go to Application Management → Alternate Access Mappings → Edit Public URLs
Step6SSL
  • Under Alternate Access Mapping Collection, select SharePoint – 80.
  • Change the Default to to the SSL site URL (e.g., https://servername.home.texas.com).  Make sure intranet, internet, custom and extranet are blank.  Click Save.
Step7SSL
  • Go back to the WFE and perform an IISReset
  • When IIS returns, launch the CA.  Remember, after an IISReset SharePoint sites, including the CA, take a minute to launch on the first time in
  • When the CA launches, click on General Application Settings → Farm Search Administration→ Search Service Application→ Content Sources →Local SharePoint sites → Under Start Addresses, change http://servername.home.tekxas.com to https://servername.home.tekxas.com.  Then run a full crawl.
Step8SSL
That should do it.

Tuesday 27 October 2015

Recursively update files & folders to a SharePoint Library


Recursively update files & folders to a SharePoint Library




using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.IO;

 private void button1_Click(object sender, EventArgs e)
        {
            string strSourcePath = txtLocalSource.Text;
            string strSiteUrl = txtServerUrl.Text;
            string strLibraryName = txtLibraryName.Text;

            try
            {
                using (SPSite site = new SPSite(@strSiteUrl))
                {
                    SPWeb Web = site.OpenWeb();
                    UploadORCreateDirectories(strSourcePath,Web.Folders[strLibraryName].SubFolders);
                }
            }
            catch(Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }

           
        }


        //function
        private void UploadORCreateDirectories(string filePath, SPFolderCollection folderCollection)
        {
            //Upload all files
            foreach (FileInfo fi in new DirectoryInfo(filePath).GetFiles())
            {
                FileStream fileStream = File.OpenRead(fi.FullName);//Read stram
                SPFile spfile = folderCollection.Folder.Files.Add(fi.Name, fileStream, true);
                spfile.Update();
            }

            //Upload Multiple Folders
            foreach (DirectoryInfo di in new DirectoryInfo(filePath).GetDirectories())
            {
                string subFolderName = di.FullName.Split('\\')[di.FullName.Split('\\').Length - 1];
                SPFolder spNewFolder = folderCollection.Add(subFolderName);
                spNewFolder.Update();
                //Recursive call to create sub folders
                UploadORCreateDirectories(di.FullName, spNewFolder.SubFolders);
            }
        }

Sunday 18 October 2015

Configure an environment for apps for SharePoint (SharePoint 2013)

Configure an environment for apps for SharePoint (SharePoint 2013)

SharePoint 2013
70 out of 141 rated this helpful - Rate this topic
  Applies to: SharePoint Foundation 2013, SharePoint Server 2013 Enterprise, SharePoint Server 2013 Standard
Topic Last Modified: 2015-07-15
Summary: Configure domain names, service applications, and URLs for apps for SharePoint 2013.
To enable users to install and use apps for SharePoint in their sites, you must configure your environment to support them. This article describes how to configure your environment to support apps. Use the Plan for apps for SharePoint 2013 article to review options and determine the values to use for configuration settings in this article.
ImportantImportant:
The steps in this article apply to both SharePoint Foundation 2013 and SharePoint Server 2013.
One of the feature updates of the March 2013 Public Update for SharePoint 2013 enables you to use multiple app domains in SharePoint 2013 environments with alternate access mapping or host-header web application configurations. For more information, see Enable apps in AAM or host-header environments for SharePoint 2013.
The following illustration summarizes the steps to take to configure an environment for apps for SharePoint.
Overview of how to configure an environment for apps for SharePoint
Process for configuring the environment for apps
These configuration steps result in example app URLs such as the following:
  • http://Apps-12345678ABCDEF.ContosoApps.com/sites/SiteName/App1Name/Pages/Home.aspx
  • https://Apps-3456789BCDEFG.ContosoApps.com/sites/SiteName/WebName/App2Name/Default.aspx
This article contains instructions for completing these steps.

Before you begin

  • You must purchase a domain name from a domain name provider for your apps, for example, ContosoApps.com.
    NoteNote:
    For security reasons, your SharePoint server runs in a different domain than where you host your apps. An effect of this is that Internet Information Services (IIS) isn't able to connect the two domains so you may encounter an error when you access your apps. To fix this error you need a web application on port 80 without a host header. For details about how to configure this, see "Error 2" in Troubleshooting setting up an environment for apps for SharePoint 2013.
  • You must be a member of the Farm Administrators group to perform the steps in this article. For some steps, you must also be a domain administrator on the domain controller.
  • Confirm that the SharePoint Administration (spadmin) and SharePoint Timer (sptimer) services are running.
    To verify this, click Start, point to Administrative Tools, and then click Services. In the Services list, verify that the SharePoint Administration and SharePoint Timer services are running.
NoteNote:
Because SharePoint 2013 runs as websites in Internet Information Services (IIS), administrators and users depend on the accessibility features that browsers provide. SharePoint 2013 supports the accessibility features of supported browsers. For more information, see the following resources:

Configure the domain names in DNS (all hosting options)

You must configure a new name in Domain Name Services (DNS) to host the apps. To help improve security, the domain name should not be a subdomain of the domain that hosts the SharePoint sites. For example, if the SharePoint sites are at Contoso.com, consider ContosoApps.com instead of App.Contoso.com as the domain name. For more information, see Plan for apps for SharePoint 2013. When an app is provisioned, it provisions a unique DNS domain name (for example, Apps-12345678ABCDEF.ContosoApps.com, where 12345678ABCDEF is a unique identifier for the app). You need a wildcard Canonical Name (CNAME) entry for your DNS domain to support these unique names.
Depending on your configuration (for example, if you are using WINS forward lookup), you might have to create a new forward lookup zone first, or you can start with a wildcard CNAME entry in the same zone as the SharePoint site domain. In the following procedures, you create a forward lookup zone, and then create a wildcard alias record for the DNS domain name that allows for individual apps to create unique domain names within your app domain. In these procedures, we use DNS Manager for Windows Server 2008 R2. For more information about DNS server in Windows Server 2008 R2, see DNS Server. If you have a different type of DNS server, follow the procedures in the documentation for that server type.
To create a forward lookup zone for the app domain name
  1. Verify that the user account that performs this procedure is a domain.administrator on the domain controller.
  2. Click Start, point to Administrative Tools, and then click DNS.
  3. In DNS Manager, right-click Forward Lookup Zones, and then click New Zone….
  4. In the New Zone Wizard, click Next.
  5. In the Zone Type page, accept the default of Primary zone, and then click Next.
  6. In the Active Directory Zone Replication Scope page, select the appropriate replication method for your environment (the default is To all DNS servers in this domain), and then click Next.
  7. In the Zone Name page, in the Zone name box type the name for your new app domain name (for example, ContosoApps.com), and then click Next.
    The New Zone Wizard shows the new domain name for apps.
    Create a domain name for apps for SharePoint
  8. On the Dynamic Update page, select the appropriate type of dynamic updates for your environment (the default is Do not allow dynamic updates), and then click Next.
  9. On the Completing the New Zone Wizard page, review the settings, and then click Finish.
For more information about how to create a forward lookup zone, see Add a Forward Lookup Zone.
You have now created a forward lookup zone (and a domain name) to use for apps in your environment.
To create a wildcard Alias (CNAME) record for the new domain name
  1. Verify that the user account that performs this procedure is a domain administrator on the domain controller.
  2. In DNS Manager, under Forward Lookup Zones, right-click the new app domain name, and then click New Alias (CNAME).
  3. In the New Resource Record dialog box, in the Alias name (uses parent domain if left blank) box, type *.
    The Fully qualified domain name (FQDN) box displays *. followed by the domain name that you created for apps. For example, *.ContosoApps.com or *.Contoso-Apps.com.
  4. Next to the Fully qualified domain name (FQDN) for target host box, type the FQDN of the server that hosts the SharePoint sites.
    For example, SharePoint.Contoso.com.
    Or:
    1. Next to the Fully qualified domain name (FQDN) for target host box, click Browse and navigate to the Forward Lookup Zone for the domain that hosts the SharePoint sites.
      For example, Contoso.com.
    2. And then navigate to the record that points to the server that hosts the SharePoint site.
      For example, SharePoint.
    New Resource Record dialog box shows the wildcard alias for the app domain and the FQDN of the server that hosts the SharePoint sites.
    Create a CNAME alias for the app domain
  5. Click OK.
For more information about how to create a wildcard alias record in DNS Manager, see Add an Alias (CNAME) Resource Record to a Zone.
You can verify the new domain name and alias by pinging them.
To verify the new domain name
  1. Verify that the user account that is performing this procedure is a domain administrator on the domain controller.
  2. Click Start, and then click Command Prompt.
  3. At the command prompt, type ping followed by a subdomain of the domain that you created, and then press ENTER.
    For example, ping Apps-12345678ABCDEF.contosoapps.com
    If the ping command returns the correct IP address, then your wildcard for the domain name was configured successfully.

Create a new wildcard SSL certificate

If you are using Secure Sockets Layer (SSL) for the SharePoint sites in your environment, or if you use any apps that use data external to the SharePoint sites, you should use SSL for your apps. To use SSL, you create an SSL certificate for your app domain (for example, ContosoApps.com).
The domain should be added in the form of a wildcard (for example, *.ContosoApps.com). You need a wildcard certificate instead of individual certificates because each installed app has its own subdomain.
NoteNote:
You can make a certificate request from your SharePoint server through Internet Information Services (IIS). Take a look at the steps for generating the request here Request an Internet Server Certificate (IIS 7) , and for installing an internet server certificate , here Install an Internet Server Certificate (IIS 7). Consult the documentation at your Certificate Authority on how to get and download your certificate.

Configure the Subscription Settings and App Management service applications

Apps rely on the App Management and Microsoft SharePoint Foundation Subscription Settings service applications. These service applications use the multi-tenancy features to provide app permissions and create the subdomains for apps. Therefore, even if you are not hosting multiple tenants, you must still establish a name for the default tenant for your environment (any SharePoint site that is not associated with a tenant will be in the default tenant).
NoteNote:
You can use the SharePoint Central Administration website to set the default tenant name (also know as the app prefix) for non-hosting environments. You must use Windows PowerShell to configure tenant names for hosting environments. You perform the steps to set the app prefix in the next section, Configure the app URLs to use.
To configure these services, you first start the services in Central Administration. After the services are started, you use Windows PowerShell to create the Subscription Settings service application, and then use either Windows PowerShell or Central Administration to create the App Management service application.
To start the Subscription Settings and App Management services in Central Administration
  1. Verify that you are a member of the farm administrators group in Central Administration.
  2. In SharePoint 2013 Central Administration, click System Settings.
  3. On the System Settings page, under Servers, click Manage services on server.
  4. On the Services on Server page, next to App Management Service, click Start.
  5. On the Services on Server page, next to Microsoft SharePoint Foundation Subscription Settings Service, click Start.
  6. Verify that the App Management and Microsoft SharePoint Foundation Subscription Settings services are running. The following illustration shows the Services on Server page where you can verify that the App Management and Subscription Settings services are running.
    Services on Server showing the App Management and Subscription Settings services running.
    Verify the services are running
To configure the Subscription Settings service application by using Windows PowerShell
  1. Verify that you have the following memberships:
    • securityadmin fixed server role on the SQL Server instance.
    • db_owner fixed database role on all databases that are to be updated.
    • Administrators group on the server on which you are running the Windows PowerShell cmdlets.
    An administrator can use the Add-SPShellAdmin cmdlet to grant permissions to use SharePoint 15 Products cmdlets.
    NoteNote:
    If you do not have permissions, contact your Setup administrator or SQL Server administrator to request permissions. For additional information about Windows PowerShell permissions, see Add-SPShellAdmin.
  2. On the Start menu, click All Programs.
  3. Click Microsoft SharePoint 2013 Products.
  4. Click SharePoint 2013 Management Shell.
  5. First you must establish the application pool, run as account, and database settings for the services. Use a managed account for the SPManagedAccount (which will be used for the application pool runas account).
    At the Windows PowerShell command prompt, type the following commands, and press ENTER after each one to create the application pool:
    $account = Get-SPManagedAccount "<AccountName>" 
    # Gets the name of the managed account and sets it to the variable $account for later use.
    

    Where:
    • <AccountName> is the name of the managed account in the SharePoint farm.

    $appPoolSubSvc = New-SPServiceApplicationPool -Name SettingsServiceAppPool -Account $account
    # Creates an application pool for the Subscription Settings service application. 
    # Uses a managed account as the security account for the application pool.
    # Stores the application pool as a variable for later use.
    
  6. At the Windows PowerShell command prompt, type the following commands, and press ENTER after each one to create the new service application and proxy:
    $appSubSvc = New-SPSubscriptionSettingsServiceApplication -ApplicationPool $appPoolSubSvc -Name SettingsServiceApp -DatabaseName <SettingsServiceDB>
    # Creates the Subscription Settings service application, using the variable to associate it with the application pool that was created earlier.
    # Stores the new service application as a variable for later use.
    

    Where:
    • <SettingsServiceDB> is the name of the Subscription Settings service database.

    $proxySubSvc = New-SPSubscriptionSettingsServiceApplicationProxy -ServiceApplication $appSubSvc
    # Creates a proxy for the Subscription Settings service application.
    
For more information, see Get-SPManagedAccount, New-SPServiceApplicationPool, New-SPSubscriptionSettingsServiceApplication, New-SPSubscriptionSettingsServiceApplicationProxy.
You can use either Windows PowerShell or Central Administration to create and configure the App Management service application. The following procedures provide the steps for each method.
To configure the App Management service application by using Windows PowerShell
  1. Verify that you have the following memberships:
    • securityadmin fixed server role on the SQL Server instance.
    • db_owner fixed database role on all databases that are to be updated.
    • Administrators group on the server on which you are running the Windows PowerShell cmdlets.
    An administrator can use the Add-SPShellAdmin cmdlet to grant permissions to use SharePoint 15 Products cmdlets.
    NoteNote:
    If you do not have permissions, contact your Setup administrator or SQL Server administrator to request permissions. For additional information about Windows PowerShell permissions, see Add-SPShellAdmin.
  2. On the Start menu, click All Programs.
  3. Click Microsoft SharePoint 2013 Products.
  4. Click SharePoint 2013 Management Shell.
  5. First you must establish the application pool, run as account, and database settings for the services. Use a managed account for the SPManagedAccount (which will be used for the application pool runas account).
    At the Windows PowerShell command prompt, type the following commands, and press ENTER after each one to create the application pool:
    $account = Get-SPManagedAccount "<AccountName>" 
    # Gets the name of the managed account and sets it to the variable $account for later use.
    

    Where:
    • <AccountName> is the name of the managed account in the SharePoint farm.

    $appPoolAppSvc = New-SPServiceApplicationPool -Name AppServiceAppPool -Account $account
    # Creates an application pool for the Application Management service application. 
    # Uses a managed account as the security account for the application pool.
    # Stores the application pool as a variable for later use.
    
  6. At the Windows PowerShell command prompt, type the following commands, and press ENTER after each one to create the new service application and proxy:
    $appAppSvc = New-SPAppManagementServiceApplication -ApplicationPool $appPoolAppSvc -Name AppServiceApp -DatabaseName <AppServiceDB>
    # Creates the Application Management service application, using the variable to associate it with the application pool that was created earlier.
    # Stores the new service application as a variable for later use.
    

    Where:
    • <AppServiceDB> is the name of the App Management service database.

    $proxyAppSvc = New-SPAppManagementServiceApplicationProxy -ServiceApplication $appAppSvc
    # Creates a proxy for the Application Management service application.
    
For more information, see Get-SPManagedAccount, New-SPServiceApplicationPool, New-SPAppManagementServiceApplication and New-SPAppManagementServiceApplicationProxy.
To create the App Management service application in Central Administration
  1. In SharePoint 2013 Central Administration, on the Application Management page, click Manage service applications.
  2. On the ribbon, click New, and then click App Management Service.
  3. In the New App Management Service Application page, in the Service Application Name box, type the name for the service application.
  4. In the Database section, in the Database Server box, type the instance of SQL Server where you want to store the database, or use the default server.
  5. In the Database Name box, type a database name, or use the default name.
    The database name must be unique.
  6. Under Database authentication, select the authentication that you want to use by doing one of the following:
    • If you want to use Windows authentication, leave this option selected. We recommend this option because Windows authentication automatically encrypts the password when it connects to SQL Server.
    • If you want to use SQL authentication, click SQL authentication. In the Account box, type the name of the account that you want the service application to use to authenticate to the SQL Server database, and then type the password in the Password box.
      NoteNote:
      In SQL authentication, an unencrypted password is sent to SQL Server. We recommend that you use SQL authentication only if you force protocol encryption to SQL Server or encrypt network traffic by using IPsec.
  7. In the Failover Database Server section, if you want to use a failover database server, specify the server name.
  8. In the Application Pool section, do one of the following:
    • Click Use existing application pool, and then select the application pool that you want to use from the drop-down list.
    • Click Create a new application pool, type the name of the new application pool, and then under Select a security account for this application pool do one of the following:
      • Click Predefined to use a predefined security account, and then select the security account from the drop-down list.
      • Click Configurable to specify a new security account to be used for an existing application pool. You can create a new account by clicking the Register new managed account link.
  9. In the Create App Management Service Application Proxy section, leave the Create App Management Service Application Proxy and add it to the default proxy group check box selected.
  10. Click OK.
    The following illustration shows the App Management service application and proxy that were created.
    Manage Service Applications page showing the App Management service application and proxy.
    The App Management service application and proxy Now you must start the service on the server.
  11. In SharePoint 2013 Central Administration, click System Settings.
  12. On the System Settings page, under Servers, click Manage services on server.
  13. On the Services on Server page, next to App Management Service, click Start.

Configure the app URLs to use

In this section, you create the app domain prefix and the tenant name to use for apps in your environment. The app URL points to your app domain and a prefix that determines how each app is named. If you host multiple tenants in your environment, you must use Windows PowerShell to configure the app URLs.
Use the following procedure to configure app URLs for non-hosting (single tenant) environments by using Central Administration.
To configure app URLs
  1. In Central Administration, click Apps.
  2. On the Apps page, click Configure App URLs.
  3. In the App domain box, type the isolated domain that you created for hosting apps.
    For example, ContosoApps.com or Contoso-Apps.com.
  4. In the App prefix box, type a name to use for the URL prefix for apps.
    For example, you could use “apps” as the prefix so that you would see a URL for each app such as “apps-12345678ABCDEF.ContosoApps.com”. The following illustration shows the Configure App URLs page after you have filled in the App domain and prefix.
    The Configure App URLs page in Central Administration shows the App domain and App prefix.
    Configure the app domain and prefix
  5. Click OK.
  6. If you will install apps and you have changed the App prefix (also known as the site subscription name), you must perform additional steps that involve restarting the World Wide Web Publishing Service (WWW Service) that hosts the apps.
    ImportantImportant:
    Restarting the WWW Service will also restart the IIS Admin Service and the Windows Process Activation Service. This will also shut down all Web sites and applications that depend on these services and they may lose existing state and will be unavailable until the services successfully restart. You should plan to perform these steps during a planned maintenance time.
    To complete the App prefix rename tasks, perform these steps:
    1. Stop the SharePoint Timer service.
    2. Restart the World Wide Web Publishing Service that hosts the apps.
    3. Start the SharePoint Timer service.
Use the following procedure to configure app URLs for multi-tenant hosting environments.
To configure app URLs by using Windows PowerShell
  1. Verify that you have the following memberships:
    • securityadmin fixed server role on the SQL Server instance.
    • db_owner fixed database role on all databases that are to be updated.
    • Administrators group on the server on which you are running the Windows PowerShell cmdlets.
    An administrator can use the Add-SPShellAdmin cmdlet to grant permissions to use SharePoint 15 Products cmdlets.
    NoteNote:
    If you do not have permissions, contact your Setup administrator or SQL Server administrator to request permissions. For additional information about Windows PowerShell permissions, see Add-SPShellAdmin.
  2. On the Start menu, click All Programs.
  3. Click Microsoft SharePoint 2013 Products.
  4. Click SharePoint 2013 Management Shell.
  5. At the Windows PowerShell command prompt, type the following commands and press ENTER after each one:
    Set-SPAppDomain <appDomain>
    

    Set-SPAppSiteSubscriptionName -Name "app" -Confirm:$false
    

    Where:
    • <appDomain> is the domain name that you created.
  6. If you will install apps and you have changed the App prefix (also known as the site subscription name), you must perform additional steps that involve restarting the World Wide Web Publishing Service (WWW Service) that hosts the apps.
    ImportantImportant:
    Restarting the WWW Service will also restart the IIS Admin Service and the Windows Process Activation Service. This will also shut down all Web sites and applications that depend on these services and they may lose existing state and will be unavailable until the services successfully restart. You should plan to perform these steps during a planned maintenance time.
    To complete the App prefix rename tasks, perform these steps:
    1. Stop the SharePoint Timer service.
    2. Restart the World Wide Web Publishing Service that hosts the apps.
    3. Start the SharePoint Timer service.
For more information, see Set-SPAppSiteSubscriptionName and Set-SPAppDomain.

Configure the Internet-facing endpoints feature (Optional)

The SharePoint Store contains apps for SharePoint intended for use with sites that require Internet-facing endpoints. By default, these apps are not available (greyed out and cannot be purchased) because they are incompatible with most sites. However, if your farm is configured to allow internet-facing end points, you can turn on the Internet-facing endpoints feature to show these apps in the SharePoint Store. You turn this feature on in Central Administration.
To configure Internet-facing endpoints for apps
  1. In Central Administration, click Application Management.
  2. On the Application Management page, click Manage Web applications.
  3. On the Manage Web Applications page, select the web application that you want to change.
  4. On the ribbon, click Manage Features.
  5. In the feature list, next to Apps that require accessible internet facing endpoints, click Activate.
  6. Click OK.
In some cases, for example, when you have an on-premises SharePoint 2013 farm where updates are installed infrequently, you will need to run a cmdlet to update the URL used to point to the SharePoint Store:
Set-SPAppStoreConfiguration -Url http://office.microsoft.com -Enable $true

Sunday 27 September 2015

Sharepoint List items Add attachment & Delete attachments


Adding Items with Attachment

string _Str_File_Name = FileUpload1.PostedFile.FileName;
            byte[] contents = GetFileStream();
            itemId = 0;
            using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["Check"];
                    web.AllowUnsafeUpdates = true;
                    SPListItem item = list.Items.Add();
                    item["Title"] = "Title1";
                    item["Citys1"] = "CCC1";
                    if ((_Str_File_Name != null) && (contents.Length > 0))
                    {
                        SPAttachmentCollection fileAttach = item.Attachments;
                        fileAttach.Add(_Str_File_Name, contents);
                    }
                    item.Update();
                    Page.Session["ItemId"] = item.ID;
                    Page.Session["ItemFileName"] = _Str_File_Name;
                    itemId = item.ID;
                    strFileName = _Str_File_Name;
                    Label1.Text = _Str_File_Name + "  " + itemId.ToString();
                }
            }
        }
        private byte[] GetFileStream()
        {
            //fuAttachment is your file select control
            if (!FileUpload1.HasFile)
                return null;
            Stream fStream = FileUpload1.PostedFile.InputStream;
            byte[] contents = new byte[fStream.Length];
            fStream.Read(contents, 0, (int)fStream.Length);
            fStream.Close();
            return contents;
        }

Deleting the Attachment / Attachments Only

 public static void DeleteAllAttachements(int iid)
        {
            using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPListItem listItem = web.Lists["Check"].GetItemById(iid);
                    List<string> fileNames = new List<string>();
                    foreach (string fileName in listItem.Attachments)
                    {
                        fileNames.Add(fileName);
                    }
                    foreach (string fileName in fileNames)
                    {
                        listItem.Attachments.Delete(fileName);
                    }
                    listItem.Update();
                }
            }
        }

//for Update the attachment
            string _Str_File_Name = FileUpload1.PostedFile.FileName;
            byte[] contents = GetFileStream();
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists["Check"];
                        web.AllowUnsafeUpdates = true;
                        // Delete List item
                        // Update the List item by ID
                        SPListItem itemToUpdate = list.GetItemById(31);
                        if ((_Str_File_Name != null) && (contents.Length > 0))
                        {
                            SPAttachmentCollection fileAttach = itemToUpdate.Attachments;
                            fileAttach.Add(_Str_File_Name, contents);
                        }
                        //itemToUpdate["Description"] = "Changed Description";
                        itemToUpdate.Update();
                        Label2.Text = "Udatead the achment pls check";
                    }
                }
            }
            catch (Exception ex)
            {
                Label2.Text = ex.Message;
            } 

Programmatically Adding, Deleting, Copying and Downloading Attachments in SPList


1. ADDING AN ATTACHMENT TO AN ITEM IN SPLIST

string _Str_File_Name = FileUpload1.PostedFile.FileName;
            byte[] contents = GetFileStream();
            int itemId = 0;
            using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["Check"];
                    web.AllowUnsafeUpdates = true;
                    SPListItem item = list.Items.Add();
                    item["Title"] = "Title1";
                    item["Citys1"] = "CCC1";
                    if ((_Str_File_Name != null) && (contents.Length > 0))
                    {
                        SPAttachmentCollection fileAttach = item.Attachments;
                        fileAttach.Add(_Str_File_Name, contents);
                    }
                    item.Update();
                    itemId = item.ID;
                }
            }

2.  DELETING AN ATTACHMENT FROM SPLIST :
private void DeleteAttachment(int NodeID)
 {
 try
 {
 SPList myList = SPContext.Current.Web.Lists[“Item List”];
SPListItem delItem = myList.GetItemById(NodeID);
 SPAttachmentCollection atCol = delItem.Attachments;
 if (delItem[“Attached FileName”] != null)
 {
 string strFileName = delItem[“Attached FileName”].ToString();
 delItem[“Attached FileName”] = string.Empty;
 atCol.Delete(strFileName);
 delItem.Update();
 }
 }
 catch (Exception eDel)
 {
 string errDel = eDel.Message;
 }
 }
3. DOWNLOADING THE ATTACHMENT :

Find the download link first then reedirect to another aspx page so that the response ending on the current page does not affect the functionalities on this :-
private void DownloadAttachment(int NodeID)
{
try
{
string AttachmentURL = string.Empty;
SPList myList = SPContext.Current.Web.Lists[“Item List”];
SPListItem attItem = myList.GetItemById(NodeID);
if (attItem[“Attached FileName”] != null)
{
AttachmentURL = “/Lists/Item%20List1/Attachments/” + NodeID.ToString() + “/” + attItem[“Attached FileName”].ToString();
System.Web.HttpContext.Current.Session[“FileName”] = attItem[“Attached FileName”].ToString();
System.Web.HttpContext.Current.Session[“Attachment”] = AttachmentURL.Trim();
}
else
{
lblReport.Text = GetMessage(110);
}
if (AttachmentURL != string.Empty)
Page.Response.Write(“”);
}
catch (Exception eDwn)
{
string errDwn = eDwn.Message;
}
}
At the aspx page you need to run the code as :
if(System.Web.HttpContext.Current.Session[“Attachment”] != null)
{
string strName = System.Web.HttpContext.Current.Session[“FileName”].ToString();
string sbURL = System.Web.HttpContext.Current.Session[“Attachment”].ToString();
System.Web.HttpResponse response;
response = System.Web.HttpContext.Current.Response;
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
response.AppendHeader(“Content-disposition”, “attachment; filename=” + strName);
response.AppendHeader(“Pragma”, “cache”);
response.AppendHeader(“Cache-control”, “private”);
response.Redirect(sbURL);
response.End();
}

4. COPYING AN ATTACHMENT FROM ONE ITEM TO ANOTHER IN SPLIST :
private void CopyAttachment(int FromID, int NodeID, string AttachedFile)
 {
 try
 {
 SPList myList = SPContext.Current.Web.ParentWeb.Lists[“Item List”];
SPListItem myItem = myList.GetItemById(NodeID);
 SPListItem myPrevItem = myList.GetItemById(FromID);
SPAttachmentCollection attColl = myPrevItem.Attachments;
SPFile attFile = myPrevItem.ParentList.ParentWeb.GetFile(myPrevItem.Attachments.UrlPrefix + AttachedFile);
 string fileRead = myPrevItem.Attachments.UrlPrefix.ToString() + AttachedFile;
StreamReader fsReader = new StreamReader(attFile.OpenBinaryStream());
 Stream fStream = fsReader.BaseStream;
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
 fStream.Dispose();
myItem.Attachments.Add(AttachedFile, contents);
 myItem.Update();
 }
 catch (Exception eCopy)
 {
 string errCopy = eCopy.Message;
 }
}

Wednesday 9 September 2015

How to read SharePoint list items attachments programmatically

SPSite mySite = new SPSite(http://Mohan:8899);
  SPWeb myweb = mySite.OpenWeb();
  SPList myList = myweb.Lists["Employees"];
  SPListItem myListItem = myList.GetItemById(1);
  foreach (String attachmentname in myListItem.Attachments)
  {
    // gets the containing directory URL

String attachmentAbsoluteURL =
   myListItem.Attachments.UrlPrefix 
+ attachmentname;

   // To get the SPSile reference to the attachment    SPFile attachmentFile = myweb.GetFile(attachmentAbsoluteURL);
 
   // To read the file content 
   Stream stream = attachmentFile.OpenBinaryStream();
   StreamReader reader = new StreamReader(stream);
   String fileContent = reader.ReadToEnd();
 
  
   }

Monday 7 September 2015

Develop SharePoint Add-ins

SharePoint Add-ins
Find in-depth articles and resources to help you build advanced capabilities into your SharePoint Add-ins.
Last modified: August 07, 2015
Applies to: apps for SharePoint | Office 365 | SharePoint Add-ins | SharePoint Foundation 2013 | SharePoint Server 2013
Note Note
The name "apps for SharePoint" is changing to "SharePoint Add-ins". During the transition, the documentation and the UI of some SharePoint products and Visual Studio tools might still use the term "apps for SharePoint". For details, see New name for apps for Office and SharePoint.
Note Note
This article assumes that you are familiar with the article SharePoint Add-ins and the getting started material that it links to.
Under Develop, we've got the following to help explain all the different things you can do in a SharePoint Add-in:
  • In-depth overviews
  • How-to articles
  • Code snippets
You'll find articles about:
  • Performing create, read, update, and delete (CRUD) operations on lists
  • How to build REST queries and interact with the new APIs
  • How and when to configure OAuth for security
SharePoint has enterprise social features like activity feeds and user profiles, along with enterprise content management features, line-of-business (LOB) interoperability features, and website design features that can really make your add-ins stand out. Learn more about them in Add SharePoint 2013 capabilities.
And, code is key, so take a look at the "Samples" menu in the Dev Center. It's a direct link to our code samples for add-ins. As soon as you've set up your development environment, you should check out a few of our samples. Take advantage of a community feature that lets you request a code sample if we don't have one you'd like to see. We take those requests, along with other doc feedback and use them in our continuous updates to the content and samples. So please, let us know if you'd like to see something!

If you're just getting started with developing SharePoint Add-ins, first take a look a SharePoint Add-ins. That page points you to key articles to get you acquainted quickly with the different kinds of SharePoint Add-ins. Before doing more advanced kinds of development with SharePoint Add-ins, you should start with a good idea of the kinds of add-ins that you want to build, the technologies that you will want to include, and the hosting options that you will want to use.

Essential tasks and resources for developing SharePoint Add-ins using the client object model, JavaScript object model, and REST endpoints in SharePoint 2013

No matter what kind of SharePoint Add-in you decide to build, your add-in will always interact in some way with a SharePoint 2013 site. The articles in Table 1 describe how to do many of the most important kinds of work with SharePoint sites by using three interfaces that are available for you to use in your SharePoint Add-ins: the client object model, the JavaScript object model, and REST endpoints.
Table 1. Basic operations with the SharePoint 2013 client object model, JavaScript object model, and REST interface
TopicDescription
Complete basic operations using SharePoint 2013 client library code Explains how to do common operations by using C# and the client object model.
Complete basic operations using JavaScript library code in SharePoint 2013 Explains how to do common operations by using the JavaScript object model.
Complete basic operations using SharePoint 2013 REST endpoints Explains how to do common operations by using the REST interface.

In addition to understanding the basic operations, you should understand the fundamental concepts of the SharePoint 2013 add-in development model. Every kind of SharePoint Add-in contains an add-in manifest file and is built into an add-in package that you deploy to a SharePoint 2013 site. And when you develop any kind of add-in you must consider a range of issues related to authentication and authorization, data access, and usability. The articles in Table 2 acquaint you with these issues and explain their implications for any kind of that you want to create.
Table 2. Fundamental concepts for working with SharePoint Add-ins
TopicDescription
Authorization and authentication of SharePoint Add-ins Guides you through core concepts related to acquiring the necessary privileges for working with SharePoint 2013 resources.
Explore the app manifest structure and the package of a SharePoint Add-in Explains how add-in manifests work and how add-in packages are built.
Create UX components in SharePoint 2013 Explores the ways in which you can build a rich user experience in SharePoint Add-ins.
Work with external data in SharePoint 2013 Explains the data access options and techniques that are available in different kinds of SharePoint Add-ins.
License your Office and SharePoint Add-ins Guides you through the add-in license framework for Office and SharePoint Add-ins.

When you are familiar with the capabilities and features of SharePoint Add-ins, you can start building more complex add-ins by putting all of the pieces together in ways that suit your requirements. The articles in Table 3 demonstrate how to integrate capabilities and create more fully featured SharePoint Add-ins.
Table 3. Advanced concepts in SharePoint Add-ins
TopicDescription
Create a provider-hosted add-in that includes a custom SharePoint list and content type Explains how to create SharePoint Add-ins that are hosted in the cloud and that include custom SharePoint lists and content types.

Complete basic operations using JavaScript library code in SharePoint 2013

In this article

SharePoint 2013 client APIs
Perform basic tasks in SharePoint 2013 using the JavaScript client object model
SharePoint website tasks
SharePoint list tasks
Create, update, and delete lists
Create, update, and delete folders
Create, read, update, and delete files
SharePoint list item tasks
Create, update, and delete list items
Access objects in the host web
Additional resources


You can use the SharePoint client object model to retrieve, update, and manage data in SharePoint 2013. SharePoint makes the object model available in several forms.
  • .NET Framework redistributable assemblies
  • JavaScript library
  • REST/OData endpoints
  • Windows Phone assemblies
  • Silverlight redistributable assemblies

The following sections describe tasks that you can complete programmatically, and they include JavaScript code examples that demonstrate the operations.
When you create a cloud-hosted add-in, you can add a reference to the object model by using HTML <script> tags. We recommend that you reference the host web because the add-in web may not exist in every scenario in cloud-hosted add-ins. You can retrieve the host web URL from the SPHostUrl query string parameter if you are using the {StandardTokens} token. You can also use your custom defined query string parameter if you are using the {HostUrl} token. After you have the host web URL, you must use JavaScript code to dynamically create the reference to the object model.
The following code example performs these tasks to add a reference to the JavaScript object model:
  • References the AJAX library from the Microsoft Content Delivery Network (CDN).
  • References the jQuery library from the Microsoft CDN.
  • Extracts the host web URL from the query string.
  • Loads the SP.Runtime.js and SP.js files by using the getScript function in jQuery. After loading the files, your program has access to the JavaScript object model for SharePoint.
  • Continues the flow in the execOperation function.
 <script
    src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"
    type="text/javascript">
</script>
<script
    type="text/javascript"
    src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js">
</script>
<script type="text/javascript">
    var hostweburl;
    // Load the required SharePoint libraries.
    $(document).ready(function () {
        // Get the URI decoded URLs.
        hostweburl =
            decodeURIComponent(
                getQueryStringParameter("SPHostUrl")
        );
        // The js files are in a URL in the form:
        // web_url/_layouts/15/resource_file
        var scriptbase = hostweburl + "/_layouts/15/";
        // Load the js files and continue to
        // the execOperation function.
        $.getScript(scriptbase + "SP.Runtime.js",
            function () {
                $.getScript(scriptbase + "SP.js", execOperation);
            }
        );
    });
    // Function to execute basic operations.
    function execOperation() {
        // Continue your program flow here.
    }
    // Function to retrieve a query string value.
    // For production purposes you may want to use
    // a library to handle the query string.
    function getQueryStringParameter(paramToRetrieve) {
        var params =
            document.URL.split("?")[1].split("&");
        var strParams = "";
        for (var i = 0; i < params.length; i = i + 1) {
            var singleParam = params[i].split("=");
            if (singleParam[0] == paramToRetrieve)
                return singleParam[1];
        }
    }
</script>

When you create a SharePoint-hosted add-in, you can add a reference to the object model by using HTML <script> tags. The add-in web in a SharePoint-hosted add-in allows you to use relative paths to reference the required files to use the JavaScript object model.
The following markup performs these tasks to add a reference to the JavaScript object model:
  • References the AJAX library from the Microsoft CDN.
  • References the SP.Runtime.js file by using a URL relative to the add-in web.
  • References the SP.js file by using a URL relative to the add-in web.
<script
    src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"
    type="text/javascript">
</script>
<script
    type="text/javascript"
    src="/_layouts/15/sp.runtime.js">
</script>
<script
    type="text/javascript"
    src="/_layouts/15/sp.js">
</script>
<script type="text/javascript">
    // Continue your program flow here.
</script>

Retrieve the properties of a website


function retrieveWebSite(siteUrl) {
    var clientContext = new SP.ClientContext(siteUrl);
    this.oWebsite = clientContext.get_web();
    clientContext.load(this.oWebsite);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
    );
}
function onQuerySucceeded(sender, args) {
    alert('Title: ' + this.oWebsite.get_title() +
        ' Description: ' + this.oWebsite.get_description());
}
   
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
        '\n' + args.get_stackTrace());
}

Retrieve only selected properties of a website

function retrieveWebSiteProperties(siteUrl) {
    var clientContext = new SP.ClientContext(siteUrl);
    this.oWebsite = clientContext.get_web();
    clientContext.load(this.oWebsite, 'Title', 'Created');
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
    );
}
function onQuerySucceeded(sender, args) {
    alert('Title: ' + this.oWebsite.get_title() +
        ' Created: ' + this.oWebsite.get_created());
}
   
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
        '\n' + args.get_stackTrace());
}

Write to a website's properties

function updateWebSite(siteUrl) {
    var clientContext = new SP.ClientContext(siteUrl);
    this.oWebsite = clientContext.get_web();
    this.oWebsite.set_title('Updated Web Site');
    this.oWebsite.set_description('This is an updated Web site.');
    this.oWebsite.update();
    clientContext.load(this.oWebsite, 'Title', 'Description');
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
    );
}
function onQuerySucceeded(sender, args) {
    alert('Title: ' + this.oWebsite.get_title() +
        ' Description: ' + this.oWebsite.get_description());
}
   
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
        '\n' + args.get_stackTrace());
}

Retrieve all properties of all lists in a website

function retrieveAllListProperties(siteUrl) {
    var clientContext = new SP.ClientContext(siteUrl);
    var oWebsite = clientContext.get_web();
    this.collList = oWebsite.get_lists();
    clientContext.load(collList);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
    );
}
function onQuerySucceeded() {
    var listInfo = '';
    var listEnumerator = collList.getEnumerator();
    while (listEnumerator.moveNext()) {
        var oList = listEnumerator.get_current();
        listInfo += 'Title: ' + oList.get_title() + ' Created: ' +
            oList.get_created().toString() + '\n';
    }
    alert(listInfo);
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
        '\n' + args.get_stackTrace());
}

Retrieve only specified properties of lists

function retrieveSpecificListProperties(siteUrl) {
    var clientContext = new SP.ClientContext(siteUrl);
    var oWebsite = clientContext.get_web();
    this.collList = oWebsite.get_lists();
    clientContext.load(collList, 'Include(Title, Id)');
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
    );
}
function onQuerySucceeded() {
    var listInfo = '';
    var listEnumerator = collList.getEnumerator();
    while (listEnumerator.moveNext()) {
        var oList = listEnumerator.get_current();
        listInfo += 'Title: ' + oList.get_title() +
            ' ID: ' + oList.get_id().toString() + '\n';
    }
    alert(listInfo);
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
        '\n' + args.get_stackTrace());
}

Store retrieved lists in a collection
 function retrieveSpecificListPropertiesToCollection(siteUrl) {
    var clientContext = new SP.ClientContext(siteUrl);
    var oWebsite = clientContext.get_web();
    var collList = oWebsite.get_lists();
    this.listInfoCollection = clientContext.loadQuery(collList, 'Include(Title, Id)');
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
    );
}
function onQuerySucceeded() {
    var listInfo = '';
    for (var i = 0; i < this.listInfoCollection.length; i++) {
        var oList = this.listInfoCollection[i];
        listInfo += 'Title: ' + oList.get_title() +
            ' ID: ' + oList.get_id().toString();
    }
    alert(listInfo.toString());
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
        '\n' + args.get_stackTrace());
}

Apply filters to list retrieval

function retrieveAllListsAllFields(siteUrl) {
    var clientContext = new SP.ClientContext(siteUrl);
    var oWebsite = clientContext.get_web();
    var collList = oWebsite.get_lists();
    this.listInfoArray = clientContext.loadQuery(collList,
        'Include(Title,Fields.Include(Title,InternalName))');
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded),
        Function.createDelegate(this, this._onQueryFailed)
    );
}
function onQuerySucceeded() {
    var listInfo = '';
    for (var i = 0; i < this.listInfoArray.length; i++) {
        var oList = this.listInfoArray[i];
        var collField = oList.get_fields();
        var fieldEnumerator = collField.getEnumerator();
           
        while (fieldEnumerator.moveNext()) {
            var oField = fieldEnumerator.get_current();
            var regEx = new RegExp('name', 'ig');
           
            if (regEx.test(oField.get_internalName())) {
                listInfo += '\nList: ' + oList.get_title() +
                    '\n\tField Title: ' + oField.get_title() +
                    '\n\tField Name: ' + oField.get_internalName();
            }
        }
    }
    alert(listInfo);
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
        '\n' + args.get_stackTrace());
}

Create and update a list

function createList(siteUrl) {
    var clientContext = new SP.ClientContext(siteUrl);
    var oWebsite = clientContext.get_web();
   
    var listCreationInfo = new SP.ListCreationInformation();
    listCreationInfo.set_title('My Announcements List');
    listCreationInfo.set_templateType(SP.ListTemplateType.announcements);
    this.oList = oWebsite.get_lists().add(listCreationInfo);
    clientContext.load(oList);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
    );
}
function onQuerySucceeded() {
    var result = oList.get_title() + ' created.';
    alert(result);
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
        '\n' + args.get_stackTrace());
}

 If you need to update the list after it has been created, you can set list properties and call the update() function before calling executeQueryAsync(succeededCallback, failedCallback), as shown in the following modifications of the previous example.

.
.
.
.
this.oList = oWebsite.get_lists().add(listCreationInfo);
oList.set_description('New Announcements List');
oList.update();
clientContext.load(oList);
clientContext.executeQueryAsync(
    Function.createDelegate(this, this.onQuerySucceeded),
    Function.createDelegate(this, this.onQueryFailed)
);

Add a field to a list

function addFieldToList(siteUrl) {
    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('Announcements');
    this.oField = oList.get_fields().addFieldAsXml(
        '<Field DisplayName=\'MyField\' Type=\'Number\' />',
        true,
        SP.AddFieldOptions.defaultValue
    );
    var fieldNumber = clientContext.castTo(oField,SP.FieldNumber);
    fieldNumber.set_maximumValue(100);
    fieldNumber.set_minimumValue(35);
    fieldNumber.update();
    clientContext.load(oField);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
    );
}
function onQuerySucceeded() {
    var result = oField.get_title() + ' added.';
    alert(result);
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
        '\n' + args.get_stackTrace());
}

Delete a list

function deleteList(siteUrl) {
    var clientContext = new SP.ClientContext(siteUrl);
    var oWebsite = clientContext.get_web();
    this.listTitle = 'My Announcements List';
    this.oList = oWebsite.get_lists().getByTitle(listTitle);
    oList.deleteObject();
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
    );
}
function onQuerySucceeded() {
    var result = listTitle + ' deleted.';
    alert(result);
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
        '\n' + args.get_stackTrace());
}

Create a folder in a document library

function createFolder(resultpanel) {
    var clientContext;
    var oWebsite;
    var oList;
    var itemCreateInfo;
    clientContext = new SP.ClientContext.get_current();
    oWebsite = clientContext.get_web();
    oList = oWebsite.get_lists().getByTitle("Shared Documents");
    itemCreateInfo = new SP.ListItemCreationInformation();
    itemCreateInfo.set_underlyingObjectType(SP.FileSystemObjectType.folder);
    itemCreateInfo.set_leafName("My new folder!");
    this.oListItem = oList.addItem(itemCreateInfo);
    this.oListItem.update();
    clientContext.load(this.oListItem);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, successHandler),
        Function.createDelegate(this, errorHandler)
    );
    function successHandler() {
        resultpanel.innerHTML = "Go to the " +
            "<a href='../Lists/Shared Documents'>document library</a> " +
            "to see your new folder.";
    }
    function errorHandler() {
        resultpanel.innerHTML =
            "Request failed: " + arguments[1].get_message();
    }
}

Update a folder in a document library

function updateFolder(resultpanel) {
    var clientContext;
    var oWebsite;
    var oList;
    clientContext = new SP.ClientContext.get_current();
    oWebsite = clientContext.get_web();
    oList = oWebsite.get_lists().getByTitle("Shared Documents");
    this.oListItem = oList.getItemById(1);
    this.oListItem.set_item("FileLeafRef", "My updated folder");
    this.oListItem.update();
    clientContext.load(this.oListItem);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, successHandler),
        Function.createDelegate(this, errorHandler)
    );
    function successHandler() {
        resultpanel.innerHTML = "Go to the " +
            "<a href='../Lists/Shared Documents'>document library</a> " +
            "to see your updated folder.";
    }
    function errorHandler() {
        resultpanel.innerHTML = "Request failed: " + arguments[1].get_message();
    }
}

Delete a folder in a document library

function deleteFolder(resultpanel) {
    var clientContext;
    var oWebsite;
    var folderUrl;
    clientContext = new SP.ClientContext.get_current();
    oWebsite = clientContext.get_web();
    clientContext.load(oWebsite);
    clientContext.executeQueryAsync(function () {
        folderUrl = oWebsite.get_serverRelativeUrl() + "/Lists/Shared Documents/Folder1";
        this.folderToDelete = oWebsite.getFolderByServerRelativeUrl(folderUrl);
        this.folderToDelete.deleteObject();
        clientContext.executeQueryAsync(
            Function.createDelegate(this, successHandler),
            Function.createDelegate(this, errorHandler)
        );
    }, errorHandler);
    function successHandler() {
        resultpanel.innerHTML = "Go to the " +
            "<a href='../Lists/Shared Documents'>document library</a> " +
            "to make sure the folder is no longer there.";
    }
    function errorHandler() {
        resultpanel.innerHTML = "Request failed: " + arguments[1].get_message();
    }
}

Create a file in a document library

function createFile(resultpanel) {
    var clientContext;
    var oWebsite;
    var oList;
    var fileCreateInfo;
    var fileContent;
    clientContext = new SP.ClientContext.get_current();
    oWebsite = clientContext.get_web();
    oList = oWebsite.get_lists().getByTitle("Shared Documents");
    fileCreateInfo = new SP.FileCreationInformation();
    fileCreateInfo.set_url("my new file.txt");
    fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
    fileContent = "The content of my new file";
    for (var i = 0; i < fileContent.length; i++) {
       
        fileCreateInfo.get_content().append(fileContent.charCodeAt(i));
    }
    this.newFile = oList.get_rootFolder().get_files().add(fileCreateInfo);
    clientContext.load(this.newFile);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, successHandler),
        Function.createDelegate(this, errorHandler)
    );
    function successHandler() {
        resultpanel.innerHTML =
            "Go to the " +
            "<a href='../Lists/Shared Documents'>document library</a> " +
            "to see your new file.";
    }
    function errorHandler() {
        resultpanel.innerHTML = "Request failed: " + arguments[1].get_message();
    }
}

Read a file in a document library

function readFile(resultpanel) {
    var clientContext;
    var oWebsite;
    var fileUrl;
    clientContext = new SP.ClientContext.get_current();
    oWebsite = clientContext.get_web();
    clientContext.load(oWebsite);
    clientContext.executeQueryAsync(function () {
        fileUrl = oWebsite.get_serverRelativeUrl() +
            "/Lists/Shared Documents/TextFile1.txt";
        $.ajax({
            url: fileUrl,
            type: "GET"
        })
            .done(Function.createDelegate(this, successHandler))
            .error(Function.createDelegate(this, errorHandler));
    }, errorHandler);
    function successHandler(data) {
        resultpanel.innerHTML =
            "The content of file \"TextFile1.txt\": " + data
    }
    function errorHandler() {
        resultpanel.innerHTML =
            "Request failed: " + arguments[2];
    }
}

Update a file in a document library

function updateFile(resultpanel) {
    var clientContext;
    var oWebsite;
    var oList;
    var fileCreateInfo;
    var fileContent;
    clientContext = new SP.ClientContext.get_current();
    oWebsite = clientContext.get_web();
    oList = oWebsite.get_lists().getByTitle("Shared Documents");
    fileCreateInfo = new SP.FileCreationInformation();
    fileCreateInfo.set_url("TextFile1.txt");
    fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
    fileCreateInfo.set_overwrite(true);
    fileContent = "The updated content of my file";
    for (var i = 0; i < fileContent.length; i++) {
        fileCreateInfo.get_content().append(fileContent.charCodeAt(i));
    }
    this.existingFile = oList.get_rootFolder().get_files().add(fileCreateInfo);
    clientContext.load(this.existingFile);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, successHandler),
        Function.createDelegate(this, errorHandler)
    );
    function successHandler() {
        resultpanel.innerHTML =
            "Go to the " +
            "<a href='../Lists/Shared Documents'>document library</a> " +
            "to see the updated \"TextFile1.txt\" file.";
    }
    function errorHandler() {
        resultpanel.innerHTML =
            "Request failed: " + arguments[1].get_message();
    }
}

Delete a file in a document library

function deleteFile(resultpanel) {
    var clientContext;
    var oWebsite;
    var fileUrl;
    clientContext = new SP.ClientContext.get_current();
    oWebsite = clientContext.get_web();
    clientContext.load(oWebsite);
    clientContext.executeQueryAsync(function () {
        fileUrl = oWebsite.get_serverRelativeUrl() +
            "/Lists/Shared Documents/TextFile1.txt";
        this.fileToDelete = oWebsite.getFileByServerRelativeUrl(fileUrl);
        this.fileToDelete.deleteObject();
        clientContext.executeQueryAsync(
            Function.createDelegate(this, successHandler),
            Function.createDelegate(this, errorHandler)
        );
    }, errorHandler);
    function successHandler() {
        resultpanel.innerHTML =
            "Go to the " +
            "<a href='../Lists/Shared Documents'>document library</a> " +
            "to confirm that the \"TextFile1.txt\" file has been deleted.";
    }
    function errorHandler() {
        resultpanel.innerHTML = "Request failed: " + arguments[1].get_message();
    }
}

Retrieve items from a list

function retrieveListItems(siteUrl) {
    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('Announcements');
       
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(
        '<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
        '<Value Type=\'Number\'>1</Value></Geq></Where></Query>' +
        '<RowLimit>10</RowLimit></View>'
    );
    this.collListItem = oList.getItems(camlQuery);
       
    clientContext.load(collListItem);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
    );
}
function onQuerySucceeded(sender, args) {
    var listItemInfo = '';
    var listItemEnumerator = collListItem.getEnumerator();
       
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        listItemInfo += '\nID: ' + oListItem.get_id() +
            '\nTitle: ' + oListItem.get_item('Title') +
            '\nBody: ' + oListItem.get_item('Body');
    }
    alert(listItemInfo.toString());
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
        '\n' + args.get_stackTrace());
}

Use the Include method to access properties of ListItem objects

Four properties of ListItem objects are not available by default when you return list items—displayName, effectiveBasePermissions, hasUniqueRoleAssignments, and roleAssignments. The previous example returns a PropertyOrFieldNotInitializedException if you try to access one of these properties. To access these properties, use the Include method as part of the query string, as shown in the following example.

function retrieveListItemsInclude(siteUrl) {
    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('Announcements');
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><RowLimit>100</RowLimit></View>');
    this.collListItem = oList.getItems(camlQuery);
    clientContext.load(
        collListItem,
        'Include(Id, DisplayName, HasUniqueRoleAssignments)'
    );
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onQuerySucceeded),
        Function.createDelegate(this, this.onQueryFailed)
    );
}
function onQuerySucceeded(sender, args) {
    var listItemInfo = '';
    var listItemEnumerator = collListItem.getEnumerator();
       
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        listItemInfo += '\nID: ' + oListItem.get_id() +
            '\nDisplay name: ' + oListItem.get_displayName() +
            '\nUnique role assignments: ' +
            oListItem.get_hasUniqueRoleAssignments();
    }
    alert(listItemInfo.toString());
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
        '\n' + args.get_stackTrace());
}

Create a list item

function createListItem(siteUrl) {
    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('Announcements');
       
    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(itemCreateInfo);
    oListItem.set_item('Title', 'My New Item!');
    oListItem.set_item('Body', 'Hello World!');
    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());
}

Update a list item

function updateListItem(siteUrl) {
    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('Announcements');
    this.oListItem = oList.getItemById(3);
    oListItem.set_item('Title', 'My Updated Title');
    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());
}

Delete a list item

function deleteListItem(siteUrl) {
    this.itemId = 2;
    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('Announcements');
    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());
}

If you want to retrieve, for example, the new item count that results from a delete operation, include a call to the update() method to refresh the list. In addition, you must load either the list object itself or the itemCount property on the list object before executing the query. If you want to retrieve both a start and end count of the list items, you must execute two queries and return the item count twice, as shown in the following modification of the previous example.


function deleteListItemDisplayCount(siteUrl) {
    this.clientContext = new SP.ClientContext(siteUrl);
    this.oList = clientContext.get_web().get_lists().getByTitle('Announcements');
    clientContext.load(oList);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.deleteItem),
        Function.createDelegate(this, this.onQueryFailed)
    );
}
function deleteItem() {
    this.itemId = 58;
    this.startCount = oList.get_itemCount();
    this.oListItem = oList.getItemById(itemId);
    oListItem.deleteObject();
    oList.update();
    clientContext.load(oList);
       
    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.displayCount),
        Function.createDelegate(this, this.onQueryFailed)
    );
}
function displayCount() {
    var endCount = oList.get_itemCount();
    var listItemInfo = 'Item deleted: ' + itemId +
        '\nStart Count: ' +  startCount +
        ' End Count: ' + endCount;
       
    alert(listItemInfo)
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
        '\n' + args.get_stackTrace());
}

While developing your add-in, you might need to access the host web to interact with items in it. Use the AppContextSite object to reference the host web or other SharePoint sites, as shown in the following example. For a full code sample, see Get the host web title using the cross-domain library (JSOM).

function execCrossDomainRequest(appweburl, hostweburl) {
    // context: The ClientContext object provides access to
    //      the web and lists objects.
    // factory: Initialize the factory object with the
    //      add-in web URL.
    var context;
    var factory;
    var appContextSite;
    context = new SP.ClientContext(appweburl);
    factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
    context.set_webRequestExecutorFactory(factory);
    appContextSite = new SP.AppContextSite(context, hostweburl);
    this.web = appContextSite.get_web();
    context.load(this.web);
    // Execute the query with all the previous
    //  options and parameters.
    context.executeQueryAsync(
        Function.createDelegate(this, successHandler),
        Function.createDelegate(this, errorHandler)
    );
    // Function to handle the success event.
    // Prints the host web's title to the page.
    function successHandler() {
        alert(this.web.get_title());
    }
    // Function to handle the error event.
    // Prints the error message to the page.
    function errorHandler(data, errorCode, errorMessage) {
        alert("Could not complete cross-domain call: " + errorMessage);
    }
}