Notes from Daily Encounters with Technology RSS 2.0
 
# Sunday, August 09, 2009

Microsoft Exchange supports Send As and Send On Behalf Of permissions to be granted to users for individual e-mail addresses. Sending e-mail from Outlook for these users is very simple – they just enter the desired address in the From field of a new message (toggled with the Show From command on the Options ribbon) and if they have the required permission it will be sent accordingly – either as if it was actually sent from that address or as sent by the user on behalf of the address in the From field.

If you want to achieve this from code there is a little more work involved. First of all the user must be authenticated on the server using one of the methods below:

SmtpClient smtp = new SmtpClient("smtp.domain.com");

// use user’s existing credentials
smtp.UseDefaultCredentials = true;

// pass username and password
smtp.Credentials = new NetworkCredentials("username", "password");

The next step is to set up the correct headers in the message otherwise the server will return error code 5.7.1 describing the permission the user does not have.

To send the e-mail as only the From property has to contain the desired address:

MailMessage mail = new MailMessage();
mail.From = new MailAddress("send.as@domain.com");

To send the e-mail on behalf of another user the Sender property must additionally contain the user’s e-mail address:

MailMessage mail = new MailMessage();
mail.From = new MailAddress("send.as@domain.com");
mail.Sender = new MailAddress("user.address@domain.com");

On a related note, the required permissions can be granted using PowerShell.

To grant the Send As permission:

Add-ADPermission –Identity "user1" –User "user2" –ExtendedRights Send-As

To grant the Send On Behalf Of permission:

Set-Mailbox "user1" -GrantSendOnBehalfTo "user2"

In both cases the user1 specifies the mailbox to grant the permission for and the user2 specifies the user to grant the permission to.

Sunday, August 09, 2009 7:39:38 PM (Central European Daylight Time, UTC+02:00)  #    Comments [0] - Trackback
Development | .NET
# Saturday, July 05, 2008

Gama System eArchive, one of the two products in our document product line, received accreditation from the Archives of the Republic of Slovenia last week. This acknowledgement by our national body means that any document stored in Gama System eArchive is automatically legally valid.

This is important for both our company and other companies looking for a long term electronic document storage solution. Our product is the first service oriented solution to receive the accreditation.

Congratulations to everyone involved in the product. Well done!

Saturday, July 05, 2008 10:37:14 PM (Central European Daylight Time, UTC+02:00)  #    Comments [1] - Trackback
Development | .NET | Personal | Software
# Tuesday, April 29, 2008

A .NET application in the company I work for recently started crashing under Windows Vista when trying to open a window implemented in an ActiveX DLL. Investigations showed that they were caused by an AccessViolationException "Attempted to read or write protected memory. This is often an indication that other memory is corrupt.". The cause was one of the ActiveX controls in the window. When instantited directly in a .NET Form the exception above was contained in a TargetInvocationException "Unable to get the window handle for the '<control name>' control. Windowless ActiveX controls are not supported.". Knowing that the control didn't suddenly turn windowless we dug deeper.

It turned out that the problem appeared with .NET Framework 2.0 Service Pack 1. Apparently it caused the C# compiler in Visual Studio 2005 and later to set the NXCOMPAT bit for all build targets without an option to turn this new behavior off. For those who don't know, this means that DEP (data execution prevention) will kick in unless it is turned off completely in the operating system. This wouldn't be a big deal unless ATL before Visual Studio 2005 didn't have a bug which caused the heap allocated memory not to be flagged as executable, which under the new circumstances results as the already mentioned exception. Windows XP has DEP turned off by default therefore everything still works but in Windows Vista it is turned on and prevents such application from functioning properly.

The best solution would of course be to recompile the ActiveX controls in Visual Studio 2005 or later but this might not be possible if they are supplied by a third party. In this case the most obvious approach to dealing with the situation is to disable DEP in Vista. There is a Data Execution Prevention tab in the Performance Options which open when you click the Settings button in the Performance frame of the Advanced tab in the System Properties dialog but it only allows switching between DEP for all processes with defined exceptions and DEP for essential Windows programs and services, i.e. executables flagged with the NXCOMPAT bit. The only way to turn DEP completely off is executing the following command with administrative privileges:

bcdedit.exe /set {current} nx AlwaysOff

After restart DEP will be turned off and problematic binaries will work once again. To restore the previous (default) state replace AlwaysOff with OptIn. The AlwaysOn option enables DEP for all processes and might cause additional problems (e.g. Google Calendar Sync in its current version 0.9.3.2 doesn't work in this mode).

Unfortunately, this solution would require all your Vista using customers to disable DEP as well which really isn't an option for commercial software. Fortunately, there is another solution. Although there is no compiler option to turn keep the NXCOMPAT bit unset, you can still do this after compilation using the editbin.exe which comes with C++ compiler for Visual Studio 2005 and later:

editbin.exe /NXCOMPAT:NO <filename.exe>

This command removes the NXCOMPAT bit and restores the behavior before .NET 2.0 SP1. If your assembly was signed it also invalidates the signature so you'll have to resign it:

sn.exe -R <filename.exe> <keyfile.snk>

You can automate this by putting the two commands in the Post-build event command line for the project:

editbin.exe /NXCOMPAT:NO "$(TargetPath)"
sn.exe -R "$(TargetPath)" "$(ProjectDir)<keyfile.snk>"

You might need to call vcvars32.bat before that to put the required executables in path and enable editbin.exe dependencies to be resolved. Note that in a completely automated build scenario using MSBuild you'll have to specify full path for the vcvars32.bat because $(DevEnvDir) resolves to *Undefined* outside Visual Studio 2005. Also your strong name key should be in a snk file instead of a password protected pfx file because sn.exe doesn't allow the password to be read from a redirected standard input.

Tuesday, April 29, 2008 3:29:08 PM (Central European Daylight Time, UTC+02:00)  #    Comments [2] - Trackback
Development | .NET | Vista
# Monday, April 14, 2008

The MonthCalendar control's BoldedDates functionality doesn't appear to work properly on Windows Vista. The dates added to any of the BoldedDates, MonthlyBoldedDates and AnnuallyBoldedDates collections are rendered just the same as those not added to any of the collections. The same code works just fine on Windows XP and causes those dates to be rendered bold. The only workaround i've managed to find is disabling visual styles in the application, i.e. commenting out the first line in the Program.Main() method of a new Windows Application:

Application.EnableVisualStyles();

Monday, April 14, 2008 9:54:58 PM (Central European Daylight Time, UTC+02:00)  #    Comments [0] - Trackback
Development | .NET | Vista
# Saturday, November 24, 2007

In my opinion RSACryptoServiceProvider class is seriously under-documented in MSDN. Since there is also no abundance of examples on the web, I spent more time than I should figuring out how to use it correctly. For future reference I'm listing below the solution to two problems I had.

The maximum byte array length for encrypting without OAEP padding is Modulus size - 11 which is written somewhere in the Encrypt() method documentation. If you pass it a larger array it will return a not so informative Unspecified error. To encrypt a larger chunk of data you have to split it in smaller parts, encrypt them individually and concatenate them back together. You have to do the same when decrypting the data, with the only difference that each part has the size of Modulus in stead of Modulus - 11. To get the modulus size you can use the following piece of code (rsa is an instance of RSACryptoServiceProvider):

RSAParameters rsaParams = rsa.ExportParameters(false);
int modulusSize = rsaParams.Modulus.Length;

Each time you instantiate RSACryptoServiceProvider it generates a new pair of keys. If you want to use existing ones, you can import them by calling:

rsa.FromXmlString(key);

The key parameter is a string with the XML representation of the keys. You can get it by calling the ToXmlString() method once and storing its results. It's only parameter specifies whether to also export the private key. I guess I don't have to remind you that you need the private key only for decryption and that you should always keep it private for the encryption to make any sense at all.

Saturday, November 24, 2007 5:31:53 PM (Central European Standard Time, UTC+01:00)  #    Comments [0] - Trackback
Development | .NET

Is the code below correct? Will inputString and outputString be equal?

string inputString = "The text to compress and decompress";
byte[] inputArray = Encoding.UTF8.GetBytes(inputString);

MemoryStream stream = new MemoryStream();
DeflateStream compressionStream =
    new DeflateStream(stream, CompressionMode.Compress);
compressionStream.Write(inputArray, 0, inputArray.Length);
compressionStream.Flush();

stream.Position = 0;

DeflateStream decompressionStream =
    new DeflateStream(stream, CompressionMode.Decompress);
byte[] outputArray = new byte[inputArray.Length];
decompressionStream.Read(outputArray, 0, outputArray.Length);
string outputString = Encoding.UTF8.GetString(outputArray);

Console.WriteLine(outputString == inputString);
Console.ReadLine();

As it turns out, they won't. The reason for it being that compressionStream.Close() was not called before reading from stream started. Calling compressionStream.Flush() is not enough in this case. I haven't managed to find this documented anywhere but the example in the DeflateStream documentation does it correctly. You can find the fixed code below. Notice the additional last parameter in the first call to the DeflateStream constructor. Without it stream will also be closed when compressionStream gets closed.

string inputString = "The text to compress and decompress";
byte[] inputArray = Encoding.UTF8.GetBytes(inputString);

MemoryStream stream = new MemoryStream();
DeflateStream compressionStream =
    new DeflateStream(stream, CompressionMode.Compress, true);
compressionStream.Write(inputArray, 0, inputArray.Length);
compressionStream.Close();

stream.Position = 0;

DeflateStream decompressionStream =
    new DeflateStream(stream, CompressionMode.Decompress);
byte[] outputArray = new byte[inputArray.Length];
decompressionStream.Read(outputArray, 0, outputArray.Length);
string outputString = Encoding.UTF8.GetString(outputArray);

Console.WriteLine(outputString == inputString);
Console.ReadLine();

Thanks once again to my coworker for suggesting this when I was already running out of ideas.

Saturday, November 24, 2007 4:44:37 PM (Central European Standard Time, UTC+01:00)  #    Comments [0] - Trackback
Development | .NET
# Tuesday, July 24, 2007

Once you start putting CruiseControl.NET to production use you'll sooner or later encounter the need for custom build tasks. There's only a limited set of them in the package and Executable Task can only do so much. Unfortunately there is not much information available on development of custom tasks. Your best sources will be:

Apart from that I feel obliged to mention a few of the most important points I've come across during the development of a few custom tasks:

  • ThoughtWorks.CruiseControl.Core.Util.ProcessExecutor is a nice little wrapper around System.Diagnostics.Process class you'll end up using quite a lot.
  • You can add your own information to the build log by calling AddTaskResult on the IIntegrationResult instance passed to your ITask.Run method. There are two overloads available: one accepting a System.String and another one accepting ITaskResult to which you can pass a new FileTaskResult instance to quickly include a complete file.
  • If you're doing any checkins to your source control system as a part of the build you should call the MarkStartTime method of your IIntegrationResult instance afterwards to prevent triggering another build of the same project by setting the last build start time after the last checkin time.
  • Make sure you use a unique ReflectorType name for your task. The service will just silently fail to start in case of a duplicate value.

This information should make your first attempts at making your own custom task a little easier.

Tuesday, July 24, 2007 1:57:26 PM (Central European Daylight Time, UTC+02:00)  #    Comments [0] - Trackback
Development | .NET
# Sunday, July 22, 2007

The 1.3.0.2918 build of CruiseControl.NET has an error in msbuild.xsl file which causes an XslLoadException to be thrown when trying to view the MSBuild output in the web dashboard. One of the users was nice enough to describe the changes to the file necessary to fix the problem. Unfortunately even the latest version of the file on the CruiseControl.NET Live site doesn't include the changes therefore I'm attaching the file to this post as convenience.

Sunday, July 22, 2007 1:24:07 PM (Central European Daylight Time, UTC+02:00)  #    Comments [0] - Trackback
Development | .NET | Downloads | Sources
msbuild.zip (1.33 KB)
# Saturday, June 02, 2007

If you need cheap and simple OCR functionality Microsoft Office Document Imaging Type Library (MODI) is a nice option if its requirements (Microsoft Office 2003 or later) and limitations (limited language support) don't bother you. Here is a simple C# function that does OCR on the image with the specified path:

static string OCR(string path)
{
    MODI.Document doc = new MODI.Document();
    doc.Create(path);
    doc.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, false, false);
    string result = ((MODI.Image)doc.Images[0]).Layout.Text;
    System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
    return result;
}

However, there is another Microsoft Office object model related problem. For Office 2003 users to be able to use your application, the MODI 11.0 (2003 version) must be referenced in the project and the release version of the application must be compiled on a machine with Office 2003 installed. In such a case VB6 still managed to compile the project on a machine with a newer version of Office installed, since the newer version of the type library was automatically used (MODI 12.0 for Office 2007 in this case). On the other hand strong type checking at compile time prevents that in C#.

If you want to keep using Office 2007 and be able to compile such a project, the only solution is to install Microsoft Office Document Imaging as the only component of Office 2003 along the existing Office 2007 installation. Unfortunately this overwrites the Microsoft Office Document Image Writer printer driver from 2007 with the older version, therefore you'll have to start a lengthy process of repairing the Office 2007 installation afterwards. And don't forget to apply all the service packs and updates for Office 2003 before that since this will also overwrite the printer driver and you'll have to repair Office 2007 once again. I learned that the hard way.

Saturday, June 02, 2007 10:39:34 AM (Central European Daylight Time, UTC+02:00)  #    Comments [4] - Trackback
Development | .NET
# Monday, December 25, 2006
I’ve recently passed the MCP exam 70-536: TS: Microsoft .NET Framework 2.0 – Application Development Foundation. My overall experience has been very positive. Although there are a few not so relevant topics I think that most of them are a must-know if you’re a .NET developer. I found the exam quite easy with only a few really nitpicking questions. Maybe I was just lucky but it was a pleasant surprise for me.

I used the Microsoft Self-Paced Training Kit as the study guide. In spite of the mistakes it contains (see errata) I still find it a useful overview of the topics covered by the exam. I even think of it as a great overview of .NET framework for every developer even if he’s not considering taking the exam. On the other hand it really shouldn’t be your only resource, more of a starting point to direct you to the topics you realize you don’t know enough about. MSDN or a more specialized book can help you from there on.

If you’re interested, I’m selling my own copy of the book at a reduced price. It is in mint condition, I’ve even left the 15% off voucher unused. On a side note: here you can always see the list of items I am selling. The link is listed among my other sites in the left column of this page.

Monday, December 25, 2006 9:49:24 AM (Central European Standard Time, UTC+01:00)  #    Comments [3] - Trackback
Development | .NET | Personal | Education
Page 1 of 3 in the Development|.NET category Next Page
Sponsored Ads

About Me

Microsoft Certified Professional

Microsoft Certified Professional

View Damir Arh's profile on LinkedIn

Profile for ExAmigan

ExAmigan

Twitter
I finished the redesign of http://www.damirscorner.com - now it's time to write some new content. 10 days ago
Firebug is great. It helped me solve a CSS problem within minutes. http://getfirebug.com/ 10 days ago
Enjoyed watching Coraline. Would love to get my hands on a scottish terrier puppet from the movie. http://digs.by/1ZsY 10 days ago
@DanijelMalik I guess it depends on the project you are deleting. 12 days ago
How to add static pages in DasBlog http://digs.by/1UwM 13 days ago
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

All Content © 2010, Damir Arh, M. Sc. Send mail to the author(s) - Privacy Policy - Sign In
Based on DasBlog theme 'Business' created by Christoph De Baene (delarou)