Download file with url as http://<site collection>/_layouts/DocIdRedir.aspx?ID=<doc id> using web request - sharepoint

I have a site collection in which Document Id feature is activated.
Documents are archived to this site collection from another site (in which Document Id is activated as well) and the only information I have about the moved file is the document id which is same between the source and the destination.
I need to download the file using web request, but my code gives '401 Unauthorised Exception'.
My code is as below:
string url = "http://<site collection>/_layouts/DocIdRedir.aspx?ID=<doc id>";
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Method = "Get";
request.PreAuthenticate = true;
var credential= new NetworkCredential(username, password, domainname);
request.Credentials = credential;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
I need to give some sort of authentication, but could not figure it out.
Any help would be greatly appreciated.
Thanks and Regards
Arjabh

Try running your code inside of a
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//code goes here
});
block

Related

How to download documents from liferay from outside application ..using liferay jsonws or any other way

Hi i am using liferay/api/secure/jsonws services to upload documents, getting documents, from a outside application , in the same way i want to download the documents also, i checked my liferay jsonws , there is no method or service which i can use for download , or i don't know about it , please suggest me a way to download documents from outside application , by using jsonws or any other way is also fine.
Edit after i got to know how to download document.
Hi I tried to download liferay document from outside application by using getURl, but every time for all document i am getting liferay login page content
i have already tried get-file-as-stream json-rpc call but that also giving me null response
the code which i have used is:
final HttpHost targetHost = new HttpHost(hostname.trim());
System.out.println(targetHost.getHostName());
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
System.out.println(creds);
final AuthScope authscope = new AuthScope(targetHost);
httpclient.getCredentialsProvider().setCredentials(authscope, creds);
final AuthCache authCache = new BasicAuthCache();
final BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
final BasicHttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
final HttpGet httpget = new HttpGet(hostname+"/documents/" + groupId + "/" + folderId + "/" + filename);
final HttpResponse response = httpclient.execute( httpget, localContext);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
final org.apache.http.HttpEntity entity = response.getEntity();
if (entity != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
entity.writeTo(baos);
return baos.toByteArray();
}
}
return null;
} finally {
httpclient.getConnectionManager().shutdown();
}
}
i am adding basic auth header will correct username and password, don't know how this login page is coming, is there any permission which i need to change or any configurations issue, please help in this.
You could use the Liferay WebDav Services to download files from your document-library. The paths to download can be inspected inside of the control-panel when clicking on a file entry (WebDAV URL toogle link). The paths usually look like: /webdav/{site-name}/document_library/{folder-name}/{file-name}
Otherwise, you could mimic the request URLs Liferay creates inside the documents-media portlet to download the file entry.
But you should take care about authentication, when your files (and folders) are not visible to guests.

Creating Google Docs Attachment via API

Is there anyway to create a Google Doc attachment via the API? The documentation doesn't specify if possible and everything I tried didn't work.
Thanks
Edit: Looking at the Basecamp API documentation https://github.com/basecamp/bcx-api/blob/master/sections/attachments.md#get-attachments, Google doc attachments have a different set of fields than uploaded files.
Classes.Basecamp.Attachment newAttachment = new Classes.Basecamp.Attachment()
{
Name = attachment.Element("name").Value,
ContentType = attachment.Element("content_type").Value,
LinkedSource = attachment.Element("linked_source").Value,
LinkedType = attachment.Element("linked_type").Value,
LinkUrl = new Uri(attachment.Element("link_url").Value)
};
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Credentials = new NetworkCredential("xxxx");
request.ContentType = "application/vnd.google-apps.document";
request.UserAgent = "xxxx";
request.Proxy = null;
This seems to create a file with no extension.
Can't seem to find another to go about this.

ServiceStack - Switch off Snapshot

I've followed instructions on how creating a ServiceStack here at:
https://github.com/ServiceStack/ServiceStack/wiki/Create-your-first-webservice
I'm sure I have followed it to the letter, but as soon as I run the web application. I get a 'Snapshot' view of my response. I understand this happens when I don't have a default view/webpage. I set up the project as a ASP.net website, not a ASP.net MVC website. Could that be the problem?
I also wrote a test console application with the following C# code. It got the response as a HTML webpage rather than as a plain string e.g. "Hello, John".
static void sendHello()
{
string contents = "john";
string url = "http://localhost:51450/hello/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentLength = contents.Length;
request.ContentType = "application/x-www-form-urlencoded";
// SEND TO WEBSERVICE
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(contents);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
Console.WriteLine(result);
}
How can I switch off the 'snapshot' view? What am I doing wrong?
The browser is requesting html so ServiceStack is returning the html snapshot.
There are a couple of ways to stop the snapshot view:
First is to use the ServiceClient classes provided by servicestack. These also have the advantage of doing automatic routing and strongly typing the response DTOs.
Next way would be to set the Accept header of the request to something like application/json or application/xml which would serialize the response into json or xml respectively. This is what the ServiceClients do internally
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
...
Another method would be to add a query string parameter called format and set it to json or xml
string url = "http://localhost:51450/hello/?format=json";
Putting the specific format requesting is the practical way to do this
string url = "http://localhost:51450/hello/?format=json";
I suggest simply deleting this feature.
public override void Configure(Container container)
{
//...
this.Plugins.RemoveAll(p => p is ServiceStack.Formats.HtmlFormat);
//...
}
Now all requests with the Content-Type=text/html will be ignored.

Issue while updating a doc when Sharepoint document ID service is activated

I am using sharepoint 2010 enterprise edition. I have activated Document ID service which will generate a doc Id for each doc when you upload. when i am first time uploading or saving the document it has no issues. It is getting saved. The issue i am facing is when i open the uploaded document and edit or update it and while saving it again it is giving the webexception "Underlying connection got disconnected. Connection closed prematurely".
I also tried to debug and found the response did not have header.
We were trying to perform in a windows application to edit and save the document.
we are trying to save the document by creating a webrequest.
please provide your idea on this issue.
please see the code below.
"
WebUrl webUrl = UrlToWebUrl(destinationUri);
System.Collections.Specialized.NameValueCollection methodData = new System.Collections.Specialized.NameValueCollection();
// Add general request to stream
methodData.Add("method","put document:" + GetServerExtensionsVersion(webUrl.SiteUrl));
methodData.Add("service_name","");
methodData.Add("put_option","overwrite,createdir,migrationsemantics");
methodData.Add("keep_checked_out","false");
HttpWebRequest req = StartWebRequest(GetAuthorURL(webUrl.SiteUrl), methodData);
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Ssl3;
System.IO.Stream reqStream = req.GetRequestStream();
RemoveSourceControlProperties(properties);
WriteDocumentData(reqStream, webUrl.FileUrl, file, properties);
reqStream.Flush();
reqStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
try
{
if (!PutDocumentResponseSuccess(GetResponseString(response)))
{
throw new FrontPageRPCException("Failed to save document.", destinationUri);
}
}
finally
{
if (null != response) response.Close();
}
}
"

Sharepoint 2010 ClientContext with kerberos & a 401 unauthorised

I can get a remote console app talking to a NTLM Sharepoint site with ClientContext and I can it talking to a remote Kerberos Sharepoint box with HttpWebRequest.GetResponse();
But I cannot get it talking to the Kerberos Sharepoint box with CientContext. Any additional pointers would be gratefully recieved.
string siteURL = "http://my.remote.sharepoint";
ClientContext ctx = new ClientContext(siteURL);
CredentialCache cc = new CredentialCache();
cc.Add(new Uri(siteURL), "Kerberos", CredentialCache.DefaultNetworkCredentials);
ctx.AuthenticationMode = ClientAuthenticationMode.Default;
ctx.Credentials =cc;
/////////////////////////////////////////////////////////////////////////////////
// This code confirms that I can access "my.remote.sharepoint" with KRB
// HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(siteURL);
// myHttpWebRequest.Credentials = cc;
// myHttpWebRequest.UseDefaultCredentials = true;
// HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
/////////////////////////////////////////////////////////////////////////////////
Web remoteWeb = ctx.Web;
ctx.Load(remoteWeb);
ctx.ExecuteQuery();
//401 unauthorised returned from here
Wireshark suggests that it returns the initial 401 & then gives up! Any ideas
Please check if a SPN is registered for that host and a reverse DNS entry exists.

Resources