archiveren

Tagarchief: c#

My 5th wp7 app just went live πŸ™‚

Its purpose: sending a text message from your browser!

Download the application from the WP marketplace, login, take another device (desktop, laptop, tablet, another phone, …) and browse to http://mendel.somee.com (my current free asp host πŸ™‚ ), login with the same credentials as before, type your message, send it to your phone, and send it again! πŸ™‚

This makes you can write an entire book-long message, on another device (maybe even with physical keyboard πŸ™‚ )

More info on the SMSer project page: https://mendel129.wordpress.com/projects/smser/

Today, I’ve submitted my 5th application the Windows Phone 7 marketplace πŸ™‚

Basically, it gives you the ability to type a text message on your computer and send it to your phone for sending it to someone…

You can find some screenshots and links to the app on this project page.

 

I’m impressed my msdn account is still valid, so I’m happy for that πŸ™‚ (but that’s another story)

Anyway, the app is in a pretty rough form, but it works, and it’s something you might use as well πŸ™‚

23 years old, and I still didn’t know how to connect a microsoft sql with c#
That needed to change!

In the end, it’s almost exact the same as php/mysql or in netbeans…
You define a connection, you open it, and you’re ready to query πŸ™‚

The hardest part was getting the data source (my local computer) right ^^
Plus, you can connect using your windows credentials (just run it), or define some specific user authentication.

In code, it looks like this:

private void button2_Click(object sender, EventArgs e)
{
 SqlConnection myConnection = new SqlConnection("server=mendelportable\\sqlexpress;Trusted_Connection=yes;database=master;connection timeout=30");

 myConnection.Open();
 SqlCommand myCommand = new SqlCommand("select * from Table1", myConnection);
 SqlDataReader dr = myCommand.ExecuteReader();
 textBox1.Text = "";
 while (dr.Read())
 {
  textBox1.Text=textBox1.Text+dr["messages"].ToString()+"\r\n";
 }
}

And once you’re connected, you’re ready to query the hell out of that database 😎

It’s absolutely nothing special, and it’s good to know!

Mission accomplished πŸ™‚

Apparently, when you create a live tile, and you use an external URI to point to an image for the tile, the operating system removes the tile after a reboot…
This behaviour doesn’t occur when you use a local resource to instantiate the tile…

Just something you don’t actually know until you see it happening ^^

Jeah, it contains prefabricated sms-messages :mrgreen:

Because my previous “reloader” app was denied from the marketplace because of some weird reasons… (promoting other mobile providers) I build around this issue…

The results is PrefabSMS.

It’s an application in which you can store sms-messages, and afterwards send them with one click of a button πŸ™‚

So, you can create a messages, let’s say “sim topup 15”, to be send to a receiving side, lets say “8989”, and you can save this in PrefabSMS πŸ™‚

Ofcourse you can use it for other things as wel, sending “<3” to your girlfriend or “spam” to random people ^^


Some usefull numbers and messages:

DL

I’ve been programming again!
This time on soms apps called “PrefabSMS” and “WOL”.
More info about the app later, but now I just want to share some code snippets about sockets en live tiles!

UDP sockets

Sockets is something introduced since WP7.5’s update mango.
Something that should have been there since the beginngin… But hey, it’s here now, so enjoy it from now on!
Anyway, a first thing to do is include the namespace.

using System.Net.Sockets;

After that we can declare some new things πŸ™‚

Socket _socket = null;
static ManualResetEvent _clientDone = new ManualResetEvent(false);
const int TIMEOUT_MILLISECONDS = 5000;
const int MAX_BUFFER_SIZE = 2048;

Which meaning is all pretty obvious I think…

After this the socket is initialized with

_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

The 3rd thing we need is a send() function.
This should be something as follows:

public string Send(byte[] payload))
{
     string response = "Operation Timeout";

     if (_socket != null)
     {
          SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
          socketEventArg.RemoteEndPoint = new IPEndPoint(IPAddress.Broadcast, 11000);
          socketEventArg.Completed += new EventHandler(delegate(object s, SocketAsyncEventArgs e)
          {
          response = e.SocketError.ToString();
          _clientDone.Set();
          });
          socketEventArg.SetBuffer(payload, 0, payload.Length);
          _clientDone.Reset();
          _socket.SendToAsync(socketEventArg);
          _clientDone.WaitOne(TIMEOUT_MILLISECONDS);
     }
     else
     {
          response = "Socket is not initialized";
     }

     return response;
}

So, after initialisation, you can call send to send your byte array into the wild!

You can change the IPEndPoint in the send function into IPEndPoint(“192.168.1.100”, 80) or something else, just an ip address and a port for the packet! πŸ™‚

Live tiles

I’ve also been playing with the live tiles. In mango you can setup live tiles to enter a deep state of your application. With this you can open a specific page with specific data in your application instead of just “regularly” opening your app…

Add following reference.

using Microsoft.Phone.Shell;

Creation

StandardTileData NewTileData = new StandardTileData
{
     BackgroundImage = new Uri("ftgxmessage.png", UriKind.Relative),
     Title = temp.sendBody,
     BackTitle = temp.sendTo,
     BackContent = temp.sendBody,
     //BackBackgroundImage = new Uri("Blue.jpg", UriKind.Relative) 
};
ShellTile.Create(new Uri("/MainPage.xaml?action="+listBox1.SelectedIndex, UriKind.Relative), NewTileData);

This piece of code instantiates a standard tile with some info. Notice: you have a front and a back of the live tile (it flips around on the home screen πŸ™‚ )

And the create() puts it on the homescreen.

An action can be included in the create function: here we call mainpage with a specified action to execute, this is done by a QueryString – see further.
Adjust at your own needs πŸ™‚

At the page data can be passed from the tile into the app (this is done by a so called QueryString). This can be accessed in the Loaded function for the program with following code:

int id = Convert.ToInt32(NavigationContext.QueryString["action"]);

Et voila, you have your action variable at hand! πŸ™‚

Deletion

When you want to delete a tile, you first have to find your tile πŸ˜›

If we put the tile from above on the homescreen, it can be identified with the action variable in the QueryString. So we use this to find our tile and identify it. And to delete it πŸ™‚

string tempstring = "action=" + listBox1.SelectedIndex;
ShellTile TileToFind = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains(tempstring));

That’s all for today πŸ™‚

Haha!
My apps are doomed to fail the Windows Marketplace tests!

1) I forgot the change “pin-to-start” icon…
2) I found a nasty little bug πŸ™‚
3) I provided a wrong password for testing πŸ˜›

The xaps are already rebuild, but I can’t re-upload them untill they are discarted by Microsoft πŸ˜›
lol

So yet another couple of days delay πŸ˜›

Jeah, it’s a rainy Sunday, so what do you do =)
Let me share some stuff I’ve learned today…

 

1. Browser

First, I needed a way to open the browser externally. Just dropping the user at a website…
This is done pretty easily.

First you need to include the following namespace

using Microsoft.Phone.Tasks;

and after that a whole lot of “tasks” become available.
Code for jumping towards IE:

WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.URL = "http://www.mendelonline.be";
webBrowserTask.Show();

so that’s one thing πŸ™‚ (thx to windowsphonegeek)

 

2. SMS

Another thing was sending an sms…
This is also done by using a special task.

SmsComposeTask composeSMS = new SmsComposeTask();
composeSMS.Body = "SIM TOPUP 15";
composeSMS.To = "8989";
composeSMS.Show();

It’s the value of the body that is send towards the number of “to” (obviously =) )
More information on ginktage (thx!)

 

3. MessageBox

For some feedback towards the user I needed a confirmation dialog.
The one I used was a eventually a simple messagebox.
Code is as follows:

if(MessageBox.Show("are you sure?", "do something", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
 {
Β Β  //some actions
}

Code taken from create.msdn.

 

4. IsolatedStorageSettings

Another thing, I needed settings to be saved.
I had done this previously using IsolatedStorageSettings, but today I encountered some problems…
The returning error was “ArgumentException was unhandled. Value does not fall within the expected range.”.

Apparently this is Microsoft’s way of saying “there is a duplicate value in the storage” πŸ˜›

So a “remove” before the “add” solved some issues.

Further I noticed that not everything was saved.
Luckily there is a “save” method available for saving (no shit πŸ˜› )

private IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;
appSettings.Remove("email");
appSettings.Add("email", "someone@contoso.com");
appSettings.Save();
tbResults.Text = (string)appSettings["email"];

Inspiration was found on msdn.

 

5. Weird numbers

While debugging I noticed some weird numbers showing up on the right side of my screen…

No idea what they where doing there, no idea where they came from…

But, Markus Egger brought me the solution

The numbers are some performance counters from VisualStudio, and they only appear while debugging πŸ™‚

Indeed, while running in release or without VisualStudio the numbers don’t even exist.

Another solved problem! Thx @ Markus!

 

6. Pin-to-start

My last submission failed because of the “pin-to-start” icon was still the default…

No idea what this meant, so I rushed to Google. Finding dzone.com with some explanation.

The icon is described in the “WMAPPManifest.xml” file.
Default it’s the file “Background.png”.

So this can of course easily be changed…

 

7. ProgressBar

Last one! Yet again from windowsphonegeek.

I wanted a nice pretty loadingbar as you’ve probably seen in many apps already.

Didn’t found out how to fix this, but eventually it isn’t hard (if you know how to do it! πŸ˜› )

The code is really easy:

ProgressBar bar = new ProgressBar();
bar.IsIndeterminate = true;

this.ContentPanel.Children.Add(bar);

And removing is done by

this.ContentPanel.Children.Remove(bar);

if you make the ProgressBar global available…

 

So, that’s it for today πŸ™‚

Maybe someone can use it πŸ™‚

You saw also some screenshots from 2 apps. Both are pending in the marketplace πŸ™‚ Further updates are coming πŸ˜‰

The Legion of the Bouncy Castle

Bouncy Castle describes itself as a a collection of APIs used in cryptography. And that’s exactly what it is :mrgreen:

There are methods for signing data, encrypting data, exchanging data, … All sort of things you want to do with data to make it secure.
More technical: X.509 certificates, PKCS, S/MIME, TLS, OpenPGP. But also raw algorithms like RSA-PSS, AES, SHA-256, and many others. Full details can be found at their website.

Here, I’ll show you a couple of tricks using this c# (and java) library.

Signing messages.

Signing is a process of having a message M, and wanting to send it to someone. This someone then can verify it’s send by you, and you alone, and the message isn’t modified.
Well make use of an algorithm developed by the RSA Laboratories called “RSA-PSS”.
This scheme takes a hash (we’ll take sha-224), combines it with a salt, takes another hash and produces a encoded message EM, the signature of our original message.

All info can be found on the pages of RSA Laboratories.

This RSA-PSS algorithm is also part of the PKCS#1-2.0 standard.

I spend some time figuring out how to use this, so I’ll give you what I know πŸ™‚
The project is created in basic .net and some c#.

Generating a signature

Creating a signature in Bouncy Castle, we’re going to need the PSSsigner()

First some global things

1. byte arrays

We need everything to be byte arrays. This because every algorithm in information security works on bit level. So a method converting utf8 to bytes is needed.

static byte[] StrToArray(string str)
{
Β Β  Β System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Β Β  Β return encoding.GetBytes(str);
}
2. key management

The signature scheme makes use of a pair os assymetric RSA keys.

In this post I’ll be using the keys given by bouncy castle. In our project we used keys generated by .net’s System.Security.Cryptography.

RsaKeyParameters privatekey = new RsaPrivateCrtKeyParameters(
 new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137", 16),
 new BigInteger("010001", 16),
 new BigInteger("33a5042a90b27d4f5451ca9bbbd0b44771a101af884340aef9885f2a4bbe92e894a724ac3c568c8f97853ad07c0266c8c6a3ca0929f1e8f11231884429fc4d9ae55fee896a10ce707c3ed7e734e44727a39574501a532683109c2abacaba283c31b4bd2f53c3ee37e352cee34f9e503bd80c0622ad79c6dcee883547c6a3b325", 16),
 new BigInteger("e7e8942720a877517273a356053ea2a1bc0c94aa72d55c6e86296b2dfc967948c0a72cbccca7eacb35706e09a1df55a1535bd9b3cc34160b3b6dcd3eda8e6443", 16),
 new BigInteger("b69dca1cf7d4d7ec81e75b90fcca874abcde123fd2700180aa90479b6e48de8d67ed24f9f19d85ba275874f542cd20dc723e6963364a1f9425452b269a6799fd", 16),
 new BigInteger("28fa13938655be1f8a159cbaca5a72ea190c30089e19cd274a556f36c4f6e19f554b34c077790427bbdd8dd3ede2448328f385d81b30e8e43b2fffa027861979", 16),
 new BigInteger("1a8b38f398fa712049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729", 16),
 new BigInteger("27156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24a79f4d", 16));

and

RsaKeyParameters publickey = new RsaKeyParameters(
false,
new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137", 16),
new BigInteger("010001", 16));

So we have a private key en a public key. The public key can be known by everyone. For more information about asymmetric cryptography I’ll forward you to Wikipedia

3.Generation

So, let’s do something useful now.

We’ll be using some random information called a “salt”. Just to add some randomness to the signature.

byte[] slt = Hex.Decode("dee959c7e06411361420ff80185ed57f3e6776af"); //a random salt Β 
PssSigner eng = new PssSigner(new RsaEngine(), new Sha224Digest(), 20); //creation of PssSigner 
eng.Init(true, new ParametersWithRandom(privatekey , new FixedRandom(slt))); //initiation of PssSigner 
eng.BlockUpdate(unsigned, 0, unsigned.Length);
byte[] signed = eng.GenerateSignature(); //generation of signature

A psssigner is initiated. with our private key.
And a signature is created πŸ™‚

That’s it….

4. Verification

Ofcourse, you’ll need to verify if the signature is correct.
This is done with the following piece of code.

bool correctsignature = false; //a boolean to indicate if the signature is correct
PssSigner eng = new PssSigner(new RsaEngine(), new Sha224Digest(), 20); //create new pss
eng.Init(false, publickey); //initiate this one
eng.BlockUpdate(message, 0, message.Length);
if (eng.VerifySignature(signature)) //verify with public key
{
Β Β  Β Console.WriteLine("message " + ArrayToStr(message) + " succeeded verification");
Β Β  Β correctsignature = true;
}
else
Β Β  Β Console.WriteLine("failed verification");

So, I hope I didn’t lie somewhere here πŸ™‚
And is also hope someone will ever use this blogpost as reference :mrgreen: