This code is showing the address on a google maps sending the address text to an url and then retrieving it in a Json object, Is there a way to transalate this code to Monodroid using Httppost from apache libraries or not?
public class MapsActivity extends MapActivity {
Geocoder geocoder = null;
MapView mapView = null;
ProgressDialog progDialog = null;
List<Address> addressList = null;
double latitude;
double longitude;
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.geoMap);
progDialog = ProgressDialog.show(MapsActivity.this, "Processing...",
"Finding Location...", true, false);
TextView txtAddress = (TextView)findViewById(R.id.location);
String locationName = "Av. Venezuela 1234 Lima Peru";
txtAddress.setText(locationName);
JSONObject location = getLocationInfo(locationName);
Boolean bool = getLatLong(location);
if(location!=null && bool != false){
int lat = (int) (latitude * 1000000);
int lng = (int) (longitude * 1000000);
GeoPoint pt = new GeoPoint(lat, lng);
mapView.getController().setZoom(16);
mapView.getController().setCenter(pt);
mapView.getController().animateTo(pt);
}else {
Dialog foundNothingDlg = new AlertDialog.Builder(
MapsActivity.this).setIcon(0)
.setTitle("Failed to Find Location")
.setPositiveButton("Ok", null)
.setMessage("Location Not Found...").create();
foundNothingDlg.show();
}
}
public JSONObject getLocationInfo(String address) {
StringBuilder stringBuilder = new StringBuilder();
try {
address = address.replaceAll(" ","%20");
HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
Log.i("JSONOBJECT: ", stringBuilder.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObject;
}
public boolean getLatLong(JSONObject jsonObject) {
try {
longitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
latitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
} catch (JSONException e) {
return false;
}
progDialog.dismiss();
return true;
}
}
HttpPost isn't bound, and it's currently very hard to bind your own Java libraries.
The easiest way to do this would be to use the equivalent .NET classes, like HttpWebRequest or WebClient.
Related
I want to read the iOS push "alert" message
parse.com has this example on their website
ParsePush.ParsePushNotificationReceived += (sender, args) => {
var payload = args.Payload;
object objectId;
if (payload.TryGetValue("objectId", out objectId)) {
DisplayRichMessageWithObjectId(objectId as string);
}
};
But how do I read the alert message from the payload?
Solution
string message = "";
try
{
var payload = args.Payload;
object aps;
if (payload.TryGetValue("aps", out aps))
{
string payloadStr = "";
try
{
payloadStr = aps.ToString();
}
catch (Exception e)
{
}
try
{
var match = Regex.Match(payloadStr, #"alert = (.*);\n");
if (match.Success)
{
string alertText = match.Groups[1].Value;
message = alertText;
}
}
catch (Exception)
{
}
}
}
Try this:
ParsePush.ParsePushNotificationReceived += (sender, args) => {
var payload = args.Payload;
object aps;
if (payload.TryGetValue("aps", out aps)) {
string payloadStr = aps as string;
}
};
Also, there should be a args.PayloadString which should give some clues about the structure of the payload.
I am not very familiar with Android app Development.
In my previous app, I had used SOAP to connect android app with SQL Server using Asp.NET webservice. But then, I came to know that JSON would be the best method because of its parsing capabilities and many other advantages. I found many samples of code but they were all using PHP, whereas I am using asp.net.
Can anyone please help me to solve the problem?
Asp.NET Webservice Code :
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetCity()
{
DAL dal = new DAL();
try
{
List<City> lstCity = new List<City>();
DataTable dt = dal.GetDataTable("Select CityId, CityName from tblCity", "TEXT");
for (int i = 0; i < dt.Rows.Count; i++)
{
City and = new City();
and.CityId = Convert.ToInt64(dt.Rows[i]["CityId"].ToString());
and.CityName = dt.Rows[i]["CityName"].ToString();
lstCity.Insert(i, and);
}
JavaScriptSerializer jsCity = new JavaScriptSerializer();
return jsCity.Serialize(lstCity);
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
Android App Code:
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
tv.setText("");
for (int i = 0; i < cityList.size(); i++) {
lables.add(cityList.get(i).getName());
}
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerFood.setAdapter(spinnerAdapter);
}
private class GetCities extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CityData.this);
pDialog.setMessage("Fetching Cities..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
ServiceHandler sh = new ServiceHandler();
String json = sh
.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray cities = jsonObj.getJSONArray("GetCity");
for (int i = 0; i < cities.length(); i++) {
JSONObject catObj = (JSONObject) cities.get(i);
City cat = new City(catObj.getInt("CityId"),
catObj.getString("CityName"));
cityList.add(cat);
}
}
} catch (JSONException e) {
// e.printStackTrace();
result = e.getMessage().toString();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
tv.setText(result);
}
}
I am getting Error Value html of type java.lang.String cannot be converted to JSONObject
you need to using asp.net web services and converting your data in json format and from android code you will request the service data
try this example
http://osmosee.wordpress.com/2013/07/20/calling-a-json-based-asp-net-web-service-from-an-android-phone/
I know this is kludgy, but in my existing Web API client code, the way I stop reading records is when my call to webRequest.GetResponse() crashes on reading and finding none, and eating the exception (I'm reading a "block/chunk" at a time, due to the bandwidth limitations of the handheld device which calls the Web API REST method).
As my conscience (so to speak) was bothering me about doing it this way (but it works!), I thought maybe I could first get the count of records and use that knowledge to preclude reading beyond the pale/edge of the world, thus avoiding the exception.
However, as can be seen here: Why is my Web API routing being re-routed / falsely routed?, I'm finding no success in trying to access multiple GET methods - I could only get the desired GET method to be called by eliminating the other one!
My existing client code is:
private void buttonGetInvItemsInBlocks_Click(object sender, EventArgs e)
{
string formatargready_uri = "http://localhost:28642/api/inventoryItems/{0}/{1}";
// Cannot start with String.Empty or a blank string (" ") assigned to lastIDFetched; they both fail for some reason - Controller method is not even called. Seems like a bug in Web API to me...
string lastIDFetched = "0";
const int RECORDS_TO_FETCH = 100;
bool moreRecordsExist = true;
try
{
while (moreRecordsExist)
{
formatargready_uri = string.Format("http://localhost:28642/api/InventoryItems/{0}/{1}", lastIDFetched, RECORDS_TO_FETCH);
var webRequest = (HttpWebRequest)WebRequest.Create(formatargready_uri);
webRequest.Method = "GET";
var webResponse = (HttpWebResponse)webRequest.GetResponse(); // <-- this throws an exception when there is no longer any data left
// It will hit this when it's done; when there are no records left, webResponse's content is "[]" and thus a length of 2
if ((webResponse.StatusCode != HttpStatusCode.OK) || (webResponse.ContentLength < 3)) {
moreRecordsExist = false;
}
else // ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 2))
{
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
var arr = JsonConvert.DeserializeObject<JArray>(s);
foreach (JObject obj in arr)
{
string id = (string)obj["Id"];
lastIDFetched = id;
int packSize = (Int16)obj["PackSize"];
string description = (string)obj["Description"];
int dept = (Int16)obj["DeptSubdeptNumber"];
int subdept = (Int16)obj["InvSubdepartment"];
string vendorId = (string)obj["InventoryName"];
string vendorItem = (string)obj["VendorItemId"];
double avgCost = (Double)obj["Cost"];
double unitList = (Double)obj["ListPrice"];
inventoryItems.Add(new WebAPIClientUtils.InventoryItem
{
Id = id,
InventoryName = vendorId,
UPC_PLU = vendorId,
VendorItemId = vendorItem,
PackSize = packSize,
Description = description,
Quantity = 0.0,
Cost = avgCost,
Margin = (unitList - avgCost),
ListPrice = unitList,
DeptSubdeptNumber = dept,
InvSubdepartment = subdept
});
// Wrap around on reaching 100 with the progress bar; it's thus sort of a hybrid determinate/indeterminate value that is shown
if (progressBar1.Value >= 100)
{
progressBar1.Value = 0;
}
progressBar1.Value += 1;
}
} // if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
} // while
if (inventoryItems.Count > 0)
{
dataGridViewGETResults.DataSource = inventoryItems;
}
MessageBox.Show(string.Format("{0} results found", inventoryItems.Count));
}
catch (Exception ex)
{
// After all records are read, this exception is thrown, so commented out the message; thus, this is really *expected*, and is not an "exception"
//MessageBox.Show(ex.Message);
}
}
}
...and the Web API REST Controller code is:
public class InventoryItemsController : ApiController
{
static readonly IInventoryItemRepository inventoryItemsRepository = new InventoryItemRepository();
public IEnumerable<InventoryItem> GetBatchOfInventoryItemsByStartingID(string ID, int CountToFetch)
{
return inventoryItemsRepository.Get(ID, CountToFetch);
}
}
...and the (im?)pertinent Repository code is:
public IEnumerable<InventoryItem> Get(string ID, int CountToFetch)
{
return inventoryItems.Where(i => 0 < String.Compare(i.Id, ID)).Take(CountToFetch);
}
One would think I could have a method like this:
public IEnumerable<InventoryItem> Get()
{
return inventoryItems.Count();
}
...which would be recognized due to having no args as being different from the other one (even without the routing extravaganza, all attempts at appeasement by me failing ignominiously anyway yesterday).
I found I can get a record count with this code:
CLIENT
private int getInvItemsCount()
{
int recCount = 0;
const string uri = "http://localhost:28642/api/InventoryItems";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "GET";
using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
{
if (webResponse.StatusCode == HttpStatusCode.OK)
{
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
Int32.TryParse(s, out recCount);
}
}
return recCount;
}
private void GetInvItemsInBlocks()
{
Cursor.Current = Cursors.WaitCursor;
try
{
string lastIDFetched = "0";
const int RECORDS_TO_FETCH = 100;
int recordsToFetch = getInvItemsCount();
bool moreRecordsExist = recordsToFetch > 0;
int totalRecordsFetched = 0;
while (moreRecordsExist)
{
string formatargready_uri = string.Format("http://localhost:28642/api/InventoryItems/{0}/{1}", lastIDFetched, RECORDS_TO_FETCH);
var webRequest = (HttpWebRequest)WebRequest.Create(formatargready_uri);
webRequest.Method = "GET";
using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
{
if (webResponse.StatusCode == HttpStatusCode.OK)
{
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
var arr = JsonConvert.DeserializeObject<JArray>(s);
foreach (JObject obj in arr)
{
var id = (string)obj["Id"];
lastIDFetched = id;
int packSize = (Int16)obj["PackSize"];
var description = (string)obj["Description"];
int dept = (Int16)obj["DeptSubdeptNumber"];
int subdept = (Int16)obj["InvSubdepartment"];
var vendorId = (string)obj["InventoryName"];
var vendorItem = (string)obj["VendorItemId"];
var avgCost = (Double)obj["Cost"];
var unitList = (Double)obj["ListPrice"];
inventoryItems.Add(new WebAPIClientUtils.InventoryItem
{
Id = id,
InventoryName = vendorId,
UPC_PLU = vendorId,
VendorItemId = vendorItem,
PackSize = packSize,
Description = description,
Quantity = 0.0,
Cost = avgCost,
Margin = (unitList - avgCost),
ListPrice = unitList,
DeptSubdeptNumber = dept,
InvSubdepartment = subdept
});
if (progressBar1.Value >= 100)
{
progressBar1.Value = 0;
}
progressBar1.Value += 1;
} // foreach
} // if (webResponse.StatusCode == HttpStatusCode.OK)
} // using HttpWebResponse
int recordsFetched = WebAPIClientUtils.WriteRecordsToMockDatabase(inventoryItems, hs);
label1.Text += string.Format("{0} records added to mock database at {1}; ", recordsFetched, DateTime.Now.ToLongTimeString());
totalRecordsFetched += recordsFetched;
moreRecordsExist = (recordsToFetch > (totalRecordsFetched+1));
} // while
if (inventoryItems.Count > 0)
{
dataGridViewGETResults.DataSource = inventoryItems;
}
}
finally
{
Cursor.Current = Cursors.Default;
}
}
SERVER
Repository Interface:
interface IInventoryItemRepository
{
. . .
int Get();
. . .
}
Repository Interface Implementation:
public class InventoryItemRepository : IInventoryItemRepository
{
private readonly List<InventoryItem> inventoryItems = new List<InventoryItem>();
. . .
public int Get()
{
return inventoryItems.Count;
}
. . .
}
Controller:
static readonly IInventoryItemRepository inventoryItemsRepository = new InventoryItemRepository();
public int GetCountOfInventoryItems()
{
return inventoryItemsRepository.Get();
}
Given the coordinates of a location, is there a way to get the place name?
I don't mean the address, I mean the "title" of the place, e.g.:
Coordinates: 76.07, -62.0 // or whatever they are
Address: 157 Riverside Avenue, Champaign, Illinois
Place name: REO Speedwagon's Rehearsal Spot
-or:
Coordinates: 76.07, -62.0 // or whatever they are
Address: 77 Sunset Strip, Hollywood, CA
Place name: Famous Amos Cookies
So is there a reverse geocoding web service or something that I can call, a la:
string placeName = GetPlaceNameForCoordinates(76.07, -62.0)
...that will return "Wal*Mart" or "Columbia Jr. College" or whatever is appropriate?
I've found references to other languages, such as java and ios (Objective C, I guess), but nothing specifically for how to do it in C# from a Windows store app...
UPDATE
I already have this for getting the address (adapted from Freeman's "Metro Revealed: Building Windows 8 apps with XAML and C#" page 75):
public static async Task<string> GetStreetAddressForCoordinates(double latitude, double longitude)
{
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("http://nominatim.openstreetmap.org");
HttpResponseMessage httpResult = await httpClient.GetAsync(
String.Format("reverse?format=json&lat={0}&lon={1}", latitude, longitude));
JsonObject jsonObject = JsonObject.Parse(await httpResult.Content.ReadAsStringAsync());
return string.format("{0} {1}", jsonObject.GetNamedObject("address").GetNamedString("house"),
jsonObject.GetNamedObject("address").GetNamedString("road"));
}
...but I see nothing for Place Name in their docs; they seem to supply house, road, village, town, city, county, postcode, and country, but no Place Name.
I usually store the latitude/longitude coordinates and then use GMaps to look up the location, then "on a best effort basis" - look up the place's name using the address - again via Google Maps.
static string baseUri =
"http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false";
string location = string.Empty;
public static void RetrieveFormatedAddress(string lat, string lng)
{
string requestUri = string.Format(baseUri, lat, lng);
using (WebClient wc = new WebClient())
{
string result = wc.DownloadString(requestUri);
var xmlElm = XElement.Parse(result);
var status = (from elm in xmlElm.Descendants() where
elm.Name == "status" select elm).FirstOrDefault();
if (status.Value.ToLower() == "ok")
{
var res = (from elm in xmlElm.Descendants() where
elm.Name == "formatted_address" select elm).FirstOrDefault();
requestUri = res.Value;
}
}
}
Edit:
Here's a simple version of the reverse:
public static Coordinate GetCoordinates(string region)
{
using (var client = new WebClient())
{
string uri = "http://maps.google.com/maps/geo?q='" + region +
"'&output=csv&key=sadfwet56346tyeryhretu6434tertertreyeryeryE1";
string[] geocodeInfo = client.DownloadString(uri).Split(',');
return new Coordinate(Convert.ToDouble(geocodeInfo[2]),
Convert.ToDouble(geocodeInfo[3]));
}
}
public struct Coordinate
{
private double lat;
private double lng;
public Coordinate(double latitude, double longitude)
{
lat = latitude;
lng = longitude;
}
public double Latitude { get { return lat; } set { lat = value; } }
public double Longitude { get { return lng; } set { lng = value; } }
}
I've found references to other languages, such as java and ios (Objective C, I guess)
Look closely into those references - most of them are likely to use reverse geocoding web services... and those could be used by your Windows Store app as well. Pick a service which has appropriate features and restrictions for your app, and make HTTP requests to it. (You may even find there's an appropriate client library available, although I guess that's relatively unlikely right now, due to the recent-ness of Windows 8...)
Geolocator geolocator = new Geolocator();
Geoposition geoposition = await geolocator.GetGeopositionAsync();
string lat = geoposition.Coordinate.Point.Position.Latitude.ToString();
string lon = geoposition.Coordinate.Point.Position.Longitude.ToString();
string baseUri = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false", lat, lon);
HttpClient client = new HttpClient();
var response = await client.GetStringAsync(baseUri);
var responseElement = XElement.Parse(response);
IEnumerable<XElement>statusElement = from st in responseElement.Elements("status") select st;
if (statusElement.FirstOrDefault() != null)
{
string status = statusElement.FirstOrDefault().Value;
if (status.ToLower() == "ok")
{
IEnumerable<XElement> resultElement = from rs in responseElement.Elements("result") select rs;
if (resultElement.FirstOrDefault() != null)
{
IEnumerable<XElement> addressElement = from ad in resultElement.FirstOrDefault().Elements("address_component") select ad;
foreach (XElement element in addressElement)
{
IEnumerable<XElement> typeElement = from te in element.Elements("type") select te;
string type = typeElement.FirstOrDefault().Value;
if(type=="locality")
{
IEnumerable<XElement> cityElement = from ln in element.Elements("long_name") select ln;
string city = cityElement.FirstOrDefault().Value;
break;
}
}
}
}
}
Use below code in c# console application. Pass the path of your CSV that has coordinate and it will fetch the address tag from the response and place it in a CSV
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Google_Padouri
{
class Program
{
static void Main(string[] args)
{
Google obj = new Google();
obj.Execute();
}
}
class Google
{
public void Execute()
{
string result = string.Empty;
try
{
Console.WriteLine("Enter complete csv path");
string path = Console.ReadLine();
//string path = #"C:\tmp\google\test_file.csv";
string[] rows = File.ReadAllLines(path);
StringBuilder sb = new StringBuilder();
int count = 0;
foreach(string row in rows)
{
string[] arr = row.Split(',');
string lat = arr[0];
string lng = arr[1];
if (count > 0)
{
result = GetResult(lat, lng);
if (result.Length > 1)
{
result = GetAddress(result);
if (result.Length > 1)
{
Console.WriteLine("Working on row number " + count);
sb.Append(lat + "," + lng + "," + result.Replace(",", "") + "\n");
//if(count==200)
//{
// break;
//}
}
else
{
Console.WriteLine("Could not fetch results");
}
}
else
{
Console.WriteLine("Google API response failed");
}
}
count = count+1;
}
string dir = Path.GetDirectoryName(path);
string file = Path.GetFileNameWithoutExtension(path);
file = file + "_output.csv";
string fullpath = dir + "\\" + file;
using (StreamWriter wrtier = File.CreateText(fullpath))
{
wrtier.Write(sb.ToString());
}
Console.Write("File compiled successfully");
Console.Read();
}
catch (Exception ex)
{
Console.Write(ex);
}
}
public string GetResult(string lat,string lang)
{
string method = "GET";
string URL = "https://maps.googleapis.com/maps/api/geocode/json?";
string Key = "key=YOUR_KEY";
string Sensor = "sensor=false&";
string latlng = "latlng=" + lat + "," + lang;
string result = string.Empty;
URL = URL + Key + Sensor + latlng;
try
{
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/json";
wc.Encoding = Encoding.UTF8;
wc.Headers.Add("User-Agent: Other");
switch (method.ToUpper())
{
case "GET":
result = wc.DownloadString(URL);
break;
}
}
}
catch (Exception ex)
{
Console.Write(ex);
Console.Read();
}
return result;
}
public string GetAddress(string data)
{
string result = string.Empty;
try
{
if (data.Length > 1)
{
JToken token = JToken.Parse(data);
JArray array = JArray.Parse(token["results"].ToString());
result = array.First["formatted_address"].ToString();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.Read();
}
return result;
}
}
}
Is it possible to make a call to the Google Charts API in a console app and save the result as a JPEG or PNG file? I can do it easily in a web app, just not quite sure how to do it in C#.
Many thanks-
https://chart.googleapis.com/chart
You could use the googlechartsharp wrapper for the Charts API to get a URL at which you can view the chart.
Using the HttpWebRequest and HttpWebResponse classes (or the WebClient class as per Joey's answer), you could capture the response stream as a byte array (the image) and write that to a file with the proper extension (a *.png file). Something like:
string chartUrl = chart.GetUrl();
byte[] chartBytes = null;
WebClient client = new WebClient();
chartBytes = client.DownloadData(chartUrl);
using (var memStream = new MemoryStream())
{
memStream.Write(chartBytes, 0, chartBytes.Length);
}
File.WriteAllBytes("C:\temp\myChart.png", chartBytes);
Use the WebClient class and its DownloadData or DownloadFile methods. Constructing the URL to retrieve is up to you.
I added my Chart generator class (working perfectly). Just call it (as seen below) add your own event method to catch the chart once it is generated and save it to the HDD.
Calling the class and generating the chart:
ChartGenerator charBartGen = new ChartGenerator();
charBartGen.ChartCreated += new ChartCreatedEventHandler(charBartGen_ChartCreated);
charBartGen.CreateBarChart(pictureBox2.Height, pictureBox2.Width,
stats.MaxChecks,
"Past 7 days",
stats.Last7DayChecks1, stats.Last7DayChecks2);
The actual class:
public class ChartGenerator
{
public event ChartCreatedEventHandler ChartCreated;
public string CreatePieChartUrl(int pHeight, int pWidth,
string[] pSeries, string pTitle, int[] pData)
{
string st = String.Format(Misc.EnUk,
#"http://chart.apis.google.com/chart?chs={0}x{1}&cht=p3&chd=t:", pWidth, pHeight);
for (int i = 0; i < pData.Length; i++)
{
st += pData[i].ToString(Misc.EnUk) + ",";
}
st = st.TrimEnd(',');
st += "&chdl=";
for (int i = 0; i < pData.Length; i++)
{
st += pSeries[i].Replace(" ", "+") + "|";
}
st = st.TrimEnd('|');
st += "&chtt=";
st += pTitle.Replace(" ", "+") + "|";
return st;
}
public void CreatePieChart(int pHeight, int pWidth,
string[] pSeries, string pTitle, int[] pData)
{
string url = CreatePieChartUrl(pHeight, pWidth,
pSeries, pTitle, pData);
Thread th = new Thread(new ParameterizedThreadStart(CreateChartAsync));
th.Start(url);
}
public string CreateBarChartUrl(int pHeight, int pWidth, int pMax,
string pTitle, int[] pData1, int[] pData2)
{
string st = String.Format(Misc.EnUk,
#"http://chart.apis.google.com/chart?chxr=0,0,{0}&chxt=y&chbh=a&chs={1}x{2}&cht=bvs&chco=4D89F9,C6D9FD&chds=0,{0},0,{0}&chd=t:",
pMax, pWidth, pHeight);
for (int i = 0; i < pData1.Length; i++)
{
st += pData1[i].ToString(Misc.EnUk) + ",";
}
st = st.TrimEnd(',');
st += "|";
for (int i = 0; i < pData2.Length; i++)
{
st += pData2[i].ToString(Misc.EnUk) + ",";
}
st = st.TrimEnd(',');
st += "&chtt=";
st += pTitle.Replace(" ", "+");
return st;
}
public void CreateBarChart(int pHeight, int pWidth,int pMax,
string pTitle, int[] pData1,int[] pData2)
{
string url = CreateBarChartUrl(pHeight, pWidth, pMax,
pTitle, pData1, pData2);
Thread th = new Thread(new ParameterizedThreadStart(CreateChartAsync));
th.Start(url);
}
private void CreateChartAsync(object pUrl)
{
string url = pUrl as string;
try
{
if (url != null)
{
using (Stream stream = GetPageContentStream(url, false))
{
Image img = Image.FromStream(stream);
if (img != null)
{
if (ChartCreated != null)
{
ChartCreated(this, new ChartCreatedEventArgs(img));
}
}
}
}
}
catch (Exception err)
{
Debug.Fail(err.Message);
}
}
/// <summary>
/// Gets the stream of the given url
/// </summary>
/// <param name="url">The url</param>
/// <param name="file">Whether this is a web file stream or a HttpWebRequest</param>
/// <returns></returns>
public static Stream GetPageContentStream(string url, bool file)
{
try
{
WebRequest wreq;
WebResponse wres;
if (file)
{
wreq = System.Net.FileWebRequest.Create(url);
}
else
{
wreq = HttpWebRequest.Create(url);
HttpWebRequest httpwrqst = wreq as HttpWebRequest;
if (httpwrqst != null)
{
httpwrqst.AllowAutoRedirect = false;
httpwrqst.Timeout = 10000;
}
}
wres = wreq.GetResponse();
return wres.GetResponseStream();
}
catch(Exception err)
{
Debug.Fail(err.Message);
Logger.AppLogger.Instance.LogError("GetPageContentStream", err);
return null;
}
}
}
public delegate void ChartCreatedEventHandler(object sender,ChartCreatedEventArgs e);
[Serializable]
public class ChartCreatedEventArgs : EventArgs
{
private readonly Image mImage;
public ChartCreatedEventArgs()
{
}
public ChartCreatedEventArgs(Image pImage)
{
mImage = pImage;
}
public Image Image
{
get
{
return mImage;
}
}
}