Programmatically instantiate a web part page in Sharepoint - c#

Is there a simple way to add a web part page to a Sharepoint site programmatically, using either the object model or web services? It seems straight-forward to create lists and add web parts in this manner, but I can't find an example of how to create a content page.
Edit: For a plain WSS installation (not MOSS).

I'm going to take the route that this isn't a collaboration/publishing site as this isn't mentioned and wss is in the tag list. Pretty clunky in comparison to using a publishing site...
First choose the web part page template you'd like to use from:
C:\Program Files\Common
Files\Microsoft Shared\web server
extensions\12\TEMPLATE\1033\STS\DOCTEMP\SMARTPGS
Then set up a stream to the template and use SPFileCollection.Add() to add it to your document library. For example:
string newFilename = "newpage.aspx";
string templateFilename = "spstd1.aspx";
string hive = SPUtility.GetGenericSetupPath("TEMPLATE\\1033\\STS\\DOCTEMP\\SMARTPGS\\");
FileStream stream = new FileStream(hive + templateFilename, FileMode.Open);
using (SPSite site = new SPSite("http://sharepoint"))
using (SPWeb web = site.OpenWeb())
{
SPFolder libraryFolder = web.GetFolder("Document Library");
SPFileCollection files = libraryFolder.Files;
SPFile newFile = files.Add(newFilename, stream);
}
Note: This solution assumes you have the US SharePoint version installed that uses the 1033 language code. Just change the path if different.

Is it a collaboration/publishing site? If so you can the following blog articles should help:
Create and Publish web pages in Publishing SharePoint sites programmatically
Programmatically create pages - and Add Web Parts
Programmatically adding pages to a MOSS Publishing site

An alternative solution to the accepted answer from #AlexAngas is to use the NewWebPage method of the SharePoint Foundation RPC Protocol, as suggested here.
private static void CreateWebPartPage(this SPWeb web, SPList list, string pageName, int layoutTemplate)
{
const string newWPPage = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<Batch>" +
"<Method ID=\"0,NewWebPage\">" +
"<SetList Scope=\"Request\">{0}</SetList>" +
"<SetVar Name=\"Cmd\">NewWebPage</SetVar>" +
"<SetVar Name=\"ID\">New</SetVar>" +
"<SetVar Name=\"Type\">WebPartPage</SetVar>" +
"<SetVar Name=\"WebPartPageTemplate\">{2}</SetVar>" +
"<SetVar Name=\"Overwrite\">true</SetVar>" +
"<SetVar Name=\"Title\">{1}</SetVar>" +
"</Method>" +
"</Batch>";
var newWPPageBatchXml = string.Format(newWPPage, list.ID, pageName, layoutTemplate);
var result = web.ProcessBatchData(newWPPageBatchXml);
}
Usage of the above extension method:
web.CreateWebPartPage(yourList, "NewPage", 2);

Related

Programatically target default document library for file upload in SP16

I made a C# application for uploading files to SharePoint. So far it Works as intended, on all document libraries except the default one. Everytime it throws an exception : List 'Documents' does not exist at site with URL 'http://...'
I've tried with "Shared Documents" as well, but same result. Does the default library have some internal name I'm not aware of?
The code for uploading is as follows:
// Get the SharePoint context
ClientContext context = new ClientContext(domain);
// Open the web
var web = context.Web;
String[] files = System.IO.File.ReadAllLines(args[0]);
foreach (String file in files)
{
// Create the new file
var newFile = new FileCreationInformation
{
Content = System.IO.File.ReadAllBytes(file),
Url = Path.GetFileName(file),
Overwrite = true
};
// Get a reference to the document library
var docs = web.Lists.GetByTitle(library);
var uploadFile = docs.RootFolder.Files.Add(newFile);
// Upload the document
context.Load(uploadFile);
}
First of all, it is much safer to get list by url, not title.
using (ClientContext context = new ClientContext("https://sharepoint.domain.com"))
{
context.Load(context.Web, w => w.ServerRelativeUrl);
context.ExecuteQuery();
List list = context.Web.GetList($"{context.Web.ServerRelativeUrl.TrimEnd('/')}/Shared Documents");
}
Also don't forget to dispose the object context.
Check enabled alternate languages (Site settings > Site Administration > Language settings). You may have more enabled languages and the default one could be different then you expect. Each language holds its own list name.

How to upload a file in share point server from a local machine connected through lan using c#

I am really new to this share point stuffs.We have a share point server with admin account in it and i was connecting it from my local machine through ip and share point port manually.
Nut i need to write a program which needs to upload the files into the share point server from the local machine to server. Is it possible in using winforms ? or only possible in web services.?
using (SPSite oSite = new SPSite(sharePointSite))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
if (!System.IO.File.Exists(fileToUpload))
throw new FileNotFoundException("File not found.", fileToUpload);
SPFolder myLibrary = oWeb.Folders[documentLibraryName];
// Prepare to upload
Boolean replaceExistingFiles = true;
String fileName = System.IO.Path.GetFileName(fileToUpload);
FileStream fileStream = File.OpenRead(fileToUpload);
// Upload document
SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
// Commit
myLibrary.Update();
}
}
tried using the above code and i getting error from the following line
using (SPSite oSite = new SPSite(sharePointSite))
and the error was
"The Web application at http://server:port/ could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application"
and am not able to upload the file.
But if i copied and paste the same URL in my local machine i can able to access the sharepoint deployed in server and i can even upload files manually from my local machine.
How to upload a file in sharepoint server from the local machine connected with LAN..??
siteURL = Main URl of the sharepoint (eg) "http://10.0.0.14:48487/";
documentListName = any of the folders in shrepoint (eg) Shared Documents
documentName = name of the file (eg)sampleword.docx , readme.txt etc
documentStream = the byte format of the file which we going to upload.
(eg)byte[] bytefile = System.IO.File.ReadAllBytes(filepath+filename);
public static void UploadDocument(string siteURL, string documentListName, string documentListURL,string documentName, byte[] documentStream = null)
{
try
{
using (SP.ClientContext clientContext = new SP.ClientContext(siteURL))
{
#region"Only if you have credentials"
NetworkCredential Cred = new NetworkCredential("username", "password");
clientContext.Credentials = Cred;
#endregion
SP.List documentsList = clientContext.Web.Lists.GetByTitle(documentListName);
var fileCreationInformation = new SP.FileCreationInformation();
//Assign to content byte[] i.e. documentStream
fileCreationInformation.Content = documentStream;
//Allow owerwrite of document
fileCreationInformation.Overwrite = true;
//Upload URL
fileCreationInformation.Url = documentName;
Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(
fileCreationInformation);
uploadFile.ListItemAllFields.Update();
clientContext.ExecuteQuery();
}
}
catch (Exception ex)
{
}
}
}
This works perfect for me :) :)
make sure your connecting to an existing site collection. the error you have received is quite self explainitory, it cannot find the site collection you have pointed it at. check your string sharePointSite to make sure there isn't a typo and that it's accessing the correct root site collection. Remember with SharePoint SPSite = Site Collection SPWeb = a website in a site collection.
i can't see any glaring errors in your code without running something up myself except to make sure that when you are calling oSite.openweb() it's for a single site within the site collection.

How to upload document with metadata to avoid duplicate versioning?

I am upload document to document library along with metadata using server object model in sharepoint foundation 2010. I am using following code
// Initialize instance of existing site collection
using (SPSite site = new SPSite(siteUrl))
{
//Initailize instance of exiting web site (for e.g. Team Site)
using (SPWeb web = site.RootWeb)
{
//Get list with specified name in the existing web site
SPList list = web.Lists[libraryName];
//Get the collection of folders in the existing web site
String url = list.RootFolder.ServerRelativeUrl.ToString();
SPFolderCollection folders = web.GetFolder(url).SubFolders;
//Add new folder in the exiting collection of folders
SPFolder folder = folders.Add(folderName);
//SPFolder folder = web.GetFolder(siteUrl + "/" + libraryName + "/" + folderName);
//byte[] fileContents = System.IO.File.ReadAllBytes(#fileUrl);
//Add file in the newly added folder with overwrite
var overWrite = true;
SPFile file = folder.Files.Add(saveFileWithName, fileContents, overWrite);
//Get the list item of the newly added file
SPListItem listItem = file.ListItemAllFields;
//Assign values to the fields of newly added file
listItem["User_x0020_Name"] = userName;
listItem["Document_x0020_Type"] = documentType;
listItem["Check_x0020_Type"] = checkType;
//Update the list item with the newly added values to the fields
listItem.Update();
//Get the unique id of the newly added list item
documentGuid = listItem["UniqueId"].ToString();
}
}
The above code works fine. I have versioning enabled on my document library. When the above code run it creates two versions in document library. One when it upload document with
SPFile file = folder.Files.Add(saveFileWithName, fileContents, overWrite);
and another when it adds values to the column User_x0020_Name, Document_x0020_Type and
Check_x0020_Type using
listItem.Update();
I want to create only only one version when user upload document as well as add metadata. How to do this ? Can you please provide me any code or link through which I can resolve the above issue ?
Keep the code same just replace "listItem.Update();" with "listItem.SystemUpdate(false);" it will update the metadata and will not increase the version number.

Can somebody provide a simple C# coding example for capturing SharePoint details for a single file?

I am working with VS 2008 and am able to apply the Microsoft.SharePoint.DLL file as a reference in the code. There are many examples avaialble for batch processing files in entire SharePoint folders, but I am looking for a simple in C# example for capturing the following properties given the following for a single file on SharePoint.
Given the following:
- URL folder path ("http://community.xx.com/yada/blah/AllItems.aspx")
- FileName ("MyFile.xls")
- UNC ("\community.xx.com\yada\blah\MyFile.xls")
Results needed for following properties:
- Modified By
- TimeLastModified
- UniqueID
- FileType
- Title
I am guessing that SPFile and SPUser need to be applied, but am not clear as to how.
Thanks
This is actually a lot easier than you think...
string fullItemUri = "http://community.xx.com/yada/blah/MyFile.xls";
using (SPSite site = new SPSite(fullItemUri))
using (SPWeb web = site.OpenWeb())
{
SPListItem item = web.GetListItem(fullItemUri);
string modifiedBy = item[SPBuiltInFieldId.Modified_x0020_By] as string;
DateTime timeLastModified = item[SPBuiltInFieldId.Last_x0020_Modified] as DateTime;
int uniqueID = item.ID;
string fileType = item[SPBuiltInFieldId.FileType] as string;
string title = item[SPBuiltInFieldId.Title] as string;
}
See the MSDN Article for SPBuiltInFieldId and SPListItem for more.

Process.Start is not working after hosting asp.net web application in IIS

I have a return a c# code to save a file in the server folder and to retrieve the saved file from the location. But this code is working fine in local machine. But after hosting the application in IIS, I can save the file in the desired location. But I can't retrieve the file from that location using
Process.Start
What would be the problem? I have searched in google and i came to know it may be due to access rights. But I don't know what would be exact problem and how to solve this? Any one please help me about how to solve this problem?
To Save the file:
string hfBrowsePath = fuplGridDocs.PostedFile.FileName;
if (hfBrowsePath != string.Empty)
{
string destfile = string.Empty;
string FilePath = ConfigurationManager.AppSettings.Get("SharedPath") + ConfigurationManager.AppSettings.Get("PODocPath") + PONumber + "\\\\";
if (!Directory.Exists(FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1)))
Directory.CreateDirectory(FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1));
FileInfo FP = new FileInfo(hfBrowsePath);
if (hfFileNameAutoGen.Value != string.Empty)
{
string[] folderfiles = Directory.GetFiles(FilePath);
foreach (string fi in folderfiles)
File.Delete(fi);
//File.Delete(FilePath + hfFileNameAutoGen.Value);
}
hfFileNameAutoGen.Value = PONumber + FP.Extension;
destfile = FilePath + hfFileNameAutoGen.Value;
//File.Copy(hfBrowsePath, destfile, true);
fuplGridDocs.PostedFile.SaveAs(destfile);
}
To retrieve the file:
String filename = lnkFileName.Text;
string FilePath = ConfigurationManager.AppSettings.Get("SharedPath") + ConfigurationManager.AppSettings.Get("PODocPath") + PONumber + "\\";
FileInfo fileToDownload = new FileInfo(FilePath + "\\" + filename);
if (fileToDownload.Exists)
Process.Start(fileToDownload.FullName);
It looks like folder security issue. The folder in which you are storing the files, Users group must have Modify access. Basically there is user(not sure but it is IIS_WPG) under which IIS Process run, that user belongs to Users group, this user must have Modify access on the folder where you are doing read writes.
Suggestions
Use Path.Combine to create folder or file path.
You can use String.Format to create strings.
Create local variables if you have same expression repeating itself like FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1)
Hope this works for you.
You may have to give permissions to the application pool that you are running. see this link http://learn.iis.net/page.aspx/624/application-pool-identities/
You can also use one of the built-in account's "LocalSystem" as application pool identity but it has some security issue's.

Categories