I'm creating a function where you can provide a content type name and target either a list or document library and create a default item. Im using the client object model for office 2013
public void MyFunction()
{
//clientContext must be authenticated already on your sharepoint site
var listName = "Default Document Set";
var docSetContentTypeName = "Document";
var newDocSetName = string.Format("Item {0}", Guid.NewGuid());
Web web = clientContext.Web;
List list = clientContext.Web.Lists.GetByTitle(listName);
clientContext.Load(clientContext.Site);
ContentTypeCollection listContentTypes = list.ContentTypes;
clientContext.Load(listContentTypes, types => types.Include
(type => type.Id, type => type.Name,
type => type.Parent));
var result = clientContext.LoadQuery(listContentTypes.Where
(c => c.Name == docSetContentTypeName));
clientContext.ExecuteQuery();
ContentType targetDocumentSetContentType = result.FirstOrDefault();
ListItemCreationInformation newItemInfo = new ListItemCreationInformation();
newItemInfo.UnderlyingObjectType = FileSystemObjectType.Folder;
newItemInfo.LeafName = newDocSetName;
ListItem newListItem = list.AddItem(newItemInfo);
newListItem["ContentTypeId"] = targetDocumentSetContentType.Id.ToString();
newListItem["Title"] = newDocSetName;
newListItem.Update();
clientContext.Load(list);
clientContext.ExecuteQuery();
}
The function works fine on ContentTypes like Item and Document Set but when I use Document, it creates an item with a content type "Document" but it has an icon of folder and acts like a folder.
Is there something I need to add?
Thanks in advance.
FileSystemObjectType.Folder is used for creating a Folder object and therefore could not be specified for creating File object. At the same time List.AddItem Method could not be used for creating a File object.
You could consider the following example that demonstrates how to create(upload) a file into Documents library:
public static void UploadFile(List list,string filePath,IDictionary<string,object> itemProperties)
{
var ctx = list.Context;
var fileInfo = new FileCreationInformation();
fileInfo.Url = Path.GetFileName(filePath);
fileInfo.Overwrite = true;
fileInfo.Content = System.IO.File.ReadAllBytes(filePath);
var file = list.RootFolder.Files.Add(fileInfo);
var listItem = file.ListItemAllFields;
foreach (var p in itemProperties)
{
listItem[p.Key] = p.Value;
}
listItem.Update();
ctx.ExecuteQuery();
}
Using Open XML SDK 2.0 for Microsoft Office you could create an empty document and upload it into Documents library:
public static void CreateAndUploadFile(List list, string filePath, IDictionary<string, object> itemProperties)
{
using (var document = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document))
{
var mainPart = document.AddMainDocumentPart();
mainPart.Document = new Document(new Body());
}
UploadFile(list, filePath, itemProperties);
}
Usage:
var list = web.Lists.GetByTitle(listTitle);
var itemProperties = new Dictionary<string,object>();
itemProperties["Title"] = "SharePoint User Guide";
CreateAndUploadFile(list, "./SharePoint User Guide.docx", itemProperties);
Related
I want to get the Content from an item from a specific Changeset. With my code, I get the correct number of items, but every property of the item is empty, only the correct URL is filled up. All other properties are set to null.
How can I solve this?
string collectionUri = #"https://tfs.myServer.de/MyProject";
using (TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(collectionUri)))
{
TfvcHttpClient tfvcClient = tpc.GetClient<TfvcHttpClient>();
var changedItems = tfvcClient.GetChangesetAsync(125453).Result;
IEnumerable<TfvcChange> changesetChanges=tfvcClient.GetChangesetChangesAsync(changedItems.ChangesetId).Result;
foreach (var itemsChange in changesetChanges)
{
Console.WriteLine(itemsChange.NewContent.Content);
}
}
This gets you the contents of the items of a changeset
private static async Task ReadContent(TfvcHttpClient tfvcClient)
{
var changesetId = 123456;
var changesetChanges = await tfvcClient.GetChangesetChangesAsync(changesetId);
var tfvcVersionDescriptor = new TfvcVersionDescriptor(null, TfvcVersionType.Changeset, changesetId.ToString());
foreach (var changesetChange in changesetChanges)
{
var path = changesetChange.Item.Path;
Stream contentStream = await tfvcClient.GetItemContentAsync(path, versionDescriptor: tfvcVersionDescriptor);
using (StreamReader streamReader = new StreamReader(contentStream))
{
var content = streamReader.ReadToEnd();
}
}
}
So, i followed a tutorial to "upload" files to a local path using ASP.net core,
this is the code:
public IActionResult About(IList<IFormFile> files)
{
foreach (var file in files)
{
var filename = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
filename = hostingEnv.WebRootPath + $#"\{filename}";
using (FileStream fs = System.IO.File.Create(filename))
{
file.CopyTo(fs);
fs.Flush();
}
}
return View();
}
I want to read the extended properties of a file (file metadata)like:
name,
author,
date posted,
etc
and to sort the files using this data, is there a way using Iformfile?
If you want to access more file metadata then the .NET framework provides ootb, I guess you need to use a third party library.
Otherwise you need to write your own COM wrapper to access those details.
See this link for a pure C# sample.
Here an example how to read the properties of a file:
Add Reference to Shell32.dll from the "Windows/System32" folder to
your project
List<string> arrHeaders = new List<string>();
List<Tuple<int, string, string>> attributes = new List<Tuple<int, string, string>>();
Shell32.Shell shell = new Shell32.Shell();
var strFileName = #"C:\Users\Admin\Google Drive\image.jpg";
Shell32.Folder objFolder = shell.NameSpace(System.IO.Path.GetDirectoryName(strFileName));
Shell32.FolderItem folderItem = objFolder.ParseName(System.IO.Path.GetFileName(strFileName));
for (int i = 0; i < short.MaxValue; i++)
{
string header = objFolder.GetDetailsOf(null, i);
if (String.IsNullOrEmpty(header))
break;
arrHeaders.Add(header);
}
// The attributes list below will contain a tuple with attribute index, name and value
// Once you know the index of the attribute you want to get,
// you can get it directly without looping, like this:
var Authors = objFolder.GetDetailsOf(folderItem, 20);
for (int i = 0; i < arrHeaders.Count; i++)
{
var attrName = arrHeaders[i];
var attrValue = objFolder.GetDetailsOf(folderItem, i);
var attrIdx = i;
attributes.Add(new Tuple<int, string, string>(attrIdx, attrName, attrValue));
Debug.WriteLine("{0}\t{1}: {2}", i, attrName, attrValue);
}
Console.ReadLine();
You can enrich this code to create custom classes and then do sorting depending on your needs.
There are many paid versions out there, but there is a free one called WindowsApiCodePack
For example accessing image metadata, I think it supports
ShellObject picture = ShellObject.FromParsingName(file);
var camera = picture.Properties.GetProperty(SystemProperties.System.Photo.CameraModel);
newItem.CameraModel = GetValue(camera, String.Empty, String.Empty);
var company = picture.Properties.GetProperty(SystemProperties.System.Photo.CameraManufacturer);
newItem.CameraMaker = GetValue(company, String.Empty, String.Empty);
What is the Uniform Type Identifer to provide to a UIDocumentMenuViewController to allow a user to select *.docx files?
The documentation in System-Declared Uniform Type Identifiers does not list a public UTType that allows filtering by .docx. An identifier exists for a standard *.doc file but not *.docx, is there instead an alternate UTType?
This is my current code:
var allowedDocumentTypes = new string[] {
UTType.RTF,
UTType.Text,
UTType.PDF,
UTType.UTF8PlainText,
UTType.RTFD,
UTType.UTF16ExternalPlainText,
UTType.UTF16PlainText,
UTType.UTF8PlainText,
UTType.FlatRTFD,
"com.microsoft.word.doc",
"com.microsoft.word.docx" // An attempt to include docx filtering.
};
var pickerMenu = new UIDocumentMenuViewController(allowedDocumentTypes, UIDocumentPickerMode.Open);
pickerMenu.DidPickDocumentPicker += (sender, args) =>
{
args.DocumentPicker.DidPickDocument += (sndr, pArgs) =>
{
var securityEnabled = pArgs.Url.StartAccessingSecurityScopedResource();
FileInfo fi = new FileInfo(pArgs.Url.Path);
var result = new SelectFileResult();
result.FilePath = fi.FullName;
result.FileName = fi.Name;
NSUrlRequest urlReq = NSUrlRequest.FromUrl(pArgs.Url);
NSUrlResponse response;
NSError error;;
var data = NSUrlConnection.SendSynchronousRequest(urlReq, out response, out error);
result.MimeType = response.MimeType;
Action onFileConsumeDone = () =>
{
pArgs.Url.StopAccessingSecurityScopedResource();
};
onFileSelected(result, onFileConsumeDone);
};
// Display the document picker
AppDelegate.TopViewController.PresentViewController(args.DocumentPicker, true, null);
};
pickerMenu.ModalPresentationStyle = UIModalPresentationStyle.Popover;
AppDelegate.TopViewController.PresentViewController(pickerMenu, true, null);
I had a shot in the dark and included the identifier com.microsoft.word.docx but it does not trigger filtering by docx.
My current solution is C# but objective-c and swift solutions accepted.
Try org.openxmlformats.wordprocessingml.document
Try
let supportedTypes: [UTType] = [UTType.content]
I am trying to transfer files from one document library on one farm to another. Since both are accessible from same network, I thought of getting column values from source and directly add it into a item on destination. Also upload the file along with the item.
List list = ccSource.Web.Lists.GetByTitle("Source Library");
ccSource.ExecuteQuery(); // ccSource is initialized with source Site collection
CamlQuery query = new CamlQuery();
ListItemCollection itemCollection = list.GetItems(CamlQuery.CreateAllItemsQuery()); //Query can also be selective
ccSource.Load(list);
ccSource.Load(itemCollection);
ccSource.ExecuteQuery();
ccSource.Load(ccSource.Web);
string[] coloumnsList = System.IO.File.ReadAllLines(#"E:\Coloumns.txt");
foreach (ListItem item in itemCollection)
{
ClientContext ccTarget. = new ClientContext("http://TargetSC/sites/mysite");
ccTarget.Credentials = new NetworkCredential("username", "pass", "domain");
ccTarget.ExecuteQuery();
var targetList = ccTarget.Web.Lists.GetByTitle("TargetLibrary");
string diskFilePath = #"E:\downloadedFile.docx"; //I have skipped the download code
var fileInfo1 = new FileCreationInformation
{
Url = System.IO.Path.GetFileName(diskFilePath),
Content = System.IO.File.ReadAllBytes(diskFilePath),
Overwrite = true
};
var file = targetList.RootFolder.Files.Add(fileInfo1);
var itemTar = file.ListItemAllFields;
//update list values
foreach (var allFields in item.FieldValues)
{
if (allFields.Key == "FileLeafRef" || checkColoumn(coloumnsList,allFields.Key))
itemTar[allFields.Key] = allFields.Value;
}
itemTar.Update();
ccTarget.ExecuteQuery(); //Exception here
}
public static bool checkColoumn(string[] arr,string query)
{
bool flag = false;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i].Equals(query))
{flag = true; break;}
}
return flag;
}
I am getting exception:
The given guid does not exist in the term storeon
ccTarget.exceuteQuery()
I'm trying to learn c#/WPF/MVVM by converting a sample WPF app to MVVM. This app opens a xml file for editing and then saves it. The app preforms well until I try to save the file, I'm getting an InvalidCastException. Here is some code
mDataSource.cs
public static List<MediaItem> Load(string filename)
{
var mediafiles = XDocument.Load(filename).Root.Elements("style").Elements("item").Select(
x => new MediaItem(
(string)x.Element("title"),
(string)x.Element("artist"),
(string)x.Element("year")));
return mediafiles.ToList();
}
MainViewModel.cs - Load the xml file
public void LoadList(string filename)
{
this.mediafiles = new ObservableCollection<MediaItemViewModel>();
List<MediaItem> mediabaseList = mDataSource.Load(filename);
foreach (MediaItem mediaitem in mediabaseList)
{
this.mediafiles.Add(new MediaItemViewModel(mediaitem));
}
this.collectionView = CollectionViewSource.GetDefaultView(mediafiles);
if (this.collectionView == null)
throw new NullReferenceException("collectionView");
this.collectionView.CurrentChanged += new EventHandler(this.OnCollectionViewCurrentChanged);
}
Saving the file
private void Save(ICollectionView collectionView)
{
mDataSource mds = new mDataSource();
mds.Save(this.collectionView);
}
mDataSource - Saving the file, during debugging data shows up properly everywhere but the exception comes on the line - MediaItem mi = (MediaItem)mediaitem; {"Unable to cast object of type 'mList.ViewModels.MediaItemViewModel' to type 'mList.Models.MediaItem'."}
public void Save(ICollectionView collectionView)
{
XDocument xdoc = new XDocument();
XElement xeRoot = new XElement("art");
XElement xeSubRoot = new XElement("style");
foreach (var mediaitem in collectionView)
{
MediaItem mi = (MediaItem)mediaitem;
XElement xRow = new XElement("item");
xRow.Add(new XElement("title", mi.Title));
xRow.Add(new XElement("artist", mi.Artist));
xRow.Add(new XElement("year", mi.Year));
xeSubRoot.Add(xRow);
}
xeRoot.Add(xeSubRoot);
xdoc.Add(xeRoot);
xdoc.Save(filename);
}
Thank You
ICollectionView (which shouldn't be referenced in your VM) contains a bunch of MediaItemViewModels.
this.mediafiles.Add(new MediaItemViewModel(mediaitem));
So, you need to get the MediaItem that is wrapped by the given MediaItemViewModel. You didn't include that code, so I can't tell you where the original MI is stored.
foreach (var mediaitem in collectionView.OfType<MediaItemViewModel>())
{
MediaItem mi = mediaitem.ThisPropertyContainsTheWrappedMediaItem;