Friday 27 May 2011

Creating folder in a document library and creating file inside that folder

In order to create programmatically folder inside library and then create file inside that folder you can use following code:

using (SPWeb web = properties.Web.Site.OpenWeb("/web"))
{
 list = web.Lists["My list"];

 SPFolderCollection collection = list.RootFolder.SubFolders;
 //Create new folder
 SPFolder folder = collection.Add("Automatically created at " + DateTime.Now.ToString().Replace(":", "-"));
 item = folder.Item;
 item[SPBuiltInFieldId.Comments] = "Automatically created";

 this.EventFiringEnabled = false;
 try
 {
  item.Update();
 }
 finally
 {
  this.EventFiringEnabled = true;
 }
}
//insert attachment to folder
if (item.Folder != null)
{
 SPFolder folder = item.Folder;
 if (properties.ListItem.Attachments.Count > 0)
 {
  SPFile file = item.Web.Site.RootWeb.GetFile(properties.ListItem.Attachments.UrlPrefix + properties.ListItem.Attachments[0]);
  byte[] imageData = file.OpenBinary();
  SPListItem contractItem = folder.Files.Add(properties.ListItem.Attachments[0], imageData).Item;
  contractItem.Update();
 }
}

Thursday 26 May 2011

Creating a generic list of an anonymous type ?!?

Yesterday I was wondering how to create a generic list of an anonymous type, something like this:
var employee = new { FirstName = "Jan", LastName = "Kowalski" };
var employeeList = new List();
At the beginning I though this was impossible, but the resolution is closer than it appears:

var employee = new { FirstName = "Jan", LastName = "Kowalski" };
var employeeList = (new[] {employee}).ToList();
employeeList.Clear();

We can extend it to create factory creating those lists:
public static List<T> CreateList<T>(T itemOftype)
{
   List<T> newList = new List<T>();
   return newList;
}