archiveren

Tagarchief: .net

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 ๐Ÿ™‚

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 ๐Ÿ˜›

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:

Yes, I’ve bought an Windows Phone device ๐Ÿ˜ˆ

And you can of course use it to call people, browse the internet and listen to some music…

But the real geek starts developing ofcourse ๐Ÿ˜Ž

I already have some idea’s for “funny/cool/useful?” programs, let’s name some of them (maybe someone can steal my ideas and make it in a REAL useful application)

  1. a dommel download meter, to see how much broadband you have left
  2. an application that shows the traffic camera’s of the flemish traffic control, perhaps with the location of the speed control?
  3. a wifi scanner that has the functionality of for example inssider

But first, getting back into programming
Second, getting back into .net-programming ๐Ÿ˜†

Maybe I’ll post some code snippets here ๐Ÿ˜‰

Wish me luck!