Is anyone having any experience with any eCommerce application where you have calculated shipping rate on fly. I am in particular referring to Australia Post service.
Could you please guide me in right direction. I am thinking of using Provider pattern by which I can plugin any shipping provider according to user's profile.
Explanation as per Australia Post is what I am looking for but if anyone has got any suggestions using any other provider, I am fine.
FYI - I am referring to ASP.net, c# (.Net 4.0)
Thanks in advance,
Australia Post has a Delivery Rate Calculator API.
The following instructions have been developed to enable you to access the functionality of the Post eDeliver Delivery Rate Calculator (DRC) directly from your merchant Website. The DRC is available to merchants who would like to offer online estimation of delivery charges to their customers.
I haven't used it so can't tell you anymore about it.
Step-1: create account and get Key
http://auspost.com.au/
Step2 : create function in your MyPage.aspx.cs page
protected string CalculateCharge(string lngth, string wdth, string hgth, string fpcode, string tpcode, string weght, string service_code)
{
string url = "https://auspost.com.au/api/postage/parcel/domestic/calculate.xml?";
url = url + "length=" + HttpUtility.UrlEncode(lngth) + "&width=" + HttpUtility.UrlEncode(wdth) + "&height=" + HttpUtility.UrlEncode(hgth) + "&from_postcode=" + HttpUtility.UrlEncode(fpcode) + "&to_postcode=" + HttpUtility.UrlEncode(tpcode) + "&option_code=&weight=" + HttpUtility.UrlEncode(weght) + "&service_code=" + HttpUtility.UrlEncode(service_code) + "&extra_cover=";
Uri objURI = new Uri(url);
HttpWebRequest objwebreq = (HttpWebRequest)WebRequest.Create(objURI);
objwebreq.ContentType = "text/xml;charset=utf-8;";
objwebreq.Method = "Get";
objwebreq.Timeout = 15000;
objwebreq.Headers.Set("AUTH-KEY", "here enter your key");
HttpWebResponse objWebResponse = (HttpWebResponse)objwebreq.GetResponse();
Stream objStream = objWebResponse.GetResponseStream();
StreamReader objStreamReader = new StreamReader(objStream);
return objStreamReader.ReadToEnd();
}
Step-3: Pass Parameter in function
button click:
protected void btnShippingCalculate_Click(object sender, EventArgs e)
{
string xmlresult = CalculateCharge("10", "10", "10", "3216","3217" ,"5", "AUS_PARCEL_REGULAR");
DataSet ds = new DataSet();
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(xmlresult);
ds.ReadXml(new System.IO.StringReader(doc.OuterXml));
GridView1.DataSource = ds;
GridView1.DataBind();
}
Note:
service_code:
AUS_PARCEL_REGULAR
AUS_PARCEL_EXPRESS
AUS_PARCEL_PLATINUM
Weight: in KG
That's It!!!
Related
I made a very simple console application which will hit MWS service and return XML document containing list of financial events. As it starts, an exception hits at line 14 'client.ListFinancialEvents(request)' and it just show null and no other information as to why its not working.
string accessKey = "AccessKey";
string secretKey = "SecretKey";
string appName = "AppName";
string appVersion = "1.0";
string serviceURL = "http://mws.amazonservices.com/Finances/2015-05-01/";
try
{
MWSFinancesServiceConfig config = new MWSFinancesServiceConfig();
config.ServiceURL = serviceURL;
MWSFinancesServiceClient client = new MWSFinancesServiceClient(accessKey, secretKey, appName, appVersion, config);
ListFinancialEventsRequest request = new ListFinancialEventsRequest();
request.SellerId = "SellerID";
request.AmazonOrderId = "111-111111111-111111111";
ListFinancialEventsResponse response = client.ListFinancialEvents(request);
Console.WriteLine("Response:");
ResponseHeaderMetadata rhmd = response.ResponseHeaderMetadata;
Console.WriteLine("RequestId: " + rhmd.RequestId);
Console.WriteLine("Timestamp: " + rhmd.Timestamp);
string responseXml = response.ToXML();
Console.WriteLine(response.ResponseHeaderMetadata);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
Console.ReadLine();
The DLLs used as reference were downloaded from here. I have already tried MWS Scratchpad and values are working fine. What could be the possible issues due to which this exception occurred and how to solve this issue?
I am posting an answer to my own question in case someone faces similar issue in the future.
I was making a very stupid mistake and it took me a week to figure it out. In service URL, instead of "http://..." it should be "https://..." and it starts working perfectly. It return complete XML as response in 'responseXml' variable.
i have a big problem and i need your help. i'm trying send to url parameters to generate the pdf file with the library winnovative. when trying the first time I have no problems and generates pdf but if I want to get the pdf again this gives me error because the parameters in url they are sent and fail to request and falls when so finally assign to generate the pdf file.
I have attached the code for review:
public override void Pagina_PrimeraCarga(object sender, EventArgs e)
{
string datosRequest = Request.QueryString["DATOS"];
char delimitadores = ';';
string[] datos = datosRequest.Split(delimitadores);
imgBanco.Attributes.Add("ImageUrl", "~/App_Themes/Imagenes/Logo.gif");
System.DateTime fecha = new System.DateTime(2014, 12, 17);
lblDia.Text = Convert.ToString(fecha.Day);
lblMes.Text = Convert.ToString(fecha.Month);
lblAno.Text = Convert.ToString(fecha.Year);
string rutEmpresa = datos[3];
int rut = Convert.ToInt32(rutEmpresa);
string rutRes = rut.ToString("N0", CultureInfo.InvariantCulture).Replace(",", ".");
rutRes = rutRes + "-" + datos[4];
lblOficina.Text = "OFICINA: " + datos[0];
lblNombreTitular.Text = "NOMBRE TITULAR: " + datos[1];
lblRut.Text = "R.U.T.: " + rutRes;
lblDireccion.Text = "DIRECCION: " + datos[2];
lblFono.Text = "FONO: " + datos[5];
}
P.D: my apologies for my bad English but my native language is Spanish
P.D.2: Thanks to everyone who could help me in this case
I think that your problem is that after postBack your query string will be empty. Try this
add hiddenfield
<asp:HiddenField runat="server" ID="hidden1" />
then in your pageLoad
if (!IsPostBack)
{
string datosRequest = Request.QueryString["DATOS"];
if(datosRequest != null)
{
//do something
hidden1.Value = datosRequest ;
}
}
else
{
datosRequest = hidden1.Value;
}
I have solved the problem. I was thinking a bit and detects when passed a second time to obtain the pdf that was creating the cookie to be passed to the other form was created and therefore did not pass the data. for this reason I had to add 2 lines but my code for closing the pdf this server delete the cookie and when consulted again remove the client:
Response.Cookies.Clear ();
myCookie.Expires = DateTime.Now.AddDays (1D);
i want to access Google analytic data and i got samples from Google data API SDK. but these coding does not working and throws exception
Execution of request failed: https://www.google.com/analytics/feeds/accounts/default
so i found the reason for this is Google updated it's to v3.0. i searched updated coding for the C#, but i couldn't find solution for this.
i have same problem as this, but with C#.
Exception thrown when using GData .NET Analytics API
i tried coding with doing changes as follows as it says in Google developer - https://developers.google.com/analytics/resources/articles/gdata-migration-guide#appendix_a
string userName = this.Username.Text;
string passWord = this.Password.Text;
AnalyticsService service = new AnalyticsService("AnalyticsSampleApp");
service.setUserCredentials(userName, passWord);
string googleAccountWebId = "AIXXXXXXXXXXXXXXXXXXXXXXXXXXX";
string profileFeedUrl = "https://www.googleapis.com/analytics/v2.4/data?key=" + googleAccountWebId;
DataQuery query2 = new DataQuery(profileFeedUrl);
query2.Ids = "12345678";
query2.Metrics = "ga:visits";
query2.Sort = "ga:visits";
query2.GAStartDate = DateTime.Now.AddMonths(-1).AddDays(-2).ToString("2011-08-01");
query2.GAEndDate = DateTime.Now.ToString("2013-09-01");
query2.StartIndex = 1;
DataFeed data = service.Query(query2);
foreach (DataEntry entry in data.Entries)
{
string st=entry.Metrics[0].Value;
}
but even i change this it throws exception in
DataFeed data = service.Query(query2);
this line. exception is as follows:
Execution of request failed: https://www.googleapis.com/analytics/v2.4/data?key=AIXXXXXXXXXXXXXXXXXXXXXX-8&start-index=1&end-date=2013-09-01&ids=12345678&metrics=ga:visits&sort=ga:visits&start-date=2011-08-01
i'm using following DLL
Google.GData.Analytics.dll
Google.GData.Client.dll
Google.GData.Extensions.dll
My Questions :
how can i correct this error?
how can i access Google analytic data? is this correct? or else what is the way to doing it??
for a example i want to get available ProfileId and their values. (Title and Page views)
Analytics Account:
I am assuming you have an analytics account already if you don't then create one, and sign up your domain here:
http://www.google.com/intl/en/analytics/
To get your API Key do this:
Follow the instructions on https://developers.google.com/analytics/resources/articles/gdata-migration-guide (Create a Project in the Google APIs Console) to generate your key Once you have it set it as part of the querystring to request to Google Analytics service, in this case:
YourAPIkEStringabcdefghijklmno
To get the profileId (Ids on the code) you should do this:
Log into your analytics account, select the desired domain on your list (blue link) click on the administrator button and on the profiles tab find the profile
configuration subtab, right there you will find the profile id in this case the eight characters long id:
12345678
Here you have some C# code to help you getting the number of visits for that Id:
public string VisitsNumber()
{
string visits = string.Empty;
string username = "youremailuser#domain.com";
string pass = "yourpassword";
string gkey = "?key=YourAPIkEYYourAPIkEYYourAPIkEYYourAPIkE";
string dataFeedUrl = "https://www.google.com/analytics/feeds/data" + gkey;
string accountFeedUrl = "https://www.googleapis.com/analytics/v2.4/management/accounts" + gkey;
AnalyticsService service = new AnalyticsService("WebApp");
service.setUserCredentials(username, pass);
DataQuery query1 = new DataQuery(dataFeedUrl);
query1.Ids = "ga:12345678";
query1.Metrics = "ga:visits";
query1.Sort = "ga:visits";
//You were setting 2013-09-01 and thats an invalid date because it hasn't been reached yet, be sure you set valid dates
//For start date is better to place an aprox date when you registered the domain on Google Analytics for example January 2nd 2012, for an end date the actual date is enough, no need to go further
query1.GAStartDate = new DateTime(2012, 1, 2).ToString("yyyy-MM-dd");
query1.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
query1.StartIndex = 1;
DataFeed dataFeedVisits = service.Query(query1);
foreach (DataEntry entry in dataFeedVisits.Entries)
{
string st = entry.Title.Text;
string ss = entry.Metrics[0].Value;
visits = ss;
}
return visits;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Write("Visits:" + this.VisitsNumber());
}
}
Since the 2.4 API is not so flexible anymore, I have another post here hacking it to get the profile Id:
Getting an specific ProfileId from registered Accounts using GData .NET Analytics API 2.4 if you need to convert the code to C# you can use the Telerik converter: http://converter.telerik.com/
I think this suffice to use the 2.4 API. If you need extra help let me know.
What I wanna do is, to get exchange rates from internet.
I found this function after long research.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string xmlResult = null;
string url;
url = "http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=" + TextBox1.Text + "&ToCurrency=" + TextBox2.Text + "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader resStream = new StreamReader(response.GetResponseStream());
XmlDocument doc = new XmlDocument();
xmlResult = resStream.ReadToEnd();
doc.LoadXml(xmlResult);
Label1.Text = "Current Exchange Rate for " + TextBox1.Text.ToUpper() + " ---> " + TextBox2.Text.ToUpper() + " value " + doc.GetElementsByTagName("double").Item(0).InnerText;
}
catch(Exception ex)
{
Label1.Text="Not a valid Currency or Try again later";
}
}
But http://www.webservicex.net/ doesn't support AZN (Azerbaijani Manat) to usd and vice versa conversion. What I wanna do is, if it's possible connect to the internet and get rates. Else use written function for conversion (I'VE already written).
What do you advice, how can I get current rates for USD and AZN (or just get result by sending USD or AZN) ? Is there anyway to get it from inside Windows forms application?
This simple algorythm will give you all that you need in a key value pair list.
public static List<KeyValuePair<string, decimal>> GetCurrencyListFromWeb(out DateTime currencyDate)
{
List<KeyValuePair<string, decimal>> returnList = new List<KeyValuePair<string, decimal>>();
string date = string.Empty;
using (XmlReader xmlr = XmlReader.Create(#"http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"))
{
xmlr.ReadToFollowing("Cube");
while (xmlr.Read())
{
if (xmlr.NodeType != XmlNodeType.Element) continue;
if (xmlr.GetAttribute("time") != null)
{
date = xmlr.GetAttribute("time");
}
else returnList.Add(new KeyValuePair<string, decimal>(xmlr.GetAttribute("currency"), decimal.Parse(xmlr.GetAttribute("rate"), CultureInfo.InvariantCulture)));
}
currencyDate = DateTime.Parse(date);
}
returnList.Add(new KeyValuePair<string, decimal>("EUR", 1));
return returnList;
}
But http://www.webservicex.net/ doesn't support AZN (Azerbaijani Manat) to usd and vice versa
So? Calculate a cross rate going through another currency.
AZN is likely a fringe currency with very limited volume or exposure. Asking OANDA (http://www.oanda.com) I am getting some quotes, including a USD conversion (http://www.oanda.com/currency/cross-rate/result?quotes=GBP"es=EUR"es=JPY"es=CHF"es=USD"es=AZN&go=Get+my+Table+%3E)
Likely webservicesx.net just has no prices for something that out of the main currencies.
Use another quote. FXCM and Oanda may have API's you can subscribe to - likely against a price.
Alternative you can see whether you can calculate a cross - go from AZN to another currency if there is a price and from there to USD. This is done frequently in FOREX though - agreeable - the USD mostly is not in the need of a cross rate calculation.
Is there anyway to get it from inside Windows forms application?
When you ask about an API on the internet, then it is totally irrelevant whether it is winforms, webforms, powershell or a vb script, either the API supports it, or not, and the UI Technology you use is irrelevant.
Maybe this will help. I Google'd and I did see some alternative web services, but the ones I looked at did not support AZN. But I didn't spend a ton of time doing that, that is your job. I did find this:
http://www.transfermate.com/en/free_currency_converter.asp
which you can add to your application, maybe by adding a browser control and embedding this on a custom page and retrieving the results to your main form. But ultimately, you answered the question yourself:
Else use written function for conversion (I'VE already written).
If you can't find a solution already out there, build it yourself.
Also try:
https://developers.google.com/finance/ and http://openexchangerates.org/
I have a facebook fanpage and I am trying to make a desktop application which can create events through this fanpage, however I'm having trouble understanding how the story goes with acces tokens, id, user permissions... If I am not mistaken once I have the accesstoken I can create an event using the facebookSDK from codeplex and the following function:
public string CreateEvent(string accessToken)
{
FacebookClient facebookClient = new FacebookClient(accessToken);
Dictionary<string, object> createEventParameters = new Dictionary<string, object>();
createEventParameters.Add("name", "My birthday party )");
createEventParameters.Add("start_time", DateTime.Now.AddDays(2).ToUniversalTime().ToString());
createEventParameters.Add("end_time", DateTime.Now.AddDays(2).AddHours(4).ToUniversalTime().ToString());
createEventParameters.Add("owner", "Balaji Birajdar");
createEventParameters.Add("description", " ( a long description can be used here..)");
//Add the "venue" details
JsonObject venueParameters = new JsonObject();
venueParameters.Add("street", "dggdfgg");
venueParameters.Add("city", "gdfgf");
venueParameters.Add("state", "gfgdfgfg");
venueParameters.Add("zip", "gfdgdfg");
venueParameters.Add("country", "gfdgfg");
venueParameters.Add("latitude", "100.0");
venueParameters.Add("longitude", "100.0");
createEventParameters.Add("venue", venueParameters);
createEventParameters.Add("privacy", "OPEN");
createEventParameters.Add("location", "fhdhdfghgh");
Add the event logo image
FacebookMediaObject logo = new FacebookMediaObject()
{
ContentType = "image/jpeg",
FileName = #"C:\logo.jpg"
};
logo.SetValue(File.ReadAllBytes(logo.FileName));
createEventParameters["#file.jpg"] = logo;
JsonObject resul = facebookClient.Post("/me/events", createEventParameters) as JsonObject;
return resul["id"].ToString();
}
Do I always need an application to do this?
I have a test application and I can get an access token from it using:
public string getToken(string strURL)
{
string strURL = "https://graph.facebook.com/oauth/access_token?client_id=149585851811979&client_secret=blablablablabalalbal&grant_type=client_credentials";
Uri Uri = new Uri(strURL);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Uri);
HttpWebResponse HWResponse = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(HWResponse.GetResponseStream());
string token = sr.ReadToEnd();
sr.Close();
token = token.Replace("access_token=", "");
return token;
}
I tried it like this but it obviously didn't work.
So my questions:
Do I always need an application? If yes, how do i connect it to my existing fan page?
Where do I set my user permissions? And how do I then login with the user?
I just think the documentation is a bit vague :s Sorry if my questions are stupid.
Any help/pseudocode is appreciated!
I am using BatchFB to create events in an App Engine app, it works for me, here is the code
// Some Date math that is from my App, but I am using Joda DateTime for output
// formatting.. I have found that if the start_time is malformed by FB standards it will
// to create an event, and give you an eventid, but the event never really gets created.
long hour = { your data }
DateTime start_time = new DateTime(d).plusHours((int)hour);
String stime = start_time.toString(ISODateTimeFormat.dateTime());
Batcher batcher = new FacebookBatcher(token);
Later<NewFeedItem> event = batcher.post(
"/events", NewFeedItem.class,
new Param("name", edata.getStringProperty(EventData.Schema.Name)),
new Param("start_time", stime )
);
long eventid = event.get().id;
I generate token on the client side with FBJS, and pass it to the server.
NewFeedItem is just a class defining an long variable, see batchFB's site..
With that said, I am thinking of switching to RestFB because I can't get BatchFB to support binary parameters with trying to post images. Also RestFB is documented better.. They seem to be related projects and refer to each other often.
I am not adding in Venue data yet, but I have read that for the GraphAPI to work, they need to be top level parameters. i.e. add in street, city, state at the same level as location and privacy..
When you try to read the event it will come in the venue parameter, but it needs to be top level when creating.. Also fallback to just using name and start_time, the only required parameters and add to that once it's working.
-John Gentilin