C# ExceptBy() extension method.

The following extension method is used to compare values from two list and it returns entities from the first list which is not present in the second list based on the key that is passed to it.

public static IEnumerable<T> ExceptBy<T, TKey>(this IEnumerable<T> items, IEnumerable<T> other,  Func<T, TKey> getKey)
{
    return from item in items
           join otherItem in other on getKey(item)
           equals getKey(otherItem) into tempItems
           from temp in tempItems.DefaultIfEmpty()
           where ReferenceEquals(null, temp) || temp.Equals(default(T))
           select item;

}

HTTP Error 500.50 – URL Rewrite Module Error. The server variable is not allowed to be set.

I recently got this error when updating my rewrite rules in my system.webServer node of my web.config. The error message stated “HTTP Error 500.50 – URL Rewrite Module Error. The server variable “SERVER_PORT” is not allowed to be set. Add the server variable name to the allowed server variable list.”

Here is how you add a server variable using IIS

STEP 1 :

In your IIS with your website selected, select URL Rewrite option step1

STEP 2

Next select the View Server Variable option step2

STEP 3

Add server variable as shown below step3

Alternately you could also add through your web.config like below under <system.webServer></system.webServer> node.

<allowedServerVariables xdt:Transform="Insert">
    <add name="SERVER_PORT" />
    <add name="REMOTE_ADDR" />
</allowedServerVariables>

Reading from a file hosted on a server using C#

This post describes how to read a file which is hosted on server i.e on some url.

Let’s say I have a .txt file hosted here – www.yassershaikh.com/salary.txt I want my code to read from this hosted file. Below is how you do it using WebClient class.

var urlToReadFrom = "http://www.yassershaikh.com/salary.txt"
using(var client = new WebClient()) {
    string s = client.DownloadString(urlToReadFrom);
    return s;
}

Hope this helps.

Convert a List of items to an XElement in C#

I have always used XElement.Parse() and StringBuilder to create an XElement of a required type. Today I came across this post on some blog and then this thread on stackoverflow which show how to do the same in a more efficient manner. Sharing it here hope this helps.

Requirement 1:

<students>
    <student>1</student>
    <student>2</student>
    <student>3</student>
    <student>4</student>
    <student>5</student>
</students>

Code:

List <int> numbers = new List <int> () {
    1, 2, 3, 4, 5
};
XElement element = new XElement("students", numbers.Select(i = > new XElement("student", i)));

Requirement 2:

<students>
    <student number="1"></student>
    <student number="2"></student>
    <student number="3"></student>
    <student number="4"></student>
    <student number="5"></student>
</students>

C# Code:

List <int> numbers = new List <int> () {
    1, 2, 3, 4, 5
};
var xelement = new XElement("students");
foreach(var item in numbers) {
    xelement.Add(new XElement("student", new XAttribute("number", item)));
}

Serialize a List of Object to JSON in C#

This can be easily be done using Json.NET. Json.NET is a popular high-performance JSON framework for .NET.

First of all, you will need to download the latest binary from here and include it your project.

using Newtonsoft.Json;

Rest of the code is pretty self explanatory…

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

var employees = new List<Employee>
{
    new Employee {FirstName = "Yasser", LastName = "Shaikh", Age = 26},
    new Employee {FirstName = "Mohsin", LastName = "Shaikh", Age = 22},
    new Employee {FirstName = "Riaz", LastName = "Shaikh", Age = 50}
};

var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(employees);

How to add additional fields when using Membership in ASP.NET MVC 4

1. Modify your UserProfile class

Here in this example I am adding a new field called “MobileNumber“, have declared it as type string.

[Table("UserProfiles")]
public class UserProfiles
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set;}
    public string Email { get; set;}
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MobileNumber { get; set; }
}

2. Add the additional property(ies) to your RegisterModel.cs

Add the new property in your Model. In this example where we want an extra field while user registration we need to update the RegisterModel class. Add validations if need be.

public class RegisterModel
{
    [Required]
    [Display(Name = "Email")]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 2)]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 2)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [Required]
    [StringLength(11, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 11)]
    [Display(Name = "Mobile No.")]
    public string MobileNumber { get; set; }

}   

3. Display additional fields on your View

Once you have update the Model you should be able to use the @Html.TextBoxFor(m => m.MobileNumber) in your view, which will bind the MobileNumber field to your ‘MobileNumber’ property declared in your model.

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

    @Html.LabelFor(m = m.Email)
    @Html.TextBoxFor(m => m.Email)

    @Html.LabelFor(m => m.Password)
    @Html.PasswordFor(m => m.Password)

    @Html.LabelFor(m => m.FirstName)
    @Html.TextBoxFor(m => m.FirstName)

    @Html.LabelFor(m => m.LastName)
    @Html.TextBoxFor(m => m.LastName)

    @Html.LabelFor(m => m.MobileNumber)
    @Html.TextBoxFor(m => m.MobileNumber)

    <input type="submit" value="Register">
}

4. Update your Controller – (AccountController in this case)

Last step, here you just need to read the value posted to your model and pass it along the repository for saving.

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
    if (ModelState.IsValid)
    {
        // Attempt to register the user
        try
        {
            WebSecurity.CreateUserAndAccount(model.Email, model.Password,
                                             new
                                                 {
                                                     FirstName = model.FirstName,
                                                     LastName = model.LastName,
                                                     MobileNumber = model.MobileNumber
                                                 });
            WebSecurity.Login(model.Email, model.Password);
            return RedirectToAction("Index", "Home");
        }
        catch (MembershipCreateUserException e)
        {
            ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

How to use distinct() method on property of a class in C#

Distinct() is used to remove all duplicate items from a list or a collection. To use this method on a property of a class, below is an extension method which you could use :

public static class MoreLinq 
{
    public static IEnumerable<T> DistinctByProperty<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property)
    {
        return items.GroupBy(property).Select(x => x.First());
    }

    // more such extensions can go in here...
}

Above I have created an extension method called “DistinctByProperty”, now you can use this property like as shown below…

var distinctEmails = customers.DistinctByProperty(x => x.EmailAddress);

References

Introduction to RabbitMQ with C# .NET, ASP.NET and ASP.NET MVC with examples

This post assumes that you already have installed and configured RabbitMq on your system or on some server. Download .NET/C# RabbitMq’s client library from http://www.rabbitmq.com/dotnet.html or from rabbitmq-dotnet-client-3.1.4-dotnet-3.0.zip

If RabbitMq has been installed on your server, you can view the management screen using this url : http://server-name:15672/, more on this you will find on this link.

Incase you havent read about what RabbitMq is and how it works I strongly recommend you to read the following links first and then come back again to this post.

Lets get started, first you’ll need to import the libraries(dll) u just downloaded.

RabbitMq-AddReferences

You can use the following class I have created, modify them to suit your requirement. Instead of hard-coding the Username, Password and other fields its better you define them in your config file and read from there.

public static class BrokerHelper
{
    public static string Username = "guest";
    public static string Password = "guest";
    public static string VirtualHost = "/";
    // "localhost" if rabbitMq is installed on the same server,
    // else enter the ip address of the server where it is installed.
    public static string HostName = "localhost";
    public static string ExchangeName = "test-exchange";
    public static string ExchangeTypeVal = ExchangeType.Direct;
    public static string QueueName = "SomeQueue";
    public static bool QueueExclusive = false;
    public static bool QueueDurable = false;
    public static bool QueueDelete = false;
    public static string RoutingKey = "yasser";

    public static IConnection Connection;
    public static IModel Channel;
    public static void Connect()
    {
        var factory = new ConnectionFactory();
        factory.UserName = Username;
        factory.Password = Password;
        factory.VirtualHost = VirtualHost;
        factory.Protocol = Protocols.FromEnvironment();
        factory.HostName = HostName;
        factory.Port = AmqpTcpEndpoint.UseDefaultPort;
        Connection = factory.CreateConnection();
        Channel = Connection.CreateModel();
    }

    public static void Disconnect()
    {
        Connection.Close(200, "Goodbye");
    }

    public static bool IsBrokerDisconnected()
    {
        if(Connection == null) return true;
        if(Connection.IsOpen) return false;
        return true;
    }

    public static void Publish(string message)
    {
        if (IsBrokerDisconnected()) Connect();

        Channel.ExchangeDeclare(ExchangeName, ExchangeTypeVal.ToString());
        Channel.QueueDeclare(QueueName, QueueDurable, QueueExclusive, QueueDelete, null);
        Channel.QueueBind(QueueName, ExchangeName, RoutingKey);
        var encodedMessage = Encoding.ASCII.GetBytes(message);
        Channel.BasicPublish(ExchangeName, RoutingKey, null, encodedMessage);
        Disconnect();
    }
}

Almost Done ! Now that we have the above classes in place, publishing our message to rabbitMq will just be the following line of code :

BrokerHelper.Publish("Hello World");

Hope this helped.

References:

How to setup Elmah.MVC with ASP.NET MVC 4 ?

What is Elmah ? ELMAH is an open source project whose purpose is to log and report unhandled exceptions in ASP.NET web applications.

Why to use Elmah ? ELMAH serves as an unobtrusive interceptor of unhandled ASP.NET exceptions, those usually manifesting with the ASP.NET yellow screen of death.

So now we know what and why to use Elmah, Lets quickly get started on how to use Elmah with your ASP.NET MVC project.

Step 1: Right click on your solution and select the “Manage Nuget Packages” option Elmah - Step 1 - Manage Nuget Packages

Step 2: In the Nuget Package manager search for “Elmah” and install the Elmah.MVC nuget extension.Step 2 - Elmah - Elmah mvc nuget search The Nuget Package manager will download and add the required dlls and modify the web.config’s <appSetting> for Elmah to work. Step 2 - Elmah - Elmah mvc nuget web config

Step 3: That’s it !! Your Elmah is now ready to test. I have generated a 404 to test if my Elmah works, ELMAH can be accessed by this url : http://yourapp.com/elmah. Elmah - Output Screen 0Elmah - Output Screen 1

Hope this helps :)

Further Reading :

How to set SmtpClient properties using web.config

SmtpClient Class allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP). Instead of assigning properties of this class in C# , we can use the <system.net> element in the web.config as shown below :

<system.net>
    <mailSettings>
        <smtp from = "email@abc.com">
            <network 
                host = "mail.abc.com"
                port = "25"
                password = "password"
                userName = "email@abc.com"
                defaultCredentials = "false"
                enableSsl = "true"
             />
         </smtp>
     </mailSettings>
 </system.net>

The advantage of this approach is that we can change the mail settings without having to rebuild the entire application.

Hope this helps :)

Further Reading :
Sending Email with System.Net.Mail