Uploading files to a SharePoint document library with metadata - sharepoint

I am using the following code to upload a file to a SharePoint Document Library but it's not attaching the metadata:
private void UploadFileToSharePoint(string strInputFileName, string sDocLibraryName)
{
SPWeb site = SPContext.Current.Web;
SPList myList = site.Lists[sDocLibraryName];
string destFileUrl = myList.RootFolder.ServerRelativeUrl + #"/New.txt";
site.AllowUnsafeUpdates = true;
// FileStream fileStream = File.Open(strInputFileName, FileMode.Open);
byte[] strm = File.ReadAllBytes(strInputFileName);
// newFile.CheckIn("File added");
//SPListItem item = newFile.Item;
//item.File.CheckOut();
Hashtable ht = new Hashtable();
ht.Add("Status Indicator", "hello");
ht.Add("Status Description", Description.Text);
ht.Add("Status", "Delayed");
//item.Update();
//item.File.CheckIn("File with metadata");
myList.RootFolder.Files.Add(destFileUrl,strm,ht, true/*overwrite*/);
myList.Update();
}
I am using this function call:
UploadFileToSharePoint(#"C:\check.txt",
"Project Status" /* name of Dc Library*/ );

I don't see where you add the metadata, i see you filling a hashtable and do nothing with it

Related

Sharepoint Online: Copy attachment of list item to a new item using Client object model

I want to read the attachments from one list item (in ItemCreated event) to another, new ListItem. How can I do this with the Client Object Model? All I found is server-side code...
Another question: Are the attachments also deleted when I delete a list item or are they still existing on the server?
I got it! The following code worked for me:
private static void NewTryToAttachFiles(ClientContext ctx, Web web, List fromList, ListItem fromItem, List toList, ListItem toItem)
{
string src = string.Format("{0}/lists/{1}/Attachments/{2}", web.Url, fromList.Title, fromItem.Id);
Folder attachmentsFolder = web.GetFolderByServerRelativeUrl(src);
web.Context.Load(attachmentsFolder);
FileCollection attachments = attachmentsFolder.Files;
web.Context.Load(attachments);
web.Context.ExecuteQuery();
if(attachments.Count > 0)
{
foreach (File attachment in attachments)
{
// FileInformation fileInfo = File.OpenBinaryDirect(ctx, attachment.ServerRelativeUrl);
ctx.Load(toItem);
var clientResultStream = attachment.OpenBinaryStream();
ctx.ExecuteQuery();
var stream = clientResultStream.Value;
AttachmentCreationInformation attachFileInfo = new AttachmentCreationInformation();
Byte[] buffer = new Byte[attachment.Length];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
System.IO.MemoryStream stream2 = new System.IO.MemoryStream(buffer);
attachFileInfo.ContentStream = stream2;
attachFileInfo.FileName = attachment.Name;
Attachment a = toItem.AttachmentFiles.Add(attachFileInfo);
ctx.Load(a);
web.Context.ExecuteQuery();
stream2.Close();
}
}
ctx.Load(toItem);
ctx.ExecuteQuery();
}
It copies the attachments of one list item (fromItem) to the new item!

SharePoint copying images from document library of a Web site to a document library in another Web site

I am moving image files from document library of a Web site to a document library in another Web site. I get the following error # line SPListItem oListItemDest = oFileDest.Item;
error:
[Microsoft.SharePoint.SPException] = {"The object specified does not belong to a list."}
Code:
try
{
using (SPSite oSiteCollectionSrc = new SPSite("http://dev:32223/"))
{
SPWeb oWebsiteSrc = oSiteCollectionSrc.AllWebs["en/people"];
SPList oListSrc = oWebsiteSrc.Lists["Images"];
SPListItemCollection collListItemsSrc = oListSrc.Items;
foreach (SPListItem oListItemSrc in collListItemsSrc)
{
SPFile oFileSrc = oListItemSrc.File;
Stream srcStream = oFileSrc.OpenBinaryStream();
using (SPSite oSiteCollectionDest = new SPSite("http://www.devmysites.com/"))
{
SPWeb oWebsiteDest = oSiteCollectionDest.OpenWeb("en/people");
SPList oListDest = oWebsiteDest.Lists["Images"];
SPFileCollection collFilesDest = oListDest.RootFolder.Files;
try
{
SPFile oFileDest = collFilesDest.Add(oListDest + #"/" + oFileSrc.Name, srcStream, true);
SPListItem oListItemDest = oFileDest.Item;
oListItemDest["Created"] = oFileDest.TimeCreated;
oListItemDest["Modified"] = oFileDest.TimeLastModified;
oListItemDest.Update();
}
catch(Exception es1)
{
Console.WriteLine("# Exception:#");
Console.WriteLine(es1.Message);
}
oWebsiteDest.Dispose();
}
}
oWebsiteSrc.Dispose();
}
}
catch (Exception es)
{
Console.WriteLine("# Exception:#");
Console.WriteLine(es.Message);
}
I have also had to copy documents between sharepoint lists, the code that I used to do it is in the answer to this question: SharePoint 2010: Copy documents between lists

Add/Create new document in SharePoint document Library programmatically

I have created a new Document Library and set up custom content type with MS Word Document Template. When i click on Create new template it works fine. but i need to be able to add some logic on a button event where it will go into that library and create a new document, so that when i go into that library i will see a new document that has been created by that button event.
i tried doing it as i would do a regular list item, but i got the following error on item.update:
To add an item to a document library, use SPFileCollection.Add()
Now i did some research but everywhere i see the code for uploading a file to the document library but no where i can find how to add a new document using my template that is associated in that doc library.
please help and thanks.
public static void colFileMtod()
{
using (SPSite objsite = new SPSite("http://smi-dev.na.sysco.net/SyscoFinance/FSR/"))
{
using (SPWeb objWeb = objsite.OpenWeb())
{
SPFileCollection collFiles = objWeb.GetFolder("BPCPublishRecord").Files;
SPList lst = objWeb.Lists["BPCPublishRecordCopy"];
if (lst != null)
{
if (objWeb.Lists.Cast<SPList>().Any(list => list.Title.Equals("BPCPublishRecordCopy", StringComparison.OrdinalIgnoreCase)))
{
foreach (SPFile file in collFiles)
{
string strDestUrl = collFiles.Folder.Url + "/" + file.Name;
byte[] binFile = file.OpenBinary();
SPUser oUserAuthor = file.Author;
SPUser oUserModified = file.ModifiedBy;
System.DateTime dtCreated = file.TimeCreated;
System.DateTime dtModified = file.TimeLastModified;
SPFile oFileNew = collFiles.Add(strDestUrl, binFile, oUserAuthor, oUserModified, dtCreated, dtModified);
SPListItem oListItem = lst.AddItem();
oListItem = oFileNew.Item;
oListItem["Created"] = dtCreated;
oListItem["Modified"] = dtModified;
oListItem.Update();
objWeb.AllowUnsafeUpdates = true;
}
}
}
}
}
}

Retrieve Image from Picture Library - REST

I am looking for some suggestion or sample around retrieving images (actual file, not URL), from a picture library using REST API.
Thanks for any input.
Task 1: Getting a List of Image libs on a given site
public static XmlNode GetPicLibListingXML(string imagingServiceURL)
{
Imaging wsImaging = new Imaging();
wsImaging.UseDefaultCredentials = true;
wsImaging.Url = imagingServiceURL;
XmlNode xnPicLibs = wsImaging.ListPictureLibrary();
return xnPicLibs;
}
Sample return XML:
<Library name="{3C1D52F5-5387-490A-9A2D-A9C99A208C00}" title="Tech Images" guid="3c1d52f5-5387-490a-9a2d-a9c99a208c00" url="Tech Images" xmlns="http://schemas.microsoft.com/sharepoint/soap/ois/" />
Task 2: Listing Images in a given library
public static XmlNode GetImageFileListing(string imagingServiceURL, string imageFileLibraryName)
{
Imaging wsImaging = new Imaging();
ImageInfo curImageInfo = new ImageInfo();
wsImaging.UseDefaultCredentials = true;
wsImaging.Url = imagingServiceURL;
XmlNode xnListItems = wsImaging.GetListItems(imageFileLibraryName, "");
return xnListItems;
}
Task 3: Download Image(s)
private const string ATTR_FILENAME = "name";
private const string FILENAMESPACEURI = "http://schemas.microsoft.com/sharepoint/soap/ois/";
public static bool DownloadImageFiles(string imagingServiceURL, string imageFileLibraryName, string[] fileNames, string saveToFolder)
{
Imaging wsImaging = new Imaging();
wsImaging.UseDefaultCredentials = true;
wsImaging.Url = imagingServiceURL;
XmlElement parent = (XmlElement)wsImaging.Download(imageFileLibraryName, string.Empty, fileNames, 0, true);
XmlNodeList files = parent.GetElementsByTagName("File", FILENAMESPACEURI);
foreach (XmlNode file in files)
{
if (Directory.Exists(saveToFolder) == false)
{
Directory.CreateDirectory(saveToFolder);
}
byte[] fileBytes = Convert.FromBase64String(file.InnerText);
using (FileStream fs = File.OpenWrite(saveToFolder + file.Attributes[ATTR_FILENAME].Value))
{
BinaryWriter writer = new BinaryWriter(fs);
writer.Write(fileBytes);
writer.Close();
}
}
return true;
}
Note:
Imaging() class is a web reference to imagining.asmx
The Download call natively returns XML so yo uneed to run it through a conversion to byte
If you need to get a reference on the Imagine web service check this on out on MSDN:
http://msdn.microsoft.com/en-us/library/imaging.imaging.aspx
source:
http://gourangaland.wordpress.com/2008/05/30/using-the-moss-imaging-web-service-to-download-imagesimaging-asmx/

xmlns to sharepoint api object

Is it possible to convert the following string to a Sharepoint API object like SPUser or SPUserValueField? (without parsing it)
"<my:Person xmlns:my=\"http://schemas.microsoft.com/office/infopath/2003/myXSD\"><my:DisplayName>devadmin</my:DisplayName><my:AccountId>GLINTT\\devadmin</my:AccountId><my:AccountType>User</my:AccountType></my:Person>"
Thanks,
David Esteves
Yes, the Microsoft.Office.Workflow.Utility assembly has Contact.ToContacts which will deserialize Person XML into an array of Contact instances.
http://msdn.microsoft.com/en-us/library/ms553588
-Oisin
Solved :)
(Just an example)
The following function retrieves the SPUser from person:
protected SPUser GetSPUserFromExtendedPropertiesDelegateTo(string xmnls_node)
{
StringBuilder oBuilder = new StringBuilder();
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(oBuilder);
System.Xml.XmlTextWriter oXmlWriter = new System.Xml.XmlTextWriter(oStringWriter);
oXmlWriter.Formatting = System.Xml.Formatting.Indented;
byte[] byteArray = Encoding.ASCII.GetBytes(xmnls_node);
MemoryStream stream = new MemoryStream(byteArray);
System.IO.Stream s = (Stream)stream;
System.IO.StreamReader _xmlFile = new System.IO.StreamReader(s);
string _content = _xmlFile.ReadToEnd();
System.Xml.XmlDocument _doc = new System.Xml.XmlDocument();
_doc.LoadXml(_content);
System.Xml.XPath.XPathNavigator navigator = _doc.CreateNavigator();
System.Xml.XmlNamespaceManager manager = new System.Xml.XmlNamespaceManager(navigator.NameTable);
manager.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD");
System.Xml.XmlNode _node = _doc.SelectSingleNode("/my:Person/my:AccountId", manager);
if (_node != null)
{
return this.workflowProperties.Web.EnsureUser(_node.InnerText.ToString());
}
return null;
}

Resources