Saturday, February 15, 2014

Using WURFL Cloud Client with an ASP.NET Web Application

Isn’t it great if you can detect the capabilities of incoming mobile website visitors, including capabilities such as whether the device is being used to access the site is a mobile/smartphone/tablet, device/model, resolution etc. With the WURFL Cloud, you can do them all. The WURFL Cloud Client is your interface to the WURFL Device Description Repository (The Device Description Repository (DDR) is a concept proposed by the Mobile Web Initiative Device Description Working Group (DDWG) of the World Wide Web Consortium.) which contains detailed definitions for thousands of mobile devices.

WURFL Cloud Client can be used with C#.NET, Java, PHP, Python, Ruby, Node.js and Perl. In this post let’s see how we can use WURFL Cloud Client with C# using an ASP.NET Web application.

First what you have to do is create an account with WURFL Cloud. There are different plans to select from such as Free, Basic, Standard and Premium. Higher the plan is, the more capabilities you get.

Here I have created a free account and after completing the necessary steps, I am in my account now. Here in the capabilities tab, you can see the capabilities which is enabled to your account.
Picture0
My Account
Picture2
Capabilities
Since it is the Free plan, I have been given with limited capabilities.

Now let’s start with creating a ASP.NET Web Application. I am going to create an empty Web Application and I will be adding a Web Form to the page. Now I need to add reference to “ScientiaMobile.WurflCloud.dll” which you can download once you have created your account.

Now Inside the page, I will have several labels to show all the capabilities for the free plan which are model_name, brand_name, is_smartphone, is_tablet and is_wireless_device.

I have the following class which will contain some properties of devices.
public class MyDeviceInfo
{
    public String UserAgent { get; set; }
    public String ServerVersion { get; set; }
    public String Library { get; set; }
    public String DeviceId { get; set; }
    public String DateOfRequest { get; set; }
    public ResponseType Source { get; set; }
    public IDictionary<String, String> Capabilities { get; set; }
    public IDictionary<String, String> Errors { get; set; }
}
Then I have another class which contains a method to get device information. Here I will need to mention the ApiKey, you can find it in your account.
Picture1
ApiKey
public class MyWurflClient
{
    public MyDeviceInfo GetDataByRequest(HttpContextBase context)
    {
        var config = new DefaultCloudClientConfig
        {
            // Your ApiKey
            ApiKey = "ApiKey"
        };
 
        var manager = new CloudClientManager(config);
 
        var info = manager.GetDeviceInfo(context, new[] 
        {   
            "model_name",
            "brand_name", 
            "is_smartphone", 
            "is_tablet", 
            "is_wireless_device" 
        });
 
        var model = new MyDeviceInfo
        {
            DeviceId = info.Id,
            ServerVersion = info.ServerVersion,
            DateOfRequest = info.WurflLastUpdate.ToString(),
            Library = manager.GetClientVersion(),
            Capabilities = info.Capabilities,
            Errors = info.Errors,
            Source = info.ResponseOrigin
        };
 
        return model;
    }
}
Now in the page load event, I am calling the above method and showing the results in the labels.
protected void Page_Load(object sender, EventArgs e)
{
    MyWurflClient client = new MyWurflClient();
    MyDeviceInfo deviceInfo = client.GetDataByRequest(new HttpContextWrapper(HttpContext.Current));
 
    Label1.Text = "model_name : " + deviceInfo.Capabilities.First(c => c.Key == "model_name").Value;
    Label2.Text = "brand_name : " + deviceInfo.Capabilities.First(c => c.Key == "brand_name").Value;
    Label3.Text = "is_smartphone : " + deviceInfo.Capabilities.First(c => c.Key == "is_smartphone").Value;
    Label4.Text = "is_tablet : " + deviceInfo.Capabilities.First(c => c.Key == "is_tablet").Value;
    Label5.Text = "is_wireless_device : " + deviceInfo.Capabilities.First(c => c.Key == "is_wireless_device").Value;
}
Now after publishing the site, I am accessing the site from my PC.
Picture1
From PC
Now when I accessed it from my phone,
wp_ss_20140213_0002
From Phone
I have uploaded the sample to my SkyDrive. Enjoy!


Happy Coding.

Regards,
Jaliya

Thursday, February 13, 2014

Use of “Enumerable.Cast” and “Enumerable.OfType” in C#

There are situations where you have a collection that doesn’t support LINQ and you want to run some LINQ queries against a particular object or set of objects inside your  collection. Enumerable.Cast<TResult> and  Enumerable.OfType<TResult> Methods are real life savers in such scenarios In this post let’s see how we can use Enumerable.Cast<TResult> and  Enumerable.OfType<TResult> to make use of LINQ on a collection which doesn't support LINQ.

Let’s go by an example. I have created a console application. There I have the following class “Employee”.
public class Employee
{
    public int EmployeeId { get; set; }
    public string FullName { get; set; }
}
Then I have a ArrayList called oArrayList which will contain set of Employee objects. As you might already know ArrayList is a non-generic IEnumerable collection where you can store almost anything.
ArrayList oArrayList = new ArrayList()
{
    new Employee()
    {
        EmployeeId=1,FullName="Jaliya Udagedara"
    },
    new Employee()
    {
        EmployeeId=2,FullName="Martin Smith"
    }
};
Now let’s say I want to write a LINQ query against my ArrayList to find all the Employees where his/her FirstName starts with the letter “J”. Now let’s consider the following LINQ query.
var query = from e in oArrayList
            where e.FullName.StartsWith("J")
            select e;
This won’t even compile, I am getting the following error.  “Could not find an implementation of the query pattern for source type System.Collections.ArrayList.  Where not found.  Consider explicitly specifying the type of the range variable e”. That’s because of the following reason. ArrayList is a non-generic collection which implements IEnumerable and you don’t know the types of the elements which are in the ArrayList. So when you are writing a LINQ query and when you can't access types' properties, because you don't know what it is.

For that I can write the following LINQ query using query syntax.
var query = from Employee e in oArrayList
            where e.FullName.StartsWith("J")
            select e;
Here I have explicitly declared the type of the range variable (Employee is the type of range variable e) to reflect the specific type of the objects in my ArrayList. Here I have put the type as Employee, that's because I know by heart there can only be Employee objects in my ArrayList. If there were some other types other than the Employee, I will definitely be getting an exception of type InvalidCastException at the run time.

When I put the type of the range variable, it is equal as calling the Enumerable.Cast<TResult>.

Enumerable.Cast<TResult> Method

What Enumerable.Cast<TResult> does is, it casts the elements of an IEnumerable to the type specified in TResult. If an element cannot be cast to type TResult, this method will throw an InvalidCastException.

So if I write the following LINQ query, it would be same as the above query with explicitly declaring the type of the range variable.

Query Syntax
var query = from e in oArrayList.Cast<Employee>()
            where e.FullName.StartsWith("J")
            select e;
Method Syntax
var query = oArrayList.Cast<Employee>()
                .Where(e => e.FullName.StartsWith("J"));
Now if we want to filter out the objects that can be cast to type specified in TResult, we need to use Enumerable.OfType<TResult>.

Enumerable.OfType<TResult> Method

Enumerable.OfType<TResult> Method filters the elements of an IEnumerable based on a type specified in TResult.

Now let’s consider the following ArrayList which consists of two strings, two integers, three Lists of type string and two objects of type “Employee”.
ArrayList oArrayList = new ArrayList()
{
    "Jaliya",
    "Smith",
    10,
    20,
    new List<string>() { "VS", "SQL" },
    new List<string>() { "VS", "Windows Azure" },
    new List<string>() { "Apple", "Orange" },
    new Employee()
    {
        EmployeeId=1,FullName="Jaliya Udagedara"
    },
    new Employee()
    {
        EmployeeId=2,FullName="Martin Smith"
    }
};
Now let’s say I want to filter out the elements  in my ArrayList using Enumerable.OfType<TResult>  method when TResult is of following types. I am putting some conditions on my queries and I don’t think I should be describing them all. Here I will be writing the LINQ queries in both syntaxs (Query and Method Syntax).

TResult is String

Query Syntax
IEnumerable<string> query = from s in oArrayList.OfType<string>()
                            where s.StartsWith("J")
                            select s;
Method Syntax
IEnumerable<string> query = oArrayList.OfType<string>()
                                .Where(s => s.StartsWith("J"));

TResult is List<string>

Query Syntax
IEnumerable<List<string>> query = from l in oArrayList.OfType<List<string>>()
                                  where l.Contains("VS")
                                  select l;

Method Syntax
IEnumerable<List<string>> query = oArrayList.OfType<List<string>>().
                                        Where(l => l.Contains("VS"));

TResult is Employee

Query Syntax
IEnumerable<Employee> query = from e in oArrayList.OfType<Employee>()
                              where e.FullName.StartsWith("J")
                              select e;

Method Syntax
IEnumerable<Employee> query = oArrayList.OfType<Employee>()
                                .Where(e => e.FullName.StartsWith("J"));

Hope you all got a good understanding on  Enumerable.Cast<TResult> Method and  Enumerable.OfType<TResult> Method.

I am uploading the full sample code to my SkyDrive, enjoy.


Happy Coding.

Regards,
Jaliya

Tuesday, February 11, 2014

What is Microsoft® “Roslyn”

By tradition compiler is a “black box”. We are pushing the source code in one end and assemblies are coming out at the other end. Something happens in between which we are not aware of. And I am sure most of you would agree, we didn’t even want to know what’s happening inside. With “Roslyn”, Microsoft is letting us not only know what is happening inside the compiler, they are letting us to use the compiler through a set of APIs.

Microsoft Unveils its Compiler as a Service technology via project “Roslyn”. “Roslyn” exposes C# and Visual Basic compilers as a set of APIs. So with “Roslyn”, compilers become services.

The “Roslyn” is currently available as a Community Technology Preview (CTP). Microsoft released the first CTP of the “Roslyn” Project back in October, 2011. That particular CTP installs on Visual Studio 2010 SP1 and it requires the Visual Studio 2010 SP1 SDK. The current latest version is Microsoft “Roslyn” September 2012 CTP installs as an extension to Visual Studio 2012 (Please note that Visual Studio 2010 is no longer supported by this CTP). When you have installed Microsoft “Roslyn” September 2012 CTP, insider Visual Studio 2012 when you click on New Project, you can see a new project template type “Roslyn”.

Microsoft "Roslyn" Project Templates
The Roslyn assemblies are also installed in the GAC. If you create an other project type instead of all above, You can still add references to use “Roslyn”.

Adding References
Not only this. Once you have installed Microsoft Roslyn CTP, you are getting a new window to Visual Studio called “C# Interactive” (If you are wondering whether there is “VB Interactive” Window, NO, there is nothing like that yet). To open the “C# Interactive” window, you don’t even have to create a new project. Just fire off Visual Studio, under View->Other Windows, there you can find “C# Interactive” window.

C# Interactive Window
There you can also see a “F# Interactive” window, but it was not installed with Microsoft Roslyn CTP. It comes with the default Visual Studio Installation. Anyway “C# Interactive” window can be very useful when you want to try out things.

Let’s say I want to check the Ping.Send() Method.

IntelliSense in C# Interactive Window
As you can see in the above picture, IntelliSense is fully supported.

Testing with C# Interactive Window
Learn more on Microsoft “Roslyn”,
   Microsoft® “Roslyn” CTP

Happy Coding.

Regards,
Jaliya

Thursday, February 6, 2014

Emailing an ASP.NET GridView

There are times you want to send an ASP.NET GridView along with data as an Email. Your recipient should receive it with the styles you have applied to the GridView inside your ASP.NET web page. This post is supposed to explain the way to achieve such a task.

First I will be creating an empty ASP.NET web application. I have nothing but a empty Web Form added to the application which I named as “Default”. Now in the code behind of the Web Form, I have following helper method which will return me a DataTable holding some data which I need to be shown in the GridView.
private DataTable GetData()
{
   DataTable dt = new DataTable();
   dt.Columns.AddRange(new DataColumn[2] 
   { 
       new DataColumn("Id"), new DataColumn("FullName")
   });
   dt.Rows.Add(1, "Jaliya Udagedara");
   dt.Rows.Add(2, "John Doe");
   dt.Rows.Add(3, "Jane Doe");
   return dt;
}
There is noting complex in the above method, just creating a DataTable with some columns, filling up some data and then returning the DataTable.

In the Web Form, I have the following design.
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1"
                runat="server" 
                AutoGenerateColumns="false"
                HeaderStyle-BackColor="#3d5bb8" 
                HeaderStyle-ForeColor="White"

                RowStyle-BackColor="#c6c6c6"
                lternatingRowStyle-BackColor="White"
                AlternatingRowStyle-ForeColor="#000">
                <Columns>
                    <asp:BoundField DataField="Id"
                        HeaderText="Id"
                        ItemStyle-Width="80" />
                    <asp:BoundField DataField="FullName"
                        HeaderText="Full Name"
                        ItemStyle-Width="200" />
                </Columns>
            </asp:GridView>
            <br />
            <asp:Button ID="btnSend" 
                runat="server" Text="Send" 
                OnClick="btnSend_Click" />
        </div>
    </form>
</body>
Here there is GridView inside a Form tag, I have applied some styles to keep my GridView look nicer. Now in the Page_Load event of my Web Form, I am binding the GridView to the DataTable which is received from above GetData() method. Now when I run the application, I am getting the following page.

GridView
ASP.NET GridView
Now comes the real requirement. When I click on Send button, an email should be sent with GridView with the styles applied along with the data.

To create the mail message and to send it I have the following method.
private void SendGridViaEmail(string htmlContent)
{
    MailMessage mailMessage = new MailMessage("sender@gmail.com", "receiver@gmail.com")
    {
        Subject = "Email an ASP.NET GridView",
        Body = "Emailed GridView:<hr />" + htmlContent,
        IsBodyHtml = true
    };
 
    SmtpClient smtpClient = new SmtpClient()
    {
        Host = "smtp.gmail.com",
        Port = 587,
        EnableSsl = true,
        Credentials = new NetworkCredential()
        {
            UserName = "sender@gmail.com",
            Password = "senderpassword"
        }
    };
    smtpClient.Send(mailMessage);
}
Above method accepts a string and that particular string will be sent as the body in my MailMessage. And please note here in my MailMessage, I am setting up the property IsBodyHtml to true. That’s because I am planning to retrieve the content of my GridView as a markup characters using the GridView.RenderControl Method. And that particular string will be the body of my MailMessage. After doing that, I am creating a SmtpClient to send the email through Gmail SMTP.

Now in my Send button click I have the following.
protected void btnSend_Click(object sender, EventArgs e)
{
    using (StringWriter stringWriter = new StringWriter())
    {
        using (HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter))
        {
            GridView1.RenderControl(htmlTextWriter);
            SendGridViaEmail(stringWriter.ToString());
        }
    }
}
Here GridView.RenderControl Method (HtmlTextWriter) Outputs server control content to the provided HtmlTextWriter object. StringWriter is required for the HtmlTextWriter to write to. It is a buffer and everything that is written to HtmlTextWriter is written to StringWriter. Then I am passing content in StringWriter to my SendGridViaEmail() method. Here you can either use,
SendGridViaEmail(htmlTextWriter.InnerWriter.ToString());
But HtmlTextWriter.InnerWriter Property will be eventually giving you the reference to underlying writer which is the used StringWriter.

Now when I run the application and click on Send button, I am getting this nice little error message which is “Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server. ”.

GridView
Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
I am sure my control 'GridView1' is placed inside a form tag with runat=server. But the problem is when we render the control using GridView.RenderControl Method, the markup will be rendered without the form tag. You can simple avoid this error by adding the following method. This Page.VerifyRenderingInServerForm Method confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.
public override void VerifyRenderingInServerForm(Control control)
{
   
}
Now when I build and run the application and click on Send button, I am not getting any errors, instead I am getting the desired output, an email sent with styled GirdView along with data.

Email
Resulting Email
Hope this helps. I am uploading the sample to my SkyDrive.


Happy Coding

Regards,
Jaliya