Upload file to a Google Site from C# Code - c#

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;
}
}

Related

Http 403 server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature

I generated SAS url with below code
var blobBuilder = new BlobSasBuilder()
{
ExpiresOn = DateTimeOffset.UtcNow.AddDays(2),
Protocol = SasProtocol.Https,
StartsOn = DateTimeOffset.UtcNow.AddDays(-2),
BlobContainerName = _containerName
};
var blockBlob = _blobContainer.GetBlobClient(fileName);
blobBuilder.SetPermissions(BlobAccountSasPermissions.Read);
var isBlobExist = blockBlob.Exists();
if (isBlobExist)
{
var uriData = blockBlob.GenerateSasUri(blobBuilder);
if (uriData != null)
{
path = uriData.AbsoluteUri;
}
}
Generated URI is working most of the time for mobile users but sometimes it returns this error message when trying to download file
server returned http 403 server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature
I am not sure what wrong am I doing here because it works most of the time but doesn't work sometime.
I am also wondering if this is the case when someone try to override the file and other user is trying to read it. Please suggest

Issues publishing image to Facebook Page via Graph API SDK .NET

Attempting this on .NET Core 3.1
After several hours of trying to publish a photo to my public facebook page (as in business page) of which I am the admin and have a long-term token for...
I keep getting the following response to my request using the official Facebook SDK for .NET. However, the image itself is never loaded.
{{"id":"786692942226147","post_id":"113260773923227_786692942226147"}}
The request looks like
var imageMedia = new FacebookMediaObject { FileName = file.FileName, ContentType = file.ContentType };
var stream = file.OpenReadStream();
var bytes = await stream.ReadAsByteArrayAsync();
imageMedia.SetValue(bytes);
var fbClient = new FacebookClient(credential.Token)
{
AppId = _config.GetValue<string>("FacebookClientId"),
AppSecret = _config.GetValue<string>("FacebookSecret")
};
dynamic parameters = new ExpandoObject();
parameters.message = request.Message;
parameters.file = imageMedia;
var result = await fbClient.PostTaskAsync($"{credential.PageId}/photos", parameters, token);
I'm sure it has something to do with the parameters I'm passing in, like parameters.file... but the docs for this thing are VERY unclear... as in "literally does not exist"
Anyone with experience getting this working, please point me in the right direction?
The solution is to change parameters.file to parameters.image...

Reading WebService Wsdl using c#.Net

We have a SOAP based web service and we are able to read its wsdl when we type in the url in Browser. We sit behind a proxy in our network but its not blocking anything and we are always able to read wsdl using browser.But when we enter the url in Browser say http://ist.services/CoreServices/coreservices?wsdl it asks for username and password which is not same as my windows credentials. So when i enter the username and password shared by the dev team , it returns the wsdl page. Please note that this webservice is developed and deployed on java based server.
How do i do the same in c#.net code and how do i pass the Security Crednetials in DiscoveryClientProtocol? I tried the below code which works for the webservices which doesn't ask for the Security credentials.
// Specify the URL to discover.
string sourceUrl = "http://ist.services/CoreServices/coreservices?wsdl";
string outputDirectory = "C:\\Temp";
DiscoveryClientProtocol client = new DiscoveryClientProtocol();
var credentials = new NetworkCredential("sunuser1", "xxxxxxx", "");
WebProxy proxy = new WebProxy("http://proxy.bingo:8000/", true) { Credentials = credentials };
client.Credentials = credentials;
// Use default credentials to access the URL being discovered.
//client.Credentials = credentials;//CredentialCache.DefaultCredentials;
client.Proxy = proxy;
String DiscoverMode = "DiscoverAny";
String ResolveMode = "ResolveAll";
try
{
DiscoveryDocument doc;
// Check to see if whether the user wanted to read in existing discovery results.
if (DiscoverMode == "ReadAll")
{
DiscoveryClientResultCollection results = client.ReadAll(Path.Combine("C:\\Temp", "results.discomap"));
//SaveMode.Value = "NoSave";
}
else
{
// Check to see if whether the user wants the capability to discover any kind of discoverable document.
if (DiscoverMode == "DiscoverAny")
{
doc = client.DiscoverAny(sourceUrl);
}
else
// Discover only discovery documents, which might contain references to other types of discoverable documents.
{
doc = client.Discover(sourceUrl);
}
// Check to see whether the user wants to resolve all possible references from the supplied URL.
if (ResolveMode == "ResolveAll")
client.ResolveAll();
else
{
// Check to see whether the user wants to resolve references nested more than one level deep.
if (ResolveMode == "ResolveOneLevel")
client.ResolveOneLevel();
else
Console.WriteLine("empty");
}
}
}
catch (Exception e2)
{
//DiscoveryResultsGrid.Columns.Clear();
//Status.Text = e2.Message;
Console.WriteLine(e2.Message);
}
// If documents were discovered, display the results in a data grid.
if (client.Documents.Count > 0)
Console.WriteLine(client);
}
}
Since the code didn't help me much , i opened the fiddler to trace the http calls when i manual read the wsdl in browser and i see it takes the credentials i entered as "Authorization: Basic cGDFDdsfdfsdsfdsgsgfg=" . In fiddler i see three calls with responses 401,302 and 200. But in my c#.net code i don't get the 200 response and it always throws me the 404 error.
I further debugged this and in httpresponse of client object i see the flag status as INVOCATION_FLAGS_INITIALIZED | INVOCATION_FLAGS_NEED_SECURITY
So looks like i need to pass the credentials as Security Credentials rather than Network credentials.
The below code has fixed the issue.
CredentialCache myCredentialCache = new CredentialCache { { new Uri(sourceUrl),
"Basic", networkCredential } };
discoveryClientProtocol.AllowAutoRedirect = true;
discoveryClientProtocol.Credentials = myCredentialCache;

Contents Posted on Facebook Page not visible?

I am trying to post on my Facebook page using c# and Facebook sdk. I am able to post the contents on my Facebook page but it is not properly visible to others. Even the admin of the page can view only the heading of the post but can not see the picture or the content of that post. But the admin of the page can see the contents of the post by clicking on ">" this sign beside post to page. Please guide me why this is happening and how can I resolve this.
protected void Page_Load(object sender, EventArgs e)
{
CheckAuthorization();
}
private void CheckAuthorization()
{
string app_id = "My App ID";
string app_secret = "My App Secret";
string scope = "publish_stream, publish_actions";
if (Request["code"] == null)
{
Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}", app_id, Request.Url.AbsoluteUri, scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",app_id,Request.Url.AbsoluteUri,scope,Request["code"].ToString(),app_secret);
HttpWebRequest request = System.Net.WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf("=")), token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
dynamic parameters = new ExpandoObject();
parameters.message = "Hello This Is My First Post To Facebook";
parameters.link = "http://www.google.com";
parameters.picture = "http://www.mywebsite.com/picture/welcome.jpg";
parameters.name = "Hello Users We welcome you all";
parameters.caption = "Posted By Ashish";
client.Post("/My Facebook Page ID/feed", parameters);
}
}
Please guide me where I am doing wrong since I am trying this for the first time after following certain posts on several websites.
You are using the user access token to post a feed to the page. So, the feeds are posted on behalf the user (not the page), which are visible as summary on the timeline.
If you post the feed on behalf of page admin itself (so that the post is visible normally on the timeline), you need to use the page access token with publish_actions permissions.
And to get the page access token you need to query: /<page-id>?fields=access_token using the normal user token with manage_pages permission.
I just want to add that sometimes your app is in MODE : developer so everything you do is visible only to the developers, it is actually the problem i had, So you need to go to your application Dashboard and look for something like "Review" [i hate giving exact paths because Facebook changes everything every once in a while], and look for something like : Your app is in development and unavailable to the public, put it to public

Updating a document in Google Docs using the API?

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.

Categories

Resources