Creating a SharePoint 2010 page via the client object model - sharepoint-2010

I am attempting to create pages in a Sharepoint 2010 pages library via the client object model but I cannot find any examples on how to do it. I have tried two approaches:
The first is to treat the Pages library as a list and try to add a list item.
static void createPage(Web w, ClientContext ctx)
{
List pages = w.Lists.GetByTitle("Pages");
//ListItem page = pages.GetItemById(0);
ListItemCreationInformation lici = new ListItemCreationInformation();
ListItem li = pages.AddItem(lici);
li["Title"] = "hello";
li.Update();
ctx.ExecuteQuery();
}
As expected, this failed with the error message:
To add an item to a document library, use SPFileCollection.Add()
The next approach I tried was to add it as a file. The problem is that the FileCreationInformation object is expecting a byte array and I am not sure what to pass to it.
static void createPage(Web w, ClientContext ctx)
{
List pages = w.Lists.GetByTitle("Pages");
FileCreationInformation file = new FileCreationInformation();
file.Url = "testpage.aspx";
file.Content = new byte[0];
file.Overwrite = true;
ctx.Load(pages.RootFolder.Files.Add(file));
ctx.ExecuteQuery();
}
The piece of code above will add an item in the Pages library but opening the file brings up a blank page which I cannot edit. From reading various topics, I suspect that it may only be possible to add pages via server side code. Any thoughts?
Thanks

The problem is that the
FileCreationInformation object is
expecting a byte array and I am not
sure what to pass to it.
You could you whatever method you want to get the page contents into a string (read it from a file, create it using a StringBuilder, etc) and then convert the string to a byte array using
System.Text.Encoding.ASCII.GetBytes()

First of all, Publishing API is not supported via Client Side Object Model (CSOM) in SharePoint 2010. But you could consider the following approach that demonstrates how to create a publishing page using SharePoint 2010 CSOM.
How to create a publishing page using SharePoint 2010 CSOM
public static void CreatePublishingPage(ClientContext ctx, string listTitle, string pageName, string pageContent)
{
const string publishingPageTemplate = "<%# Page Inherits=\"Microsoft.SharePoint.Publishing.TemplateRedirectionPage,Microsoft.SharePoint.Publishing,Version=14.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c\" %> <%# Reference VirtualPath=\"~TemplatePageUrl\" %> <%# Reference VirtualPath=\"~masterurl/custom.master\" %>";
var pagesList = ctx.Web.Lists.GetByTitle(listTitle);
var fileInfo = new FileCreationInformation
{
Url = pageName,
Content = Encoding.UTF8.GetBytes(publishingPageTemplate),
Overwrite = true
};
var pageFile = pagesList.RootFolder.Files.Add(fileInfo);
var pageItem = pageFile.ListItemAllFields;
if (!ctx.Site.IsPropertyAvailable("ServerRelativeUrl"))
{
ctx.Load(ctx.Site);
ctx.ExecuteQuery();
}
pageItem["PublishingPageLayout"] = string.Format("{0}_catalogs/masterpage/ArticleLeft.aspx, ArticleLeft",ctx.Site.ServerRelativeUrl);
pageItem["PublishingPageContent"] = pageContent;
pageItem.Update();
ctx.ExecuteQuery();
}
Usage
using (var ctx = new ClientContext(url))
{
ctx.Credentials = new NetworkCredential("username", "password", "domain");
CreatePublishingPage(ctx, "Pages", "Greetings.aspx", "Welcome to SharePoint!");
}

Related

non-invocable member 'File' cannot be used like a method error message- what am I missing?

I have a Blazor Application which had files uploaded to a upload folder on the web server. I am in the process of trying to figure out the code to download an uploaded file in the browser for retrieval and viewing. Right now the code is as below (the download part from code examples on the internet)
public void FileDetailsToolbarClickHandler(Syncfusion.Blazor.Navigations.ClickEventArgs args)
{
string path = null;
string uploads = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot\\uploads");
path = uploads + "\\" + SelectedFileName;
if (args.Item.Text == "Delete")
{
//Code for Deleting goes here
//UploadRef.Remove();
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
FileDetailsService.FileDetailsDelete(SelectedFileId); //NavigationManager.NavigateTo($"/ServiceRequestNotes/servicerequestnoteadd");
NavigationManager.NavigateTo($"/ServiceRequests/serviceRequestsaddedit2/{Id}", forceLoad: true);
}
else
{
// its a download
IFileProvider provider = new PhysicalFileProvider(uploads);
IFileInfo fileinfo = provider.GetFileInfo(path + SelectedFileName);
var readStream = fileinfo.CreateReadStream();
var mimeType = "application/pdf";
return File(readStream, mimeType, SelectedFileName);
}
}
On the last statement I am a getting the following error message
non-invocable member 'File' cannot be used like a method error message
What am I missing or do I need to change or add to have the output from the readstream render to the browser?
The blazor application is a blazor server app not WASM. It does not make use of API controllers.
Any advice?
This is a void method. You can't return anything at all. Also, if you're trying to instantiate a File object, you'd have to use the new keyword.

Accessing the Request.Content in the new ASP.NET vnext web api way of doing things?

I have searched high and low for this one and can't seem to find a way of accessing the Request.Content in an MVC web api. I basically am trying to create a File Service to and from Azure Blob and Table storage (table for storing metadata about the file, blob for the actual file)....
I was converting the steps in the following link, but this is where I have come unstuck
the back end I have working but can't find a way of the new unified controller passing a fileobject from json post through to the service! Any ideas would be greatly appreciated as always... or am I just going about this the wrong way?
Article here....
UPDATE: so to clarify, what I am trying to do in the new MVC 6 (where you no longer have an apicontroller to inherit from) is to access a file that has been uploaded to the api from a JSON post. That is the long and short of what I am trying to achieve.
I am trying to use the article based on the old Web API which uses the Request.Content to access it, however even if I use the WebAPIShim which they provide I still come unstuck with other objects or properties that are no longer available so I'm wondering if I need to approach it a different way, but either way, all I am trying to do is to get a file from a JSON post to a MVC 6 Web api and pass that file to my back end service....
ANY IDEAS?
Here is an example without relying on model binding.
You can always find the request data in Request.Body, or use Request.Form to get the request body as a form.
[HttpPost]
public async Task<IActionResult> UploadFile()
{
if (Request.Form.Files != null && Request.Form.Files.Count > 0)
{
var file = Request.Form.Files[0];
var contentType = file.ContentType;
using (var fileStream = file.OpenReadStream())
{
using (var memoryStream = new MemoryStream())
{
await fileStream.CopyToAsync(memoryStream);
// do what you want with memoryStream.ToArray()
}
}
}
return new JsonResult(new { });
}
If the only thing in your request is a File you can use the IFormFile class in your action:
public FileDetails UploadSingle(IFormFile file)
{
FileDetails fileDetails;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
fileDetails = new FileDetails
{
Filename = parsedContentDisposition.FileName,
Content = fileContent
};
}
return fileDetails;
}

PDF generation in mvc4 with itextsharp

I am working on pdf generation, it is successfully implemented using itextsharp.dll. It’s working fine on local environment after publish also. We have our own server at other site
But same code doesn't work on the server,pdf is not generated instead it gives an error: 'The document has no pages.'
Initially I thought it is due to no data in document but it works locally with or without data in the document.
I had code implemented as follows to make a web request Is any problem in that ??
try
{
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(strPdfData + "?objpatId=" + patID);
var response = myHttpWebRequest.GetResponse();
myHttpWebRequest.Timeout = 900000;
var stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
content = sr.ReadToEnd();
}
create a method in the controller:
[HttpGet]
public JsonResult GetFile()
{
var json = new WebClient().DownloadFile(string address, string fileName);
//This code is just to convert the file to json you can keep it in file format and send to the view
dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
var oc = Newtonsoft.Json.JsonConvert.DeserializeObject<countdata[]>(Convert.ToString(result.countdata));
return Json(oc, JsonRequestBehavior.AllowGet);
}
In the view just call this function:
#Url.Action('genPDF','GetFile');

How can I do a search with Google Custom Search API for .NET?

I just discovered the Google APIs Client Library for .NET, but because of lack of documentation I have a hard time to figure it out.
I am trying to do a simple test, by doing a custom search, and I have looked among other, at the following namespace:
Google.Apis.Customsearch.v1.Data.Query
I have tried to create a query object and fill out SearchTerms, but how can I fetch results from that query?
My bad, my first answer was not using the Google APIs.
As a pre-requisite, you need to get the Google API client library
(In particular, you will need to reference Google.Apis.dll in your project). Now, assuming you've got your API key and the CX, here is the same code that gets the results, but now using the actual APIs:
string apiKey = "YOUR KEY HERE";
string cx = "YOUR CX HERE";
string query = "YOUR SEARCH HERE";
Google.Apis.Customsearch.v1.CustomsearchService svc = new Google.Apis.Customsearch.v1.CustomsearchService();
svc.Key = apiKey;
Google.Apis.Customsearch.v1.CseResource.ListRequest listRequest = svc.Cse.List(query);
listRequest.Cx = cx;
Google.Apis.Customsearch.v1.Data.Search search = listRequest.Fetch();
foreach (Google.Apis.Customsearch.v1.Data.Result result in search.Items)
{
Console.WriteLine("Title: {0}", result.Title);
Console.WriteLine("Link: {0}", result.Link);
}
First of all, you need to make sure you've generated your API Key and the CX. I am assuming you've done that already, otherwise you can do it at those locations:
API Key (you need to create a new browser key)
CX (you need to create a custom search engine)
Once you have those, here is a simple console app that performs the search and dumps all the titles/links:
static void Main(string[] args)
{
WebClient webClient = new WebClient();
string apiKey = "YOUR KEY HERE";
string cx = "YOUR CX HERE";
string query = "YOUR SEARCH HERE";
string result = webClient.DownloadString(String.Format("https://www.googleapis.com/customsearch/v1?key={0}&cx={1}&q={2}&alt=json", apiKey, cx, query));
JavaScriptSerializer serializer = new JavaScriptSerializer();
Dictionary<string, object> collection = serializer.Deserialize<Dictionary<string, object>>(result);
foreach (Dictionary<string, object> item in (IEnumerable)collection["items"])
{
Console.WriteLine("Title: {0}", item["title"]);
Console.WriteLine("Link: {0}", item["link"]);
Console.WriteLine();
}
}
As you can see, I'm using a generic JSON deserialization into a dictionary instead of being strongly-typed. This is for convenience purposes, since I don't want to create a class that implements the search results schema. With this approach, the payload is the nested set of key-value pairs. What interests you most is the items collection, which is the search result (first page, I presume). I am only accessing the "title" and "link" properties, but there are many more than you can either see from the documentation or inspect in the debugger.
look at API Reference
using code from google-api-dotnet-client
CustomsearchService svc = new CustomsearchService();
string json = File.ReadAllText("jsonfile",Encoding.UTF8);
Search googleRes = null;
ISerializer des = new NewtonsoftJsonSerializer();
googleRes = des.Deserialize<Search>(json);
or
CustomsearchService svc = new CustomsearchService();
Search googleRes = null;
ISerializer des = new NewtonsoftJsonSerializer();
using (var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
googleRes = des.Deserialize<Search>(fileStream);
}
with the stream you can also read off of webClient or HttpRequest, as you wish
Google.Apis.Customsearch.v1 Client Library
http://www.nuget.org/packages/Google.Apis.Customsearch.v1/
you may start from Getting Started with the API.

opening url based file in filestream

I have a document which is stored in doc library of sharepoint..now i want to open and read data from it ...how can i do it ..filestream does not take url as input ..please help.
Try SPFile.OpenBinaryStream
From SharePoint 2007 - Read content from SPFile:
string content = string.Empty;
using (SPSite oSite = new SPSite("http://localhost/"))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
SPDocumentLibrary doclib = (SPDocumentLibrary)oWeb.GetList(DocLibUrl);
SPFile htmlFile = doclib.Items[0].File;
using (System.IO.StreamReader reader = new System.IO.StreamReader(htmlFile.OpenBinaryStream()))
{
content = reader.ReadToEnd();
}
}
}
Sounds like you need to use a HTTPRequest object to retrieve the file. Here is a code example:
http://geeknotes.wordpress.com/2008/01/10/saving-a-possibly-binary-file-from-a-url-in-c/