MOSS 2007, programmatically downloading document folder; Can't connect to Document folder - c#

I'm attempting to programmatically download all files from a document folder on a Sharepoint 2007 site. So far, I'm able to connect to the site, but am having issues connecting to the folders and download them.
try{
using(SPSite site = new SPSite("http://mysharepointserver/sites/subsite")){
using(SPWeb web = site.OpenWeb()){
Console.Write("Connected to site");
SPFolder testFolder = web.Folder["testFolder"];
//example method downloading folder
downloadFolder(testFolder);
}
}
}
catch(Exception e){
Log(e.ToString());
}
My console write works,so I know I am connecting to the site correctly.
My log file outputs:
System.ArgumentException: Value does not fall within the expected range.
at Microsoft.SharePoint.SPListCollection.GetListByName(String strListName, Boolean bThrowException)
at Microsoft.SharePoint.SPListCollection.get_Item(String strListName)
I also attempted to print out the following:
using(SPWeb web = site.OpenWeb()){
Console.Write("Connected to site");
Console.Write(web.lists);
SPFolder testFolder = web.Folder["testFolder"];
//example method downloading folder
downloadFolder(testFolder);
}
Which outputs the following to console:
Connected to site
Microsoft.SharePoint.SPListCollection
But I'm not certain how to navigate through SPListCollection to retrieve my folder "testFolder"
Any help would be appreciated. Thanks!

When you connect to share point site, there are different types of libraries. Library that contains documents and folders is DocumentLibrary and not ListLibrary. Once you have the item / library by ID, cast it to correct SPDocumentLibrary to retrieve items you want.
Use https://learn.microsoft.com/en-us/dotnet/api/microsoft.sharepoint.spdocumentlibrary?view=sharepoint-server to get different methods and properties of DocumentLibrary to retrieve the testFolder.
Example of accessing document library item from :https://social.msdn.microsoft.com/Forums/en-US/5ee7fb55-5d90-4d28-8990-bf00479f891f/how-to-get-spdocumentlibrary?forum=sharepointdevelopmentprevious
SPSite siteCollection = this.Site;
SPWeb site = this.Web;
// obtain query string values
string ListId = Request.QueryString["ListId"];
string ItemId = Request.QueryString["ItemId"];
// create list object and list item object
SPList list = site.Lists[new Guid(ListId)];
SPListItem item = list.Items.GetItemById(Convert.ToInt32(ItemId));
// query for information about list and list item
string ListTitle = list.Title;
string ItemTitle = item.Title;
if (list is SPDocumentLibrary) {
SPDocumentLibrary documentLibrary = (SPDocumentLibrary)list;
string DocumentTemplateUrl = documentLibrary.DocumentTemplateUrl;
SPFile file = item.File;
string FileAuthor = file.Author.Name;
string FileSize = file.TotalLength.ToString("0,###") + " bits";
}

Related

EWS how do I create a Searchfolder in my own mailbox?

I use following Code to Create a SearchFolder but as it gets to the "Save" line it throws following error:
The email address associated with a folder Id does not match the
mailbox you are operating on.
private SearchFolder CreateSearchFolder( string email, SearchFilter filter)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
service.Credentials = new WebCredentials("mailboxworker", "password");
service.AutodiscoverUrl(email);
FolderId folderId = new FolderId(WellKnownFolderName.Inbox, new Mailbox(email));
FolderId searchFolderId = new FolderId(WellKnownFolderName.SearchFolders, new Mailbox(email));
// Create the folder.
SearchFolder searchFolder = new SearchFolder(service);
searchFolder.DisplayName = "Folder of " + email;
searchFolder.SearchParameters.SearchFilter = filter;
// Set the folder to search.
searchFolder.SearchParameters.RootFolderIds.Add(folderId);
// Set the search traversal. Deep will search all subfolders.
searchFolder.SearchParameters.Traversal = SearchFolderTraversal.Deep;
// Call Save to make the EWS call to create the folder.
searchFolder.Save(searchFolderId);
return searchFolder;
}
What am I doing wrong?
associated with a folder Id does not match the mailbox
All the times I've bumped into this I've fixed it using the Microsoft.Exchange.WebServices.Data WellKnownFolderName enum instead of a string folderId
Here is a working example from MSDN: Create a search folder by using the EWS Managed API
This example assumes that the ExchangeService object has been initialized with valid values in the Credentials and Url properties.
using Microsoft.Exchange.WebServices.Data;
static void CreateSearchFolder(string email)
{
// Create the folder.
SearchFolder searchFolder = new SearchFolder(service);
searchFolder.DisplayName = "From Developer";
// Create a search filter to express the criteria for the folder.
EmailAddress developer= new EmailAddress("Jeremy#stackoverflow.com");
SearchFilter.IsEqualTo fromManagerFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.Sender, developer);
// Set the search filter.
searchFolder.SearchParameters.SearchFilter = fromManagerFilter;
// Set the folder to search.
searchFolder.SearchParameters.RootFolderIds.Add(WellKnownFolderName.Inbox);
// Set the search traversal. Deep will search all subfolders.
searchFolder.SearchParameters.Traversal = SearchFolderTraversal.Deep;
// Call Save to make the EWS call to create the folder.
searchFolder.Save(WellKnownFolderName.SearchFolders);
}
Here is another example on MSDN Creating search folders by using the EWS Managed API 2.0

Why I can't insert a file into a SharePoint list via code? It goes into exception, seems that the access is denied

I am very new in SharePoint (I am using SharePoint 2013) and I am experiencing a strange problem. This is very strange because in another section of my application it works fine (in another subsite).
So basically into SharePoint I have a SharePoint list named Protocollo.
My code contains the following lines that add a document (a file) into a subfolder of the previous SharePoint List:
internal static int InsertItem(Dictionary<string, object> prot, Documento doc, bool assignVisibility, bool newItem)
{
int state = 0;
SPListItem item = null;
UOR currUOR = null;
List<UOR> path = new List<UOR>();
SPWeb web = SPContext.Current.Web;
string siglaAOO = web.Properties["sigla_aoo"];
DBConnection dbConfig = ArxeiaProtocollo.Util.ProtUtils.InitializeDBConnection();
dbConfig.Database = siglaAOO;
string username = web.CurrentUser.LoginName;
try
{
SPList list = web.Lists["Protocollo"];
web.AllowUnsafeUpdates = true;
SPFolderCollection folders = list.RootFolder.SubFolders;
SPFolder annoFolder;
DateTime dateProt = Convert.ToDateTime(prot["Data protocollo"]);
try
{
annoFolder = folders[dateProt.Year.ToString()];
}
catch
{
annoFolder = folders.Add(dateProt.Year.ToString());
}
SPFolder meseFolder;
try
{
meseFolder = annoFolder.SubFolders[dateProt.Month.ToString("D2")];
}
catch
{
meseFolder = annoFolder.SubFolders.Add(dateProt.Month.ToString("D2"));
}
SPFolder dayFolder;
try
{
dayFolder = meseFolder.SubFolders[dateProt.Day.ToString("D2")];
}
catch
{
dayFolder = meseFolder.SubFolders.Add(dateProt.Day.ToString("D2"));
}
SPFile spFile = dayFolder.Files.Add(doc.Nome, doc.File, true);
............................................................
............................................................
............................................................
}
As you can see the previous code retrievce the Protocollo list from the current website allowing updates on it by:
SPList list = web.Lists["Protocollo"];
web.AllowUnsafeUpdates = true;
Then into this list it creates (it doesn't exist) a gerarcic folders structure for year (annoFolder), month (meseFolder) and day (dayFolder).
It works fine, I tried to delete these folder structure from my SharePoint site and performing this method it is created again, infact this is what I obtained:
As you can see it correctly creates this folder structure into my SharePoint list (named Protocollo) into the current website.
Ok finnally my code try to insert a document into the last subfolder (the dayfolder) by:
SPFile spFile = dayFolder.Files.Add(doc.Nome, doc.File, true);
I am passing to the Add() method: the name of the file, the byte array representing the file and the true boolean value.
The problem is that performing this line I obtain the following exception that is not providing information:
{Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}
Then in my front end it appears a "denied access" popup window.
The strange thing is that another sites in my SharePoint that uses the same code have no problem. Another strange thing is that manually uploading the file into this location of the list it works fine so I think that it should not be a user permission problem.
Some idea? What can I try to do to solve this strange problem?
SharePoint codes run using the Application Pool user in IIS not the user that you have logged in to SharePoint, so it is common to get an access denied error even when you have access. So I would suggest you check the permission for the AppPool account on the Protocollo library. Or you can use SPSecurity.RunWithElevatedPrivileges if you have trust in the user that will run the code.
Beware of the pitfalls though.
Here is a sample usage:
Guid siteId = SPContext.Current.Site.ID;
Guid webId = SPContext.Current.Web.ID;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteId))
{
using (SPWeb web = site.OpenWeb(webId))
{
// Your code here
}
}
});

403 on file creation while using Hadoop.WebHDFSClient, Although was able to create Folders in HDFS

This code works till the folder creation then could not create file and throws 403. am I missing some thing here for authentication. I am new to Hadoop and trying to learn hdInsight.
private static void uploadFile()
{
//set variables
string srcFileName = #"./prime/in/integers.txt";
string destFolderName = #"/prime/in";
string destFileName = #"integers.txt";
string outputFolderName= #"/prime/out";
//connect to hadoop cluster
Uri myUri = new Uri("http://DXPZN72-LP:50070");
string userName = "hadoop";
WebHDFSClient myClient = new WebHDFSClient(myUri, userName);
//drop destination directory (if exists)
myClient.DeleteDirectory(destFolderName, true).Wait();
//create destination directory
myClient.CreateDirectory(destFolderName).Wait();
//create outputFolderName directory
myClient.CreateDirectory(outputFolderName).Wait();
//load file to destination directory
var res= myClient.CreateFile(srcFileName, "/" +destFileName);
res.Wait();
//list file contents of destination directory
Console.WriteLine();
Console.WriteLine("Contents of " +destFolderName);
myClient.GetDirectoryStatus(destFolderName).ContinueWith(
ds => ds.Result.Files.ToList().ForEach(
f => Console.WriteLine("t" +f.PathSuffix)
));
//keep command window open until user presses enter
Console.ReadLine();
}
This was found to be a service needed restarted.Although I was able to create folders but was not able to create File with a 403.
I restarted my machine then tried again, the issue was gone and I was able to create file as well.

When renaming a file in SharePoint via client object model, the filename gets trimmed if there's a dot in between

I wrote a small application using the SharePoint client object model, which renames all files inside a SharePoint 2010 document library.
Everything works well, except if the filename should contain a dot somewhere in between, it get's trimmed, starting with the dot.
For example, when the new filename should be "my fi.le name" it ends up with "my fi" in SharePoint. The extension of the file (.pdf in my case) stays correct by the way.
Here's what I'm doing (in general):
ClientContext clientContext = new ClientContext("http://sp.example.com/thesite);
List list = clientContext.Web.Lists.GetByTitle("mydoclibrary");
ListItemCollection col = list.GetItems(CamlQuery.CreateAllItemsQuery());
clientContext.Load(col);
clientContext.ExecuteQuery();
foreach (var doc in col)
{
if (doc.FileSystemObjectType == FileSystemObjectType.File)
{
doc["FileLeafRef"] = "my fi.le name";
doc.Update();
clientContext.ExecuteQuery();
}
}
When I'm renamig the file in SharePoint manually via browser (edit properties), everything works as it should: The dot stays and the filename won't be trimmed at all.
Is "FileLeafRef" the wrong property? Any ideas what's the cause here?
Using FileLeafRef property it is possible to update file name but without extension.
How to rename file using SharePoint CSOM
Use File.MoveTo method to rename a file:
public static void RenameFile(ClientContext ctx,string fileUrl,string newName)
{
var file = ctx.Web.GetFileByServerRelativeUrl(fileUrl);
ctx.Load(file.ListItemAllFields);
ctx.ExecuteQuery();
file.MoveTo(file.ListItemAllFields["FileDirRef"] + "/" + newName, MoveOperations.Overwrite);
ctx.ExecuteQuery();
}
Usage
using (var ctx = new ClientContext(webUrl))
{
RenameFile(ctx, "/Shared Documents/User Guide.docx", "User Guide 2013.docx");
}

Web.GetFileByServerRelativeUrl throws "Value does not fall within expected range"

I have a SP Online site where I store Documents, I have no issues adding/retrieving documents but in the delete flow I get an error during retrieval of a File object.
public static void DeleteDocument()
{
using (ClientContext ctx = ClientContextFactory.Create("https://my-sponline-site.sharepoint.com/sites/documentsite"))
{
Web web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
string relativeUrl = "/Documents/images.jpg";
File file = web.GetFileByServerRelativeUrl(relativeUrl);
ctx.Load(file);
file.DeleteObject();
ctx.ExecuteQuery();
}
}
Full Url of the file is "https://my-sponline-site.sharepoint.com/sites/documentsite/Documents/images.jpg" (No more accessible 2016-12-07)
When I execute this, I get a ServerException :
Value does not fall within the expected range.
The Context is working fine as I'm able to add/retrieve items from the library and the context user is administrator.
I tried adding the web url to the relativeUrl so it would be "/documentsite/Documents/images.jpg" but I get the same error.
I can't seem to figure this out, any suggestions?
Thanks
string relativeUrl = "/sites/documentsite/Documents/images.jpg";

Categories

Resources