Tag Archive for 'c#'

How to invoke a common coded web test method from GetRequestEnumerator()?

It’s a fact that coded web test methods give more flexibility to the developer, i.e. common code reuse. So let’s create a coded web test in whose GetRequestEnumerator() method you want to call a common method which tests some other requests. Let’s make it look as GetCommonRequests() in the example below:

public class AWebTest : WebTest
{
    private IEnumerator<WebTestRequest> GetCommonRequests()
    {
        WebTestRequest req1 = new WebTestRequest("http://google.com");
        yield return req1;

        WebTestRequest req2 = new WebTestRequest("http://google.com");
        yield return req2;
    }

    public override IEnumerator<WebTestRequest> GetRequestEnumerator()
    {
        WebTestRequest req = new WebTestRequest("http://google.com");
        yield return req;

        GetCommonRequests();
    }
}

You would expect to see three requests in the test result. You will see only one though…

Continue reading ‘How to invoke a common coded web test method from GetRequestEnumerator()?’

How to quickly add logging to a coded web test?

A coded web test, as opposed to a basic web test, brings more flexibility to the developer: conditioning, looping, code re-usage, etc. If you haven’t created one yet, you can follow an instruction on MSDN.

Now, because a coded web test can have some logic inside, it makes sense to add logging so that there’s a trace on what’s going on while it executes.

Continue reading ‘How to quickly add logging to a coded web test?’

Robust generation of XML documentation comments for C#

Writing comments is something you need to get used to; sooner or later you will understand it’s worth writing comments. Haven’t you find yourself in a sitation where you don’t understand what a couple of lines of YOUR OWN code do? I have…

XML documentation comments are also important, particularly for public members/methods. Even if your project doesn’t require generating full XML documentation of the code, using Intellisense can be much more effective if it summarizes the method you are trying to use. If you want to generate XML documentation for C# in the twinkling of an eye you MUST install Roland Weigelt’s GhostDoc plugin for Visual Studio. Let me cite the author:

Continue reading ‘Robust generation of XML documentation comments for C#’

Castle.ActiveRecord.Framework.ActiveRecordException: Could not perform Delete for XXX —> NHibernate.Exceptions.GenericADOException: could not delete collection

The beginning of the stack trace I got today looked as below:

2009-05-19 11:01:45,078 ERROR [5232] XXX - Speaker already deleted: Castle.ActiveRecord.Framework.ActiveRecordException: Could not perform Delete for Speaker ---> NHibernate.Exceptions.GenericADOException: could not delete collection: [XXX#XXX][SQL: SQL not available] ---> System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'SpeakerId', table 'XXX.dbo.lnk_Session_Speaker'; column does not allow nulls. UPDATE fails.
The statement has been terminated.
   ...
   at SpeakerProxy3e9fd3b0e82745c2b91b8a353acaa93d.DeleteAndFlush()

Background

I had three tables and classes representing them: Session / app_Session, Speaker / app_Speaker, and SessionSpeaker / lnk_Session_Speaker.

Continue reading ‘Castle.ActiveRecord.Framework.ActiveRecordException: Could not perform Delete for XXX —> NHibernate.Exceptions.GenericADOException: could not delete collection’

C# 3.0 Pocket Reference: Instant Help for C# 3.0 Programmers

For those who work with C# I’d like to recommend a book which is a kind of summary of knowledge on C# 3.0. The book is quite short (and small by the way – yet pocket reference) but it covers lots of details on C# and describes what’s new in C# 3.0. Everything in short and simple, with code snippets.

I read this book as a first step towards TS: Microsoft .NET Framework – Application Development Foundation. Basically, I’ve started wondering if passing this exam is not a good step in my .NET career and this is the entry point.

Anyway this book is not a C# bible, but it can really help as a knowledge reresher.

Recommended.

Reblog this post [with Zemanta]

C#, decimal.toString(), and how to get rid of trailing zeros

Today I spend A LOT OF time on trying to display a percentage – string representation of a decimal but without trailing zeros, e.g. 15.1% instead of 15.10%.

In the application I already had NumberFormatInfo for displaying monetary values and percentages. An object of that type was defined as follows:

NumberFormatInfo nfi = new NumberFormatInfo();
nfi.PercentDecimalDigits = 2;
// some additional settings for nfi
// (including monetary and numeric attributes)

Continue reading ‘C#, decimal.toString(), and how to get rid of trailing zeros’

System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

One of my applications was supposed to use image having its URL. The Image was instantiated with the stream the server that stored the image file responded with after being requested as below:

// create a request for image
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(IMAGE_URL);
request.Method = "GET";
request.ContentType = "multipart/form-data";
request.UserAgent = "Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0";
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
request.Credentials = CredentialCache.DefaultCredentials;

// get response from the server
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();

// create image from stream
Image image = Image.FromStream(resStream);

It worked like a charm when TCP port was used (regular, non-decure connection) but whenever the image was available at a URL that was secured (https://xxx.xx) I was getting the following stack trace:

Continue reading ‘System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.’

MonoRail – RenderMailMessage – System.ArgumentNullException: Value cannot be null. Parameter name: format

This was a nasty issue…

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentNullException:
Value cannot be null.
Parameter name: format
   at System.String.Format(IFormatProvider provider, String format, Object[] args)
   at System.String.Format(String format, Object arg0, Object arg1)
   --- End of inner exception stack trace ---

Background

This is part of the stack trace I got in one of my applications which uses MonoRail. I got it while creating the Castle.Components.Common.EmailSender.Message in order to prepare the content of the email having the name of its template file (vm):

Message msg = RenderMailMessage(templateName)

That view file defined the content and used data from PropertyBag and from Resource files.

Just to recall a resource file (resx) is bound with the controller class with this definition:

[Resource("text", "LocalizationSample.Resources.Home")]

What was wrong there? I was sure templateName passed as the parameter was correct – it for sure pointed to correct vm file. Moreover, that piece of code was defined in a superclass which was extended by this particular controller and another one which also could send this email. Of course there was no problem with sending email by the latter.

Solution

The problem here was I used this construction in the vm file:

$string.format($text.someText, $param1, $param2)

And for some reason I forgot to bind the appropriate resource file (the one referenced with $text) with one of the controllers. As a result string.format failed because $param1 and $param2 couldn’t be injected into string which was not found.

Summary of Communities to Communities (C2C) 2009 Conference

C2C is a history now. I attended .NET stream and one session on SQL. The conference as a whole was very interesting, well organised, and basically developing. It was a Polish conference so most sessions were conducted in Polish but there were a couple of speakers from abroad too, and they spoke in English.

Basically I’m happy I had a chance to attend the conference. Below are my notes and comments. Please note they are my comments; should I write something which is not true or accurate, please let me know, sometimes pace was fast so I might have skipped something :)
Continue reading ‘Summary of Communities to Communities (C2C) 2009 Conference’

System.IO.IOException: The process cannot access the file used as attachment with MailMessage

Recently I had to improve the mechanism of sending emails so that files can be attached to it. As I used MailMessage it seemed to be an easy task, especially that MSDN provided an example of how to do it. They assumed there that the file used as the attachment was already on the server and it shouldn’t be deleted after the email is sent.

However, I had to upload this file and therefore remove it afterwards. At the end of the day I ended up with an exception thrown while removing the file:

System.IO.IOException: The process cannot access the file 'XXX' because it is being used by another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.File.Delete(String path)

Solution

There’s a simple fix for that. After the email is sent but before the uploaded attachment is deleted use Displose() method of MailMessage. This way you will release all resources used by MailMessage.

Alternatively you can create MaillMessage within using block. As a result all resources will be released (disposed or closed) automatically when execution of the block completes.

using(MailMessage email = new MailMessage(...))
{
}



Switch to our mobile site