The most common way to do this is by using a try/catch block when you try to use the indexer on SPListCollection. Well, I am pleased to tell you about a new method I discovered on SPListCollection that really made my day. The new TryGetList method takes the name of a list and will get this, return a null if the list doesn’t exist. Take a look at this code.
using (SPSite siteCollection = new SPSite("http://moss-server"))
{
SPList myCustomList = siteCollection.RootWeb.Lists.TryGetList("MyCustomList");
// doesn't throw exception!
if (myCustomList != null)
{
// do something
}
}
Showing posts with label Upload document. Show all posts
Showing posts with label Upload document. Show all posts
Monday, January 24, 2011
Quick overview of Master Pages in SharePoint 2010
The first master page we will talk about is v4.master. This is the default team site master page used with version 4 of the UI. This will be the master page you typically use. It provides the ribbon bar and all of the other new visual UI changes such as the site actions menu on the left side.
If you did an upgrade to SharePoint 2010 and haven’t transitioned to the new UI yet, the old master page is still in default.master. This looks just like the master page you use in SharePoint v3 today. It doesn’t have the ribbon bar and the site actions menu is still on the right side.
The search pages by default now use minimal.master. This is a really slimmed down master page with next to nothing on it. It doesn’t even have navigation. I’m not sure why they opted to use this page in Search Center, but I think it provides an issue with people trying to leave the search center. The Office Web Applications also use this master page but that makes a little more sense because it provides more screen real estate.
The last page I will mention is simple.master. This page is used for login and error pages. From what I understand, it can’t be customized (I have no idea why), but it can be replaced.
Thanks
Sanjay Tiwari
www.YashiTech.com
If you did an upgrade to SharePoint 2010 and haven’t transitioned to the new UI yet, the old master page is still in default.master. This looks just like the master page you use in SharePoint v3 today. It doesn’t have the ribbon bar and the site actions menu is still on the right side.
The search pages by default now use minimal.master. This is a really slimmed down master page with next to nothing on it. It doesn’t even have navigation. I’m not sure why they opted to use this page in Search Center, but I think it provides an issue with people trying to leave the search center. The Office Web Applications also use this master page but that makes a little more sense because it provides more screen real estate.
The last page I will mention is simple.master. This page is used for login and error pages. From what I understand, it can’t be customized (I have no idea why), but it can be replaced.
Thanks
Sanjay Tiwari
www.YashiTech.com
Thursday, May 20, 2010
How to add webpart programmatically in SharePoint webpart page
Adding webpart programmatically in SharePoint webpart page
There are two scenarios:
1. you add a web part that is displaying data for a list, which is called List View Webpart. List view webpart will be created automatically when you create a list.
Here is the code to achieve that.
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
// Get a reference to a web and a list
SPSite site = new SPSite("http://localhost:8000");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["Contacts"];
// Instantiate the web part
ListViewWebPart wp = new ListViewWebPart();
wp.ZoneID = "Left";
wp.ListName = list.ID.ToString("B").ToUpper();
wp.ViewGuid = list.DefaultView.ID.ToString("B").ToUpper();
// Get the web part collection
SPWebPartCollection coll = web.GetWebPartCollection("default.aspx", Storage.Shared);
// Add the web part
coll.Add(wp);
2. you add any other web part (e.g. a custom web part or a 3rd party web part like the SmartPart). The
// Get a reference to a web and a list
SPSite site = new SPSite("http://localhost:8000");
SPWeb web = site.OpenWeb();
// Get the web part collection
SPWebPartCollection coll = web.GetWebPartCollection("default.aspx", Storage.Shared);
string dwp = @" Left SmartPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=dd064a5b12b5277a SmartPart.UserControlWebpart ~\UserControls ";
coll.Add(dwp);
The first section is the same, get a reference to your site and the WebPartCollection (you don’t need a reference to a list). Next you need to build a XML string containing the information about the web part you want to add. The contents of that string are the same as the DWP file that you need to create to use your custom web parts. A trick to figure out what needs to be in there (especially if you want to specify values for some properties) is to put the web part on a page (using the web interface), and choose “Export” from the dropdown menu of the web part. This will save the contents of the DWP in a file. Finally you can add the web part by calling the Add method of the WebPartCollection and using the dwp string as a parameter.
There are two scenarios:
1. you add a web part that is displaying data for a list, which is called List View Webpart. List view webpart will be created automatically when you create a list.
Here is the code to achieve that.
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
// Get a reference to a web and a list
SPSite site = new SPSite("http://localhost:8000");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["Contacts"];
// Instantiate the web part
ListViewWebPart wp = new ListViewWebPart();
wp.ZoneID = "Left";
wp.ListName = list.ID.ToString("B").ToUpper();
wp.ViewGuid = list.DefaultView.ID.ToString("B").ToUpper();
// Get the web part collection
SPWebPartCollection coll = web.GetWebPartCollection("default.aspx", Storage.Shared);
// Add the web part
coll.Add(wp);
2. you add any other web part (e.g. a custom web part or a 3rd party web part like the SmartPart). The
// Get a reference to a web and a list
SPSite site = new SPSite("http://localhost:8000");
SPWeb web = site.OpenWeb();
// Get the web part collection
SPWebPartCollection coll = web.GetWebPartCollection("default.aspx", Storage.Shared);
string dwp = @"
coll.Add(dwp);
The first section is the same, get a reference to your site and the WebPartCollection (you don’t need a reference to a list). Next you need to build a XML string containing the information about the web part you want to add. The contents of that string are the same as the DWP file that you need to create to use your custom web parts. A trick to figure out what needs to be in there (especially if you want to specify values for some properties) is to put the web part on a page (using the web interface), and choose “Export” from the dropdown menu of the web part. This will save the contents of the DWP in a file. Finally you can add the web part by calling the Add method of the WebPartCollection and using the dwp string as a parameter.
Tuesday, May 18, 2010
Creating a SharePoint List programmatically using the object model
Creating a SharePoint List programmatically using the object model
There are two ways to create a SharePoint list programmatically
1. Creating a List programmatically by using out of the box List Template Types, there are many OOTB list templates are available in the SharePoint, list of some of them is geven below.
You can create a list by picking one of the List Template Types available in the SPListTemplateType object
SPSite site = SPContext.Current.Site;
SPWeb web = site.RootWeb;
web.AllowUnsafeUpdates = true;
Guid listId = web.Lists.Add("Test Custom List", "The new custom list", SPListTemplateType.GenericList);
SPList list = web.Lists[listId];
web.AllowUnsafeUpdates = false;
site.Dispose();
web.Dispose();
OOTB List Templates
Events
Contacts
Tasks
PictureLibrary
DiscussionBoard
Survey
DocumentLibrary
Links
Document Library
Announcements
GenericList
WorkflowHistory
DataConnectionLibrary
DataSources
GanttTasks
CustomGrid
NoCodeWorkflows
XMLForm
WebPageLibrary
WorkflowProcess
Form Library
wiki
Wiki Page Library
Picture Library
Picture
Contacts
Calendar
Discussion Board
Project Tasks
Issue Tracking
Custom List
Custom List in Datasheet View
Survey Survey
Custom Workflow Process
Languages and Translators
Translation Management Library
DataSources
Data Connection Library
Workflow History
No Code Workflows
2. Creating a List programmatically with Custom List Template Types
If you have created your own custom list template, you will need to reference the id by enumerating what List Template Types are available at the Site Collection.
SPSite site = SPContext.Current.Site;
SPWeb web = site.RootWeb;
web.AllowUnsafeUpdates = true;
SPListTemplateCollection listTemplates = site.GetCustomListTemplates(mySite);
SPListTemplate template = listTemplates["Enter template name here"];
Guid listId = web.Lists.Add("Test Custom List", "The new custom list", template);
SPList list = web.Lists[listId];
web.AllowUnsafeUpdates = false;
site.Dispose();
web.Dispose();
There are some otherways also like using Feature etc to create a sharepoint list, which I am going to explain it in my next post.
Thanks
Sanjay Tiwari
Dallas, Texas
There are two ways to create a SharePoint list programmatically
1. Creating a List programmatically by using out of the box List Template Types, there are many OOTB list templates are available in the SharePoint, list of some of them is geven below.
You can create a list by picking one of the List Template Types available in the SPListTemplateType object
SPSite site = SPContext.Current.Site;
SPWeb web = site.RootWeb;
web.AllowUnsafeUpdates = true;
Guid listId = web.Lists.Add("Test Custom List", "The new custom list", SPListTemplateType.GenericList);
SPList list = web.Lists[listId];
web.AllowUnsafeUpdates = false;
site.Dispose();
web.Dispose();
OOTB List Templates
Events
Contacts
Tasks
PictureLibrary
DiscussionBoard
Survey
DocumentLibrary
Links
Document Library
Announcements
GenericList
WorkflowHistory
DataConnectionLibrary
DataSources
GanttTasks
CustomGrid
NoCodeWorkflows
XMLForm
WebPageLibrary
WorkflowProcess
Form Library
wiki
Wiki Page Library
Picture Library
Picture
Contacts
Calendar
Discussion Board
Project Tasks
Issue Tracking
Custom List
Custom List in Datasheet View
Survey Survey
Custom Workflow Process
Languages and Translators
Translation Management Library
DataSources
Data Connection Library
Workflow History
No Code Workflows
2. Creating a List programmatically with Custom List Template Types
If you have created your own custom list template, you will need to reference the id by enumerating what List Template Types are available at the Site Collection.
SPSite site = SPContext.Current.Site;
SPWeb web = site.RootWeb;
web.AllowUnsafeUpdates = true;
SPListTemplateCollection listTemplates = site.GetCustomListTemplates(mySite);
SPListTemplate template = listTemplates["Enter template name here"];
Guid listId = web.Lists.Add("Test Custom List", "The new custom list", template);
SPList list = web.Lists[listId];
web.AllowUnsafeUpdates = false;
site.Dispose();
web.Dispose();
There are some otherways also like using Feature etc to create a sharepoint list, which I am going to explain it in my next post.
Thanks
Sanjay Tiwari
Dallas, Texas
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
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
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
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
Subscribe to:
Posts (Atom)