Wednesday, April 28, 2010

How to get the latest version lable of a file

Some time it is required just to know the what was the last version of the file saved in the version enabled document library.



public Double getLastVersion(string flname, bool tt)
{
string doclibname = ConfigurationManager.AppSettings["doclibname"].ToString();
Double ver = 0;
//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() == flname+ ".doc")
{
ver = System.Convert.ToDouble(file.UIVersionLabel);
Break;
}
}
return ver;

}
}
}


Thanks
Sanjay Tiwari
Dallas, Texas

How to delete a file from SharePoint document library.

To delete a file and all its versions from a document library where you know only the file name and not the item id etc, there is no other way but to loop through the file collection returned by "Library.File" and break the loop once you find and delete the file.

Here is the example



public void DeleteFile(string FinalFileName)
{
string s_FileName = "";
//Get the library name from webconfig file
string doclibname = ConfigurationManager.AppSettings["doclibname"].ToString();
//Get site object
SPSite objSite = SPContext.Current.Site;
SPWeb objWeb = objSite.OpenWeb();
//Get the library
SPFolder mylibrary = objWeb.Folders[doclibname];
foreach (SPFile file in mylibrary.Files)
{
if (file.Name.ToString().ToUpper() == FinalFileName.ToUpper())
{
//delete the file and exit the loop
objWeb.AllowUnsafeUpdates = true;
file.Delete();
mylibrary.Update();
objWeb.AllowUnsafeUpdates = false;
break;

}
}

}



Thanks
Sanjay Tiwari
Dallas, Texas

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