Maps with Windows Forms application - c#

I am building a C#/Winforms application that requires a map (a la Google maps, Bing maps etc.). But I am terribly confused by the ToU (licensing) - non-commercial use etc.
My questions:
What mapping provider would you suggest (preferably free) to embed with a winforms application, for commercial purposes.
What mapping provider would you recommend if the app is "offline" i.e. cannot get tiles from a mapping server.
Google Earth seemed quite promising until I read in the ToU of non-commercial use only clause, would you know if that is waivable through purchase of a license? Any commercial alternatives?

For Windows application, try looking for OpenStreetMap for windows form integration using a browser control
For offline solution you will require map data. One of the most used map data format is Shapefiles which is an ESRI standard, you can download OpenStreetMap data and convert it to Shapefiles and then you can import them in your application. There are open source project which are using Shapefiles for map rendering and other GIS functionalities. namely SharpMap and DotSpatial (Both are .Net implementation)
You can search for Google Earth Pro, also try World Wind from NASA (which is free)

This is excellent, you can check different providers and select one that meets both legal and tech requirenments:
Great Maps for Windows Forms & Presentation
Just download code and check out the demo!

Try This Code Using Web browser control
this code to get direction between two location
System.Text.StringBuilder queryaddress = new System.Text.StringBuilder();
string sStreet = string.Empty;
string sCity = string.Empty;
string sState = string.Empty;
string sPincode = string.Empty;
string sProvider_no = string.Empty;
queryaddress.Append("https://www.google.com/maps/dir/");
if (!string.IsNullOrEmpty(txtprovider_no.Text)) {
sProvider_no = txtprovider_no.Text.Replace(" ", "+");
queryaddress.Append(sProvider_no + "," + "+");
}
if (!string.IsNullOrEmpty(txtState.Text)) {
sState = txtState.Text.Replace(" ", "+");
queryaddress.Append(sState + "," + "+");
}
if (!string.IsNullOrEmpty(txtCity.Text)) {
sCity = txtCity.Text.Replace(" ", "+");
queryaddress.Append(sCity + "," + "+");
}
if (!string.IsNullOrEmpty(txtPincode.Text)) {
sPincode = txtPincode.Text.Replace(" ", "+");
queryaddress.Append(sPincode);
}
queryaddress.Append("/");
sStreet = string.Empty;
sCity = string.Empty;
sState = string.Empty;
sPincode = string.Empty;
if (!string.IsNullOrEmpty(txtlindmark.Text)) {
sStreet = txtlindmark.Text.Replace(" ", "+");
queryaddress.Append(sStreet + "," + "+");
}
if (!string.IsNullOrEmpty(txtclient_city.Text)) {
sCity = txtclient_city.Text.Replace(" ", "+");
queryaddress.Append(sCity + "," + "+");
}
if (!string.IsNullOrEmpty(ttxtclient_city.Text)) {
sPincode = ttxtclient_city.Text.Replace(" ", "+");
queryaddress.Append(sPincode);
}
if (!string.IsNullOrEmpty(txtclient_state.Text)) {
sState = txtclient_state.Text.Replace(" ", "+");
queryaddress.Append(sState + "," + "+");
}
WBR.Navigate(queryaddress.ToString());

Related

"Given Path Format Is Not Supported"... Can you help me?

So, I made a speech recognizer and it was working fine, I'm not sure why is it giving me this error right now. Any ideas?
String res = e.Result.Text;
string yol = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
string settings = ("#" + yol + "\\" + "settings" + "\\");
if (res == "Hi Bot")
{
pictureBox1.Image = Image.FromFile(settings + "mybot.png"); -->That's where i get the error
say(greetings_random());
}
string yol = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
string settings = ("#" + yol + "\\" + "settings" + "\\");
This means that settings has the value "#C:\Path\To\Executable\settings\".
That's probably not what you want -- I'm not sure what the # is trying to achieve, but it's not valid at the beginning of a path like that.
For future, debugging this code and inspecting the settings variable would quickly have shown the problem.
That said, it's recommended to use Path.Join (.NET Core 2.1+) or Path.Combine instead of string concatenation to create paths like this.

Porting winform application to run on raspberry PI

I have a c# winform application that I want to port to run on my new Raspberry PI 3. I'm in moaning mode because I thought that my app would just run. That is not the case at all. My winform app uses quart. net, the aforge library and common .net libraries such as system.configuration.
I though I would start with my logging class as someone had mentioned that non UI code should be easy to convert if anything needed changing at all.
This looks like I'm going to have to reinvent the wheel. To be specific for startes have a look at the function below. Any code that uses system.configuration will not work.
Is there any easier way of getting my app to work or do I have to literally convert almost all my code. Is the aforge library even going to work on the PI?
Is quart.net going to work?
Right now I feel like giving up and buying a small windows PC that runs "proper" windows.
C# Winform Code
class Logging
{
public void Write_To_Log_File(String Message, String Procedure, String Error_Code, String Error_String)
{
try
{
// If the log file is bigger than allowed size then archive
if (File.Exists(#ConfigurationManager.AppSettings["LogSavePath"]))
{
FileInfo file = new FileInfo(#ConfigurationManager.AppSettings["LogSavePath"]);
if (file.Length > Convert.ToInt32(ConfigurationManager.AppSettings["FileLogSizeLimit"]))
{
// Rename the file
File.Move(#ConfigurationManager.AppSettings["LogSavePath"], #ConfigurationManager.AppSettings["LogSavePath"] + string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now) + ".csv");
}
}
// If log file does not exist then create it and add the headers
if (File.Exists(#ConfigurationManager.AppSettings["LogSavePath"]))
{
}
else
{
// Create the file
System.IO.File.Create("LogSavePath");
// Add data
string[] Headers = { "Time" + "," + "_Message" + "," + "Procedure" + "," + "Error_Code" + "," + "Error_String" };
System.IO.File.AppendAllLines(#ConfigurationManager.AppSettings["LogSavePath"], Headers);
}
if (File.Exists(#ConfigurationManager.AppSettings["LogSavePath"]))
{
string[] Log = { DateTime.Now.ToString() + "," + Message + "," + Procedure + "," + Error_Code + "," + Error_String };
System.IO.File.AppendAllLines(#ConfigurationManager.AppSettings["LogSavePath"], Log);
}
}
catch
{
}
}
}
Microsoft launched a Windows 10 IoT Core Porting Tool for this purpose. This can assist you in migrating from Win32 apps and libraries to Windows 10 IoT Core apps. More details here: https://developer.microsoft.com/en-us/windows/iot/win10/tools/iotapiportingtool

Creating a HMAC signature for AWS REST query in C#

So I'm trying to do a REST API call to AWS' SNS service, but I keep getting an IncompleteSignature error. I based myself on http://www.jokecamp.com/blog/examples-of-creating-base64-hashes-using-hmac-sha256-in-different-languages/#csharp on how to create the signature and http://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/HMACAuth.html to find out what to sign.
Here's the test code I came up with:
static void Main(string[] args)
{
string region = "us-west-2";
string msg = "This is a test!";
string secret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
string key = "XXXXXXXXXXXXXXX";
string arn = "arn:aws:sns:us-west-2:xxxxxxxxxx:snstest1";
string query = "Action=Publish&Message=" + HttpUtility.UrlEncode(msg) + "&MessageStructure=json&TargetArn=" + HttpUtility.UrlEncode(arn) + "&SignatureMethod=HmacSHA256&AWSAccessKeyId=" + key + "&SignatureVersion=2&Timestamp=" + HttpUtility.UrlEncode(DateTime.UtcNow.ToString("o"));
string tosign = "GET\nsns." + region + ".amazonaws.com\n/\n" + query;
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(secret);
byte[] messageBytes = encoding.GetBytes(tosign);
var hmacsha256 = new HMACSHA256(keyByte);
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
query += "&signature=" + HttpUtility.UrlEncode(Convert.ToBase64String(hashmessage));
Console.WriteLine("REST Call: https://sns." + region + ".amazonaws.com/?" + query);
}
Any idea what might be wrong?
EDIT: I tried changing the signature part with the code from http://wiki.alphasoftware.com/~alphafiv/DotNet+Example%3A+Digital+Hash it uses CharArray instead of the byte[], not sure which is right, it produces a different signature but it still doesn't work with AWS.
EDIT2: After long tries I finally figured out that AWS expects Signature= and not signature=, but now I'm getting a SignatureDoesNotMatch error, so I need to figure that out next. Also I don't know why this kind of question would get downvoted. Once I figure out the syntax, an AWS API call would be trivial to do in any app. If you use the AWS .NET SDK you're adding 6 megs to your binary. How is that not a worthwhile endeavor?
SOLUTION:
This code works and will send a SNS notification without the AWS SDK:
static void Main(string[] args)
{
string region = "us-west-2";
string msg = "Test test: sfdfds\nfsd: sdsda\n";
string secret = "XXXXXXXXXXXXXXXXXXX";
string key = "ZZZZZZZZZZZ";
string arn = "arn:aws:sns:us-west-2:YYYYYYYYYYY:snstest1";
string query = "AWSAccessKeyId=" + Uri.EscapeDataString(key) + "&Action=Publish&Message=" + Uri.EscapeDataString(msg) + "&SignatureMethod=HmacSHA256&SignatureVersion=2&TargetArn=" + Uri.EscapeDataString(arn) + "&Timestamp=" + Uri.EscapeDataString(System.DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"));
string tosign = "GET\nsns." + region + ".amazonaws.com\n/\n" + query;
Console.WriteLine(tosign + "\n");
UTF8Encoding encoding = new UTF8Encoding();
HMACSHA256 hmac = new HMACSHA256(encoding.GetBytes(secret));
string signature = Convert.ToBase64String(hmac.ComputeHash(encoding.GetBytes(tosign)));
query += "&Signature=" + Uri.EscapeDataString(signature);
Console.WriteLine("REST Call: https://sns." + region + ".amazonaws.com/?" + query);
}
There is nothing wrong with rolling your own solution rather than using the SDKs. In fact, I prefer it, because in addition to more lightweight code, you are more likely to understand problems with unexpected behavior because you are working with the native interface.
Here's what you are missing:
Add the query string parameters ... sorted using lexicographic byte ordering
http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html
For example, TargetArn should not be before SignatureMethod. They all need to be sorted. There is only one possible correct signature for any given message, so the sort order is critical.

Setting up google analytics for desktop application

I have a desktop application written in C#. I want to collect user statistics in google analytics. For instance I want to know when user pressed on specific button and what was value in text control when he did it.
I am sending events data as explained here. I tried to do this either with WebClient.UploadValues like in this question and also with WebClient.UploadString
I have set up new google analytics account. When I was asked what I want to track (website or mobile app) I have selected mobile app (there was no choice for desktop apps).
The problem is that I don't see any data in my Google Analytics account. I know it may take some time while new data will appear there but I have waited for 3 days. And also I don't see anything in real time view when I test my application ( I also have some websites with analytics connected and when I browse them I see new pageviews in realtime section).
What am I doing wrong?
Here is the code that I use:
private static string _googleURL = "http://www.google-analytics.com/collect";
private static string _gaid = "UA-12345678-9";
public static void TestMethod()
{
try
{
string data = "";
data += "v=" + HttpUtility.UrlEncode("1");
data += "&" + "tid" + "=" + HttpUtility.UrlEncode(_gaid);
data += "&" + "cid" + "=" + HttpUtility.UrlEncode(Guid.NewGuid().ToString());
data += "&" + "t" + "=" + HttpUtility.UrlEncode("event");
data += "&" + "ec" + "=" + HttpUtility.UrlEncode("testevent");
data += "&" + "ea" + "=" + HttpUtility.UrlEncode("testaction");
data += "&" + "el" + "=" + HttpUtility.UrlEncode("testlabel");
using (var client = new WebClient())
{
client.UploadString(_googleURL, "POST", data);
}
}
catch (Exception ex)
{
Trace.WriteLine(ex);
}
}

Java to C# code converter [duplicate]

This question already has answers here:
Tool to convert java to c# code [closed]
(4 answers)
Closed 6 years ago.
Are there any converters available that converts Java code to C#?
I need to convert the below code into C#
String token = new String("");
URL url1 =new URL( "http", domain, Integer.valueOf(portnum), "/Workplace/setCredentials?op=getUserToken&userId="+username+"&password="+password +"&verify=true");
URLConnection conn1=url1.openConnection();
((HttpURLConnection)conn1).setRequestMethod("POST");
InputStream contentFileUrlStream = conn1.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(contentFileUrlStream));
token=br.readLine();
String encodedAPIToken = URLEncoder.encode(token);
String doubleEncodedAPIToken ="ut=" + encodedAPIToken;//.substring(0, encodedAPIToken.length()-1);
//String doubleEncodedAPIToken ="ut=" + URLEncoder.encode(encodedAPIToken);
//String userToken = "ut=" + URLEncoder.encode(token, "UTF-8"); //URLEncoder.encode(token);
String vsId = "vsId=" + URLEncoder.encode(docId.substring(5, docId.length()), "UTF-8");
url="http://" + domain + ":" + portnum + "/Workplace/getContent?objectStoreName=RMROS&objectType=document&" + vsId + "&" +doubleEncodedAPIToken;
String vsId = "vsId=" + URLEncoder.encode(docId.substring(5, docId.length()), "UTF-8");
url="http://" + domain + ":" + portnum + "/Workplace/getContent?objectStoreName=RMROS&objectType=document&" + vsId + "&" +doubleEncodedAPIToken;
Thanks in advance
The below links might help:
Microsoft Launches Java-to-C# Converter;
Tangible Software Solutions inc..
The code is not very complicated, but if you don't have the time to translate it, you can use a tool like JLCA(Java Language Conversion Assistant 2.0).
You can try VaryCode Domain no longer exists and no valid snapshots in the Wayback Machine
But you used classes like URLEncoder, BufferedReader etc. that are hard to convert to C# without losing some Java-specific features. For this particular part of code it is insignificant but in prospect you can get some unpredicted behavior of the whole converted program.

Categories

Resources