Upload video fail to youtube from asp.net website by data api - asp.net

I am trying to upload video in my ASP.net website to YouTube using the data API but I am getting this error: "The remote server returned an error: (403) Forbidden."
I am using the below code:
YouTubeRequestSettings settings = new YouTubeRequestSettings("VideoPortal", "Developer_Key", "username", "password");
YouTubeRequest request = new YouTubeRequest(settings);
Video newVideo = new Video();
newVideo.Title = "testvideo";//txttitle.Text.Trim();
newVideo.Tags.Add(new MediaCategory("Autos", YouTubeNameTable.CategorySchema));
newVideo.Keywords = "testvideo";//txtkeyword.Text.Trim();
newVideo.Description = "testvideodesc";//txtdesc.Text.Trim();
newVideo.YouTubeEntry.Private = false;
newVideo.Tags.Add(new MediaCategory("mydevtag, anotherdevtag",
YouTubeNameTable.DeveloperTagSchema));
newVideo.YouTubeEntry.Location = new GeoRssWhere(37, -122);
// alternatively, you could just specify a descriptive string
// newVideo.YouTubeEntry.setYouTubeExtension("location", "Mountain View, CA");
string path = Server.MapPath("video/Screen-Recording.mov");
newVideo.YouTubeEntry.MediaSource = new MediaFileSource(path,
"video/quicktime");
settings.Timeout = 100000000;
Video createdVideo = request.Upload(newVideo);
Can anybody please suggest to me how I can make this code work and resolve the error?

what the HTTP response body's content is when you get back your HTTP 403 response? There should be an error message in the response body that provides an explanation of what went wrong

Related

How to get completed signed document from docuSign in asp.net

string accountID = "*****";
string envolopeID = "****************";
apiClient = new ApiClient("https://demo.docusign.net/restapi");
apiClient.SetBasePath("https://account-d.docusign.com/restapi/v2.0/accounts/" + accountID + "/envelopes/" + envolopeID + "/documents/1" );
code = Request.QueryString["code"].ToString();
OAuth.OAuthToken oAuthToken = GenerateAccessToken(IntegratorKey, ClientSecret, code, "userID", "password");
apiClient.Configuration.DefaultHeader.Add("Authorization", "Bearer " + oAuthToken.access_token);
EnvelopesApi envelopesApi = new EnvelopesApi(apiClient);
Stream results1 = envelopesApi.GetDocument(accountID, envolopeID, "1");
I am trying to get signed completed document from DocuSign but unable to download it.
after getting response in result1 gives error as below
ReadTimeout = 'results1.ReadTimeout' threw an exception of type 'System.InvalidOperationException'
WriteTimeout = 'results1.WriteTimeout' threw an exception of type 'System.InvalidOperationException'
Is my code/logic is correct? How to download signed completed document from DocuSign? Please help to download document.
I am using ASP.Net web forms and .NET framework 4.5.2
DocuSign.eSign.dll 5.2.0
DocuSign.Integration.Client.dll 1.7.2
Thanking you...
What does GenerateAccessToken() do? the "password" is making me think this thing is not the correct way to obtain OAuth 2.0 token. If you generated the token correctly then try this for the first few lines:
For now, your code in demo/developer account, you don't need to set baseURL just to get you working. The URL you had there is wrong.
var apiClient = new ApiClient(basePath);
apiClient.Configuration.DefaultHeader.Add("Authorization", "Bearer " + accessToken);
var envelopesApi = new EnvelopesApi(apiClient);
Find more about downloading completed documents.

How to add header in Rest aussured pf RestTemplate

I have been trying to automate some API Testing using either resttemplate or Restassured library but im facing issues on post request. I cant seems to figure how to handle this. I keep getting 415 unsupported type error , I tried many ideas already and read hundreds of threads. Please if someone have a solution let me know.
This is the developer code
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.APPLICATION_JSON)
public Response postData(#FormDataParam("file") InputStream is,
#FormDataParam("file") FormDataContentDisposition fileName,
#FormDataParam("checkInCommInfoInput") String checkInCommInfoInput,
#HeaderParam("authorization") String authString) { }
This is what I tried with resttemplate
String addURI = "https://myURI";
HttpHeaders headers = new HttpHeaders();
//headers.add("Accept","*/*");
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", " a values will be here ");
System.out.println("**************************"+headers.getContentType());
String jsonBody = "my json file will be here";
//System.out.println("\n\n" + jsonBody);
HttpEntity<String> entity = new HttpEntity<String>(jsonBody, headers);
//POST Method to Add New Employee
response = this.restTemplate.postForEntity(addURI, entity, String.class);
responseBodyPOST = response.getBody();
// Write response to file
responseBody = response.getBody().toString();
What I tried with RestAssured
RestAssured.useRelaxedHTTPSValidation();
RestAssured.baseURI ="https://myURI";
EncoderConfig encoderconfig = new EncoderConfig();
Response response = RestAssured.given()
.header("Content-Type","application/json" )
.header("Authorization", "a vvalues will be here")
.header("Accept",ContentType.JSON )
.config(RestAssured.config()
.encoderConfig(encoderconfig.appendDefaultContentCharsetToContentTypeIfUndefined(false)))
//.contentType(ContentType.JSON)
// .accept("application/json")
.log().all().body(jsonBody).post()
.then()
.assertThat()
.log().ifError()
.statusCode(200)
.extract().response();
System.out.println("-------------"+ response.getBody().asString());
API under test #Consumes(MediaType.MULTIPART_FORM_DATA) but the test sends content with .header("Content-Type","application/json" )
415 error as you have clearly mentioned unsupported type error there is a content type mismatch between what the body content that the test client sends and what the API accepts.
See this blogpost: https://blog.jayway.com/2011/09/15/multipart-form-data-file-uploading-made-simple-with-rest-assured/ on how to do send MULTIPART_FORM_DATA

Do I need to investigate HTTP 401 cached by Fiddler during the HttpWebRequest post to ASP.NET WebApi server

I am totally new to WebApi and WebRequests and other things.
After hours of googling, finally, I managed to do POST using C# and HttpWebRequest.
When I do HttpWebRequest in debug mode using Visual Studio I do not get any exceptions.
My app work as I accept , I get data to webApi server and also get back data.
To be sure how my app communicate with WebApi server I start Fiddler Web Debugger.
During the POST to WebApi, Fiddler chace 401 errors
{"Message":"Authorization has been denied for this request."}
Steping step by step in debuger I fund that following lines of code doing 401 error
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.Credentials = new NetworkCredential(username, password);
wr.Method = "POST";
wr.ContentType = "application/json";
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(body);
wr.ContentLength = byteArray.Length;
using (System.IO.Stream dataStream = wr.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length); //After this line of code Fidler Chace HTTP 401
}
Later in code when I do wr.GetResponse() I do get status 200OK.
My questions are :
Do I need to redesign my code to avoid this error in Fiddler ?
Is there other methods to fill HttpWebRequest whit jsonSting beside using GetRequestStream() ?
If your service is enabled with Windows Authentcation, then in Fiddler, you can select the option to automatically authenticate using your logged on credentials by going here:
Composer tab -> Options tab -> Automatically Authenticate
Also, why not use HttpClient from System.Net.Http?...It has a much better and easy programming model...example:
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri("http://localhost:9095/");
HttpResponseMessage response = client.PostAsJsonAsync<Customer>("api/values", cust).Result;

Open website with Basic authentication by asp.net

I want to open a website on a button click of asp.net web page. The website have basic authentication to open. I am using following code but its not the desired code to open website.
CredentialCache credentialCache = new CredentialCache();
NetworkCredential credentials = new NetworkCredential("uid", "pwd", "domain");
credentialCache.Add(new Uri("https://www.abc.com"), "Basic", credentials);
var request = (HttpWebRequest)WebRequest.Create("https://www.abc.com");
request.Credentials = credentialCache;
HttpWebResponse res1 = (HttpWebResponse)request.GetResponse();
using (HttpWebResponse res = (HttpWebResponse)request.GetResponse())
{
string ss = res.ResponseUri.ToString();
StreamReader sr = new StreamReader(res.GetResponseStream());
Response.Write (sr.ReadToEnd());
}
Response.Write write the html of the requested page on my page but I need to redirect to that page to access the website.
After a long search and R & D finally i got the solution of this problem. We need to add the reference of a COM Component Microsoft Internet Controls i.e. using SHDocVw;
When we try to open any website which requires the basic authentication then server respond with "HTTP/1.1 401 Unauthorized\r\n" and requires the client credentials and sends the header "www_authenticate" to the client when any browser recieve this header then its open the pop up box to insert the client credentials and we pass the client credentials to the server. Then server allows to access the application.
If we pass the client credentials on the first request to the server then it allows to access the application and don't requires the client credentials.
I have passed the client credentials with the following code .
InternetExplorer IEControl = new InternetExplorer();
IWebBrowserApp webBrowserCtl = (IWebBrowserApp)IEControl;
string strUserName = "UserName";
string strPassword = "Password";
string strAuthenticationHeader = "Authorization: Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(strUserName + ":" + strPassword)) + "\r\n";
webBrowserCtl.Visible = true;
webBrowserCtl.Navigate("http://www.abc.com/Home.aspx", null, null, null, strAuthenticationHeader);
Thanks
Rahul Pratap Singh

HTML scraping: Forms authentication failed for the request. The ticket supplied has expired

The ActiveForums module we're using as part of our DotNetNuke system has a bug in the XML for it's RSS feed. It doesn't correctly encode ampersands, it leaves them as & rather than encoding them as &
I've reported the bug to the company, but in the mean time I need a fix. So what I've done is create an intermediary page that makes a request to the RSS feed via a System.Net.HttpWebRequest.Create(url) and them performs a Regex.Replace to replaces any unencoded ampersands.
The problem is that when I run the code on our production server I get an exception: The remote server returned an error: (500) Internal Server Error.
The only reason I could think of was around authentication (As the server requires NTLM), however as far as I can tell I'm doing this part of it correctly. My code is shown below:
string html = string.Empty;
string url = "http://intranet.nt.avs/dnn/Default.aspx?tabid=130";
WebResponse response;
WebRequest request = System.Net.HttpWebRequest.Create(url);
request.PreAuthenticate = true;
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
response = request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()) )
{
html = sr.ReadToEnd();
}
// Clean invalid XML
html = Regex.Replace( html, "&(?!amp;|gt;|lt;|quot;|apos;)", "&", RegexOptions.Multiline | RegexOptions.IgnoreCase );
Response.ContentType = "text/xml";
Response.Write( html );
Updated: Here's what the event log says
Error code: 4005
Event message: Forms authentication failed for the request. Reason: The ticket supplied has expired

Resources