.NET


I talked earlier about Cloud Services, and many vendors like Amazon, RackSpace, etc. are used more for consumer services and enterprises are generally weary of clouds – part of it being paranoia and might be baseless (because of coming up with a process of doing things differently) and a valid reason being security (authenticating with Active Directory) and not wanting to part with services that are not totally in a business’s control, because this could be a business’s core or its IP.
But, the result is that there big  savings, so it is worth looking into.
So, understand and address all the inhibitions to move to a cloud.

Now, the solutions for these are quite vendor-specific (Azure might have them, while Amazon may not), so I’ll mainly talk about Azure.
I mainly see 2 hurdles in using Azure viz.
1. Authentication
2. Proprietary (in-house) Services

In the case of authentication, IT cannot really move the entire Active Directory to the Cloud (and should not), which means that we need a third-party authentication with Azure (that’s what its called, because Azure does not authenticate you then) and our company.
That is, a user uses Azure, but has to authenticate first and this is done externally on- premises of the company (known as on-prem).
This is known as an on-prem/ off-prem solution in industry parlance.

For this, we can use WCF with the Azure Service Bus.
From the Azure website:

Think of the Service Bus as a way to communicate with Azure, and the communication happens between Azure and your company.
So, via this mechanism, Azure can callback into your company, which addresses both authentication and the services issue.

This also means that you need modular services that can be called by someone, which is anyway a good goal to have.

To inform your IT, Azure also provides the following features:

Virtual Machines— Allows you to move your virtual hard disks (VHDs) back and forth between on-premises and the cloud.
Existing workloads such as Microsoft SQL Server or Microsoft SharePoint can be migrated to the Cloud.
Use your own customized Windows Server or Linux images, or select from a gallery.

Windows Azure Virtual Network— Lets you provision and manage virtual private networks (VPNs) in Windows Azure, as well as securely extend on-premises networks into the cloud.
It provides control over network topology, including configuration of IP addresses, routing tables and security policies and uses the industry-standard IPSEC protocol to provide a secure connection between your corporate VPN gateway and Windows Azure.

Availability in New Countries— As of now (May 2013), availability is expanded to 48 new countries, including Russia, South Korea, Taiwan, Turkey, Egypt, South Africa, and Ukraine, making Windows Azure one of the most widely available cloud platforms in the industry with offerings in 89 countries and in 19 local currencies.

Here are details, and an example for you as a developer – http://www.windowsazure.com/en-us/develop/net/tutorials/hybrid-solution/

So, the Cloud is not only for consumer services, and with a little planning, Enterprises can use it as well.

I am building a website on Windows Azure (which is free, and a great offering) with Visual Studio 2010. The site is developed in MVC4 on .NET 4.0 and I am using Web Deploy in VS to publish this website from VS to Azure.

Things were smooth, but I suddenly started getting a problem with the deployment.
The error stated:
Web deployment task failed. (Could not complete the request to remote agent URL ‘https://waws-prod-blu-001.publish.azurewebsites.windows.net/msdeploy.axd?site=xxx.)

Could not complete the request to remote agent URL ‘https://waws-prod-blu-001.publish.azurewebsites.windows.net/msdeploy.axd?site=xxx’.
The request was aborted: The request was canceled.
COM object that has been separated from its underlying RCW cannot be used.

This is a very cryptic message and I did all kinds of things to resolve it.
Even searching for this was not too fruitful.

The answer was to restart Visual Studio and things started working again…like magic.

My hypothesis is that the connection was terminated somehow, and this was cached, so Web deploy kept giving this error. This is just a guess and I have n o idea how it works, but hopefully this post helps you from losing your mind..

A common problem in asp.net is using the membership items that ship with asp and using a User in relationships to the other database tables you have, as a foreign key (to the User table and so, you need to get the User Guid for use in Creates or Edits in your code.

Fyi, the out-of-the-box asp authentication is FormsAuthentication.

Note that the User has a primary key of type uniqueidentifier (in Sql Server terms) which is a Guid in C# terms.
So, your foreign key column must be of type uniqueidentifier.

The way to get the Guid of the currently logged-in user is:

var mu = System.Web.Security.Membership.GetUser();
Guid userKey = (Guid)mu.ProviderUserKey;

This gets you the Guid of the currently logged-in user, and the way to check if a user is logged-in is by using: if (User.Identity.IsAuthenticated)

This works in ASP.NET 4 or MVC3 (all these versions now confuse me)

While making a website in MVC3 on ASP.NET, I got the error: “The entry ‘xyz’ has already been added.”.
I realized that somehow my data Context was already being created by EF and I was getting this error.

The fix for this was to change my ConnectionString (in web.config) to not be of this same name.

I realized that in code-first models, the connection string had to match the database being created, which should match the context class, derived from DbContext.  This was happening in this “database-first” case as well.

I made this short post because many folks are baffled by this error, and I hope this post helps them.

While developing Win Phone apps, there are a few options for having a timer. Here are 2 possibilities which provide precision vs. blocking/overhead:

1. Dispatch timer
This is basically a timer that runs on the UI thread and so is precise but can block the UI for any refreshes and activity when it executes, so be careful how/when you use it.

It can be declared and created as:

System.Windows.Threading.DispatcherTimer _predictionTimer = new System.Windows.Threading.DispatcherTimer();

It is set up as: (Do this in the Page loaded event, for the Page)

_predictionTimer.Interval = new TimeSpan(0, 0, TIMER_INTERVAL_SECONDS);
_predictionTimer.Tick += new EventHandler(PredictionTimerEvent);
_predictionTimer.Start();

Note: If you type in the += after the second statement, hitting Tab twice will also generate a callback stub in code (like the one below) for you.

The method to call for the timer event is written as:

void PredictionTimerEvent(object sender, EventArgs e)
{
   …do something…}

2. IDisposible timer

This timer is not very precise, but runs on its own thread and not the UI thread  and so does not block the UI. It does need to switch contexts to do anything with the UI/display. So, you need to get a handle to the UI thread to do anything with the display. I use the MVVM Light Messenger and subscribe to a message that I then send in the timer so I don’t need to do any switching myself.

It is declared as:

        IDisposable _timer;

It is created as: (Do this in the Page loaded event)

if (_timer== null)

{

        IScheduler scheduler = Scheduler.Dispatcher;

    _timer = scheduler.Schedule

                              (new Action<Action<TimeSpan>>TimerInterrupt), 
                    TimeSpan.FromSeconds(TIMER_INTERVAL_SECONDS));

}

The timer event handler is written as:

        void TimerInterrupt(Action<TimeSpan> action)         {             …do something…             action(TimeSpan.FromSeconds(TIMER_INTERVAL_SECONDS));         }

To kill the timer (while navigating away, for e.g.)

_timer.Dispose();  //kill timer

Both of the above essentially do the same thing, but there are different reasons to use either.
Hope that helps.

Many people ask about REST authentication, so here are a few possible approaches.

Simply put, a server provides access to resources by users/clients, and authentication is a mechanism used to identify users. A REST request you make or consume may require authentication in most business situations.

There is really nothing special about REST calls when it comes to authentication because they are ultimately just http requests, only the URL style is “RESTful”, and the techniques below apply to any http implementation, including ASP.NET.
Here are some scenarios that do not involve any third-parties at run-time.

1. Http authentication over SSL

This seems to be a common approach, whereby the client (webpage or application) sends a username and password (un/pw) in the http header to the server over SSL (encryption is important since the un/pw is clear text). The server retrieves this un/pw and authenticates/authorizes the request accordingly.
There are a number of ways to store a user data and authenticate the un/pw against it, from the built-in asp.NET Membership stuff to a simple match of passwords in a User table.

Your IIS website/service can be set up to use “basic authentication”, from website- properties – Directory Security (tab) – Auth and Access control – Edit and check the required box.
Servers that support basic http auth. are usually configured to “require a pre-authorization”. I don’t know how to do this in IIS.

Server code:

The incoming request has a http Request header, which you can get the auth information from.
In your incoming aspx or auth layer, you can get this from Request.Headers[“Authorization”] and will be of the format “Basic dW46cHc=”.

Here’s some aspx code you can use:
Remember to add a try/catch in there.

protected void Page_Load(object sender, EventArgs e)
{
    const string BASIC = "Basic ";

    string authHeader = Request.Headers["Authorization"];

    if (!string.IsNullOrEmpty(authHeader) && authHeader.Contains(BASIC))
    {
        string auth = authHeader.Substring(BASIC.Length);
        System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
        System.Text.Decoder utf8Decode = encoder.GetDecoder();

        byte[] credentialBuffer = Convert.FromBase64String(auth);
        int charCount = utf8Decode.GetCharCount(credentialBuffer, 0, credentialBuffer.Length);
        char[] decoded_char = new char[charCount];
        utf8Decode.GetChars(credentialBuffer, 0, credentialBuffer.Length, decoded_char, 0);
        string authDecoded = new String(decoded_char);

        string[] unpw = authDecoded.Split(':');
        string username = unpw[0];
        string pwd = unpw[1];
    }

…
…
…
}

At the end of this, you will have the supplied credentials in username and pwd.

Client code:

In basic auth with pre-auth required, you make an initial http request without credentials (don’t get confused by the phrase pre-auth) and the server returns a Response code of 401. This indicates that the server is looking for auth info and you resubmit the request this time with the un/pw in the http header. Setting the PreAuthenticate property of your HttpWebRequest object to TRUE, and the auth information will be sent automatically in the http header by .NET, while making any future requests to that URI.
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.preauthenticate.aspx
If the server is not configured for pre-auth, you send the un/pw directly in the initial request.

Here is some sample code for your client to supply basic http auth.. For CRUD operations, you would need to POST some information (for an update) and that is included here.
For plain URL access, replace the method from POST to GET and remove the lines that write to the Request stream.

Add usings at the top:

using System.Net;
using System.IO;
using System.Text;

To post a string called myContent to myURL

try
{

HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create(myURL);
req.Method = "POST";
req.Timeout = 10000;        // 10 seconds timeout
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = myContent.Length;
byte[] credentialBuffer = new UTF8Encoding().GetBytes(username + ":" + password);
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(credentialBuffer);
stream = req.GetRequestStream();
stream.Write(Encoding.Default.GetBytes(myContent), 0, myContent.Length);
}
catch (Exception ex)
{
    … //error handling

throw new Exception(ex.Message);
}
finally
{
    if (stream != null)
        stream.Close();
}

Now, to read in the response (for your request object req).

HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
stream = resp.GetResponseStream();

byte[] readBuf = new byte[2048]; //whatever the expected size

int bytesRead = stream.Read(readBuf, 0, 2048);
string readData = Encoding.ASCII.GetString(readBuf);
stream.Close();

string received = readData.Trim();

2. Client certificates

This is the most secure form of identifying a particular client. I will add that is constrained because it needs certificate installation and is expensive but it has its uses in mostly B2B but maybe B2C scenarios as well.
For e.g. A financial application wants to retrieve data from a financial warehouse.

Client certificates identify the client making the request, and are issued by third-parties, like Verisign, who verify the client while issuing the certificate, and vouch for the authenticity of the client.

This URL has pretty much everything you need to know about certificates: http://msdn.microsoft.com/en-us/magazine/cc163454.aspx

Hope that helped…
In the future, I will write about oAuth and federated services.

In this post, I will lay out a basic Design Pattern for you to show data in a View.

Let’s start from the web request. This is typically routed to a method on a Controller.
In the method, you would typically execute some business logic and that may call down in the data layer that accesses the database.
After all that, you would end up returning a View of some sort, that is then rendered.
http request –> Controller.action –> returns View –> rendered by Framework

Controller Action

In the Action/method, let’s call a business method that returns a PersonModel for a given Id.
The business method could check for Authorization, etc., and maybe call a method GetPerson in the Data Layer. You could have a thin DataHelper layer that would translate Database entities to Business objects/Models; it provides re-usability to the translation functionality, for consumption by multiple business objects.

Action –> DataHelper –> Data Ops -> Database

Database Operations

With .NET 4.0, Microsoft is pushing us away from LINQ to SQL and towards Entity Data framework which is greatly improved. So, that’s what we’ll use.
Choose Project: Add new item: (I typically click on the Data group to filter): ADO.NET Entity Data Model.
It’s pretty straightforward to connect to a database, etc., and after you’re done, drag tables from the Server Explorer onto the ER designer surface. In our example, you would drag the Person table onto it, and that would create a Person Entity object mapping to the database.

Let’s say you add a GetPerson method to the DataHelper that takes an id, and returns a PersonModel, and the method access the database to get the data.

GetPerson –> GetDBPerson(id) –> Create and populate a PersonModel

The getDBPerson could be a method that fires a LINQ query and returns the ER entity.
For e.g.


MyContext db = new MyContext();

var pers = from p in db.Persons
                     where p.Id = id
                     select p.

return p.FirstOrDefault();

GetPerson could then translate the ER Entity to a model.


PersonModel pers = new PersonModel
                   {
                      Name = dbPers.FirstName;
                   };
return pers;

So, our business method now has the (populated) model.

The controller needs to take this and return a View.

Returning Typed Views

You may know MVC 2 supports strongly typed Views. What this means is that you can create a View based on a typed object, and directly access that object in the aspx code while rendering the View. This provides compile-time checks that make you code more robust and tightly coupled, and also provides Intellisense benefits.

This is done by a View inheriting from a typed ViewPage, which is declared in the View markup by:

Inherits=”System.Web.Mvc.ViewPage<AllergyWeb.Models.PersonModel>”

The View is created like this:


PersonModel person = DataHelper.GetPerson(12345);

return View(person);

In the markup, you can access the model (named as model) directly.
For e.g. <%: model.FirstName) %>

In this case, model is of type Person.

Hopefully now you understand typed Views, and have a basic pattern for showing database data on the web page from a View.

Next Page »