The first part of the program is to retrieve the employee user ID (or signature) from an API URL once the name has been entered. (Which I have done)
The second part, the user will enter a specific "to" and "from" date.
Using the signature obtained from the first part and the dates that the user enters, the program should pass this information to an API address and obtain information accordingly.
My question is that I am not sure how to pass the obtained signature to the new API address + the "to" and "from" date.
The first part of the program to retrieve the signature (works perfectly):
namespace TimeSheets_Try_11.Controllers
{
class WebAPI
{
public string Getsignature(string name)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var cookies = FullWebBrowserCookie.GetCookieInternal(new Uri(StaticStrings.UrlIora), false);
WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers.Add("Cookie:" + cookies);
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.UseDefaultCredentials = true;
string uri = "";
uri = StaticStrings.UrlIora + name;
var response = wc.DownloadString(uri);
var status = JsonConvert.DeserializeObject<List<Employeename>>(response);
string signame = status.Select(js => js.signature).First();
return signame;
}
The second part that I have written so far:
public string[] GetTime(double fromDate, double toDate, string username)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var cookies = FullWebBrowserCookie.GetCookieInternal(new Uri(StaticStrings.UrlNcert), false);
WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers.Add("Cookie:" + cookies);
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.UseDefaultCredentials = true;
string url = "";
url = StaticStrings.UrlNcert + username + "&fromDate=" + fromDate + "&toDate=" + toDate;
var respons = wc.DownloadString(url);
OracleHour ndata = JsonConvert.DeserializeObject<OracleHour>(respons);
var Get_Odnum = ndata.orderNumber;
var Dt_Work = ndata.dateOfWork;
var hrType = ndata.hourType;
var hr = ndata.hours;
var des = ndata.description;
var surname = ndata.surveyor;
string[] myncertdata = { Get_Odnum, Dt_Work.ToString(), hrType, hr.ToString(), des, surname };
return myncertdata;
}
}
}
The API strings:
namespace TimeSheets_Try_11.Controllers
{
class StaticStrings
{
public static string UrlIora = "https://iora.dnvgl.com/api/dictionary/employee/";
public static string UrlNcert = "https://cmcservices.dnvgl.com/Finance/api/oracleReportingCost?user=VERIT" + #"\";
}
}
For example if we are using the name "Jane Dow" from the date 9/22/20 - 9/29/20, the api strings will be
UrlIora = "https://iora.dnvgl.com/api/dictionary/employee/Jane
UrlNcert = "https://cmcservices.dnvgl.com/Finance/api/oracleReportingCost?user=VERIT\JDOW&fromDate=2020-09-22&toDate=2020-09-29"
Trivial way - change UrlNcert to url without query at first:
class StaticStrings
{
public static string UrlIora = "https://iora.dnvgl.com/api/dictionary/employee/";
public static string UrlNcert = "https://cmcservices.dnvgl.com/Finance/api/oracleReportingCost";
}
Then in your api call get values for username, fromDate and toDate and use string interpolation.
var url = $"{StaticStrings.UrlNcert}?user={username}&fromDate={fromDate:yyyy-MM-dd}&toDate={toDate:yyyy-MM-dd}";
If you want more complex way, check UriBuilder
Related
I have used json code to call the controller/action method and convert the json format inside the project,everything worked in my localhost and my server which i had, but it was not working in some other server like US server, I don't know why it throws.
Is it cause Network or IIS confirguration or code issue? If Firewall or port issue means how to change their settings?
I have attached the code which I tried,
Class :
public class Jsonget
{
public static string jsonconvert(string url)
{
string currentsite = HttpContext.Current.Request.Url.Authority;
WebClient wc = new WebClient();
wc.Encoding = Encoding.UTF8;
wc.Encoding = UTF8Encoding.UTF8;
var uri = new Uri(HttpContext.Current.Request.Url.AbsoluteUri);
var requestType = uri.Scheme;
string jsonurl = requestType + "://" + currentsite + url;
var jsondata = wc.DownloadString(jsonurl);
string jsonresult = "{\"results\":" + jsondata.ToString() + "}";
return jsonresult;
}
}
Index.cshtml:
jsonurl = Url.Action("GetallPrograms", "Admin", new { Name = "testprogram" });
getjsonresult = Jsonget.jsonconvert(jsonurl);
Newtonsoft.Json.Linq.JObject programList = Newtonsoft.Json.Linq.JObject.Parse(getjsonresult);
foreach (var pgm in programList["results"])
{
<p>#((string)pgm["ProgramName"])</p>
}
AdminController:
public JsonResult GetallPrograms(string Name)
{
var programList = new List<CustomAttribute>();
BaseController bc = new BaseController();
try
{
var Exist_programs = (from n in bc.db.Programs where n.Name == Name select n).ToList();
foreach (var exist in Exist_programs)
{
programList.Add(new CustomAttribute
{
ProgramName = exist.ProgramName,
Id = exist.Id.ToString()
});
}
}
catch
{
programList.Add(new CustomAttribute
{
ProgramName ="",
Id = ""
});
}
return Json(programList, JsonRequestBehavior.AllowGet);
}
Please give suggestion to fix this?
I'm trying to create a HTTP url request to get Amazon items by its ASIN Array. I'm using the same code in my Objective-c code for the same reason and it's work perfectly.
But i'm getting this messeage everytime i try to access the url in my chrome:
The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
This is the code i'm using:
private void GetFinalUrlForAsinArray(ArrayList asinArr)
{
String timeStamp = GetTimeStamp();
String amazonAPIUrl = "http://webservices.amazon.com/onca/xml?";
ArrayList param = new ArrayList();
param.Add("AWSAccessKeyId=myawsaccesskeyid");
param.Add("AssociateTag=myassociatetag");
param.Add("IdType=ASIN");
param.Add(string.Join(",", asinArr.ToArray()));
param.Add("Operation=ItemLookup");
param.Add("ResponseGroup=ItemAttributes,Offers");
param.Add("Service=AWSECommerceService");
param.Add(String.Format("Timestamp={0}", timeStamp));
amazonAPIUrl += string.Join("&", param.ToArray());
string queryString = new System.Uri(amazonAPIUrl).Query;
var queryDictionary = HttpUtility.ParseQueryString(queryString);
ArrayList queryItemsNew = new ArrayList();
foreach (var query in queryDictionary)
{
String name = HttpUtility.UrlEncode((string)query);
String value = HttpUtility.UrlEncode((string)queryDictionary.Get((string)query));
queryItemsNew.Add(String.Format("{0}={1}", name,value));
}
String path = string.Join("&", queryItemsNew.ToArray());
String finalPath = String.Format("GET\nwebservices.amazon.com\n/onca/xml\n{0}",path);
string signature = HmacSha256Digest(finalPath);
String finalUrl = String.Format("http://webservices.amazon.com/onca/xml?{0}&Signature={1}", path, signature);
}
private String GetTimeStamp()
{
DateTime d = DateTime.UtcNow;
String str = d.ToString("yyyy-MM-dd''T''HH:mm:ss''Z''");
return str;
}
private static string HmacSha256Digest(string message)
{
UTF8Encoding encoding = new UTF8Encoding();
HMACSHA256 hmac = new HMACSHA256(encoding.GetBytes(mysecret));
string signature = Convert.ToBase64String(hmac.ComputeHash(encoding.GetBytes(message)));
String sigEncoded = Uri.EscapeDataString(signature);
return sigEncoded;
}
Having had a look at the API documentation it looks like you've missed the ItemId key here:
param.Add(string.Join(",", asinArr.ToArray()));
I'm guessing you meant it to be:
param.Add("ItemId=" + string.Join(",", asinArr.ToArray()));
It otherwise looks to comply with the spec, the only other thing I noted was the example had the URL encoding as uppercase i.e. %3A rather than the C# default %3a.
Solved!!! - See last edit.
In my MVC app I make calls out to a Web API service with HMAC Authentication Filterign. My Get (GetMultipleItemsRequest) works, but my Post does not. If I turn off HMAC authentication filtering all of them work. I'm not sure why the POSTS do not work, but the GETs do.
I make the GET call from my code like this (this one works):
var productsClient = new RestClient<Role>(System.Configuration.ConfigurationManager.AppSettings["WebApiUrl"],
"xxxxxxxxxxxxxxx", true);
var getManyResult = productsClient.GetMultipleItemsRequest("api/Role").Result;
I make the POST call from my code like this (this one only works when I turn off HMAC):
private RestClient<Profile> profileClient = new RestClient<Profile>(System.Configuration.ConfigurationManager.AppSettings["WebApiUrl"],
"xxxxxxxxxxxxxxx", true);
[HttpPost]
public ActionResult ProfileImport(IEnumerable<HttpPostedFileBase> files)
{
//...
var postResult = profileClient.PostRequest("api/Profile", newProfile).Result;
}
My RestClient builds like this:
public class RestClient<T> where T : class
{
//...
private void SetupClient(HttpClient client, string methodName, string apiUrl, T content = null)
{
const string secretTokenName = "SecretToken";
client.BaseAddress = new Uri(_baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (_hmacSecret)
{
client.DefaultRequestHeaders.Date = DateTime.UtcNow;
var datePart = client.DefaultRequestHeaders.Date.Value.UtcDateTime.ToString(CultureInfo.InvariantCulture);
var fullUri = _baseAddress + apiUrl;
var contentMD5 = "";
if (content != null)
{
var json = new JavaScriptSerializer().Serialize(content);
contentMD5 = Hashing.GetHashMD5OfString(json); // <--- Javascript serialized version is hashed
}
var messageRepresentation =
methodName + "\n" +
contentMD5 + "\n" +
datePart + "\n" +
fullUri;
var sharedSecretValue = ConfigurationManager.AppSettings[_sharedSecretName];
var hmac = Hashing.GetHashHMACSHA256OfString(messageRepresentation, sharedSecretValue);
client.DefaultRequestHeaders.Add(secretTokenName, hmac);
}
else if (!string.IsNullOrWhiteSpace(_sharedSecretName))
{
var sharedSecretValue = ConfigurationManager.AppSettings[_sharedSecretName];
client.DefaultRequestHeaders.Add(secretTokenName, sharedSecretValue);
}
}
public async Task<T[]> GetMultipleItemsRequest(string apiUrl)
{
T[] result = null;
try
{
using (var client = new HttpClient())
{
SetupClient(client, "GET", apiUrl);
var response = await client.GetAsync(apiUrl).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
await response.Content.ReadAsStringAsync().ContinueWith((Task<string> x) =>
{
if (x.IsFaulted)
throw x.Exception;
result = JsonConvert.DeserializeObject<T[]>(x.Result);
});
}
}
catch (HttpRequestException exception)
{
if (exception.Message.Contains("401 (Unauthorized)"))
{
}
else if (exception.Message.Contains("403 (Forbidden)"))
{
}
}
catch (Exception)
{
}
return result;
}
public async Task<T> PostRequest(string apiUrl, T postObject)
{
T result = null;
try
{
using (var client = new HttpClient())
{
SetupClient(client, "POST", apiUrl, postObject);
var response = await client.PostAsync(apiUrl, postObject, new JsonMediaTypeFormatter()).ConfigureAwait(false); //<--- not javascript formatted
response.EnsureSuccessStatusCode();
await response.Content.ReadAsStringAsync().ContinueWith((Task<string> x) =>
{
if (x.IsFaulted)
throw x.Exception;
result = JsonConvert.DeserializeObject<T>(x.Result);
});
}
}
catch (HttpRequestException exception)
{
if (exception.Message.Contains("401 (Unauthorized)"))
{
}
else if (exception.Message.Contains("403 (Forbidden)"))
{
}
}
catch (Exception)
{
}
return result;
}
//...
}
My Web API Controller is defined like this:
[SecretAuthenticationFilter(SharedSecretName = "xxxxxxxxxxxxxxx", HmacSecret = true)]
public class ProfileController : ApiController
{
[HttpPost]
[ResponseType(typeof(Profile))]
public IHttpActionResult PostProfile(Profile Profile)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
GuidValue = Guid.NewGuid();
Resource res = new Resource();
res.ResourceId = GuidValue;
var data23 = Resourceservices.Insert(res);
Profile.ProfileId = data23.ResourceId;
_profileservices.Insert(Profile);
return CreatedAtRoute("DefaultApi", new { id = Profile.ProfileId }, Profile);
}
}
Here is some of what SecretAuthenticationFilter does:
//now try to read the content as string
string content = actionContext.Request.Content.ReadAsStringAsync().Result;
var contentMD5 = content == "" ? "" : Hashing.GetHashMD5OfString(content); //<-- Hashing the non-JavaScriptSerialized
var datePart = "";
var requestDate = DateTime.Now.AddDays(-2);
if (actionContext.Request.Headers.Date != null)
{
requestDate = actionContext.Request.Headers.Date.Value.UtcDateTime;
datePart = requestDate.ToString(CultureInfo.InvariantCulture);
}
var methodName = actionContext.Request.Method.Method;
var fullUri = actionContext.Request.RequestUri.ToString();
var messageRepresentation =
methodName + "\n" +
contentMD5 + "\n" +
datePart + "\n" +
fullUri;
var expectedValue = Hashing.GetHashHMACSHA256OfString(messageRepresentation, sharedSecretValue);
// Are the hmacs the same, and have we received it within +/- 5 mins (sending and
// receiving servers may not have exactly the same time)
if (messageSecretValue == expectedValue
&& requestDate > DateTime.UtcNow.AddMinutes(-5)
&& requestDate < DateTime.UtcNow.AddMinutes(5))
goodRequest = true;
Any idea why HMAC doesn't work for the POST?
EDIT:
When SecretAuthenticationFilter tries to compare the HMAC sent, with what it thinks the HMAC should be they don't match. The reason is the MD5Hash of the content doesn't match the MD5Hash of the received content. The RestClient hashes the content using a JavaScriptSerializer.Serialized version of the content, but then the PostRequest passes the object as JsonMediaTypeFormatted.
These two types don't get formatted the same. For instance, the JavaScriptSerializer give's us dates like this:
\"EnteredDate\":\"\/Date(1434642998639)\/\"
The passed content has dates like this:
\"EnteredDate\":\"2015-06-18T11:56:38.6390407-04:00\"
I guess I need the hash to use the same data that's passed, so the Filter on the other end can confirm it correctly. Thoughts?
EDIT:
Found the answer, I needed to change the SetupClient code from using this line:
var json = new JavaScriptSerializer().Serialize(content);
contentMD5 = Hashing.GetHashMD5OfString(json);
To using this:
var json = JsonConvert.SerializeObject(content);
contentMD5 = Hashing.GetHashMD5OfString(json);
Now the sent content (formatted via JSON) will match the hashed content.
I was not the person who wrote this code originally. :)
Found the answer, I needed to change the SetupClient code from using this line:
var json = new JavaScriptSerializer().Serialize(content);
contentMD5 = Hashing.GetHashMD5OfString(json);
To using this:
var json = JsonConvert.SerializeObject(content);
contentMD5 = Hashing.GetHashMD5OfString(json);
Now the content used for the hash will be formatted as JSON and will match the sent content (which is also formatted via JSON).
i have created a we bservice named test.asmx which looks like this:
[WebService(Namespace = "http://insforia.com/Webservices/StockTickers/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[WebMethod(Description = "Using stock symbol gets delayed stock information from Yahoo.", EnableSession = false)]
public string[] GetQuote()
{
string username = Session["username"].ToString();
string company = "BSE-100.BO+COALINDIA.BO+TCS.BO+WIPRO.BO+SBIN.NS+MNM.BO+RCOM.BO+TATASTL.BO+GMRINFRA.BO+ICICIBANK.BO";
string stockcodes = "sl1c6";
string url = "http://in.finance.yahoo.com/d/quotes.csv?s=" + company + "&f=" + stockcodes;
var webRequest = HttpWebRequest.Create(url);
var webResponse = webRequest.GetResponse();
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
{
buffer = sr.ReadToEnd();
}
var buffer = buffer.Replace("\"", "");
buffer = buffer.Replace("\r\n", ",");
var bufferList = buffer.Split(new char[] { ',' });
return bufferList;
}
and i am calling this web service in my aspx page like this:
private string userid = "admin";
protected void Page_Load(object sender, EventArgs e)
{
Session["username"] = userid;
test oo = new test();
bufferList = oo.GetQuote();
}
the thing is its working perfectly in my localhost but when i uploaded it on server its giving me an error that it couldn't find the test
to see the exact error this is the link :
http://insforia.com/Webservices/StockTickers/stockmain.aspx
i don't understand what to do? why this is happening. i know this is a very stupid question to ask here but i am trying this from yesterday.
try to dont use session.
send param for userName;
public string[] GetQuote(string UserName)
{
...
return bufferList;
}
How can I call eBay and request it to return search results array?
This is what I came up with so far:
string endpoint = "https://api.ebay.com/wsapi";
string siteId = "0";
string appId = "*"; // use your app ID
string devId = "*"; // use your dev ID
string certId = "*"; // use your cert ID
string version = "405";
string requestURL = endpoint
+ "?callname=FindProducts"
+ "&siteid=" + siteId
+ "&appid=" + appId
+ "&version=" + version
+ "&routing=default"
+ "&AvailableItemsOnly=true"
+ "&QueryKeywords=nvidia"
+ "&itemFilter(0).name=ListingType"
+ "&itemFilter(0).value(0)=FixedPrice"
+ "&itemFilter(0).value(1)=Auction"
+ "&CategoryID=27386";
How can I wrap it into request and get a response in some-sort of data-structure? I have gotten the SDK.
I needed to use the eBay finding API;
public GetItemCall getItemDataFromEbay(String itemId)
{
ApiContext oContext = new ApiContext();
oContext.ApiCredential.ApiAccount.Developer = ""; // use your dev ID
oContext.ApiCredential.ApiAccount.Application = ""; // use your app ID
oContext.ApiCredential.ApiAccount.Certificate = ""; // use your cert ID
oContext.ApiCredential.eBayToken = ""; //set the AuthToken
//set the endpoint (sandbox) use https://api.ebay.com/wsapi for production
oContext.SoapApiServerUrl = "https://api.ebay.com/wsapi";
//set the Site of the Context
oContext.Site = eBay.Service.Core.Soap.SiteCodeType.US;
//the WSDL Version used for this SDK build
oContext.Version = "735";
//very important, let's setup the logging
ApiLogManager oLogManager = new ApiLogManager();
oLogManager.ApiLoggerList.Add(new eBay.Service.Util.FileLogger("GetItem.log", true, true, true));
oLogManager.EnableLogging = true;
oContext.ApiLogManager = oLogManager;
GetItemCall oGetItemCall = new GetItemCall(oContext);
//' set the Version used in the call
oGetItemCall.Version = oContext.Version;
//' set the Site of the call
oGetItemCall.Site = oContext.Site;
//' enable the compression feature
oGetItemCall.EnableCompression = true;
oGetItemCall.DetailLevelList.Add(eBay.Service.Core.Soap.DetailLevelCodeType.ReturnAll);
oGetItemCall.ItemID = itemId;
try
{
oGetItemCall.GetItem(oGetItemCall.ItemID);
}
catch (Exception E)
{
Console.Write(E.ToString());
oGetItemCall.GetItem(itemId);
}
GC.Collect();
return oGetItemCall;
}