Updating a document in Google Docs using the API? - c#

I want to update the contents of the already uploaded Google Doc file.
I'm using the below code:
DocumentsService service = new DocumentsService("app-v1");
string auth = gLogin2();
service.SetAuthenticationToken(auth);
Stream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(
"CONTENTS PLEASE CHANGE"));
DocumentEntry entry = service.Update(new Uri("feedURL"), stream, "text/plain",
"nameOfDoc") as DocumentEntry;
For "feedURL" I tried using all the possible links: alternate, self, edit, edit-media even resumable-edit-media, but I keep on getting exceptions.
Also how do I read a response with such requests?
I just started using this API. Earlier, I was using it on the protocol level so was sending GET/POST requests and receiving web responses. I don't know how to get or read response in this case.
UPDATE:
Now the code I'm using is:
RequestSettings _settings;
string DocumentContentType = "text/html";
_settings = new RequestSettings("Stickies", "EMAIL", "PASSWORD");
var request = new DocumentsRequest(_settings);
//var entryToUpdate = doc.DocumentEntry;
var updatedContent = "new content..."; ;
var mediaUri = new Uri(string.Format(DocumentsListQuery.mediaUriTemplate, rid));
Trace.WriteLine(mediaUri);
var textStream = new MemoryStream(Encoding.UTF8.GetBytes(updatedContent));
var reqFactory = (GDataRequestFactory)request.Service.RequestFactory;
reqFactory.CustomHeaders.Add(string.Format("{0}: {1}", GDataRequestFactory.IfMatch, et));
var oldEtag = et;
DocumentEntry entry = request.Service.Update(mediaUri, textStream, DocumentContentType, title) as DocumentEntry;
Debug.WriteLine(string.Format("ETag changed while saving {0}: {1} -> {2}", title, oldEtag,et));
Trace.WriteLine("reached");
And the exception I'm getting is:
{"The remote server returned an error: (412) Precondition Failed."}
I'm getting this exception at DocumentEntry entry = request.Service.Update(mediaUri, textStream, DocumentContentType, title) as DocumentEntry;

Solved.. Exception precondition Failed was due to Etag mismatch
The above UPDATED code works perfectly for saving a document.

Related

CreateUploadSession returns "The OData request is not supported"

I am attempting to do step 1 in C#, according to Attach large files to Outlook messages as attachments from the Microsoft Graph documentation.
The GraphServiceClient and message id I'm using works fine when uploading small attachments. When uploading large attachments, however, I received this error:
The OData request is not supported.
Based on my code below, I believe I have followed the documentation correctly.
Does anyone have any idea why I would get the error message I do?
var attachmentItem = new AttachmentItem
{
AttachmentType = AttachmentType.File,
Name = file.Name,
Size = file.Length //3.5MB test file
};
UploadSession session = await GraphAPIConnection.GraphClient
.Me
.Messages[message.Id]
.Attachments
.CreateUploadSession(attachmentItem)
.Request()
.PostAsync();
I have validated that the file, message, and attachmentItem properties have all been created properly prior to attempting the call.
Using Packages:
Microsoft.Graph.Core.1.20.0
Microsoft.Graph.Beta.0.12.0-preview
UPDATE 1:
I discovered that my endpoint when creating my GraphServiceClient was using v1.0 rather than beta. Upon changing it, I was met with the following error further into my code:
InvalidAudience
using (Stream fileStream = System.IO.File.OpenRead(file.FullName))
{
if (session != null)
{
int maxSizeChunk = (320 * 1024) * 4;
List<Exception> exceptions = new List<Exception>();
byte[] readBuffer = new byte[maxSizeChunk];
ChunkedUploadProvider uploadProvider =
new ChunkedUploadProvider
(session, GraphAPIConnection.GraphClient, fileStream, maxSizeChunk);
IEnumerable<UploadChunkRequest> chunkRequests =
uploadProvider
.GetUploadChunkRequests();
foreach (UploadChunkRequest request in chunkRequests)
{
UploadChunkResult result =
await uploadProvider
.GetChunkRequestResponseAsync
(request, readBuffer, exceptions);
//ERROR HERE
}
}
}
My impression is that Graph does not need to use the alternative Outlook API. Yet, the upload session seems to use it regardless:
request.RequestUrl:
https://outlook.office.com:443/api/beta/...
request.Client.BaseUrl:
https://graph.microsoft.com/beta
Does this mean that I need additional scopes to properly access that API?
Do I need to generate a new client just to do so?

Steps for using Google custom search API in .NET

I am trying to use Google custom search API in my .NET project.
I have an API Key provided by my company.
I have created a custom search engine using my Google account and copied the 'cx' value.
I am using the following code:
string apiKey = "My company Key";
string cx = "Cx";
string query = tbSearch.Text;
WebClient webClient = new WebClient();
webClient.Headers.Add("user-agent", "Only a test!");
string result = webClient.DownloadString(String.Format("https://www.googleapis.com/customsearch/v1?key={0}&cx={1}&q={2}&alt=json", apiKey, cx, query));
I am getting the following error: "The remote server returned an error: (403) Forbidden. "
I have tried the following code too:
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 result1 in search.Items)
{
Console.WriteLine("Title: {0}", result1.Title);
Console.WriteLine("Link: {0}", result1.Link);
}
Here I get the following exception at Fetch():
Google.Apis.Requests.RequestError
Access Not Configured [403]
Errors [Message[Access Not Configured] Location[ - ] Reason[accessNotConfigured] Domain[usageLimits]
Is CX parameter required?
Am I getting the error because I am using the Key provided by my company and using the CX parameter from
custom search engine using my Google account?
Is there any other way of getting 'cx'? We don't want to display Google ADs.
Thank you very much in advance for help.
I'm not sure if you are still interested in this.
To get results without ads you need to pay for it.
Info # Google
and yes the cx is required because it specifies the google custom search engine that you want to use to search.
you can create a custom search engine from This google page
and here is the current code to retrieve search results for the current api version 1.3.0-beta
string apiKey = "Your api key";
string cx = "Your custom search engine id";
string query = "Your query";
var svc = new Google.Apis.Customsearch.v1.CustomsearchService(new BaseClientService.Initializer { ApiKey = apiKey });
var listRequest = svc.Cse.List(query);
listRequest.Cx = cx;
var search = listRequest.Fetch();
foreach (var result in search.Items)
{
Response.Output.WriteLine("Title: {0}", result.Title);
Response.Output.WriteLine("Link: {0}", result.Link);
}
Hope this helps
Instead of,
var search = listRequest.Fetch();
But now it does not supports Fetch() method, rather you need to use Execute() method.
var search = listRequest.Execute();
var listRequest = svc.Cse.List(query);
error !!!
you should use :
var listRequest = svc.Cse.List();
and then :
listRequest.Q=query

Upload file to a Google Site from C# Code

Any idea of how to upload a file to Google site from c#?
I am trying to upload but getting a 403 error. However, I am using the same credentials to connect to the site and get the list of attachments and pages present on the site.
Any help would be greatly appreciated!!
They most likely have an anti-CSRF scheme that stores temporal identifiers in the page and/or cookies, this is specifically to hinder bots.
You are most likely submitting a request without the proper CSRF tokens and get rejected. I would recommend analyzing how they handle CSRF, after this point it will most likely boil down to making a WebRequest to the page and so you can get any cookies they get back, along with having the form so you can scrape out any hidden fields that are relevant. Then move those over to your post request that you're attempting to the send the file to.
I figured out the problem and resolved it. Below is the complete function:
public bool UploadAttachment()
{
try
{
//AsyncSendData data = new AsyncSendData();
string parentUrl = Cabinets["Cabinet1"].ToString();
string parentID = parentUrl.Split('/')[7];
AtomEntry entry = new AtomEntry();
entry.Title.Text = "abc.jpg";
AtomCategory cat = new AtomCategory();
cat.Term = ATTACHMENT_TERM;
cat.Label = "attachment";
cat.Scheme = KIND_SCHEME;
entry.Categories.Add(cat);
AtomLink link = new AtomLink();
link.Rel = PARENT_REL;
link.HRef = parentUrl;
entry.Links.Add(link);
AtomContent content = new AtomContent();
FileInfo info = new FileInfo("C:\\Bluehills.txt");
FileStream stream = info.Open(FileMode.Open,FileAccess.ReadWrite,FileShare.ReadWrite);
this.setUserCredentials(userName, password);
Uri postUri = new Uri(makeFeedUri("content"));
entry.Source = new AtomSource();
//this.EntrySend(postUri, entry, GDataRequestType.Insert);
// Send the request and receive the response:
AtomEntry insertedEntry = this.Insert(postUri, stream, (string)DocumentTypes["TXT"], "bluehills");
return true;
}
catch (Exception ex)
{
return false;
}
}

asp.net c# google api Documents - 401 Unauthorized

I have this code
DocumentsService vService = new DocumentsService("test");
vService.setUserCredentials("vUserName", "vPassword");
RequestSettings vSettings = new RequestSettings("test");
DocumentsRequest vDocReq = new DocumentsRequest(vSettings);
Feed<Document> vFeed = vDocReq.GetEverything();
foreach (Document d in vFeed.Entries) {
lbxDocumente.Items.Add(d.Title + " " + d.Author);
}
Why do I get this exception?
System.Net.WebException: The remote server returned an error: (401) Unauthorized
This line is trying to authenticate with the actual strings "vUserName" and "vPassword":
vService.setUserCredentials("vUserName", "vPassword");
Did you mean it to be this instead, in order to use variables which you've initialized elsewhere?
vService.setUserCredentials(vUserName, vPassword);
(What's with the v prefix, by the way? I generally don't like prefixes like this at all, but I've never even seen v as a prefix before...)
EDIT: You're also not associating the request with the service anywhere. I've tried this code, and it works fine:
DocumentsService service = new DocumentsService("test");
service.setUserCredentials(user, password);
RequestSettings settings = new RequestSettings("test");
DocumentsRequest docReq = new DocumentsRequest(settings);
docReq.Service = service;
Feed<Document> feed = docReq.GetEverything();
foreach (Document d in feed.Entries) {
Console.WriteLine(d.Title);
}

Amazon (AWS) - The request must contain the parameter Signature

I'm struggling with the final part of getting my first bit of code working with the AWS - I have got this far, I attached the web reference in VS and this have this
amazon.AWSECommerceService service = new amazon.AWSECommerceService();
// prepare an ItemSearch request
amazon.ItemSearchRequest request = new amazon.ItemSearchRequest();
request.SearchIndex = "DVD";
request.Title = "scream";
request.ResponseGroup = new string[] { "Small" };
amazon.ItemSearch itemSearch = new amazon.ItemSearch();
itemSearch.AssociateTag = "";
itemSearch.Request = new ItemSearchRequest[] { request };
itemSearch.AWSAccessKeyId = ConfigurationManager.AppSettings["AwsAccessKeyId"];
itemSearch.Request = new ItemSearchRequest[] { request };
ItemSearchResponse response = service.ItemSearch(itemSearch);
// write out the results
foreach (var item in response.Items[0].Item)
{
Response.Write(item.ItemAttributes.Title + "<br>");
}
I get the error
The request must contain the parameter Signature.
I know you have to 'sign' requests now, but can't figure out 'where' I would do this or how? any help greatly appreciated?
You have to add to the SOAP request headers including your Amazon access key ID, a timestamp, and the SHA256 hash of the request operation and the timestamp. To accomplish that, you would need access to the SOAP message just before it is going to be sent out. There's a walkthrough and a sample project I put together at http://flyingpies.wordpress.com/2009/08/01/17/.
For the record:
Another reason to get this error is due to keywords with spaces in it.
Example:
'http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=xxx&AssociateTag=usernetmax-20&Version=2011-08-01&Operation=ItemSearch&ResponseGroup=Medium,Offers&SearchIndex=All&Keywords=Baby
Stroller&MerchantId=All&Condition=All&Availability=Available&ItemPage=1&Timestamp=2012-05-16T02:17:32Z&Signature=ye5c2jo99cr3%2BPXVkMyXX8vMhTC21UO4XfHpA21%2BUCs%3D'
It should be:
'http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=xxx&AssociateTag=usernetmax-20&Version=2011-08-01&Operation=ItemSearch&ResponseGroup=Medium,Offers&SearchIndex=All&Keywords=Baby%20Stroller&MerchantId=All&Condition=All&Availability=Available&ItemPage=1&Timestamp=2012-05-16T02:17:32Z&Signature=ye5c2jo99cr3%2BPXVkMyXX8vMhTC21UO4XfHpA21%2BUCs%3D'
PHP solution:
$Keywords = str_replace(' ', '%20', $Keywords);
or
$Keywords = urlencode($Keywords);

Categories

Resources