i am working on function that deletes a file from Share Point Documents. The function works but it throws exception that file not found.  protected void DeleteFile(string filename, Uri hostWeb)     {         using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity))         {             Web web = clientContext.Web;             List docs = web.Lists.GetByTitle("Documents");              Microsoft.SharePoint.Client.File f = web.GetFileByServerRelativeUrl("/Shared Documents/" + filename);             f.DeleteObject();             clientContext.Load(f);             clientContext.ExecuteQuery(); // Delete file here but throw Exception                             Console.Write("deleted");         }     }
120569
I'm trying to delete an Item from a list using the following code:   using System; using Microsoft.SharePoint.Client; using SP = Microsoft.SharePoint.Client;  namespace Microsoft.SDK.SharePointServices.Samples { class DeleteListItem {     static void Main()     {            string siteUrl = "http://MyServer/sites/MySiteCollection";          ClientContext clientContext = new ClientContext(siteUrl);         SP.List oList = clientContext.Web.Lists.GetByTitle("Announcements");         ListItem oListItem = oList.GetItemById(2);          oListItem.DeleteObject();          clientContext.ExecuteQuery();      } }   }  for any item Id I try to delete, I  always get the same  message :       Item does not exist. It may have been deleted by another user.
960
See code:   var file1 = "50.xsl"; var file2 = "30.doc"; getFileExtension(file1); //returns xsl getFileExtension(file2); //returns doc  function getFileExtension(filename) {     /*TODO*/ }
103762
I currently have a file on the root of my external hard drive simply named ._., which I am guessing was added to my hard drive after using it on my MacBook a while ago.  I'm trying to delete this file on my Windows 10 machine; however Windows keeps claiming the file cannot be found.    I also tried deleting the file through an elevated command prompt; however the same message is returned.    Is there any way I can delete this file from my hard drive through Windows?
70393
Is there any way to check whether a file is locked without using a try/catch block?    Right now, the only way I know of is to just open the file and catch any System.IO.IOException.
26657
Below is my code to read items from a document library.  var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('DocumentList')/items?$select=customerID"; $.ajax({       url: url,       method: "GET",       headers: {           "Accept": "application/json; odata=verbose"       },       success: function(data) {           $.each(data.d.results, function(index, item) {             arrayCustomerID[index] = item.customerID;         });       },       error: function(data) {           console.log("error");       }   });     This work for the normal case but what should I do so that it works if I have more than 5000 items in the document library.
6154
In the example below, is the connection going to close and disposed when an exception is thrown if it is within a using statement?  using (var conn = new SqlConnection("...")) {     conn.Open();     // stuff happens here and exception is thrown... }   I know this code below will make sure that it does, but I'm curious how using statement does it.  var conn; try {     conn = new SqlConnection("...");     conn.Open();     // stuff happens here and exception is thrown... } // catch it or let it bubble up finally {     conn.Dispose(); }   Related:
119445
I have a SharePoint 2010 web site with a master page that has a counter on it. I'm trying to update that counter using the ECMAScript. The code I have falls nicely into the success method - but I cannot find the right call to get a count. I have tried length, length(), count &amp; count(). Does anybody have any suggestions?  I have the code working, but only by enumerating through the results of the list and incrementing a count.  This is what I have so far, as an example:-  &lt;script type="text/javascript"&gt;     var clientContext = null;     var web = null;     ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");     function Initialize()     {         clientContext = new SP.ClientContext.get_current();         web = clientContext.get_web();         var list = web.get_lists().getByTitle("Absences");         var camlQuery = new SP.CamlQuery();         var q = "&lt;Where&gt;&lt;Eq&gt;&lt;FieldRef Name='StatusID' /&gt;&lt;Value Type='Integer'&gt;1&lt;/Value&gt;&lt;/Eq&gt;&lt;/Where&gt;";         camlQuery.set_viewXml(q);         this.listItems = list.getItems(camlQuery);         clientContext.load(listItems, 'Include(Id)');         clientContext.executeQueryAsync(Function.createDelegate(this, this.onListItemsLoadSuccess),          Function.createDelegate(this, this.onQueryFailed));     }     function onListItemsLoadSuccess(sender, args) {         var count = 0;         var listEnumerator = this.listItems.getEnumerator();         //iterate though all of the items         while (listEnumerator.moveNext()) {             count = count + 1;         }          $('#spnNumberOfAbsences').text(count);     }      function onQueryFailed(sender, args) {         alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());     } &lt;/script&gt;
12427
I have two document libraries on the same web, and am wanting to move the files from one to the other using JSOM/CSOM.  Can anyone please shed some light on how to do this?  Thanks
207
I have a java program which take path as argument. I want to check whether given path is existing or not before doing other validation. Eg: If i give a path D:\Log\Sample which is not not exist, it has to throw filenotfound exception. How can i do that?
122089
I try to add an item to my sharepoint list from a custom web part. Is there any mistake in my code?  [WebMethod]         public static string AjouterDemande()         {             SPList ListeDemandeConge = SPContext.Current.Site.RootWeb.Lists["DEMANDE CONGÉ"];             SPListItem ListItem = ListeDemandeConge.Items.Add();             ListItem["CODE"] = code;             ListItem["DEMANDEUR"] = Utilisateur.LoginName;             ListItem["DATE DEMANDE"] = DateTime.Today.Date;             ListItem["DATE FIN"] = EndDateD;             ListItem["DATE DEPART"] = StartDateD;             ListItem["DUREE"] = int.Parse(DayCount);             ListItem["PREMIER RESPONSABLE"] = Employe.FirstSuperior.LoginName;             ListItem["DEUXIEME RESPONSABLE"] = Employe.SecondSuperior.LoginName;             ListItem["PRESENCE PRES"] = Boolean.Parse(FirstRespPresent);             ListItem["SOLDE CONGE"] = Conge.SoldeAnneeConge;             ListItem["MOIS"] = int.Parse(StartDateTab[1]);             ListItem["ANNEE"] = int.Parse(StartDateTab[0]);             ListItem["JOURS APPROUVEES"] = 0;             ListItem.Update();             ListeDemandeConge.Update();             return "true";          }   When I use F10 to process debugging step by step and get to my listitem.update(), it went out without giving any error.
78509
I have a SharePoint 2013 autohosted app with a number of lists inside of it.  I would like to be able to soft delete a list item using the REST API and have it go to the Recycle Bin instead of being permanently deleted.  According to  that should be the default:     Use the HTTP DELETE command against the specific endpoint URL to delete the SharePoint object represented by that endpoint. In the case of recyclable objects, such as lists, files, and list items, this results in a Recycle operation.   However whenever I delete an item using the REST API (with HTTP DELETE) it does not go into the Recycle Bin and instead appears to be permanently deleted.  If I go to the ".../{app_name}/Lists/{list_name}/AllItems.aspx" page and delete list items through that interface instead, then they nicely go into the Recycle Bin.  Does anyone know how to move list items into the Recycle Bin using only the REST API?
120145
I am currently trying to write a Dynamics CRM 2011 plugin that creates a new SharePoint 2010 site (within an existing site collection) for every account that is created. I have the code for creating a library, which uses the following methods:          private static ClientContext CreateSharePointConnection()         {             try             {                 Uri spSiteUrl = new Uri(Constants.SharePointSiteName);                 using (ClientContext spcontext = new ClientContext(spSiteUrl))                 {                     spcontext.Credentials                         = new System.Net.NetworkCredential(Constants.UserName                             , Constants.Password, Constants.DomainName);                     return spcontext;                 }             }             catch (Exception ex)             {                 throw new Exception("SharePointMethods.CreateSharePointConnection (General Exception: "                     + ex.Message + ")");             }         }  private static void CreateDocumentLibrary(ClientContext _clientContext             , string _documentLibraryName, string _documentLibraryDescription)         {             try             {                 Web web = _clientContext.Web;                 _clientContext.Load(web);                 _clientContext.ExecuteQuery();                 ListCreationInformation lci = new ListCreationInformation();                 lci.Title = _documentLibraryName;                 lci.Description = _documentLibraryDescription;                 lci.TemplateType = 101;                 List newDocumentLibrary = web.Lists.Add(lci);                 newDocumentLibrary.ContentTypesEnabled = true;                 newDocumentLibrary.Update();                 _clientContext.ExecuteQuery();             }             catch (Exception ex)             {                 throw new Exception("SharePointMethods.CreateDocumentLibrary('" + _documentLibraryName                     + "') (General Exception: " + ex.Message + ")");             }         }   So I would like to write a method CreateSite instead of CreateDocumentLibrary. However, all examples I can find on the web for programmatically creating a Site are using SPSite, SPWeb, etc. Something like this:  private static void CreateSite(string _siteName, string _siteDescription) {     try     {         SPSite site = new SPSite(Constants.SharePointSiteName);         SPWeb web = site.OpenWeb();         SPWebCollection wc = web.Webs;         string siteTemplate = web.WebTemplate;         wc.Add(Constants.SharePointSiteName, _siteName, _siteDescription, 1043, siteTemplate, true, false);     }     catch (Exception ex)     {         throw new Exception("SharePointMethods.CreateSite('" + _siteName             + "') (General Exception: " + ex.Message + ")");     } }   However this is NOT a solution for my problem, because the SPSite, SPWeb, etc. only work on the local machine and I want to create a Site from a remote (in my case CRM) server. Anyone got an idea how to solve this.  PS: Code might still contain memory leaks, so please be carful when you use it for production purposes!
115602
I'm trying to batch create wiki pages from an xml file, and have found a few posts that I'm trying to combine, such as  one. There's some problem with my code (Sharepoint isn't creating the pages), but it's not giving me an error message. I'm pretty sure this code is over-complicated, but I'm not sure which parts are necessary, and which are extraneous. Thanks for the help.  CODE:   Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.SharePoint.Client.dll' Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.SharePoint.Client.Runtime.dll'  function CreateTestWiki() { [CmdletBinding()]     Param(     [Parameter(Mandatory=$true)]     [string]$SiteUrl,     [Parameter(Mandatory=$false)]     [string]$PageTitle,     [Parameter(Mandatory=$false)]     [string]$PageUrl,     [Parameter(Mandatory=$false)]     [string]$PageContent,     [Parameter(Mandatory=$false)]     [string]$PageLayout,     [Parameter(Mandatory=$false)]     [switch]$CheckIn,     [Parameter(Mandatory=$false)]     [switch]$Publish,     [Parameter(Mandatory=$false)]     [switch]$CreateFromXml,     [Parameter(Mandatory=$false)]     [string]$XmlInput,     [Parameter(Mandatory=$false)][System.Net.NetworkCredential]$credentials     ) #Region CreateFromXml if ($CreateFromXml) { # Read in list of pages from XML [xml]$pagesXML = Get-Content $($XmlInput) if ($pagesXML -eq $null) { return } # Get publishing web $site = New-Object Microsoft.SharePoint.SPSite($SiteUrl) $psite = New-Object Microsoft.SharePoint.Publishing.PublishingSite($site) $web = $site.OpenWeb() $pWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web) $templateRedirectionPageMarkup = '&lt;%@ Page Inherits="Microsoft.SharePoint.Publishing.TemplateRedirectionPage,Microsoft.SharePoint.Publishing,Version=14.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c" %&gt; &lt;%@ Reference VirtualPath="~TemplatePageUrl" %&gt; &lt;%@ Reference VirtualPath="~masterurl/custom.master" %&gt;';  $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($webUrl) $ctx.Credentials = $credentials   $wikiPages = $ctx.Web.Lists.GetByTitle("Pages") $load = [Microsoft.SharePoint.Client.ClientContext].GetMethod("Load")  $listLoad = $load.MakeGenericMethod([Microsoft.SharePoint.Client.List])  $listLoad.Invoke($ctx,@($wikiPages,$null))  $ctx.ExecuteQuery()  # Loop through each page node to extract filename $pagesXML.Pages.Page | ForEach-Object {     $PageTitle = [string]$_.PageTitle     $PageUrl = [string]$_.PageUrl     $PageLayout = [string]$_.PageLayout     $PageContent = [string]$_.PageContent     $ctype = $psite.ContentTypes[$PageLayout]     $layouts = $psite.GetPageLayouts($ctype, $true)     $layout = $layouts[0]     Write-Host "Creating $($PageTitle)"      # Create blank page     $pages = $pWeb.GetPublishingPages($pWeb)     $page = $pages.Add($PageUrl, $Layout)     #$newPage = $pWeb.AddPublishingPage($PageUrl,$PageLayout)     $page.Update()      # Update the filename to the one specified in the XML     $item = $page.ListItem     $item["Title"] = $PageTitle;     $item["Page Content"] = $PageContent;     $item.Update()     # Check-in and publish page     if ($CheckIn){$item.File.CheckIn("")}     if ($Publish){$item.File.Publish("");} } #End ForEach Loop # Dispose of the web $web.Dispose() } #End CreateFromXml #EndRegion CreateFromXml  }
23361
I have the following code in Visual Studio 2005.      Dim OutFile As System.IO.StreamWriter     Try         OutFile = New System.IO.StreamWriter(Filename)        // Do stuff with OutFile     Catch Ex As Exception        // Handle Exception     Finally        If OutFile IsNot Nothing Then OutFile.Close()     End Try   But VS2005 brings up the warning for the line "If OutFile IsNot.." that      Variable 'OutFile' is used before it has been assigned a value. A null reference exception could result at runtime.   Is there some way of removing this warning by subtly altering the code or is there just a better way of doing what I'm trying to do?  Thanks  Rob
24358
I'm trying to retrieve a file from a server using SFTP (as opposed to FTPS) using Java. How can I do this?
79802
It is discouraged to simply catch System.Exception. Instead, only the &quot;known&quot; exceptions should be caught. Now, this sometimes leads to unnecessary repetitive code, for example: try {     WebId = new Guid(queryString[&quot;web&quot;]); } catch (FormatException) {     WebId = Guid.Empty; } catch (OverflowException) {     WebId = Guid.Empty; }  I wonder: Is there a way to catch both exceptions and only call the WebId = Guid.Empty call once? The given example is rather simple, as it's only a . But imagine code where you modify an object multiple times, and if one of the manipulations fails expectedly, you want to &quot;reset&quot; the object. However, if there is an unexpected exception, I still want to throw that higher.
110124
using System; using System.Security.Permissions; using Microsoft.SharePoint; using Microsoft.SharePoint.Security; using Microsoft.SharePoint.Utilities; using Microsoft.SharePoint.Workflow;  namespace Change_Title_Event.Change_Title {     /// &lt;summary&gt;     /// List Item Events     /// &lt;/summary&gt;     public class Change_Title : SPItemEventReceiver     {        /// &lt;summary&gt;        /// An item is being added.        /// &lt;/summary&gt;        public override void ItemAdding(SPItemEventProperties properties)        {            properties.AfterProperties["Title"] = "Kevin: Changed by event receiver at" + DateTime.Now.TimeOfDay.ToString();            base.ItemAdding(properties);        }       } }   Where simple example, which works perfect on my local Sharepoint 2010. It is sandboxed.  But when I package this solution, it do not work on Sharepoint Online. I does not give any Errors either.  I think I am doing something wrong, something simple, but I can't simply find anything on Google about it.  Here is another who asks on the MSDN forum, but gets a very wierd reply, that I do not understand.