Jan 14, 2016

EditorTemplates in MVC

Before today, I just knew the concept of Editor Templates in MVC but had never used them in an application.

So today, I was stuck up with a scenario where there was a registration page containing a common area of the form(which can be used in other places) e.g. address.
My models were structured something similar to what is shown below.




Coming from WebForms background(and not knowing how to use Editor Templates), I created a View for the Register action and a PartialView for the Address section. It was something as shown below.



The Get action method was working fine but the Post action method was not able to fetch me the values from the PartialView. It was just returning null, no matter what I did.


Then, while going through a post, I realised that Editor Templates was just the solution that I was looking for.

So, let's go through how to create Editor Templates in this scenario.

1. Our pain point here is the AddressDetails coming as null. What is it's type?? Address. So, create a file with the name Address.cshtml inside Shared\EditorTemplates folder. Create the folder EditorTemplates, if not present already.


2. Now, for the best part. In the Register view, replace the Html.RenderPartial, with EditorFor, as shown below.


That's all, aaaand it works.


MVC model binding takes care of all this heavy-lifting for us behind-the-scenes. It's so beautiful and elegant. :)

I hope this helps you as well.



Jan 10, 2016

Differences between Azure Deployment models - Resource Manager and Service Management(Classic)


When I started learning Azure, there was only one portal(Service Management(Classic)) where we could manage, monitor and provision all the resources. Now, we have another portal(Resource Manager) which can also be used to manage these resources.
The idea is that gradually, all the functionalities will be moved from Classic portal to Resource Manager. So, the question is, why did Microsoft create another portal for managing the same set of resources. The main reason for this change is the underlying architecture of Classic portal.
Due to this architecture change, the following resource providers differentiate between the two models:-
  1. Compute
  2. Storage
  3. Network

Primary Features:-

Following are the features of Resource Manager.
  1. The resources of a solution can be managed, deployed and monitored as a group. We can manage resources in the following 4 ways:-
    • Using the Azure Portal.
    • By using the Powershell cmdlets. For versions earlier than 1.0, we should use “Switch-AzureMode –Name AzureResourceManager” to switch to Resource Manager from Service Management(Classic). For 1.0 and above, new cmdlets have been exposed. We can use the format verb-AzureRm.
    • Using the Azure Resource Manager REST APIs.
    • Azure command line interface runs in arm mode. “azure config mode arm”.
  2. Since Resource Manager is the new type of deployment model, the resources provided by the 3 providers mentioned above do not have any suffix to their names. This is as opposed to Classic model where “Virtual Network” would be mentioned as “Virtual Network(Classic)”.
Following are the features of Service Management(Classic).
  1. The segregation in this deployment model is based on the services which are provided. There is no way to group the related resources together in it. We can manage resource using the following 4 ways:-
    • Using the Classic Portal.
    • By using the Powershell cmdlets. For versions earlier than 1.0, we can use “Switch-AzureMode –Name AzureServiceManagement”. For 1.0 and above, we can use continue to use the cmdlets for Service version i.e. without the Rm in verb-AzureRm.
    • Using the Service Management REST APIs.
    • Azure command line interface runs in default or asm mode.
  2. Since Resource Manager has come out, the 3 resource providers listed above have to be identified separately. To do that, “classic” is added behind resources which are created in the classic portal, as shown below
.Classic-vs-RM


Architecture:-

1. Resource Manager
The Resource Manager is divided into three resource providers. All these resource providers combine together to ensure that a VM is up and running. This componentization of resources allows more flexibility during configuring a VM. A Resource Group is a logical container which holds all these resources together so that they can be managed together. The Resource Manager has the following components(refer to the diagram below):-
    • Storage Resource Provider(SRP) – This requires a storage account which contains several VHDs. These VHDs contain the OS running on the VM, temporary and permanent data.
    • Compute Resource Provider(CRP) – This consists of VMs(required) and Availability Groups(optional).
    • Network Resource Provider(NRP) – This consists of required NIC and Virtual Network and optional Load Balancer and Network Security Groups(NSGs).
Architecture - Resource Manager


2. Service Management(Classic)
The Service Management architecture contains the following components(refer to the diagram below):-
  • A Cloud Service(required) which contains a Virtual Machine(required). This VM has a Network Interface Card(NIC) and a private IP address which is provided by Azure. The cloud service also contains a Load Balancer(required) which has a Public IP address and default endpoints for Remote Desktop and Powershell.
  • A Storage Account(required) which contains the VHDs for Operating System, temporary data and other permanent data.
  • A Virtual Network(optional) which contains a subnetted structure. The VM can be assigned to one of the subnets.
Architecture - Classic

These are the main differences between the two deployment models. I hope that this will give you some idea about why resources are created the way they are in the two deployment models of Azure.







Jan 7, 2016

Streams in Powershell

We have the following 7 types of streams in Powershell.

  1. Write-Output
  2. Write-Host
  3. Write-Debug
  4. Write-Verbose
  5. Write-Error
  6. Write-Warning
  7. Write-Information(introduced in v5.0)

We will take a look at each of them below:-

  1. Write-Output - It is used to write the result to the output stream. In the example below, we can see that since the result from first cmdlet is passed to the second cmdlet, the filter condition is applied and "Roshan" is filtered out due to it's length.
  2. Write-Host - It sends the output directly to the console. Due to this, it cannot be piped with other cmdlets. Here, in the example below, continuing from the first example, we can see that "Roshan" is displayed on the screen because it is directly written on the console and the filter condition is not applied on it.
  3. Write-Debug - It is used to write debug information on the console. By default, the $DebugPreference is set to SilentlyContinue. So, by default the message will not be displayed on the console. If we set the $DebugPreference to Continue, the debug messages will start appearing on the screen.
  4. Write-Verbose - This cmdlet is used to provide additional information about the command that is being debugged. Similar to Write-Debug, this cmdlet has $VerbosePreference which needs to be set to Continue for the messages to be displayed on the screen.
  5. Write-Error - It writes the result to the Error stream.
  6. Write-Warning - It writes a warning message. Similar to Write-Debug and Write-Verbose, it has $WarningPreference which needs to be set to Continue for it to be displayed on the console.
  7. Write-Information - It displays additional information about the execution of any script. Depending on the $InformationPreference, it displays those messages during the execution of the scripts.
Hope this gives you a head start on the various available streams in Powershell.

Jan 5, 2016

SecureString class

So, yesterday I came across a class called SecureString.
Let's check it out in this blog.

It is placed under the System.Security namespace.

We can use this class to store values that are confidential in nature viz passwords, credit-card details etc. This class ensures that the object is deleted from the memory when it is not required anymore.

The main difference between a normal String and SecureString is that a String is immutable(an object whose state cannot be modified once it is created) but when it's job is done cannot be removed from the memory. In other words, we do not have any control over when it will be GC'ed. So, this leaves us with a potential risk of this sensitive information being revealed.
Here, SecureString comes to our rescue. SecureString can be modified till we explicitly mark it as read-only. It can be removed from memory by calling the Dispose method explicitly or by the GC.


One major problem that I see with passwords being stored as plain-text in memory is the crashes. As we all know, Windows is notorious for crashing(much better nowadays as compared to the past). Suppose you are using an application which asked for your username and password. It was stored as plain-text in the process. Now, that process crashes and a crash dump gets generated. If that crash dump gets transmitted to crash analysis service, someone unauthorized can access your username and password from a big enough crash dump. Think about it.

It is still very limited in it's ease of use. One prominent API which stores the value as SecureString is NetworkCredential. It exposes two properties which expose the value as SecureString as well as String. NetworkCredential class is used to store the credentials for password-based authentication schemes like Kerberos, NTLM, basic and digest.

Nice article on this topic: How to properly convert SecureString to String.

Jan 4, 2016

Sending mail with SmtpClient - Certificate issues


SmtpClient has following methods for sending mails.

  1. Send(MailMessage)
  2. Send(string, string, string, string)
  3. SendAsync(MailMessage, Object) (Here, "object" can be any reference which allows the callback to identify the send operation.)
  4. SendAsync(string, string, string, string, Object) (Here, "object" can be any reference which allows the callback to identify the send operation.) 

For these methods, we need to provide the MailMessage(Sl. No. 1 and 3) with all the details like From, To, Subject, Body etc.(Sl. No. 2 and 4) or we can provide it in the parameters directly.

To send mails using normal TCP/IP without SSL connection the server does not need to have any certificates. Due to this, EnableSsl property can be false for SmtpClient class. 
If the emails needs to be sent over SSL/TLS connection, you don't need to install certificates on your machine. The data is encrypted by server certificate public/private key pair.

AlternateViews can be used to display mail in different formats e.g. if we are displaying HTML in our email and the user does not have an HTML reader then we should provide some data in plain-text also so that the user can get some information from the page.

SmtpClient does not have a Finalize method. We need to call the Dispose method to exlicitly free up the resources.


Nov 17, 2012

Empty Reference file generation error

Yesterday, I came across this issue where the App.config for a Class Library was not getting modified on addition of a Service Reference. Ideally, the App.config should get the endpoint, bindings, behaviours and other details from the service reference url.

So, I went about looking into the issue.
After investigation I found that since the Reference file getting generated was empty, it was not updating the App.config. This was happening because of conflict of types in the referenced assemblies. When I was trying to add the service reference, the Client which was consuming this service also referenced the same type as contained in the DataContract of the service.

To resolve this error, I did the following:-
1) Right-click the Service Reference which is added to the Client.
2) Click "Configure Service Reference".
3) Uncheck "Reuse types in referenced assemblies" and click Ok.

This ensured that the types are not reused in the Referenced assemblies.
Now, the Reference file was generated and the App.config was also updated.

Hope it helps.