Feed

It is a bit weird to notice that a .Net Framework method returns NotImplementedException. At least it was for me, mainly because it is not documented anywhere in the msdn documentation.

It turns out that Graphics.DrawImage throws this exception when an Image object is passed in. This is really funny,  since this method actually expects an Image object as its first argument, so my first-try code to print an image file was:

   1:  public void PrintImage(string fileName)
   2:   
   3:  {
   4:   
   5:        Image img = Image.FromFile(fileName);
   6:        PrintDocument printDoc = new PrintDocument();
   7:        printDoc.DocumentName = this.m_sFilename;
   8:        printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
   9:        printDoc.Print();
  10:   
  11:  }
  12:   
  13:  private void PrintPage(object sender, PrintPageEventArgs e)
  14:  {
  15:        // Throws NotImplementedException!!!
  16:   
  17:        e.Graphics.DrawImage(
  18:             this.printedImage,
  19:             new Point(e.MarginBounds.Left, e.MarginBounds.Top));
  20:   
  21:        e.HasMorePages = false;
  22:  }

Weird, eh?! So, the solution? 

   1:  Bitmap img = (Bitmap)Image.FromFile(fileName); 

 Bitmap class extends Image, so, IMHO, DrawImage should determine in runtime that the image passed in is actually is a Bitmap and do whatever it has to do, but, strangely, it complains and throws a NotImplementedException for the exactly same runtime object.

Can someone explain what is happening here?

Tags: , ,

Sometimes you need to pass data to a web page and at the same time you need to be able to provide a permalink to that URL to the user. In this case, you don't have any option other than passing those parameters through the Query String. Otherwise, you could use the Form, Session state, database or any other persistence or data transport mechanism.

I recently had to create a page that needed to receive some sensitive parameters and, at the same time, I needed to be able to provide the URL to the user, so that he/she could view that same page. However, I needed to somehow make the parameters private to the system, so that no one could decypher what data the actual parameters held. The only solution I found was to encrypt the Query String values!

For those who are not very familiar with the subject (like me), cryptography can be a really scary thing! Thankfully, Jeff Atwood, founder of the famous codinghorror.com blog (which of I am a fan also!) wrote a great article at Code Project with some simple background, definitions and a .NET code for those who do not have a strong background on the subject.

I not only found that very useful but also ported the code to C# to fulfill my needs. This tool helped me with the rough conversion but I still had to do some conversion by hand, since the code did not compile at first try.

I separated the code logically in different files for better reading. It can be downloaded here.

Below is a simple usage of the Simmetric-key class with the Rijndael (AES) provider to encrypt the query string variable in one page, send it, and then decrypt in the other side:

   1:  Symmetric symEncryption = new Symmetric(Symmetric.Provider.Rijndael);
   2:  symEncryption.Key.Text = "SomeKey";
   3:   
   4:  string sSensitiveText = "Some sensitive data";
   5:  string sEncryptedData = symEncryption.Encrypt(new Data(sSensitiveText)).Base64;
   6:   
   7:  // fearlessly send sEncryptedData in your query string
   8:  Response.Redirect(
	"http://www.someurl.com/somepage.aspx?data=" + Server.UrlEncode(sEncryptedData));
   9:   
  10:  ...
  11:   
  12:  // in the other side, decrypt the text you just received
  13:  string sDecryptedText = symEncryption.Decrypt(
	new Data(Request.QueryString["data"].FromBase64())).Text;
  14:   
  15:  // outputs "Some sensitive data"
  16:  Console.WriteLine(sDecryptedText); 

Hope this helps someone :)

Tags: ,

Here is something I found out today that might be useful for Sql Server users out there:

If you need to pass a variable to a sql script file in runtime, you can use the sqlcmd tool with the -v option, for example:

sqlcmd -S localhost\SQLEXPRESS -i myscript.sql -v myVar1="myVar1Value" myVar2="myVar2Value"

Then, inside the sql script, those variables can be accessed using the $(var) format:

ALTER TABLE [dbo].[$(myVar1)] INSERT ... VALUES ($(myVar2), $(myVar3) ...)

You can also specify these vars inside the sql script with setvar. More information in this MSDN article (Using sqlcmd with Scripting Variables).

Tags:

I ran into a FileNotFoundException lately when working with the latest NUnit release 2.5. It seems like its assemblies are not being added to the .Net Framework GAC (Global Assembly Cache), so this means that, unless you manually copy them to the same directory as you're working on, you'll have to manually add them to the GAC.

There is a well explained reply in StackOverflow (again) telling how to use the "gacutil" to solve this. Basically all you have to do is unregister all your old versions of NUnit (if any) and then use gacutil /i to register the assemblies.

Tags:

In C#, you are not able to serialize an object that does not have a parameterless constructor. At least, XmlSerializer is not able to do this. It seems like BinaryFormatter is able, as per this StackOverflow question.

This means you are not able to Xml serialize some object like this, also:

var myObj = new
{
    MyPropertyString = "prop1value",
    MyPropertyInt = 2,
    MyPropertyList = new List<string> { "bananas", "apples", "pees" }
});

I needed to be able to serialize this kind of object to database in a human-readable format so, if you don't need to output in Xml format specifically, you can try this great Json.NET library by James Newton-King, that worked smoothly for me, as easy as:

string jsonString = JsonConvert.SerializeObject(_myObj);

Surely you can do many other things with this library, which you can find out by yourself.

Whoever tried to use SQL Server Express for any medium sized project, has probably experienced some really painful problems accessing the database file.

Express is a free version of this well known Microsoft database engine which is targeted for smaller business. It has some limitations when compared to the other enterprise-targeted versions.

One of its key differences is that, unlike the other versions, you don't need a database instance to start working. The only thing you need is an empty MDF file to start off. It can be created from Visual Studio (Add New Item > SQL Server Database) and you're ready to go. However, here is where the problems start...

The big issue is that the MDF is a regular windows file, like any other. This means that only one process is able to modify it at a time.

If you use Visual Studio and/or SQL Server Management Studio regularly, you have probably run into this error when working with SQL Server Express:

There are several reason reasons that could cause this. Here are two that I found most recurring:

Cause 1. The NETWORK SERVICE user is not able to open the database file because it does not have rights to do so.

Solution 1.  Edit the file permissions and grant Read/Write rights to it: Right mouse click on file or containing folder > Security > Advanced > Edit

If the NETWORK SERVICE is already on the list, make sure it has read/write permission.

Else, click Add... and type NETWORK SERVICE in the edit field. Add the proper permissions and click Ok in all the open Windows. Reload the webpage.

In some machines, I've seen the user IIS_IUSRS instead of NETWORK SERVICE, so you can try this one as well. (if it exists)

 

Cause 2.  Visual Studio is locking the database file. In some cases, when you edit the database inside VS using the Server Explorer window, the handle remais open even after you close the connection with the database.

Solution 2.  If your Visual Studio is open, go to the Server Explorer window and make sure the database connection closed.

 
 
If you are using SQL Server Management Studio Express, you have to Detach the database (do not forget to check the checkbox "Drop Connections" in the subsequent screen):

 
Go to your webpage and try reloading it.  It should work now. In case it doesn't work, try closing your Solution inside VS or close the whole VS window. I've seen cases where VS keeps the database locked even after you closed the connection in the Server Explorer. Unfortunately, the error above isn't related to an open connection and this is why it sometimes it gets really hard to diagnose the issue.
 
As I said before, only one connection may be open with the SQL Express database file at a time, so always make sure there is no other program with it open. This does not mean that it does not allow concurrent users using the database, but Visual Studio and Management Studio manage to open it in such a way that locks the file entirely. The reason is unknown to me. 

Tags:

About the Author

myself
My name is Felipe Lima and I am a Software Engineer and co-founder at Quavio, a digital agency at Porto Alegre, Brazil. I am interested in technology, programming with the .Net Framework and sports. Check out my full profile.

Powered by BlogEngine.NET 1.4.5.0