Thursday, April 15, 2010

Uploading a document into SharePoint Document Library Part 2

Yes, this is part 2. Uploading a document in a sharepoint document library where the settings for the document libary are

1. Create a version each time you edit a file in this document library? Yes (Create major or minor versions )
2. Require documents to be checked out before they can be edited? Yes

And after uploding the document

1. You want to update a metadata column also for same document.
2. Check the document back in.

Here in this process followings are the main steps

Step 1: Get the file in binary format to be uploaded.
Step 2: Check if the file already exists in the library.
Step 3: Check if file is already checked out by somebody else.
Step 4: If file exists and not checked out by anybody else then check it out. (You wont be able to upload a file if it is not checked out).
Step 5: Upload the file.
Step 6: Check-in the file.



protected void HandleUploadDocument(object sender, EventArgs eventArgs)
{
try
{



bool flgPublish = true;

if (attachdoc.PostedFile != null)
{
if (attachdoc.PostedFile.ContentLength > 0)
{

string filename = attachdoc.PostedFile.FileName.ToString();
string[] split = filename.Split(new Char[] { '\\' });
filename = split[split.Length - 1].ToString();

System.IO.Stream strm = attachdoc.PostedFile.InputStream;
byte[] byt = new byte[Convert.ToInt32(attachdoc.PostedFile.ContentLength)];
strm.Read(byt, 0, Convert.ToInt32(attachdoc.PostedFile.ContentLength));
strm.Close();

// Open site where document library is created.
SPSite objSite = SPContext.Current.Site;
SPWeb objWeb = objSite.OpenWeb();
SPFolder mylibrary = objWeb.Folders["Project Documents"];

if (objWeb.GetFile("Project Documents/" + filename).Exists)
{
if (objWeb.GetFile("Project Documents/" + filename).CheckOutStatus == SPFile.SPCheckOutStatus.None)
{
objWeb.GetFile("Project Documents/" + filename).CheckOut();
}
else
{
flgPublish = false;
SPUser chkBy = objWeb.GetFile("Project Documents/" + filename).CheckedOutBy;
url = "checkedout";
lblLessonListError.Text = "Cannot upload the file. File is checked out by " + chkBy.LoginName;
trLessonListError.Visible = true;
}
}

if (flgPublish == true)
{
objWeb.AllowUnsafeUpdates = true;
SPFile spfile = mylibrary.Files.Add(System.IO.Path.GetFileName(filename), byt, true);

SPDocumentLibrary docs = (SPDocumentLibrary)objWeb.Lists[mylibrary.ContainingDocumentLibrary];
SPListItem item = docs.Items[spfile.UniqueId];
item["Project_x0020_Phase"] = "Metadata Text";
item.Update();

spfile.CheckIn("Checked in", SPCheckinType.MinorCheckIn);
objWeb.AllowUnsafeUpdates = false;
url = spfile.Item["Encoded Absolute URL"].ToString();
}

}
}


}
catch (Exception ex)
{
SW = File.AppendText("D:\\temp\\LogImport.txt");
SW.WriteLine(" Error Occurred : " + ex.Message + " User : " + SPContext.Current.Web.CurrentUser.ToString() + " " + DateTime.Now.ToString() + " " + ex.StackTrace);
SW.WriteLine("--------------------------------------------------");
SW.Close();
}

}



Leave the question, I will respond for any of your query.

Thanks
Sanjay Tiwari
s_tiwari05@yahoo.com

Tuesday, April 6, 2010

Upload a document into SharePoint library programmatically

Its very simple and straight forward. Steps are

1. Get instance of site using SPSite class
2. Get Instance of web using SPWeb class
3. Get the Library instance using SPFolder class, where you want to upload document.
4. Get the file to be uploaded.
5. Get the FileStream of the file to be uploaded.



public void publishDocumentToSharepoint(string filename)
{
string fileToUpload = "D:\\temp\\" + filename;
using (SPSite objSite = SPContext.Current.Site)
{
using (SPWeb objWeb = objSite.OpenWeb())
{
if (System.IO.File.Exists("D:\\temp\\" + filename))
{
SPFolder mylibrary = objWeb.Folders["Project Documents"];
Boolean replaceExistingFile = true;
string fileName = System.IO.Path.GetFileName(fileToUpload);
FileStream fileStream = File.OpenRead(fileToUpload);
objWeb.AllowUnsafeUpdates = true;
SPFile spfile = mylibrary.Files.Add(fileName, fileStream, replaceExistingFile);
mylibrary.Update();
fileStream.Close();
fileStream.Dispose();
objWeb.AllowUnsafeUpdates = false;
}
}
}



}



Questions/queries/suggestions are welcome.

Thanks
Sanjay Tiwari

Monday, March 29, 2010

UIVersionLabel property of file object, yes this is the property which will give you the latest version of a file stored in a version enabled document liabrary. so steps are ;

1- Create SPSite object
2- Get SWeb object.
3- Get the library
4- Get the file and then use UIVersionlable property to get the latest version.



public void getLastVersion()
{
string doclibname = ConfigurationManager.AppSettings["doclibname"].ToString();
string fname = "filename.doc";


bool blnFound = false;
//get the latest version
using (SPSite objSite = SPContext.Current.Site)
{
using (SPWeb objWeb = objSite.OpenWeb())
{
SPFolder mylibrary = objWeb.Folders[doclibname];
foreach (SPFile file in mylibrary.Files)
{
if (file.Name.ToString() == fname + ".doc")
{
blnFound = true;
lblVersion.Text = file.UIVersionLabel;
lblDate.Text = file.TimeLastModified.ToString("MM/dd/yyyy");
}
}
if (blnFound == false)
{
lblVersion.Text = "Not Available";
lblDate.Text = "Not Available";
}

}
}
}


Thanks
Sanjay Tiwari

Thursday, March 25, 2010

As usual, you need to reference liabraries System.Configuration to access AppSettings and Microsoft.Sharepoint for sharepoint object model

public void DeleteFile(string FinalFileName)
{
string s_FileName = "";
string doclibname = ConfigurationManager.AppSettings["doclibname"].ToString();
SPSite objSite = SPContext.Current.Site;
SPWeb objWeb = objSite.OpenWeb();
SPFolder mylibrary = objWeb.Folders[doclibname];
foreach (SPFile file in mylibrary.Files)
{
if (file.Name.ToString().ToUpper() == FinalFileName.ToUpper())
{
objWeb.AllowUnsafeUpdates = true;
file.Delete();
mylibrary.Update();
break;

}
}

}

Friday, January 16, 2009

Retrieving data from multiple sharepoint lists.

we can use SPSiteDataQuery Class to get data from multiple sharepoint lists, which may be located in multiple Web sites in the same Web site collection.

Here is the example.

SPSiteDataQuery objSPSiteDataQuery;
objSPSiteDataQuery = new SPSiteDataQuery();
objSPSiteDataQuery.Query = strCAMLQuery;
objSPSiteDataQuery.Lists = " ";
objSPSiteDataQuery.Webs = "";
objSPSiteDataQuery.ViewFields = "";
if (web.GetSiteData(objSPSiteDataQuery).Rows.Count > 0)
{
dt = web.GetSiteData(objSPSiteDataQuery);
}


Here I have used only one sharepoint list you can specify multiple lists also like below.


objSPSiteDataQuery.Lists="";

Hope it will help.

Wednesday, December 10, 2008

Creating a sharepoint page dynamically.

The SPWeb object for a site exposes a Files property with a public Add method that allows you to add new site pages. There is an overloaded version of the Add method that allows you pass a stream object with the content of the new page. The following example demonstrates writing the contents of a new page to a Memory Stream object and then using it to create a new site page named Hello.htm.

//write out new page in memory stream.
MemoryStream stream=new MemoryStream();
StreamWriter writer=new StreamWriter(stream);
writer.WriteLine("");
writer.WriteLine("Hello, world");
writer.WriteLine("");
writer.Flush();

//add new page to site
SPWeb site=SPContext.Current.Web;
site.Files.Add("hello.htm",stream);



Let me know if you have any question.

Thanks,
Sanjay

Friday, December 5, 2008

How to create a custom e-mail alert handler in Microsoft Office SharePoint Server

This method creates a class that inherits from the IAlertNotificationHandler interface and that uses the OnNotification method. This method lets you intercept the outgoing e-mail alerts and modify them. You can access most of the properties of the alert. By using XML parsing and SharePoint object model code, you can extract all the information that you must have to modify the e-mail alert. Then, you can build the HTML stub to display the e-mail alert based on your requirements. Also, you can send the e-mail alert by using SharePoint̢۪s SendMail functionality.

public class Class1:IAlertNotifyHandler
{

#region IAlertNotifyHandler Members

public bool OnNotification(SPAlertHandlerParams ahp)
{
try
{
SPSite site = new SPSite(ahp.siteUrl+ahp.webUrl);
SPWeb web = site.OpenWeb();
SPList list=web.Lists[ahp.a.ListID];
SPListItem item = list.GetItemById(ahp.eventData[0].itemId) ;

string FullPath=HttpUtility.UrlPathEncode(ahp.siteUrl+""+ahp.webUrl+""+list.Title+""+item.Name);
string ListPath = HttpUtility.UrlPathEncode(ahp.siteUrl + "" + ahp.webUrl + "" + list.Title);
string webPath=HttpUtility.UrlPathEncode(ahp.siteUrl+""+ahp.webUrl);

string build = "";
if (ahp.eventData[0].eventType==1)
eventType="Added";
else if(ahp.eventData[0].eventType==2)
eventType="Changed";
else if(ahp.eventData[0].eventType==3)
eventType="Deleted";

build = ""+
"

"+ item.Name.ToString() +" has been "+eventType +"

"+
""+
""+
"" +
"
"+
"Modify my Settings
View "+item.Name+"View " + list.Title + "
";
string subject=list.Title.ToString() ;
SPUtility.SendEmail(web,true , false, ahp.headers["to"].ToString(), subject,build);
return false;
}
catch (System.Exception ex)
{
return false;
}
}

#endregion
}

You can put your questions/Suggestions in the comment section, I w ill try to respond as soon as possible.

Thanks,
Sanjay