Getting error : Could not create SSL/TLS secure channel - c#

I am creating Shutterstock web application for searching images.
take a look on the code
function createImageComponent(image) {
var wrapper = $('<div>');
var thumbWrapper = $('<div>');
var thumbnail = $('<img>');
var description = $('<p>');
$(thumbnail).attr('src', image.assets.preview.url);
$(thumbWrapper)
.addClass('thumbnail-wrapper')
.css('height', image.assets.)
.css('width', image.assets.preview.width)
.append(thumbnail);
$(description)
.text(image.description)
.attr('title', image.description);
$(wrapper)
.addClass('media-wrapper image')
.append(thumbWrapper)
.append(description);
return wrapper;
}
// Create video wrapper component
function createVideoComponent(video) {
var wrapper = $('<div>');
var preview = $('<video>');
var description = $('<p>');
$(preview)
.attr('src', video.assets.thumb_mp4.url)
.attr('controls', true)
.attr('autoplay', true);
$(description)
.text(video.description)
.attr('title', video.description);
$(wrapper)
.addClass('media-wrapper video')
.append(preview)
.append(description);
return wrapper;
}
// Search media by type
function search(opts, media_type) {
var $container = $('#' + media_type + '-search-results');
var createComponentFunc = media_type === 'image' ? createImageComponent : createVideoComponent;
// Get Client ID and Client Secret for use in the Authorization header
var clientId = $('input[name=client_id]').val();
var clientSecret = $('input[name=client_secret]').val();
var jqxhr = $.ajax({
url: 'https://api.shutterstock.com/v2/' + media_type + 's/search',
data: opts,
headers: {
// Base 64 encode 'client_id:client_secret'
Authorization: 'Basic ' + window.btoa(clientId + ':' + clientSecret)
}
})
.done(function(data) {
if (data.total_count === 0) {
$container.append('<p>No Results</p>');
return;
}
$.each(data.data, function(i, item) {
var component = createComponentFunc(item);
$container.append(component);
});
})
.fail(function(xhr, status, err) {
alert('Failed to retrieve ' + media_type + ' search results:\n' + JSON.stringify(xhr.responseJSON, null, 2));
});
return jqxhr;
}
// On Page Load
$(function() {
$('#search-form').submit(function(e) {
e.preventDefault();
// Clear current media results
$('#image-search-results, #video-search-results').empty();
// Serialize form options
var opts = $("input[value != '']", this).serialize();
// Search and display images
search(opts, 'image');
// Search and display videos
search(opts, 'video');
return false;
});
});
This code is for searching images using shutterstock basic authentication.I want to create it using c#.
and i am using the following code :
LoadHttpPageWithBasicAuthentication(#"https://api.shutterstock.com/v2/images/232713811?view=full", "ClientID", "Clientsecrate");
private string LoadHttpPageWithBasicAuthentication(string url, string username, string password)
{
Uri myUri = new Uri(url);
WebRequest myWebRequest = HttpWebRequest.Create(myUri);
HttpWebRequest myHttpWebRequest = (HttpWebRequest)myWebRequest;
NetworkCredential myNetworkCredential = new NetworkCredential(username, password);
CredentialCache myCredentialCache = new CredentialCache();
myCredentialCache.Add(myUri, "Basic", myNetworkCredential);
myHttpWebRequest.PreAuthenticate = true;
myHttpWebRequest.Credentials = myCredentialCache;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
WebResponse myWebResponse = myWebRequest.GetResponse();
Stream responseStream = myWebResponse.GetResponseStream();
StreamReader myStreamReader = new StreamReader(responseStream, Encoding.Default);
string pageContent = myStreamReader.ReadToEnd();
responseStream.Close();
myWebResponse.Close();
return pageContent;
}
But i am getting the error
The request was aborted: Could not create SSL/TLS secure channel.
Please help what is the error stuck with this problem.

This was happening for me also for the shutterstock API .try to put this code
try
{
var request = (HttpWebRequest)WebRequest.Create("https://api.shutterstock.com/v2/images/232713811?view=full");
var username = "YourClientID";
var password = "YourClientSecrate";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
request.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
request.UserAgent = "MyApp 1.0";
var response = (HttpWebResponse)request.GetResponse();
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
// Image myojb = (Image)js.Deserialize(objText, typeof(Image));
var myojb = JsonConvert.DeserializeObject<RootObject>(objText);
// Response.Write(reader.ReadToEnd());
}
}
catch (WebException ea)
{
Console.WriteLine(ea.Message);
using (var stream = ea.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
You need to Deserialize the response data as what result you want.

Related

Google reCaptcha in Web API 2 c#

I have an ASP.NET Web API 2 Project. I am trying to read Google Captcha from the form.
I tried this Code:
public string Post(FoundingRequest model)
{
var response = Request["g-recaptcha-response"];
string secretKey = "my key";
var client = new WebClient();
var result = client.DownloadString(
$"https://www.google.com/recaptcha/api/siteverify?secret={secretKey}&response={response}");
var obj = JObject.Parse(result);
model.Captcha = (bool)obj.SelectToken("success");
....
}
but I am receiving an Error on the first line:
Cannot apply indexing with [] to an expression of type
'HttpRequestMessage'
why? and how to solve it? thank you
That method's body for me works fine:
const string secretKey = "YOUR KEY";
string responseFromServer = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + response);
using (WebResponse resp = req.GetResponse())
using (Stream dataStream = resp.GetResponseStream())
{
if (dataStream != null)
{
using (StreamReader reader = new StreamReader(dataStream))
{
// Read the content.
responseFromServer = reader.ReadToEnd();
}
}
}
dynamic jsonResponse = new JavaScriptSerializer().DeserializeObject(responseFromServer);
return jsonResponse == null || bool.Parse(jsonResponse["success"].ToString());
Update
Regarding the comment, it can be checked on the client side
var response = window.grecaptcha.getResponse()
And then pass this variable to Web API
This is part of my client script:
if (typeof window.grecaptcha != 'undefined') {
var capResponse = window.grecaptcha.getResponse();
if (!capResponse || capResponse.length === 0) {
user.isCaptchaPassed = false;
//alert("Captcha not Passed");
return false;
}
user.gReCaptcha = capResponse;
}
"user" is JS object created before, which passed through JS to server. (AJAX call)
Here's how I did it. I don't use the ChallangeTs so I didn't bother
trying to figure out why it wasn't converting to DateTime properly.
Maybe someone else has that solved.
public class ReCaptchaResponse
{
public bool Success;
public string ChallengeTs;
public string Hostname;
public object[] ErrorCodes;
}
[HttpPost]
[Route("captcha")]
public bool Captcha([FromBody] string token)
{
bool isHuman = true;
try
{
string secretKey = ConfigurationManager.AppSettings["reCaptchaPrivateKey"];
Uri uri = new Uri("https://www.google.com/recaptcha/api/siteverify" +
$"?secret={secretKey}&response={token}");
HttpWebRequest request = WebRequest.CreateHttp(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = 0;
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string result = streamReader.ReadToEnd();
ReCaptchaResponse reCaptchaResponse = JsonConvert.DeserializeObject<ReCaptchaResponse>(result);
isHuman = reCaptchaResponse.Success;
}
catch (Exception ex)
{
Trace.WriteLine("reCaptcha error: " + ex);
}
return isHuman;
}
I found the answer, I created a hidden input with a certain name and updated its value on Captcha call back. Code:
<input type="hidden" value="" id="recaptcha" name="recaptcha" />
<div class="g-recaptcha" data-callback="imNotARobot" data-sitekey="key"></div>
and the Javascript is:
<script type="text/javascript">
var imNotARobot = function () {
$("#recaptcha").val(grecaptcha.getResponse());
};
</script>
server side:
public string Recaptcha { get; set; }
and the model binder does all the work.
I assume this request is coming from a form, change this:
var response = Request["g-recaptcha-response"];
To this:
var response = Request.Form["g-Recaptcha-Response"];
Also Change this:
var result = client.DownloadString($"https://www.google.com/recaptcha/api/siteverify?secret={secretKey}&response={response}");
To this:
var result = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, response));

Need to login in to remote website using c#

I am trying to log in to a remote website via a login form so I can access a sub page via iFrame so I have to pass the validation to set a cookie or a session so I can get to the sub page with the iFrame Maybe there is a better way to do this I am not 100% sure if anyone has any suggestions please let me know. I am getting access denied error:
<script type="text/javascript">
function submitEstimoteLogin() {
setTimeout(function () {
var ifr = document.getElementById("iFrameLogin");
var ifrDoc = ifr.contentDocument || ifr.contentWindow.document;
var theForm = ifrDoc.forms[0];
var username = theform.getElementById("username");
username.value = "email";
var password = theform.getElementById("password");
password.value = "password";
var sbutton = thefrom.getElementById("");
}, 5000);
}
</script>
<iframe id="iFrameLogin" src="http://cloud.estimote.com" onload="submitEstimoteLogin();" ></iframe>
I have also tried it via code behind I am getting a 404 error:
public String GetWebContent(String username, String password)
{
String urlSignin = "https://cloud.estimote.com/";
String urlLogin = "https://cloud.estimote.com/";
Uri uriSignin = new Uri(urlSignin);
Uri uriLogin = new Uri(urlLogin);
Hashtable formData = new Hashtable();
formData.Add("username", new Hashtable());
formData.Add("password", new Hashtable());
((Hashtable)formData["username"])["value"] = username;
((Hashtable)formData["password"])["value"] = password;
String postData = "";
foreach (string name in formData.Keys)
{
postData += "&" + name + "=" + ((Hashtable)formData[name])["value"];
}
postData = postData.Substring(1);
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
HttpWebRequest webReq;
HttpWebResponse webResp;
CookieContainer cookies = new CookieContainer();
String responseString = "";
try
{
webReq = (HttpWebRequest)WebRequest.Create(urlSignin);
webResp = (HttpWebResponse)webReq.GetResponse();
for (int i = 0; i < webResp.Headers.Count; i++)
{
string name = webResp.Headers.GetKey(i);
if (name != "Set-Cookie")
continue;
string value = webResp.Headers.Get(i);
foreach (var singleCookie in value.Split(','))
{
Match match = Regex.Match(singleCookie, "(.+?)=(.+?);");
if (match.Captures.Count == 0)
continue;
webResp.Cookies.Add(
new Cookie(
match.Groups[1].ToString(),
match.Groups[2].ToString(),
"/",
webReq.Host.Split(':')[0]));
}
}
cookies.Add(webResp.Cookies);
string sessionCookie = webResp.Headers["Set-Cookie"];
responseString = new StreamReader(webResp.GetResponseStream()).ReadToEnd();
string respCookie = sessionCookie.Substring(0, sessionCookie.IndexOf(';'));
char[] separator = { '=' };
string[] cookieValues = respCookie.Split(separator);
string part1 = HttpUtility.UrlEncode(cookieValues[1]);
cookies.Add(new Cookie(cookieValues[0], part1 , "/", "cloud.estimote.com"));
webReq = (HttpWebRequest)WebRequest.Create(urlLogin);
webReq.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
webReq.Referer = urlSignin;
webReq.KeepAlive = true;
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.ContentLength = data.Length;
webReq.AllowAutoRedirect = false;
webReq.CookieContainer = cookies;
webReq.Timeout = 30000;
webReq.ReadWriteTimeout = 60000;
webReq.GetRequestStream().Write(data, 0, data.Length);
webReq.GetRequestStream().Close();
webResp = (HttpWebResponse)webReq.GetResponse();
responseString = new StreamReader(webResp.GetResponseStream()).ReadToEnd();
webResp.Close();
return responseString;
}
catch (Exception ex)
{
throw ex;
}
}

How to create a virtual application and directories in azure website programmatically

We use Windows Azure website management library and create a web app programmatically by using C# code but we cannot create a virtual directory inside a web app. please help me how to create virtual directory inside a web app programmatically
My Code here
var websiteManagementClient =
CloudContext.Clients.CreateWebSiteManagementClient(Credentials);
var webSpaces = websiteManagementClient.WebSpaces.List();
var webSpace = webSpaces.FirstOrDefault(x => x.GeoRegion == "South Central US");
if (webSpace == null)
{
throw new Exception(string.Format("No webspace for region {0} found", "South Central US"));
}
var webHostingPlans = websiteManagementClient.WebHostingPlans.List(webSpace.Name);
var webHostingPlan = webHostingPlans.FirstOrDefault();
if (webHostingPlan == null)
{
throw new Exception(string.Format("No webhostingplan found"));
}
try
{
var website = websiteManagementClient.WebSites.Get(webSpace.Name, "MyAzureTestSite", null);
if (website != null)
{
throw new Exception(string.Format("The website {0} already exists", ""));
}
}
catch (Exception)
{
}
var websiteCreateParams = new WebSiteCreateParameters();
websiteCreateParams.Name = "MyAzureTestSite";
websiteCreateParams.ServerFarm = webHostingPlan.Name;
websiteManagementClient.WebSites.Create(webSpace.Name, websiteCreateParams);
At first I tried to create virtual directory with the help of Azure SDK but was not successful. Finally, I used http request to create it.
If you can use this method, you can check it out on my blog.
http://kapiltak.blogspot.in/2015/10/how-to-create-virtual-application-in.html
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Threading;
namespace ConsoleApplication1
{
public class Azure
{
private string loginpath = "https://login.windows.net/{0}";
private string apiEndpoint = "https://management.azure.com/";
//Fill these up
private string webSiteName = "{your webSiteName}";
private string webSpaceName = "Default-Web-SoutheastAsia"; //Insert your webSpaceName here
private string tenantId = "{your tenantId}";
private string clientId = "{your client Id}";
private string subscriptionId = "{your subscription Id}";
//Not needed to set in console app because a function is called to get the token
//string token = "";
public void CreateVD(string name)
{
try
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(String.Format(#"https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Web/sites/{2}/config/web?api-version=2015-08-01",subscriptionId,webSpaceName,webSiteName));
request.Headers.Add("x-ms-version", "2013-03-01");
request.ContentType = "application/json";
var token = GetAuthorizationHeader();
request.Headers.Add("Authorization", "Bearer" + " " + token);
System.Net.WebResponse response = request.GetResponse();
string data = "";
using (System.IO.Stream stream = response.GetResponseStream())
{
System.IO.StreamReader sr = new System.IO.StreamReader(stream);
data = sr.ReadToEnd();
sr.Close();
stream.Close();
Console.WriteLine("data found");
}
if (data == "")
{
Console.WriteLine("Error in collecting data");
return;
}
string path = name, directory = name;
data = data.Replace("virtualApplications\":[", "virtualApplications\":[{\"virtualPath\":\"/" + path + "\",\"physicalPath\":\"site\\\\wwwroot\\\\" + directory + "\",\"preloadEnabled\":false,\"virtualDirectories\":null},");
request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(String.Format(#"https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Web/sites/{2}/config/web?api-version=2015-08-01",subscriptionId,webSpaceName,webSiteName));
request.Headers.Add("x-ms-version", "2013-03-01");
request.ContentType = "application/json";
request.AllowWriteStreamBuffering = false;
request.Accept = "Accept=application/json";
request.SendChunked = false;
request.Headers.Add("Authorization", "Bearer" + " " + token);
request.ContentLength = data.Length;
request.Method = "PUT";
System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
sw.Write(data);
sw.Close();
response = request.GetResponse();
using (System.IO.Stream stream = response.GetResponseStream())
{
data = (new System.IO.StreamReader(stream)).ReadToEnd();
Console.WriteLine("DONE");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
}
private string GetAuthorizationHeader()
{
AuthenticationResult result = null;
var context = new AuthenticationContext(string.Format(loginpath, tenantId));
var thread = new Thread(() =>
{
result = context.AcquireToken(apiEndpoint, clientId, new Uri(redirectUri));
});
thread.SetApartmentState(ApartmentState.STA);
thread.Name = "AquireTokenThread";
thread.Start();
thread.Join();
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
return token;
}
}
}
This code can be used to create virtual directory from website itself but you cannot use "GetAuthorizationHeader()" method to get the token. Instead you can get the token by running the console app once and use a breakpoint to get the string value. Use this value in the code and remove the "GetAuthorizationHeader()" method.

Upload audio file to soundcloud using c#

WebClient client = new WebClient();
string postData = "client_id=" + "b408123adf1e3a950876d84475587ca2"
+ "&client_secret=" + "d74a342169f5f5b369622d582f77b09e"
+ "&grant_type=password&username=" + "biksad" //your username
+ "&password=" + "369789";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://soundcloud.com/biksad/tracks") as HttpWebRequest;
//some default headers
request.Accept = "*/*";
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");
//file array
var files = new UploadFile[] { new UploadFile(filePath, "#" + fileName, "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "biksad");
form.Add("track[sharing]", "public");
form.Add("oauth_token", tokenInfo);
form.Add("format", "json");
form.Add("Filename", fileName);
form.Add("Upload", "Submit Query");
string lblInfo;
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
lblInfo = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
lblInfo = ex.ToString();
}
I want to upload an audio file from my server to my soundcloud account. I got this error:
Cannot close stream until all bytes are written.
How can I detect "form" values correctly(track[title],track[sharing]...etc.)?
this link will show you what all the fields on that POST mean
http://developers.soundcloud.com/docs/api/reference#tracks
you can also use this tool they provide to look at what the URL should contain:
http://developers.soundcloud.com/console

Toggl API v8 with .NET

I'm trying to use the new Toggl API (v8) with .NET C#. I've based my code on the example from litemedia (http://litemedia.info/connect-to-toggl-api-with-net), but it was originally created for version 1 of the API.
private const string TogglTasksUrl = "https://www.toggl.com/api/v8/tasks.json";
private const string TogglAuthUrl = "https://www.toggl.com/api/v8/me"; //sessions.json";
private const string AuthenticationType = "Basic";
private const string ApiToken = "user token goes here";
private const string Password = "api_token";
public static void Main(string[] args)
{
CookieContainer container = new CookieContainer();
var authRequest = (HttpWebRequest)HttpWebRequest.Create(TogglAuthUrl);
authRequest.Credentials = CredentialCache.DefaultCredentials;
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded";
authRequest.CookieContainer = container;
string value = ApiToken; //= Convert.ToBase64String(Encoding.Unicode.GetBytes(ApiToken));
value = string.Format("{1}:{0}", Password, value);
//value = Convert.ToBase64String(Encoding.Unicode.GetBytes(value));
authRequest.ContentLength = value.Length;
using (StreamWriter writer = new StreamWriter(authRequest.GetRequestStream(), Encoding.ASCII))
{
writer.Write(value);
}
try
{
var authResponse = (HttpWebResponse)authRequest.GetResponse();
using (var reader = new StreamReader(authResponse.GetResponseStream(), Encoding.UTF8))
{
string content = reader.ReadToEnd();
}
HttpWebRequest tasksRequest = (HttpWebRequest)HttpWebRequest.Create(TogglTasksUrl);
tasksRequest.CookieContainer = container;
//var jsonResult = string.Empty;
var tasksResponse = (HttpWebResponse)tasksRequest.GetResponse();
MemoryStream ms = new MemoryStream();
tasksResponse.GetResponseStream().CopyTo(ms);
//using (var reader = new StreamReader(tasksResponse.GetResponseStream(), Encoding.UTF8))
//{
// jsonResult = reader.ReadToEnd();
//}
ms.Seek(0, SeekOrigin.Begin);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Task));
var tasks = ser.ReadObject(ms) as List<Task>;
ms.Close();
//var tasks = DataContractJsonConvert.DeserializeObject<Task[]>(jsonResult);
foreach (var task in tasks)
{
Console.WriteLine(
"{0} - {1}: {2} starting {3:yyyy-MM-dd HH:mm}",
task.Project.Name,
task.Description,
TimeSpan.FromSeconds(task.Duration),
task.Start);
}
}
catch (System.Exception ex)
{
throw;
}
}
The following line is returning a 404 error.
var authResponse = (HttpWebResponse)authRequest.GetResponse();
Here is code that works. Since I was looking for this answer recently there might still be others as lost as me.
Notes: I used Encoding.Default.GetBytes() because Encoding.Unicode.GetBytes() did not give me a correct result on my .NET string. I hope it doesn't depend on the default setup of Visual Studio.
The content-type is "application/json".
Sorry, I haven't tried a POST version yet.
string ApiToken = "user token goes here";
string url = "https://www.toggl.com/api/v8/me";
string userpass = ApiToken + ":api_token";
string userpassB64 = Convert.ToBase64String(Encoding.Default.GetBytes(userpass.Trim()));
string authHeader = "Basic " + userpassB64;
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(url);
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Method = "GET";
authRequest.ContentType = "application/json";
//authRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
var response = (HttpWebResponse)authRequest.GetResponse();
string result = null;
using (Stream stream = response.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
result = sr.ReadToEnd();
sr.Close();
}
if (null != result)
{
System.Diagnostics.Debug.WriteLine(result.ToString());
}
// Get the headers
object headers = response.Headers;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message + "\n" + e.ToString());
}

Categories

Resources