I am upload document to document library along with metadata using server object model in sharepoint foundation 2010. I am using following code
// Initialize instance of existing site collection
using (SPSite site = new SPSite(siteUrl))
{
//Initailize instance of exiting web site (for e.g. Team Site)
using (SPWeb web = site.RootWeb)
{
//Get list with specified name in the existing web site
SPList list = web.Lists[libraryName];
//Get the collection of folders in the existing web site
String url = list.RootFolder.ServerRelativeUrl.ToString();
SPFolderCollection folders = web.GetFolder(url).SubFolders;
//Add new folder in the exiting collection of folders
SPFolder folder = folders.Add(folderName);
//SPFolder folder = web.GetFolder(siteUrl + "/" + libraryName + "/" + folderName);
//byte[] fileContents = System.IO.File.ReadAllBytes(#fileUrl);
//Add file in the newly added folder with overwrite
var overWrite = true;
SPFile file = folder.Files.Add(saveFileWithName, fileContents, overWrite);
//Get the list item of the newly added file
SPListItem listItem = file.ListItemAllFields;
//Assign values to the fields of newly added file
listItem["User_x0020_Name"] = userName;
listItem["Document_x0020_Type"] = documentType;
listItem["Check_x0020_Type"] = checkType;
//Update the list item with the newly added values to the fields
listItem.Update();
//Get the unique id of the newly added list item
documentGuid = listItem["UniqueId"].ToString();
}
}
The above code works fine. I have versioning enabled on my document library. When the above code run it creates two versions in document library. One when it upload document with
SPFile file = folder.Files.Add(saveFileWithName, fileContents, overWrite);
and another when it adds values to the column User_x0020_Name, Document_x0020_Type and
Check_x0020_Type using
listItem.Update();
I want to create only only one version when user upload document as well as add metadata. How to do this ? Can you please provide me any code or link through which I can resolve the above issue ?
Keep the code same just replace "listItem.Update();" with "listItem.SystemUpdate(false);" it will update the metadata and will not increase the version number.
Related
This is similar to my previous question:
Downloading images from publicly shared folder on Dropbox
I have this piece of code (simplified version) that needs to download all images from publicly shared folder and all sub-folders.
using Dropbox.Api;
using Dropbox.Api.Files;
...
// AccessToken - get it from app console
// FolderToDownload - https://www.dropbox.com/sh/{unicorn_string}?dl=0
using (var dbx = new DropboxClient(_dropboxSettings.AccessToken))
{
var sharedLink = new SharedLink(_dropboxSettings.FolderToDownload);
var sharedFiles = await dbx.Files.ListFolderAsync(path: "", sharedLink: sharedLink);
// var sharedFiles = await dbx.Files.ListFolderAsync(path: "", sharedLink: sharedLink, recursive: true);
// "recursive: true" throws: Error in call to API function "files/list_folder": Recursive list folder is not supported for shared link.
foreach (var entry in sharedFiles.Entries)
{
if (entry.IsFile)
{
var link = await dbx.Sharing.GetSharedLinkFileAsync(url: _dropboxSettings.FolderToDownload, path: "/" + entry.Name);
var byteArray = await link.GetContentAsByteArrayAsync();
}
if (entry.IsFolder)
{
var subFolder = entry.AsFolder;
// var folderContent = await dbx.Files.ListFolderAsync(path: subFolder.Id);
// var subFolderSharedLink = new SharedLink(???);
}
}
}
How do I list entries of all sub-folders?
For any given subfolder, to list its contents, you'll need to call back to ListFolderAsync again, using the same sharedLink value, but supplying a path value for the subfolder, relative to the root folder for the shared link.
For example, if you list the contents of the folder shared link, and one of the entries is a folder with the name "SomeFolder", to then list the contents of "SomeFolder", you would need to make a call like:
await dbx.Files.ListFolderAsync(path: "/SomeFolder", sharedLink: sharedLink);
I am trying to open a multipage HTML web page (i.e. test.html, test.css and test.js) which has been downloaded dynamically (thefore can't use assets) and stored in the apps internal storage (Xamarin.Essentials.FileSystem.AppDataDirectory).
The URL I am trying to use is as follows:
file:///data/user/0/com.test/files/HTML/Test.html
However I just get file not found.
var filesToDownload = new string[] { "http://myserver/test/test.html", "http://myserver/test/test.css" };
var directory = System.IO.Path.Combine(Xamarin.Essentials.FileSystem.AppDataDirectory, "HTML");
if (System.IO.Directory.Exists(directory))
{
System.IO.Directory.Delete(directory, true);
}
System.IO.Directory.CreateDirectory(directory);
using (var wc = new System.Net.WebClient())
{
foreach (var f in filesToDownload)
{
wc.DownloadFile(f, System.IO.Path.Combine(directory, System.IO.Path.GetFileName(f)));
}
}
var source = new UrlWebViewSource
{
Url = System.IO.Path.Combine("file://" + directory, "Test.html")
};
WebView1.Source = source;
There are several points you have to make sure:
1 Add the Xamarin.Essentials NuGet package to each project
2 http://myserver/test/test.html and http://myserver/test/test.css are existed and accessible.
3 The file name of webview source should be the same with the file name you have written to your storage. Not Test.html, but test.html
So
Url = System.IO.Path.Combine("file://" + directory, "Test.html") should be modified to
Url = System.IO.Path.Combine("file://" + directory, "test.html")
I made a C# application for uploading files to SharePoint. So far it Works as intended, on all document libraries except the default one. Everytime it throws an exception : List 'Documents' does not exist at site with URL 'http://...'
I've tried with "Shared Documents" as well, but same result. Does the default library have some internal name I'm not aware of?
The code for uploading is as follows:
// Get the SharePoint context
ClientContext context = new ClientContext(domain);
// Open the web
var web = context.Web;
String[] files = System.IO.File.ReadAllLines(args[0]);
foreach (String file in files)
{
// Create the new file
var newFile = new FileCreationInformation
{
Content = System.IO.File.ReadAllBytes(file),
Url = Path.GetFileName(file),
Overwrite = true
};
// Get a reference to the document library
var docs = web.Lists.GetByTitle(library);
var uploadFile = docs.RootFolder.Files.Add(newFile);
// Upload the document
context.Load(uploadFile);
}
First of all, it is much safer to get list by url, not title.
using (ClientContext context = new ClientContext("https://sharepoint.domain.com"))
{
context.Load(context.Web, w => w.ServerRelativeUrl);
context.ExecuteQuery();
List list = context.Web.GetList($"{context.Web.ServerRelativeUrl.TrimEnd('/')}/Shared Documents");
}
Also don't forget to dispose the object context.
Check enabled alternate languages (Site settings > Site Administration > Language settings). You may have more enabled languages and the default one could be different then you expect. Each language holds its own list name.
I wanted to create a subfolder in web server. Once the customer uploads the document and those files should be saved in folder with name that is from one of the field values from the table.
Here is my controller part
public ActionResult UploadLoader(FormCollection fc, IncidentInfo model, IEnumerable<HttpPostedFileBase> files)
{
int i = 0;
foreach (var file in files)
{
if (file.ContentLength > 0)
{
//add function to test for file types
// extract only the filename
var fileName = Path.GetFileName(file.FileName);
switch (i)
{
case 0:
model.File1_Filename = fileName;
break;
case 1:
model.File2_Filename = fileName;
break;
}
// store the file inside ~/UploadedDocs/ claim number as folder name
var path = Path.Combine(Server.MapPath("~/UploadedDocs/"), model.fh_claim_num + fileName);
// this is the string you have to save in your DB
string filepathToSave = "UploadedDocs/" + model.fh_claim_num + fileName;
file.SaveAs(path);
This is not working.
My confusion is can I get the values from model. Also is it better to attach the folder name inside the directory or outside.
**Bit new to MVC please ignore if any mistake
Thanks
should be saved in folder with name that is from one of the field values from the table
That leads me to believe you haven't created the folder yet to house the files yet. You'll need to use Directory.CreateDirectory() to create the directory that will house the files for that claim number before you attempt to save the file upload.
Is there a simple way to add a web part page to a Sharepoint site programmatically, using either the object model or web services? It seems straight-forward to create lists and add web parts in this manner, but I can't find an example of how to create a content page.
Edit: For a plain WSS installation (not MOSS).
I'm going to take the route that this isn't a collaboration/publishing site as this isn't mentioned and wss is in the tag list. Pretty clunky in comparison to using a publishing site...
First choose the web part page template you'd like to use from:
C:\Program Files\Common
Files\Microsoft Shared\web server
extensions\12\TEMPLATE\1033\STS\DOCTEMP\SMARTPGS
Then set up a stream to the template and use SPFileCollection.Add() to add it to your document library. For example:
string newFilename = "newpage.aspx";
string templateFilename = "spstd1.aspx";
string hive = SPUtility.GetGenericSetupPath("TEMPLATE\\1033\\STS\\DOCTEMP\\SMARTPGS\\");
FileStream stream = new FileStream(hive + templateFilename, FileMode.Open);
using (SPSite site = new SPSite("http://sharepoint"))
using (SPWeb web = site.OpenWeb())
{
SPFolder libraryFolder = web.GetFolder("Document Library");
SPFileCollection files = libraryFolder.Files;
SPFile newFile = files.Add(newFilename, stream);
}
Note: This solution assumes you have the US SharePoint version installed that uses the 1033 language code. Just change the path if different.
Is it a collaboration/publishing site? If so you can the following blog articles should help:
Create and Publish web pages in Publishing SharePoint sites programmatically
Programmatically create pages - and Add Web Parts
Programmatically adding pages to a MOSS Publishing site
An alternative solution to the accepted answer from #AlexAngas is to use the NewWebPage method of the SharePoint Foundation RPC Protocol, as suggested here.
private static void CreateWebPartPage(this SPWeb web, SPList list, string pageName, int layoutTemplate)
{
const string newWPPage = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<Batch>" +
"<Method ID=\"0,NewWebPage\">" +
"<SetList Scope=\"Request\">{0}</SetList>" +
"<SetVar Name=\"Cmd\">NewWebPage</SetVar>" +
"<SetVar Name=\"ID\">New</SetVar>" +
"<SetVar Name=\"Type\">WebPartPage</SetVar>" +
"<SetVar Name=\"WebPartPageTemplate\">{2}</SetVar>" +
"<SetVar Name=\"Overwrite\">true</SetVar>" +
"<SetVar Name=\"Title\">{1}</SetVar>" +
"</Method>" +
"</Batch>";
var newWPPageBatchXml = string.Format(newWPPage, list.ID, pageName, layoutTemplate);
var result = web.ProcessBatchData(newWPPageBatchXml);
}
Usage of the above extension method:
web.CreateWebPartPage(yourList, "NewPage", 2);