How to serialize Nested JSON? - c#

I have following nested JSON:
{"Command":"helo",
"parameter" : {"Configured":false, "ApplicationString":"Something", "Hostname":"some",
"IPAddress":"0.0.0.0",
"UniqueID":"",
"Username":"me"}}
And I need to pass this string as JSON object to POST call to my web service in C#. Could anyone help me how to do this step?
Note: I am able to pass simple JSON like below:
var request = (HttpWebRequest)WebRequest.Create("http://localhost:8084");
request.ContentType = "text/json";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
Command = "test",
name="pooja"
});
streamWriter.Write(json);
}
If I follow the same way to pass nested json like below :
string json = new JavaScriptSerializer().Serialize(new
{
Command = "test",
parameter = new JavaScriptSerializer().Serialize(new
{
Command = "test",
}),
});
I get below output :
{"Command":"test","parameter":"{\"Command\":\"test\"}"}

Let me know if you have any issues.
void Main()
{
CommandParamater exampleCommand = new CommandParamater
{
Command = "Foo",
Parameter = new Parameter
{
ApplicationString = "App String Foo",
Configured = true,
Hostname = "Bar",
IPAddress = "8.8.8.8",
UniqueID = Guid.NewGuid().ToString(),
Username = "FooBar"
}
};
string uri = "http://localhost:8084";
string data = JsonConvert.SerializeObject(exampleCommand);
Html htmlClient = new Html();
htmlClient.Post(uri, data, "application/json");
}
public class Html
{
public string Post(string uri, string data, string contentType)
{
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.ContentType = contentType;
request.ContentLength = dataBytes.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(dataBytes, 0, dataBytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
public class Parameter
{
[JsonProperty("Configured")]
public bool Configured { get; set; }
[JsonProperty("ApplicationString")]
public string ApplicationString { get; set; }
[JsonProperty("Hostname")]
public string Hostname { get; set; }
[JsonProperty("IPAddress")]
public string IPAddress { get; set; }
[JsonProperty("UniqueID")]
public string UniqueID { get; set; }
[JsonProperty("Username")]
public string Username { get; set; }
}
public class CommandParamater
{
[JsonProperty("Command")]
public string Command { get; set; }
[JsonProperty("parameter")]
public Parameter Parameter { get; set; }
}

It may help you.
private string MakeRequest(string uri, string jsnPostData, string method)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
if (request != null)
{
request.Method = method;
request.Timeout = 2000000;
request.ContentType = "application/json";
request.KeepAlive = true;
byte[] data = Encoding.UTF8.GetBytes(jsnPostData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
return result;
}
else
return "";
}
catch (Exception ex)
{
Response.Write("<b>Error :</b>" + ex.Message + "</br>");
return "";
}
}

Related

How to send full entity to WCF Restful service (Post) to do an update?

Using RestfulServiceMgr class, I am able to GetProducts and GetProductById. But not sure how to do it for update product, when I need to send entire entity to WCF restful service to do the update.
WCF Restful Service :
[OperationContract]
[WebInvoke(Method = "POST")]
void UpdateProduct(Entity_Product eProduct);
[OperationContract]
[WebInvoke(Method = "POST")]
void UpdateProductDetails(Entity_ProductDetails eProductDetails);
Calling Resful Service with RestfulServiceMgr Class :
public void UpdateProduct(Entity_Product ProductData, Entity_ProductDetails ProductDetailsData)
{
client.EndPoint = #Constants.Url_UpdateProduct;
client.Method = HttpVerb.POST;
client.PostData = "{postData: value}";
client.MakeRequest();
client.EndPoint = #Constants.Url_UpdateProductDetails;
client.Method = HttpVerb.POST;
client.PostData = "{postData: value}";
client.MakeRequest();
}
RestfulServiceMgr Restful Calls Helper Class :
public class RestfulServiceMgr
{
public string EndPoint { get; set; }
public HttpVerb Method { get; set; }
public string ContentType { get; set; }
public string PostData { get; set; }
public RestfulServiceMgr()
{
EndPoint = "";
Method = HttpVerb.GET;
ContentType = "application/json";
PostData = "";
}
public RestfulServiceMgr(string endpoint)
{
EndPoint = endpoint;
Method = HttpVerb.GET;
ContentType = "application/json";
PostData = "";
}
public RestfulServiceMgr(string endpoint, HttpVerb method)
{
EndPoint = endpoint;
Method = method;
ContentType = "application/json";
PostData = "";
}
public RestfulServiceMgr(string endpoint, HttpVerb method, string postData)
{
EndPoint = endpoint;
Method = method;
ContentType = "application/json";
PostData = postData;
}
public string MakeRequest()
{
return MakeRequest("");
}
public string MakeRequest(string parameters)
{
var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);
request.Method = Method.ToString();
request.ContentLength = 0;
request.ContentType = ContentType;
if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.POST)
{
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);
request.ContentLength = bytes.Length;
using (var writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
}
using (var response = (HttpWebResponse)request.GetResponse())
{
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
// grab the response
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
return responseValue;
}
}
}
Works !!!
client.EndPoint = #Constants.Url_UpdateProduct;
client.Method = HttpVerb.POST;
client.PostData = new JavaScriptSerializer().Serialize(ProductData);
client.MakeRequest();

Pass login arguments to REST service

Trying to call REST service using C# application:
namespace SrvClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public class RestClient
{
public string EndPoint { get; set; }
public HttpVerb Method { get; set; }
public string ContentType { get; set; }
public string PostData { get; set; }
public RestClient()
{
EndPoint = "";
Method = HttpVerb.GET;
ContentType = "text/xml";
PostData = "";
}
public RestClient(string endpoint)
{
EndPoint = endpoint;
Method = HttpVerb.GET;
ContentType = "text/xml";
PostData = "";
}
public RestClient(string endpoint, HttpVerb method)
{
EndPoint = endpoint;
Method = method;
ContentType = "text/xml";
PostData = "";
}
public RestClient(string endpoint, HttpVerb method, string postData)
{
EndPoint = endpoint;
Method = method;
ContentType = "text/xml";
PostData = postData;
}
public string MakeRequest()
{
return MakeRequest("");
}
public string MakeRequest(string parameters)
{
var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);
request.Method = Method.ToString();
request.ContentLength = 0;
request.ContentType = ContentType;
if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.PUT)
{
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);
request.ContentLength = bytes.Length;
using (var writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
}
using (var response = (HttpWebResponse)request.GetResponse())
{
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
// grab the response
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
return responseValue;
}
}
} // class
private void button1_Click(object sender, EventArgs e)
{
var client = new RestClient();
client.EndPoint = #"http://localhost:11332";
client.Method = HttpVerb.GET;
client.PostData = "{postData: value}";
var json = client.MakeRequest("/Account/Login");
}
}
}
As call result I have string:
"<!DOCTYPE html>\r\n<html>\r\n<head>\r\n\t<meta charset=\"utf-8\" />\r\n\t<title>Login - My ASP.NET Application</title>\r\n\t\r\n</head>\r\n<body>\r\n\t\t<p>Welcome login)</p>\r\n\t\r\n\r\n\r\n<h2>Login</h2>\r\n\r\n<form action=\"/Account/Login\" method=\"post\"><input name=\"__RequestVerificationToken\" type=\"hidden\" value=\"_fykbIPsr7u1kGba8zUirPqbqnMG_-eyztTSwSJxB3XksVdrUrLWjsyC9NXWugXn34AxZerny4coFb5_6ILNpMmmG4GZgI-U_Oqhl1VQSzk1\" />\t<p>username:<br /><input class=\"text-box single-line\" id=\"UserName\" name=\"UserName\" type=\"text\" value=\"\" /></p>\r\n\t<p>pin:<br /><input class=\"text-box single-line\" id=\"Pin\" name=\"Pin\" type=\"text\" value=\"\" /></p>\r\n\t<p><input type=\"submit\" value=\"login\" /></p>\r\n</form>\r\n\t<script type=\"text/javascript\" src=\"/Content/js/jquery-2.1.4.min.js\"></script>\r\n\t<script type=\"text/javascript\" src=\"/Content/js/jquery-ui-1.11.4.min.js\"></script>\r\n\t\r\n\r\n<!-- Visual Studio Browser Link -->\r\n<script type=\"application/json\" id=\"__browserLink_initializationData\">\r\n {\"appName\":\"Unknown\",\"requestId\":\"fba1d156c3114ecbbe989a83cd4616c7\"}\r\n</script>\r\n<script type=\"text/javascript\" src=\"http://localhost:21213/b011fdffd90446038f2d9d01cd2a32bf/browserLink\" async=\"async\"></script>\r\n<!-- End Browser Link -->\r\n\r\n</body>\r\n</html>\r\n"
Looks like I need to login. How to make login call in this case?

Why the error in coming while creating a JIRA issue using REST API (C#)?

I am working on a requirement where I need to create multiple issues in one go by Using the REST API. However, I start with uploading a single issue because I am new in API integration. I write few lines of code in c#. Here is my code:
static void Main(string[] args)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
JiraCreateIssueRequest jcir = new JiraCreateIssueRequest();
//////////////////////////////////////////////////////////////////
string sUsername = "aaa#xyz.com";
string sPassword = "TestPassword";
string uri = #"https://domain.atlassian.net/rest/api/2/issue";
Uri address = new Uri(uri);
HttpWebRequest request;
//HttpWebResponse response = null;
StreamReader sr;
string sData = null;
string returnXML = string.Empty;
if (address == null) { throw new ArgumentNullException("address"); }
//jcir.project.ID = 100;
//jcir.Summary = "This issue is created by JIRA REST Api";
//jcir.Description = "This issue is created by JIRA REST Api";
//jcir.IssueType.ID = 1;
sData = #"{""fields"":{""project"":{""key"": ""SITT""},""summary"": ""REST API Uploading"",""description"":""Creating an issue via REST API"",""issuetype"": {""name"": ""Test""}}}";
//sData = jcir.ToString();
try
{
// Create and initialize the web request
request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
// Add the Authorization header to the web request
request.Credentials = new NetworkCredential(sUsername, sPassword);
//Write Data
if (sData != null)
{
byte[] byteData = UTF8Encoding.UTF8.GetBytes(sData);
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string str = reader.ReadToEnd();
}
}
}
catch (WebException wex)
{
// This exception will be raised if the server didn't return 200 - OK
// Try to retrieve more information about the error
if (wex.Response != null)
{
using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
{
try
{
string sError = string.Format("The server returned '{0}' with the status code {1} ({2:d}).",
errorResponse.StatusDescription, errorResponse.StatusCode,
errorResponse.StatusCode);
sr = new StreamReader(errorResponse.GetResponseStream(), Encoding.UTF8);
returnXML = sr.ReadToEnd();
}
finally
{
if (errorResponse != null) errorResponse.Close();
}
}
}
else
{
throw new Exception(wex.Message);
}
}
}
public class JiraCreateIssueRequest
{
protected JavaScriptSerializer jss = new JavaScriptSerializer();
public JiraProject project = new JiraProject();
public string Summary { get; set; }
public string Description { get; set; }
public JiraIssueType IssueType = new JiraIssueType();
public override string ToString()
{
return jss.Serialize(this);
}
}
public class JiraCreateIssueResponse
{
}
public class JiraProject
{
public int ID { get; set; }
//public string Key { get; set; }
}
public class JiraIssueType
{
public int ID { get; set; }
//public string Name { get; set; }
}
But when I am running the above code, I am getting the '400' error. I googled it and found that this usually this error comes when the URL or the Username/Password are incorrect. I cross checked both the things however its correct.
May I know why this error is coming or what will be the resolution of the problem?
Your password is not your login password, it's an API token that you get from here:
https://id.atlassian.com/manage/api-tokens
Generate a token, then use that as your password.

Request the access_token Instagram

I got the following problem:
I am trying to implement Instagram into my website. However I am stuck on the step where I need to get the Acces token. The api's documentation says I need to request it like this :
curl \-F 'client_id=CLIENT-ID' \
-F 'client_secret=CLIENT-SECRET' \
-F 'grant_type=authorization_code' \
-F 'redirect_uri=YOUR-REDIRECT-URI' \
-F 'code=CODE' \https://api.instagram.com/oauth/access_token
I use ASP.NET so I found this equivalent OAuth 2.0 In .NET With Instagram API:
NameValueCollection parameters = new NameValueCollection();
parameters.Add("client_id", "ssdfsdfsdfsdfsdf");
parameters.Add("client_secret", "sdsdfdsfsdfsdfsdfsdfsdf");
parameters.Add("grant_type", "authorization_code");
parameters.Add("redirect_uri", "http://localhost:2422/LoginsGuests/GetLoginPage");
parameters.Add("code", code);
WebClient client = new WebClient();
var result = client.UploadValues("https://api.instagram.com/oauth/access_token", parameters);
var response = System.Text.Encoding.Default.GetString(result);
However I keep getting:
System.Net.WebException: The remote server returned an error: (400) Bad Request.
What I am i doing wrong?
Almost there the instagram api expects a POST not a GET.
Add the "POST" parameter.
var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
Also check the instagram settings -> redirect url.
Then this may help don't forget to add a reference to Newtonsoft.Json. Is in .Net version 4.5.1:
using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
namespace Instagram
{
public class InstagramClient
{
public InstagramClient(string code)
{
GetToken(code);
}
private void GetToken(string code)
{
using (var wb = new WebClient())
{
var parameters = new NameValueCollection
{
{"client_id", "ClientId"},
{"client_secret", "ClientSecret"},
{"grant_type", "authorization_code"},
{"redirect_uri", "RedirectUri"},
{"code", code}
};
var response = wb.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
string json = Encoding.ASCII.GetString(response);
try
{
var OauthResponse = (InstagramOAuthResponse) Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(InstagramOAuthResponse));
}
catch (Exception ex)
{
//handle ex if needed.
}
}
}
public class InstagramOAuthResponse
{
public string access_token { get; set; }
public User user { get; set; }
}
public class User : System.Security.Principal.IIdentity
{
public string username { get; set; }
public string website { get; set; }
public string profile_picture { get; set; }
public string full_name { get; set; }
public string bio { get; set; }
public string id { get; set; }
public string OAuthToken { get; set; }
public string AuthenticationType
{
get { return "Instagram"; }
}
public bool IsAuthenticated
{
get { return !string.IsNullOrEmpty(id); }
}
public string Name
{
get
{
return String.IsNullOrEmpty(full_name) ? "unknown" : full_name;
}
}
}
}
}
If you prefer HttpWebRequest class:
var request = (HttpWebRequest)WebRequest.Create("https://api.instagram.com/oauth/access_token/");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var requestDetails = "client_id=" + AppConfig.InstagramClientId;
requestDetails += "&client_secret=" + AppConfig.InstagramClientSecret;
requestDetails += "&grant_type=authorization_code";
requestDetails += "&redirect_uri=" + redirectUrl;
requestDetails += "&code=" + exchangeCode;
byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
request.ContentLength = bytes.Length;
using (Stream outputStream = request.GetRequestStream())
{
outputStream.Write(bytes, 0, bytes.Length);
}
var response = request.GetResponse();
var code = ((HttpWebResponse)response).StatusCode;
if (code == HttpStatusCode.OK)
{
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var jsonString = streamReader.ReadToEnd();
var accessToken = ParseAccessToken(jsonString);
return accessToken;
}
}

Facebook Graph API ASP.NET Post image

I'm trying to post a photo to Facebook using Graph API. I have managed to post a message to my timeline, but not a photo. The Facebook-debugger gives no errors and the object properties are correct.
public class oAuthFacebook
{
public enum Method { GET, POST };
public const string AUTHORIZE = "https://graph.facebook.com/oauth/authorize";
public const string ACCESS_TOKEN = "https://graph.facebook.com/oauth/access_token";
public const string CALLBACK_URL ="http://test.com/FbCallback.aspx";
private string _consumerKey = "";
private string _consumerSecret = "";
private string _token = "";
public string ConsumerKey
{
get
{
if (_consumerKey.Length == 0)
{
_consumerKey = "";
}
return _consumerKey;
}
set { _consumerKey = value; }
}
public string ConsumerSecret
{
get
{
if (_consumerSecret.Length == 0)
{
_consumerSecret = "";
}
return _consumerSecret;
}
set { _consumerSecret = value; }
}
public string Token { get { return _token; } set { _token = value; } }
public string AuthorizationLinkGet()
{
return string.Format("{0}?client_id={1}&redirect_uri={2}&,publish_actions",
AUTHORIZE, this.ConsumerKey, CALLBACK_URL);
}
public void AccessTokenGet(string authToken)
{
this.Token = authToken;
string accessTokenUrl = string.Format("{0}?client_id={1}&redirect_uri=
{2}&client_secret={3}&code={4}",
ACCESS_TOKEN, this.ConsumerKey, CALLBACK_URL, this.ConsumerSecret, authToken);
string response = WebRequest(Method.GET, accessTokenUrl, String.Empty);
if (response.Length > 0)
{
NameValueCollection qs = HttpUtility.ParseQueryString(response);
if (qs["access_token"] != null)
{
this.Token = qs["access_token"];
}
}
}
public string WebRequest(Method method, string url, string postData)
{
HttpWebRequest webRequest = null;
StreamWriter requestWriter = null;
string responseData = "";
webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
webRequest.Method = method.ToString();
webRequest.ServicePoint.Expect100Continue = false;
webRequest.UserAgent = "http://test.com";
webRequest.Timeout = 40000;
if (method == Method.POST)
{
webRequest.ContentType = "application/x-www-form-urlencoded";
requestWriter = new StreamWriter(webRequest.GetRequestStream());
try
{
requestWriter.Write(postData);
}
catch
{
throw;
}
finally
{
requestWriter.Close();
requestWriter = null;
}
}
responseData = WebResponseGet(webRequest);
webRequest = null;
return responseData;
}
public string WebResponseGet(HttpWebRequest webRequest)
{
StreamReader responseReader = null;
string responseData = "";
try
{
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
}
catch
{
throw;
}
finally
{
webRequest.GetResponse().GetResponseStream().Close();
responseReader.Close();
responseReader = null;
}
return responseData;
}
And this is how I sent a testmessage, it works fine:
var json = oAuth.WebRequest(oAuthFacebook.Method.POST, url, "message=" +
HttpUtility.UrlEncode("Testmessage"));
I've tried for days to get it to work with a photo instead, any ideas of what I'm doing wrong?
I can suggest to look at FB C# SDK (available here or in NuGet) instead of sending raw requests. Here is my function I use to upload images to FB album (you should either know album ID or you can create it as well, or you can enumerate all the albums and get the one you need):
public static string UploadPhoto(string imageName, string albumID, string accesstoken, string photoComment = null, bool doNotPostStory = false)
{
var fbAPI = new FacebookApp(accesstoken);
var p = new FacebookMediaObject {FileName = path};
p.SetValue( <<YOUR IMAGE GOES HERE AS byte[]>>);
p.ContentType = "multipart/form-data";
var param = new Dictionary<string, object> { {"attachment", p} };
if (!string.IsNullOrEmpty(photoComment))
param.Add("message", photoComment);
// http://stackoverflow.com/questions/7340949/is-it-possible-to-upload-a-photo-to-fanpage-album-without-publishing-it
// http://developers.facebook.com/blog/post/482/
if (doNotPostStory == true)
{
param.Add("no_story", "1");
}
var result = fbAPI.Post(string.Format("http://graph.facebook.com/{0}/photos", albumID), param);
return result.ToString();
}

Categories

Resources