Tag Archives: C#

Multithreading in .NET 4.0

.NET 4.5 has way more multhreading and asynch features than 4.0.
Unfortunately I was stuck with 4.0 and had to create simple multithreading solution for one of project modules.
It appeared it was really simple to use:

int param1 = 10;
var task = Task.Factory.StartNew(() => CallSomeMethod(param1));

That’s it!

Unity – The type Interface does not have an accessible constructor

Had a constructor accepting string parameter

public CustomerRepo(string dbContext)
{
	if (dbContext == "AWContext")
	{
		_context = new AWContext();
	}
	else
	{
		throw new ArgumentException("Invalid dbContext name");
	}
}

registered following instructions from MSDN

container.RegisterType<ICustomerRepo, CustomerRepo>(
    "test", 
    new InjectionConstructor("AWContext")
);

The “test” is just a name of current mapping. But it didn’t work until I completely removed it(!):

container.RegisterType<ICustomerRepo, CustomerRepo>(
    new InjectionConstructor("AWContext")
);

C# String was not recognized as a valid DateTime

Sometimes while testing someones code, I am getting such exception. Last thing what I want to do is to is fix it 🙂
For example:

// ...
var p = new List<Person>()
{
    new Person() { FirstName="John", LastName="Koenig",
	StartDate = DateTime.Parse("10/17/1975"), Rating=6 },
// ...

This date format, looks like US one, would not work if your current Culture is, say, Canadian.
Just override system setting by adding following line before the code. (If you have different time
format, adjust CultureInfo setting accordingly of course)

// ...
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
// ...

ASP.NET C# Send email in background thread

System.Threading.Thread thread = new System.Threading.Thread(delegate()
{
    SMTPSend(message);
});

thread.IsBackground = true;
thread.Start();

private static void SMTPSend(MailMessage message)
{
    try
        {
            SmtpClient smtp = new SmtpClient();
            ...

On the presentation layer you do not need any AJAX or JavaScript calling code from the backend
Just plain ASP.NET button

<asp:Button ID="btnSend" runat="server" Text="Send Email" onclick="btnSend_Click" />

Code behind

protected void btnSend_Click(object sender, EventArgs e)
{
    try
    {
        Notifications.Send(email);
    }
    catch (Exception ex)
    {
        litResult.Text = ex.ToString();
    }
}

AWS EC2 – Get running instances only

AWS SDK has Console Sample project where you can see code populating number of your running Instances.

DescribeInstancesResponse ec2Response = ec2.DescribeInstances(request);
int numInstances = 0;
numInstances = ec2Response.Reservations.Count;
Console.WriteLine("You have " + numInstances + " Amazon EC2 instance(s) running.");

What you actually get is number of all your Instances, no matter if they are running or not.
If you want to get only running ones, query Reservations collection filtering by their State

DescribeInstancesRequest instanceRequest = new DescribeInstancesRequest();
List<Reservation> reservations = ec2.DescribeInstances(instanceRequest).Reservations;
List<Instance> runningInstances = reservations.Where(r => r.Instances.Any(i => i.State.Name == "running")).Select(r => r.Instances[0]).ToList();
numInstances = runningInstances.Count;

C# check if a string contains an element from a collection

List of strings

if(listOfStrings.Any(s => myString.IndexOf(s, StringComparison.OrdinalIgnoreCase) >= 0))
{
    result = listOfStrings[myString];
}

Dictionary, accessing string as a Key

if(dictionaryOfStrings.Keys.Any(c => myString.IndexOf(c, StringComparison.OrdinalIgnoreCase) > 0))
{
    result = dictionaryOfStrings[myString];
}

Dictionary, accessing string as a Value

if(dictionaryOfStrings.Values.Any(c => myString.IndexOf(c, StringComparison.OrdinalIgnoreCase) > 0))
{
    foreach (KeyValuePair<string, string> pair in dictionaryOfStrings)
    {
        if (myString.Equals(pair.Value))
        {
            result = pair.Key;
        } 
    }
}

C# simple email and phone validation using Regular Expressions

	string emailRegex = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|ca|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)\b";
	string phoneRegex = @"^\d{10}$";

	Match phoneMatch = Regex.Match(phone, phoneRegex);
	Match emailMatch = Regex.Match(email, emailRegex);
	
	if (!emailMatch.Success)
	{
		yield return new ValidationResult("Email is invalid", new[] { "ContactEmail" });
	}