Friday, March 30, 2012

How to install Async CTP V3 properly

Installing Async CTP V3 can be a really headache, trust me I know it from my experience. I have also seen in the forum posts and all, many people in the community having trouble installing Async CTP.

One week back I have installed Async CTP V3 in my laptop which have Visual Studio 2010 Professional with SP1 without any trouble and yesterday I tried to install it in my office computer. It was a really quick installation, but as quick it was, the installation was a total failure. The failure was, the installation was supposed to create a folder named "Microsoft Visual Studio Async CTP" in "My Documents" folder. For some reason it was not there. I tried two three times, but the result was the same.

So last night after coming home, I uninstalled my Async CTP V3 installation and thought to reinstall and figure out what was going on. I ended up getting my nice little Visual Studio crashed.

Just now I got everything up and running including Async CTP V3, so thought to write this post, so it would help you all to stay out of trouble while battling with Async CTP V3 installation. There are some key things that you should consider before installing Async CTP V3 on Visual Studio 2010 Professional with SP1.
  1. You can't have Microsoft ASP.NET MVC 3 installed.
  2. You can't have Microsoft ASP.NET MVC 3 - Visual Studio 2010 Tools installed.
  3. You can't have Microsoft ASP.NET Web Pages - Visual Studio 2010 Tools installed.
  4. You can't have NuGet installed.
  5. You can't have Update for Microsoft Visual Studio 2010 - KB2385361 installed.
(I saw some really important articles have mentioned we can't have "Microsoft ASP.NET Web Pages" installed either. But now I have it installed, but still I got everything up and running perfectly. I am pretty sure they must have really good reason to put it there, but in my case since "Microsoft ASP.NET Web Pages" didn't give me any pain I am not putting it up there.)
Here are the screen shots of my successful installation.

Installation Succeeded.

Installation at My Documents folder.
Async CTP in Visual Studio
Having "Microsoft ASP.NET Web Pages" installed.

If you try to install Async CTP V3 while having any of the above mentioned features installed in your computer, the things that can happen is your installation can take longer than usual. There is a very much possibility that it will get stuck in the middle. The worst case is you will lose your Visual Studio. You will have to repair your Visual Studio or even there can be times you will have uninstall all and start installing Visual Studio from the beginning.

One important thing I have noticed is, for some reason, the reason for my Visual Studios' crash was Windows Phone Developer Tools. First what I did was I uninstalled Windows Phone Developer Tools. But still I couldn't open Visual Studio. Then I had to repair Visual Studio and then I installed Async CTP V3.

Feel free to post your questions if you face any trouble installing Async CTP. More than happy to help.

Happy Coding.

Regards,
Jaliya

Thursday, March 29, 2012

What's new in C# 5.0

As some of you might already know the beta release of Visual Studio version 11 which includes the C# version 5, Visual Basic version 11 and .NET CLR version 4.5 is available for download now.

On this week's MVP Mondays series Fahao Tang, one of the Visual C# MVPs' in the community has published this nice little article on Introduction of New Features in C# 5.0. Thought to share it with you all and add something along which I have learned while experiencing the beauty of Visual Studio Async CTP.

In C# 5.0 there are two main new key features,
  1. Async Programming
  2. Caller Information
01. Async Programming

Microsoft has introduced this Async Programming or Asynchronous Programming with two keywords. One is async modifier and the other is await operator. With this new approach, asynchronous and concurrent programming will be much easier and the code would be easier to write, easier to understand and maintain.

async

The async modifier indicates the compiler that a method or a lambda expression is asynchronous. A method that is marked with the async modifier is referred to as an async method. An async method typically contains one or more occurrences of the await operator, but the absence of an operator does not cause a compiler error. Instead the compiler issues a warning for such methods. If an async method doesn’t use the await operator, the method will not be suspended and will be executing as a synchronous method, despite the async modifier.

Important thing to note with async methods is, an async method can have only following return types : void, Task and Task(Of TResult).
private async void btnStart_Click(object sender, RoutedEventArgs e)
await

Inside an async method, the await operator is applied to a task to suspend execution of the method until the task is completed (which means await requires a task (using System.Threading.Tasks) to await on). In the meantime, control is returned to the caller of the method. The suspension is accomplished without exiting the async method, and it does not cause finally blocks to run. 

The things to note here is if we use try catch block, try catch block is capable of handling any exception occurring in caller or in the async method without any extra work.

To take the concept clearly let's take a look at the following code.
private void btnStart_Click(object sender, RoutedEventArgs e)
{   
    //call one
    var result = GetContent("http://msdn.microsoft.com/");
    //call two
    var result = GetContentAsync("http://msdn.microsoft.com/");               

    //some code here
}
private string GetContent(string address)
{   
    try
    {
        string result = new WebClient().DownloadString(address);
        return result;
    }
    catch (Exception ex)
    {
        throw;
    }
}
The above button click event would be a general button click event where the whole code will be executing line by line. When the event get fired our code will call the GetContent method and will download the all the html content in "http://msdn.microsoft.com/" as a string and it will get stored in the string variable result and it will be returned to the caller. Then we can do what ever we want to do with that. The core point in the above way is, the execution of line "//some code here" will hold until the download completes. In that time if you try to move your application across your desktop or if you click on your application you will see that your application gets unresponsive.

For that here comes async and await. You can mark your method async and you can change the DownloadString to it's asynchronous type which is DownloadStringTaskAsync. Now since await always requires a task to await on and DownloadStringTaskAsync will return a task you can easily put await and modify the code like this.Now what will happen is, when the event get fired our code will call the GetContent method and will download the all the html content in "http://msdn.microsoft.com/" in the background while executing next lines continuously which are in "//some code here". So when you move your application across your desktop or if you click on your application there will be no hang outs or unresponsive messages.
private async Task<string> GetContentAsync(string address)
{   
    try
    {
        return await new WebClient().DownloadStringTaskAsync(address);
    }
    catch (Exception ex)
    {
        throw;
    }
}
02. Caller Information

Using this new feature we will be able obtain information about the caller of a method. This is possible via Caller Info attributes, using that we can identify the file path of the caller's source code, the line number in the caller's source code, and the member name of the caller. This information is helpful for tracing, debugging, and creating diagnostic tools.


For more information,
     What's New for Visual C# in Visual Studio 11 Beta

Happy Coding.

Regards,
Jaliya

Tuesday, March 27, 2012

Who really is this farm account in SharePoint 2010

If you have been working with SharePoint and if you are reading articles related to SharePoint, this word, "Farm Account" appears a lot in them and definitely you should be familiar with it. But I am pretty sure you must be wondering where you are defining this farm account at the first place in SharePoint. Is it your domain Administrator or someone else.

This is the place where you define the farm account for your SharePoint 2010.

Specify Configuration Database Settings

Even though the SharePoint 2010 Product Configuration Wizard asks you to specify a user as a database access account, it's not just an database access account. This account is the farm account which is used as the application pool identity for Central Administration and as the process account for the Microsoft SharePoint Foundation 2010 Timer service.

The server farm account requires the domain user account permissions. But I am always granting him domain administrator's permission and of course it's not required.

After you run the SharePoint Configuration Wizard, machine-level permissions include:
  • Membership in the WSS_ADMIN_WPG Windows security group for the SharePoint Foundation 2010 Timer service.
  • Membership in WSS_RESTRICTED_WPG for the Central Administration and Timer service application pools.
  • Membership in WSS_WPG for the Central Administration application pool.

After you run the configuration wizards, SQL Server and database permissions include:
  • Dbcreator fixed server role.
  • Securityadmin fixed server role.
  • db_owner for all SharePoint Server 2010 databases.
  • Membership in the WSS_CONTENT_APPLICATION_POOLS role for the SharePoint Server 2010 server farm configuration database.
  • Membership in the WSS_CONTENT_APPLICATION_POOLS role for the SharePoint Server 2010 SharePoint_Admin content database.

After you have completed the Product Configuration Wizard and when you are logged into SharePoint, in the right top corner of the bowser if you are logged in as "DOMAIN\Administrator", you are not logged in from the farm account. It is from your domain administrators account. If you are logged in as "System Account", then it is from your farm account. Please identify the difference.

For more information on account permissions and security settings on SharePoint 2010,
     Visit

Happy Coding.

Regards,
Jaliya

Tuesday, March 20, 2012

Handling Authentication and Authorization in ASP.NET

Handling authentication and authorization is one of the important things that we should consider when developing a interactive web site. First of all we should identify the difference between authentication and authorization, since these two words gives a total different meanings.

Authentication means verification of the user's identity which also means verifying the user who he claims to be. Once the user has been authenticated, the authorization process determines whether that identity has access to a given resource. For example if the user is an Administrator, he is authorized to do all the changes in all the resources, If he is a normal user, he is only authorized to do some changes, or may be he will not be able to do any changes. So basically Authorization is checking whether the user has relevant rights to access the resources.

So in ASP.NET, we can use three ways to handle authentication and authorization.
  1. Windows Authentication
  2. Forms Authentication
  3. Passport Authentication


01. Windows Authentication

Windows Authentication is mostly used in web sites running in a intranet. This mode of authentication uses standard windows user names and passwords as user's credentials to access the website. This is how you can enable Windows Authentication in you web site. Change your Web.config file as follows.
<authentication mode="Windows">
        
</authentication>
      
<authorization>
    <allow users="RAVANA\Jaliya"/> <!--allow Jaliya to access-->
    <deny users="*"/><!--deny all users except allowed users-->
</authorization>
Now you have all set for your Windows Authentication in the Web.config file. In here under <authorization> there are several things that you can change like allow/deny all/some/none users and roles etc. Then what you have to do is enable Windows Authentication in IIS. For that go to IIS, select your web site and in your right hand panel double click on Authentication. right click on Windows Authentication and click on Enable. Now try to browser your site and you will be presented with a login page.



02. Forms Authentication

Forms Authentication is mostly used in web sites running in internet. Forms authentication lets you authenticate users by using your own code and then maintain an authentication token in a cookie or in the page URL. You can create a login page that collects credentials from the user and that includes code to validate and authenticate the credentials. To validate we need to compare the submitted information with some kind of previously entered information. We can use the Web.config file, a SQL Server database, a customer database, windows active directory and various other kinds of data sources to store those information.

This is how forms authentication handles authentication.
  • We generally configure the application to redirect all the unauthenticated requests to the login page when users try to access a protected web page. User inputs their credentials and after validating them, if they are correct, then we redirect the request back to the originally requested page with an appropriate authentication ticket (cookie). 
  • If you do not want to redirect to be done, you can just get the forms authentication cookie and set it to the user. So since now user have cookie attached, user's browser passes the authentication cookie with the request.  Because of that on subsequent requests, user will be bypassing the login page when he is requested for credentials.
Let's see how to configure forms authentication in a web site. By default when you create a web site in Visual Studio 2010, in Web.config file <authentication mode=" "> is set to "Forms".
<authentication mode="Forms">
    <forms loginUrl="~/Account/Login.aspx" timeout="2880" defaultUrl="Home.aspx" cookieless=""/>
</authentication>
The values you can set here are,
  • loginUrl - URL for the login page that the FormsAuthentication class will redirect to if no valid authentication cookie is found.
  • timeout - Specifies the time, in integer minutes. Sets the authentication time-out.
  • defaultUrl - URL that the FormsAuthentication class will redirect after successfull authentication.
  • cookieless - The default is UseDeviceProfile.
    • AutoDetect - Specifies that cookies are used, if the device profile supports cookies; otherwise, cookies are not used. For desktop browsers that are known to support cookies, a probing mechanism will be used to try to use cookies, when enabled. If a device does not support cookies, no probing mechanism will be used. Simply means depending on your browser configuration it can either use cookies or pass the authentication information encrypted via browser URL.
    • UseCookies -  Specifies that cookies will always be used, regardless of the device and you would like the forms authentication mechanism to create cookie when the authentication is successful.
    • UseDeviceProfile - Specifies that cookies are used, if the browser supports cookies; otherwise, cookies are not used. For devices that support cookies, no attempt is made to probe to determine whether cookie support is enabled.
    • UseUri - Specifies that cookies will never be used. You would like to pass data encrypted via the browser URL query string.
Now in your Login button click event,
using System.Web.Security;

protected void btnLogin_Click(object sender, EventArgs e)
{
    if (ValidateUser(txtUserName.text, txtPassword.text))
    {
        //true to CreatePersistentCookie
        FormsAuthentication.RedirectFromLoginPage(txtUserName.text, true);
    }
    else
    {
        FormsAuthentication.RedirectToLoginPage();
    }
}

private bool ValidateUser(string username, string password)
{
    //your own validation code
    //return true or false
}
There are couple of things you should know. To get a better understanding about the concept here, you can store user names and passwords in Web.config file which is of course not recommended in production environment and validate them by calling Authenticate method in the FormsAuthentication class instead of writing custom validation.
FormsAuthentication.Authenticate(txtUserName.text, txtPassword.text);
Roles

ASP.NET provides the concept of roles that gives each role a different view on specific pages.
<location path="Finance">
    <system.web> 
        <authorization>
            <allow roles="Fin" />
            <deny users="*" />
        </authorization>
    </system.web>
</location>
Location here means the folder name which holds the .aspx for some specific role. In here, <location path="Finance"> means that all .aspx files under the  Finance folder are protected. <allow roles="Fin" /><deny users="*" /> mean deny every one from accessing pages under Finance except those having the Fin role.

Using forms authentication you can implement Single Sign-On(SSO) in which when you successfully logged in to one site, you don't need to enter your credentials to other related sites. You are signed on across multiple sites.


03. Passport Authentication

Passport authentication is based on the passport website provided by the Microsoft. It is a single sign-on web service developed and provided by Microsoft that allows users to log in to many websites using one account. So when user logins with credentials it will be reached to the passport website where authentication will happen. If Authentication is successful it will return a token to your website.

So this post has only described the basics of Authentication and Authorization in ASP.NET. It's up for you to explore the rest. Appreciate your feedback.

Happy Coding.

Regards,
Jaliya

Tuesday, March 13, 2012

Connecting to Analysis Services in a remote computer using Impersonation with C# - Microsoft SQL Server 2008 R2

My last post was about trying to connect to remote Analysis Services and it was using a tool like BIDS (Business Intelligence Development Studio) or Microsoft SQL Server 2008 R2 Report Builder 3 etc. Today I am going to write about successfully connecting to remote Analysis Services using C#.

If you have not read my previous post about connecting to remote Analysis Services, I think it's better if you can read it first.

So, now I will begin. Now I have logged in to my machine as local administrator and I have no permission to remote Analysis Services. I needed to programmatically create a connection with remote Analysis Services and I tried a lot using various ways.I tried passing both the username and password which has access to remote Analysis Services in connection string in my AdomdConnection. But it was again this same error as I previously had.

Error
Then suddenly this came to my mind, "Impersonation". Of course, If I can access the remote Analysis Services from the windows login of the account which has permission to Analysis Services, from the code if I impersonate myself as that user, I should be able to access Analysis Services without passing any usernames and passwords in the connection string. (Not to mention, the other alternative would be, switch the user and log into the machine using the account which has access to Analysis Services and running Visual Studio from that account each time you want to create the connectivity.)

So from the code, I impersonated my self as the user which has access to Analysis Services and initialized the AdomdConnection. The connection successfully got created and I was able to retrieve database information successfully. And it's my happy day.

Happy Coding.

Regards,
Jaliya

Connecting to Analysis Services in a remote computer - Microsoft SQL Server 2008 R2

Recently I had a requirement to connect to a Microsoft SQL Server 2008 R2 Analysis Services which was running in a remote computer. And it's Analysis Services authentication was configured for Windows Authentication. Connecting and retrieving data from an Analysis Services located in a remote computer seems to be a real puzzle, so thought to write this post.

So my requirement was to query a cube which was deployed in the remote Analysis Services. Of course, I can't connect through SSMS (SQL Server Management Studio) through my windows login, because when I choose Analysis Services as Connect to Server type, authentication section is disabled. My first target was to create a successful connection with the remote Analysis Services.

One of my colleagues told me, we can create a successful connection this way.
  1. In the remote server, create a user account and permit access to Analysis Services.
  2. In my machine, create a user account, same user name and password as in created remote server user account.
  3. Now, from my windows login try creating the connection with the credentials of created user account using some tool like BIDS (Business Intelligence Development Studio), Microsoft SQL Server 2008 R2 Report Builder 3 etc.
Well I thought of using BIDS, and I tried for around an hour. It was this error I was getting and then I had enough. 
Error
Then I thought to go forward with Report Builder.

Using Build selected a Server Name
Using the Build button, I have typed my server name and I did not change anything and tested the connection. Again I got this error "A connection cannot be made. Ensure that the server is running.".

Error
Then I went to Credentials tab and entered my created user account details.

Created account credentials

Came back and tested the connection. It said "Non-Windows user credentials were supplied for a non-http connection to Analysis Services."

Error
Then I went back to the credentials tab and ticked "Use as Windows credentials.".

Use as Windows credentials
Came back and again tested the connection and this time I got a message "Connection created successfully."

Connection created successfully.
So since the connection got created successfully, I thought to select a database. For that I clicked the Build button and clicked on the "Connect to a database" drop down box. Application got freezed for sometime and then there were no databases. I am pretty sure my remote Analysis Service has Adventure Works 2008R2 cube and I did a test connection from that window. Here is what I got.

Error
Isn't this weird? I was having a terrible time with this and then I logged in to my machine using created account. I opened SSMS, selected Analysis Services as Connect to Server type and clicked on Connect. I successfully got connected to remote Analysis Services. With BIDS and Report Builder, it was same as easy as SSMS. 

What I can't understand is, to access data in a remote Analysis Services, do we really have to create a same account as in remote machine and every time we need to access, do we have to switch our windows logins? I did a lot of testing in my test environment, but non of them worked. Please I am desperately looking for an answer to this. I really appreciate your valuable feedback.

Update - Tuesday, March 13, 2012

If you are using Report Builder, you can connect to remote Analysis Services using OLE DB as Connection type instead of Microsoft SQL Server Analysis Services.  

Select OLE DB
Click on Build button. On the next window, click on the drop down where "SQL Server Native Client 10.0" is highlighted and select "Microsoft OLE DB Provider for Analysis Services 10.0".

Select OLE DB Provider
Microsoft OLE DB Provider for Analysis Services 10.0 
Provide credentials of the created user which has access to remote  Analysis Services.

Provide credentials
Test Connection Succeeded.
You will see that, your test connection gets succeeded and you will receive all the database names in your remote Analysis Services in the Initial Catalog drop down box and you can select one as Initial Catalog.

Happy Coding.

Regards,
Jaliya

Saturday, March 10, 2012

What is ADOMD.NET

In simple, ADOMD.NET is an extension of ADO.NET. ADOMD.NET is a Microsoft .NET Framework data provider that is designed to communicate with Microsoft SQL Server Analysis Services. Using this extension we can read multidimensional schema, query cubes, and retrieve the results. ADOMD.NET commands or queries can be sent in Multidimensional Expressions (MDX), Data Mining Extensions (DMX), Analysis Services Scripting Language (ASSL), or even a limited syntax of SQL, and the command may or may not return a result.

The ADOMD.NET data provider is represented by the Microsoft.AnalysisServices.AdomdClient namespace which is included in the Microsoft.AnalysisServices.AdomdClient.dll located in,
"C:\Program Files\Microsoft.NET\ADOMD.NET\100."
Sample Connection
string conString = "Data Source=RAVANA;Initial Catalog=AdvWorks";
string query = "your MDX/DMX etc query";
AdomdConnection oAdomdConnection = new AdomdConnection(conString);
oAdomdConnection.Open();
AdomdCommand oAdomdCommand = new AdomdCommand(query, oAdomdConnection);
AdomdDataReader oAdomdDataReader = oAdomdCommand.ExecuteReader();
while (oAdomdDataReader.Read())
{
      //reading values
}
oAdomdDataReader.Close();
oAdomdConnection.Close();

The AdomdConnection class represents a connection to a multidimensional data source. The AdomdDataReader class retrieves a forward-only, read-only stream of data from a data source and is similar to other data reader classes in ADO.NET. The Read( ) method of the AdomdDataReader object advances to the next row and retrieves the results.

Happy Coding.

Regards,
Jaliya

Wednesday, March 7, 2012

ASP.NET Configuration Files

ASP.NET configuration data is stored in XML text files, each named Web.config. Web.config files can appear in multiple directories in ASP.NET applications. If you have Microsoft SharePoint installed, you can check it by observing folders in the following directory, "C:\inetpub\wwwroot\wss\VirtualDirectories".

Each Web.config file applies configuration settings to its own directory and to all the child directories below it. Settings in child directories can optionally override or modify settings that are specified by the parent directories. Apart from that additional Web.config files can be located in a Web site's subfolders to provide overrides that apply specifically to those folders within that site.

The root of the ASP.NET configuration hierarchy is the , "C:\Windows\Microsoft.NET\Framework\VersionNumber\Config\Web.config" file, which includes settings that apply to all ASP.NET applications that run a specific version of the Microsoft .NET Framework. Since each ASP.NET application that you will create will inherit from default configuration settings from the root Web.config file, you only need to create Web.config files for settings that will override the default settings.

There are number of important settings that can be stored in the configuration file. Here are some of the most frequently used configurations, stored conveniently inside Web.config file.
  • Database connectivity information
  • Session state information
  • Error Handling
  • Security

Happy Coding.

Regards,
Jaliya