Google Cloud Printing exception 426 requires HTTPS - c#

I am having a problem with Google Cloud Printing, it always throw an error when I submit a print job using C#:
The remote server returned an error: (426) Requires HTTPS..
I even try it on http://www.google.com/cloudprint/simulate.html but the same problem.
Any way to workaround this or am I missing something?

This is an example of the HTTP POST message which finally got the Submit operation working.
POST http://www.google.com/cloudprint/submit?printerid=<printerid>&output=json HTTP/1.1
Host: www.google.com
Content-Length: 44544
X-CloudPrint-Proxy: Google-JS
Content-Type: multipart/form-data; boundary=----CloudPrintFormBoundaryqeq6g6ncj5v7
------CloudPrintFormBoundaryqeq6g6ncj5v7
Content-Disposition: form-data; name="capabilities"
{"capabilities":[{}]}
------CloudPrintFormBoundaryqeq6g6ncj5v7
Content-Disposition: form-data; name="contentType"
dataUrl
------CloudPrintFormBoundaryqeq6g6ncj5v7
Content-Disposition: form-data; name="title"
zodiac-pig-pic.jpg
------CloudPrintFormBoundaryqeq6g6ncj5v7
Content-Disposition: form-data; name="content"
data:image/jpeg;base64,JVBERi0xLjQKJeHp69MKMiAwIG...2NgolJUVPRg==
------CloudPrintFormBoundaryqeq6g6ncj5v7--
This is the complete code if it helps:
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using GoogleCloudPrintServices.DTO;
namespace GoogleCloudPrintServices.Support
{
public class GoogleCloudPrint
{
public string UserName { get; set; }
public string Password { get; set; }
public string Source { get; set; }
private const int ServiceTimeout = 10000;
public GoogleCloudPrint (String source)
{
Source = source;
}
public CloudPrintJob PrintDocument (string printerId, string title, byte[] document, String mimeType)
{
try
{
string authCode;
if (!Authorize (out authCode))
return new CloudPrintJob { success = false };
var b64 = Convert.ToBase64String (document);
var request = (HttpWebRequest)WebRequest.Create ("http://www.google.com/cloudprint/submit?output=json&printerid=" + printerId);
request.Method = "POST";
// Setup the web request
SetupWebRequest (request);
// Add the headers
request.Headers.Add ("X-CloudPrint-Proxy", Source);
request.Headers.Add ("Authorization", "GoogleLogin auth=" + authCode);
var p = new PostData ();
p.Params.Add (new PostDataParam { Name = "printerid", Value = printerId, Type = PostDataParamType.Field });
p.Params.Add (new PostDataParam { Name = "capabilities", Value = "{\"capabilities\":[{}]}", Type = PostDataParamType.Field });
p.Params.Add (new PostDataParam { Name = "contentType", Value = "dataUrl", Type = PostDataParamType.Field });
p.Params.Add (new PostDataParam { Name = "title", Value = title, Type = PostDataParamType.Field });
p.Params.Add (new PostDataParam
{
Name = "content",
Type = PostDataParamType.Field,
Value = "data:" + mimeType + ";base64," + b64
});
var postData = p.GetPostData ();
Trace.WriteLine (postData);
byte[] data = Encoding.UTF8.GetBytes (postData);
request.ContentType = "multipart/form-data; boundary=" + p.Boundary;
Stream stream = request.GetRequestStream ();
stream.Write (data, 0, data.Length);
stream.Close ();
// Get response
var response = (HttpWebResponse)request.GetResponse ();
var responseContent = new StreamReader (response.GetResponseStream ()).ReadToEnd ();
var serializer = new DataContractJsonSerializer (typeof (CloudPrintJob));
var ms = new MemoryStream (Encoding.Unicode.GetBytes (responseContent));
var printJob = serializer.ReadObject (ms) as CloudPrintJob;
return printJob;
}
catch (Exception ex)
{
return new CloudPrintJob { success = false, message = ex.Message };
}
}
public CloudPrinters Printers
{
get
{
var printers = new CloudPrinters ();
string authCode;
if (!Authorize (out authCode))
return new CloudPrinters { success = false };
try
{
var request = (HttpWebRequest)WebRequest.Create ("http://www.google.com/cloudprint/search?output=json");
request.Method = "POST";
// Setup the web request
SetupWebRequest (request);
// Add the headers
request.Headers.Add ("X-CloudPrint-Proxy", Source);
request.Headers.Add ("Authorization", "GoogleLogin auth=" + authCode);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = 0;
var response = (HttpWebResponse)request.GetResponse ();
var responseContent = new StreamReader (response.GetResponseStream ()).ReadToEnd ();
var serializer = new DataContractJsonSerializer (typeof (CloudPrinters));
var ms = new MemoryStream (Encoding.Unicode.GetBytes (responseContent));
printers = serializer.ReadObject (ms) as CloudPrinters;
return printers;
}
catch (Exception)
{
return printers;
}
}
}
private bool Authorize (out string authCode)
{
var result = false;
authCode = "";
var queryString = String.Format ("https://www.google.com/accounts/ClientLogin?accountType=HOSTED_OR_GOOGLE&Email={0}&Passwd={1}&service=cloudprint&source={2}",
UserName, Password, Source);
var request = (HttpWebRequest)WebRequest.Create (queryString);
// Setup the web request
SetupWebRequest (request);
var response = (HttpWebResponse)request.GetResponse ();
var responseContent = new StreamReader (response.GetResponseStream ()).ReadToEnd ();
var split = responseContent.Split ('\n');
foreach (var s in split)
{
var nvsplit = s.Split ('=');
if (nvsplit.Length == 2)
{
if (nvsplit[0] == "Auth")
{
authCode = nvsplit[1];
result = true;
}
}
}
return result;
}
private static void SetupWebRequest (HttpWebRequest webRequest)
{
// Get the details
var appSettings = ConfigurationManager.AppSettings;
// Create some credentials
if (!String.IsNullOrWhiteSpace (appSettings["ProxyUsername"]))
{
var cred = new NetworkCredential (appSettings["ProxyUsername"], appSettings["ProxyPassword"],
appSettings["ProxyDomain"]);
// Set the credentials
webRequest.Credentials = cred;
webRequest.Proxy = WebRequest.DefaultWebProxy;
webRequest.Proxy.Credentials = cred;
}
// Set the timeout
webRequest.Timeout = ServiceTimeout;
webRequest.ServicePoint.ConnectionLeaseTimeout = ServiceTimeout;
webRequest.ServicePoint.MaxIdleTime = ServiceTimeout;
// Turn off the 100's
webRequest.ServicePoint.Expect100Continue = false;
}
}
}
using System.Runtime.Serialization;
namespace GoogleCloudPrintServices.DTO
{
[DataContract]
public class CloudPrinter
{
[DataMember (Order = 0)]
public string id { get; set; }
[DataMember (Order = 1)]
public string name { get; set; }
[DataMember (Order = 2)]
public string description { get; set; }
[DataMember (Order = 3)]
public string proxy { get; set; }
[DataMember (Order = 4)]
public string status { get; set; }
[DataMember (Order = 5)]
public string capsHash { get; set; }
[DataMember (Order = 6)]
public string createTime { get; set; }
[DataMember (Order = 7)]
public string updateTime { get; set; }
[DataMember (Order = 8)]
public string accessTime { get; set; }
[DataMember (Order = 9)]
public bool confirmed { get; set; }
[DataMember (Order = 10)]
public int numberOfDocuments { get; set; }
[DataMember (Order = 11)]
public int numberOfPages { get; set; }
}
}
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace GoogleCloudPrintServices.DTO
{
[DataContract]
public class CloudPrinters
{
[DataMember (Order = 0)]
public bool success { get; set; }
[DataMember (Order = 1)]
public List<CloudPrinter> printers { get; set; }
}
}
using System.Runtime.Serialization;
namespace GoogleCloudPrintServices.DTO
{
[DataContract]
public class CloudPrintJob
{
[DataMember (Order = 0)]
public bool success { get; set; }
[DataMember (Order = 1)]
public string message { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace GoogleCloudPrintServices.Support
{
internal class PostData
{
private const String CRLF = "\r\n";
public string Boundary { get; set; }
private List<PostDataParam> _mParams;
public List<PostDataParam> Params
{
get { return _mParams; }
set { _mParams = value; }
}
public PostData ()
{
// Get boundary, default is --AaB03x
Boundary = "----CloudPrintFormBoundary" + DateTime.UtcNow;
// The set of parameters
_mParams = new List<PostDataParam> ();
}
public string GetPostData ()
{
var sb = new StringBuilder ();
foreach (var p in _mParams)
{
sb.Append ("--" + Boundary).Append (CRLF);
if (p.Type == PostDataParamType.File)
{
sb.Append (string.Format ("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"", p.Name, p.FileName)).Append (CRLF);
sb.Append ("Content-Type: ").Append (p.FileMimeType).Append (CRLF);
sb.Append ("Content-Transfer-Encoding: base64").Append (CRLF);
sb.Append ("").Append (CRLF);
sb.Append (p.Value).Append (CRLF);
}
else
{
sb.Append (string.Format ("Content-Disposition: form-data; name=\"{0}\"", p.Name)).Append (CRLF);
sb.Append ("").Append (CRLF);
sb.Append (p.Value).Append (CRLF);
}
}
sb.Append ("--" + Boundary + "--").Append (CRLF);
return sb.ToString ();
}
}
public enum PostDataParamType
{
Field,
File
}
public class PostDataParam
{
public string Name { get; set; }
public string FileName { get; set; }
public string FileMimeType { get; set; }
public string Value { get; set; }
public PostDataParamType Type { get; set; }
public PostDataParam ()
{
FileMimeType = "text/plain";
}
}
}

Just use HTTPS instead of HTTP. Some GCP API has transferred to HTTPS.

Related

Webrequest c# API null once reached the API

I am trying to send a request from server side to my API, here is my code from Server
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:59606/api/values/UserCheck");
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"username\":\"User\"," +
"\"password\":\"Mypassword\"," +
"\"logonfrom\":\"DOMAIN\\DomainName\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
Console.ReadLine();
}
May API code are below:
[HttpPost]
[ActionName("UserCheck")]
public bool UserCheck([FromBody]User value)
{
ContextType CT = ContextType.Domain;
if (value.logonfrom.Split('\\')[0] == "DOMAIN")
{
CT = ContextType.Domain;
}else if(value.logonfrom.Split('\\')[0] == "MACHINE")
{
CT = ContextType.Machine;
}else
{
return false;
}
return CheckCredentials(value.username, value.password, CT,value.logonfrom.Split('\\')[1]);
}
when my request reach the Action of UserCheck, the value of
([FromBody]User value)
is null
my Class for the User is below
public class User
{
public string username { get; set; }
public string password { get; set; }
public string system { get; set; }
public string IP { get; set; }
public string logonfrom { get; set; }
}
BUT once i remove the logonfrom variable from json there is no error, i mean the parameter (value) successfully captures the content i sent.
Thanks
use the following peace of code.
string json = JsonConvert.SerializeObject(new { username = "afsa", password = "fsaf", system = "fsaf", ip = "fsf", logonfrom ="fsfsd"});

sending push notification using FCM on android device

I can able to send the push notification on my android application using the console. but using server side code, I get the successfully message send notification but actually notification does not able to receive at device end. Please, tell me what is wrong with my code:
public static string SendPushNotification() {
try {
string applicationID = "AAAA4GkXVHA:....-qRw";
string senderId = "963..28";
string deviceId = "APA91bHLV...IC4s";
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var data = new {
to = deviceId,
notification = new {
body = "hema",
title = "hem",
//priority = "normal",
//sound = "Enabled"
},
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
tRequest.ContentLength = byteArray.Length;
using (Stream dataStream = tRequest.GetRequestStream()) {
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse()) {
using (Stream dataStreamResponse = tResponse.GetResponseStream()) {
using (StreamReader tReader = new StreamReader(dataStreamResponse)) {
String sResponseFromServer = tReader.ReadToEnd();
string str = sResponseFromServer;
return str;
}
}
}
}
}
catch (Exception ex) {
string str = ex.Message;
return str;
}
}
where I got the response in return is as follows :
{"multicast_id":8288766196764532656,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1481612825945796%6ad79a87f9fd7ecd"}]}
Sending the json in right format:
{
"to" : "APA91bHLV__P6Qer8U70j82blZt0VdDgc2zo_4DtAD4_MtE-......",
"notification" : {
"body" : "Success!",
"title" : "Hema",
"icon" : "myicon"
}
}
To check it properly, you can also use the postman:
Even I experienced the same problem. Finish all the steps in connecting the FCM from Client side. If you implement GetMessage() method from client side, only then your device is able to get the Notification from Server side
I wrote a small tutorial for this: https://www.kendar.org/?p=/tutorials/notifications with an Android app and a .Net core Server. To summarize here is the "main" server code
public NotificationResult Send(NotificationModel messageData)
{
var result = "-1";
var webAddr = "https://fcm.googleapis.com/fcm/send";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "key=PROJECTSETTINGS->Cloud Messagings->Server Key");
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string strNJson = JsonConvert.SerializeObject(new NotificationMessage
{
To = "/topics/ServiceNow",
Data = new NotificationData
{
Description = messageData.Description,
IncidentNo = messageData.IncidentNo,
ShortDesc = messageData.ShortDesc
},
Notification = new Notification
{
Title = "ServiceNow: Incident No." + messageData.IncidentNo,
Text = "Notification"
}
});
streamWriter.Write(strNJson);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return new NotificationResult
{
Result = result
};
}
And the classes that wrap the message to FCM (with the Json annotations to correct the mismatch between .Net and Json naming standards)
public class NotificationData
{
public string ShortDesc { get; set; }
public long IncidentNo { get; set; }
public string Description { get; set; }
}
public class Notification
{
public Notification()
{
Sound = "default";
}
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
[JsonProperty("sound")]
public string Sound { get; set; }
}
public class NotificationMessage
{
[JsonProperty("to")]
public string To { get; set; }
[JsonProperty("data")]
public NotificationData Data { get; set; }
[JsonProperty("notification")]
public Notification Notification { get; set; }
}

While trying to upload video using daily motion API i got this error "The request was aborted: The request was canceled."

i am using daily motion API for uploading videos from my application but when try to upload more than 2 MB sized video i get this error "The request was aborted: The request was canceled." and this error invoked by this line of code var responseBytes = client.UploadFile(uploadUrl, fileToUpload);
and this is my code which i am using to upload video
public static void Main(MyVideo video)
{
var accessToken = GetAccessToken();
Authorize(accessToken);
var fileToUpload = video.Path;
var uploadUrl = GetFileUploadUrl(accessToken);
var response = GetFileUploadResponse(fileToUpload, accessToken, uploadUrl);
var uploadedResponse = PublishVideo(response, accessToken);
}
public class UploadResponse
{
public string format { get; set; }
public string acodec { get; set; }
public string vcodec { get; set; }
public int duration { get; set; }
public int bitrate { get; set; }
public string dimension { get; set; }
public string name { get; set; }
public int size { get; set; }
public string url { get; set; }
public string hash { get; set; }
public string seal { get; set; }
public override string ToString()
{
var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy;
System.Reflection.PropertyInfo[] infos = this.GetType().GetProperties(flags);
StringBuilder sb = new StringBuilder();
string typeName = this.GetType().Name;
sb.AppendLine(typeName);
sb.AppendLine(string.Empty.PadRight(typeName.Length + 5, '='));
foreach (var info in infos)
{
object value = info.GetValue(this, null);
sb.AppendFormat("{0}: {1}{2}", info.Name, value != null ? value : "null", Environment.NewLine);
}
return sb.ToString();
}
}
private static UploadResponse GetFileUploadResponse(string fileToUpload, string accessToken, string uploadUrl)
{
// ServicePointManager.DefaultConnectionLimit = 900000;
//HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(uploadUrl);
//wr.KeepAlive = false;
//wr.Timeout = System.Threading.Timeout.Infinite;
//wr.ProtocolVersion = HttpVersion.Version10;
var client = new WebClient();
client.Headers.Add("Authorization", "OAuth " + accessToken);
var responseBytes = client.UploadFile(uploadUrl, fileToUpload);
var responseString = Encoding.UTF8.GetString(responseBytes);
var response = JsonConvert.DeserializeObject<UploadResponse>(responseString);
return response;
}
and i have already tried al the possible solutionsu provided on Stackoverflow earlier also done with http execution time and we client time out but not working please someone help me

Using the Constant Contact C# .net-sdk v2 to create/add

I'm using the official version 2 of the Constant Contact .net-sdk found here.
I've been unable to find methods for the following:
Creating a Contact List
Adding a contact to a Contact List
Removing a contact from a Contact List
Adding multiple contacts to a Contact List
Creating an Email Campaign
These features clearly exist in v2 of the API found here, but seem missing from the SDK.
Any help in accessing this functionality is appreciated.
Create Contact.
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "<Replace with your oAuth Token>");
ContactObject cont = new ContactObject
{
first_name = "Deepu",
last_name = "Madhusoodanan"
};
var email_addresses = new List<EmailAddress>
{
new EmailAddress{email_address = "deepumi1#gmail.com"}
};
cont.email_addresses = email_addresses;
cont.lists = new List<List>
{
new List {id = "<Replace with your List Id>"}
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(cont);
string MessageType = "application/json";
using (var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, "https://api.constantcontact.com/v2/contacts?api_key=<Replace with your API key>"))
{
request.Headers.Add("Accept", MessageType);
request.Content = new StringContent(json);
request.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(MessageType);
using (var response = await client.SendAsync(request).ConfigureAwait(false))
{
string responseXml = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var code = response.StatusCode;
}
request.Content.Dispose();
}
}
}
catch (Exception exp)
{
//log exception here
}
/*Model class*/
public class Address
{
public string address_type { get; set; }
public string city { get; set; }
public string country_code { get; set; }
public string line1 { get; set; }
public string line2 { get; set; }
public string line3 { get; set; }
public string postal_code { get; set; }
public string state_code { get; set; }
public string sub_postal_code { get; set; }
}
public class List
{
public string id { get; set; }
}
public class EmailAddress
{
public string email_address { get; set; }
}
public class ContactObject
{
public List<Address> addresses { get; set; }
public List<List> lists { get; set; }
public string cell_phone { get; set; }
public string company_name { get; set; }
public bool confirmed { get; set; }
public List<EmailAddress> email_addresses { get; set; }
public string fax { get; set; }
public string first_name { get; set; }
public string home_phone { get; set; }
public string job_title { get; set; }
public string last_name { get; set; }
public string middle_name { get; set; }
public string prefix_name { get; set; }
public string work_phone { get; set; }
}
Note : You have to replace oAuth token, API key and List id.
Delete method based on the api document.(http://developer.constantcontact.com/docs/contacts-api/contacts-resource.html?method=DELETE)
Note : I have not tested the delete method yet.
private async Task<string> DeleteContact(string contactId)
{
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "<Replace with your oAuth Token>");
using (var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Delete, "https://api.constantcontact.com/v2/contacts/" + contactId + "?api_key=<Replace with your API key>"))
{
using (var response = await client.SendAsync(request).ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
}
}
}
catch (Exception exp)
{
//log exp here
}
return string.Empty;
}
Here is my solution for adding a contact. What I did was combine the code that Deepu provided with the Constant Contact API v2. I also had to remove async and await references because they are incompatible with VS2010. I have not tried DELETE yet...
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Http;
using CTCT.Components.Contacts;
using System.Net.Http.Headers;
/// <summary>
/// Constant Contact Helper Class for POST, PUT, and DELETE
/// </summary>
public class ConstantContactHelper
{
private string _accessToken = ConfigurationManager.AppSettings["ccAccessToken"];
private Dictionary<string, System.Net.Http.HttpMethod> requestDict = new Dictionary<string, System.Net.Http.HttpMethod> {
{"GET", HttpMethod.Get},
{"POST", HttpMethod.Post},
{"PUT", HttpMethod.Put},
{"DELETE", HttpMethod.Delete}
};
private System.Net.Http.HttpMethod requestMethod = null;
private Dictionary<string, ConstantContactURI> uriDict = new Dictionary<string, ConstantContactURI> {
{"AddContact", new ConstantContactURI("contacts")},
{"AddContactList", new ConstantContactURI("lists")},
{"AddEmailCampaign", new ConstantContactURI("campaigns")},
};
private ConstantContactURI URI_Handler = new ConstantContactURI();
private ContactRequestBody RequestBody = new ContactRequestBody();
private const string messageType = "application/json";
public string jsonRequest = null;
public string responseXml = null;
public string status_code = null;
public ConstantContactHelper() {}
public ConstantContactHelper(string methodKey, string uriKey, string firstName, string lastName, string emailAddress, string listId)
{
this.requestMethod = this.requestDict[methodKey];
this.URI_Handler = this.uriDict[uriKey];
this.RequestBody = new ContactRequestBody(firstName, lastName, emailAddress, listId);
}
// Return Response as a string
public void TryRequest()
{
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this._accessToken);
var json = Newtonsoft.Json.JsonConvert.SerializeObject(this.RequestBody.contact);
this.jsonRequest = json;
using (var request = new HttpRequestMessage(HttpMethod.Post, this.URI_Handler.fullURI))
{
request.Headers.Add("Accept", messageType);
request.Content = new StringContent(json);
request.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(messageType);
using (var response = client.SendAsync(request))
{
this.responseXml = response.Result.Content.ReadAsStreamAsync().ConfigureAwait(false).ToString();
this.status_code = response.Status.ToString();
}
request.Content.Dispose();
}
}
}
catch(Exception exp)
{
// Handle Exception
this.responseXml = "Unhandled exception: " + exp.ToString();
}
}
}
public class ConstantContactURI
{
private const string baseURI = "https://api.constantcontact.com/v2/";
private const string queryPrefix = "?api_key=";
private string _apiKey = ConfigurationManager.AppSettings["ccApiKey"];
public string fullURI = null;
public ConstantContactURI() {}
public ConstantContactURI(string specificPath)
{
this.fullURI = baseURI + specificPath + queryPrefix + _apiKey;
}
}
public class ContactRequestBody
{
public Contact contact = new Contact();
private List<EmailAddress> email_addresses = new List<EmailAddress>()
{
new EmailAddress{
EmailAddr = "",
Status = Status.Active,
ConfirmStatus = ConfirmStatus.NoConfirmationRequired
}
};
private List<ContactList> lists = new List<ContactList>()
{
new ContactList {Id = ""}
};
public ContactRequestBody() { }
public ContactRequestBody(string firstName, string lastName, string emailAddress, string listId)
{
this.contact.FirstName = firstName;
this.contact.LastName = lastName;
this.email_addresses[0].EmailAddr = emailAddress;
this.contact.EmailAddresses = this.email_addresses;
this.lists[0].Id = listId;
this.contact.Lists = this.lists;
}
}
An Example call from an aspx.cs page looks like this:
ConstantContactHelper requestHelper = new ConstantContactHelper("POST", "AddContact", firstName.Text, lastName.Text, emailBox.Text, listId);
requestHelper.TryRequest();
lbTest.Text = requestHelper.jsonRequest + ", status code:" + requestHelper.status_code + ", xml:" + requestHelper.responseXml;

Upload image to kraken.io API using .Net C#

I'm pretty new to web services. Right now I have problem with using the kraken.io API to resize an uploaded image.
When requesting the response, it always throws an exception.
Any help is appreciated. Thank you very much.
Reference to kraken.io API Docs:
https://kraken.io/docs/upload-url
This is what I have done so far
Trigger:
byte[] data = new byte[fuImage.PostedFile.ContentLength];
fuImage.PostedFile.InputStream.Read(data, 0, fuImage.PostedFile.ContentLength);
objKraken krakenio = new objKraken();
krakenio.wait = true;
krakenio.resize = new objKResize() { width = Base_Controller.DealsWidth, height = Base_Controller.DealsHeight, strategy = "exact" };
Controller_Kraken.UploadFile(data, krakenio);
Controller:
public const string UploadAPIUrl = "https://api.kraken.io/v1/upload";
public static bool UploadFile(byte[] data, objKraken krakenInfo)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(UploadAPIUrl);
webRequest.Method = "POST";
webRequest.ContentType = "multipart/form-data";
string jsonString = JsonConvert.SerializeObject(krakenInfo);
webRequest.ContentLength = data.Length + jsonString.Length;
using (Stream postStream = webRequest.GetRequestStream())
{ // Send the data.
postStream.Write(data, 0, data.Length);
using (StreamWriter swRequest = new StreamWriter(postStream))
{
swRequest.Write(jsonString);
swRequest.Flush();
}
postStream.Close();
}
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
{
string responseText;
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
responseText = reader.ReadToEnd();
}
if (responseText == "true")
{ return true; }
else
{ return false; }
}
else
{ return false; }
}
}
catch
{ return false; }
}
Object:
public class objKraken
{
public objKAuth auth { get { return new objKAuth(); } }
public objKResize resize { get; set; }
public bool wait { get; set; }
}
public class objKAuth
{
public string api_key { get { return ConfigurationManager.AppSettings["ApiKey"]; } }
public string api_secret { get { return ConfigurationManager.AppSettings["SecretKey"]; } }
}
public class objKResize
{
public int width { get; set; }
public int height { get; set; }
public string strategy { get; set; }
}

Categories