Tuesday, May 22, 2012

Managing Sessions in Azure using Table Storage

Hi Again,

After a long break I'm posting something new on my blog. This time something related to Windows Azure development. 

This post is about how we can manage a session in Windows Azure. As we know that there are different ways of session management in ASP.NET like:

In Proc
Out Proc (SQL Server and State Server)
Custom

So here I've used a Custom mode to store the session in Windows Azure which is called Table Storage. Below are the steps which allow us to store our session on Azure storage account using Table Storage method:

1) We have to download the code for Table Storage provider developed by Windows Azure team from the below URL:
2) Compile the project downloaded from the above URL and add the dll as a reference in your project.

3) In the web.config of the project, add the following setting in the< sessionState> section:
<sessionState mode="Custom" customProvider="TableStorageSessionStateProvider">
<providers>
<clear/>
<add name="TableStorageSessionStateProvider" type="Microsoft.Samples.ServiceHosting.AspProviders.TableStorageSessionStateProvider" />
</providers>
</sessionState>

4) Go to the web role properties and add the following setting in the ServiceConfiguration.csfg file:

<ConfigurationSettings>
<Setting name="DataConnectionString" value="DefaultEndpointsProtocol=https;AccountName=<Azure Storage Account Name>;AccountKey=<Azure Storage Account Key> " />
</ConfigurationSettings>
You can add this setting in the web.config or app.config file of your application also:
<appSettings>
<add key="DataConnectionString"value="DefaultEndpointsProtocol=https;AccountName=<Azure Storage Account Name>;AccountKey=<Azure Storage Account Key> " />
</appSettings>

5) In the Global.asax file of the project, get the CloudStorageAccount details before accessing the table storage. Write the following code to achieve this:
usingMicrosoft.WindowsAzure;
usingMicrosoft.WindowsAzure.ServiceRuntime;
usingSystem.Configuration;
protected void Application_Start()
{
CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSettingPublisher) => { varconnectionString = RoleEnvironment.IsAvailable ? RoleEnvironment.GetConfigurationSettingValue(configName) : ConfigurationManager.AppSettings[configName]; configSettingPublisher(connectionString); });
}

In the above code, if you have not specified the “DataConnectionString” in the Role configuration, it will try to look up in the web.config or app.config of your application. So make sure, the “DataConnectionString” must be present in either of these two places.

6) Connect to Server Explorer and in the Windows Azure Storage section, add the new storage account with the Account Name and Key provided in the step 4. You will be able to see the Session table in the Azure.
Cheers
Ankit 

Friday, April 20, 2012

Adding URLs into Favorites/Bookmarks with Javascript


In one of a requirement, I had a link on my page, which on clicked, should add the URL of the page to the Favorites in IE and Bookmarks in Firefox/Safari etc.
So here is my script which will add the passed on URL into the favorites of the browser.
function addToFavoritesSSO(text, msg, returnUrl) {
        var link = returnUrl;
        var browserIndex = navigator.userAgent.indexOf('Safari');                   
        try {

            if (window.sidebar) {
                window.sidebar.addPanel(text, link, "");
            }
            else if (window.external) {
                window.external.AddFavorite(link, text);
            }
            else if (browserIndex != -1) {
                alert('Please press CTRL+D (or Command+D for macs) to bookmark this
page.');
            }
            else {
                alert('Please press CTRL+D (or Command+D for macs) to bookmark this
page.');
            }
        }
        catch (e) {
            alert(msg);
        }
    } 

One of the tough tasks is to add the bookmark in safari and chrome. Since both of these browsers don’t allow accessing the bookmarks programmatically, I’m just showing the shortcut keys to add the URL to bookmark.
I’ll update the function, once I find the solution to add bookmark through JavaScript for Safari and Chrome.
Cheers
Ankit

Thursday, April 19, 2012

Deploying SSRS reports on Report Server through batch file


I was working on some SSRS reports which I’ve to deploy on the report server in the various test and production environments.
So it was decided to automate this process of deploying all reports in one go rather than manually deploying each report one by one.
So here’s how the deployment script was created:
1)      Create a folder on your Report Server where you needs to drop your report files:
“C:\ReportsToPublish\”
2)      Now there is a file which comes with SQL Server samples whose extension is “.rss” which actually contains some VB code which will go through each report in your ReportsToPublish folder and then deploy them one by one. I’ve placed this .rss file in same ReportsToPublish folder.

“C:\ReportsToPublish\PublishReports.rss” 

3)      Now we have to edit the PublishReports.rss file. Here we’ll provide the connection string for the Reports Data source, the reports to be published, and the folder on report server in which reports will be published i.e. parent folder and setting the data source to each report. The code below that we need to edit in the PublishReports.rss:
Dim definition As [Byte]() = Nothing
Dim warnings As Warning() = Nothing
Dim parentFolder As String = "<parent folder name>"
Dim parentPath As String = "/" + parentFolder
Dim filePath As String = "C:\ReportsToPublish\Reports\"
Dim dataSourcePath As String = "/Data Sources" 

Public Sub Main()

    rs.Credentials = System.Net.CredentialCache.DefaultCredentials  

    'Create the parent folder

    Try

        rs.CreateFolder(parentFolder, "/", Nothing)
        Console.WriteLine("Parent folder {0} created successfully", parentFolder)
   
    Catch e As SoapException
                Console.WriteLine(e.Detail("Message").InnerXml)
    Catch e As Exception
        Console.WriteLine(e.Message)

    End Try 

    'Create the Reports shared data source

    CreateDataSource("<datasource name>", "SQL", "data source=(local);initial catalog=<database name>")    

    'Publish the sample reports
    PublishReport("<your report name>")  

    'Set data source for the reports   
    SetReportDataSource("<your report name>") 

End Sub 

4)      Now create a batch file which will use the PublishReport.rss file to deploy the reports on report server. The code for the batch file will be: 

echo 'Publishing reports on the report server' 

rs -i "C:\ReportsToPublish\PublishReports.rss" -s "http://localhost/reportserver"

Cheers
Ankit

Wednesday, April 18, 2012

Remote deployment of assemblies in GAC using psexec


Hi,

I was working on my deployment automation task and in that one requirement was to deploy the assemblies on a remote machine from the build machine.

To accomplish this, I used a light weight tool called "psexec" which is available on Microsoft Technet site: http://technet.microsoft.com/en-us/sysinternals/bb897553.

In my deployment process, I knew the which are assemblies that needs to be deployed in GAC of the test server which I kept it in a folder. So I read that folder in a for loop and picked up every assembly one by one and deployed them into the GAC of the remote server. And then generate a text file which contains the list of assemblies actually deployed from that folder.

Here's the piece of code which you can refer to execute the remote deployment of assemblies into GAC.

Please note that the account which is running these scripts should have the necessary rights on the remote machine where the assemblies need to be deployed.

1) Let us say the assemblies that need to be deployed in GAC are located at:

set dlllocation=D:\AssembliesToBeGAC\

2) Let us say the text file which contains assembly list is:

set dlllist=D:\AssembliesToBeGAC\list.txt

3) The location where you have psexec executable file stored is:

set psexec=D:\AssembliesToBeGAC\psexec.exe

4) The location of gacutil.exe is:

set gacutil=D:\AssembliesToBeGAC\gacutil.exe 

Now execute the below command in a batch file:

FOR /R %dlllocation% %%G in (*.dll) DO (Echo %%G>> %dlllist%)

%psexec% -u username -p password /accepteula -i %<DeploymentServer>% %gacutil% /il %dlllist%

The above commands will actually deploy the assemblies present in folder into GAC of a remote machine.

 Cheers
Ankit

Tuesday, April 17, 2012

LINQ query for OData services for multiple tables .NET 3.5

Hi,
I faced this problem while working on LINQ to Odata services in .NET Framework 3.5. My requirement was as follows:
I've an entity say A, which contains a navigation property say B. A and B are having Many to Many relationship
For the entity B, I've another navigation property say C. B and C are having Many to Many relationship.
Now my task is how to filter A on the basis of C which is indirectly related to A. The solution is easily available for framework 4.0 but I wanted a solution for .NET 3.5 as the methods like .Any(), .Contains(), .Except() are not supported when I consume Odata service in framework 3.5.

So here's what I've figured out to complete my task:

var certList = from x in a.Expand("b/c").AsEnumerable()
                           from y in a.b
                           from z in y.c                          
where z.cID == Convert.ToInt16("3")
                           select x;

Something similar to the above query gave me the desired results.

So the whole idea here is since A contains entity B which in turns contains entity C, I need to expand both B and C.

In the above query, I took Y (entity B present in A)  and then I took Z (entity C present in B) and filtered C according to my given filter.

Hope this gives an idea about solving some of the complex queries when methods like Any(), Contains() etc. are not supported by your framework.

Cheers
Ankit

Introduction - This is my first blog

Hi,

I'm Ankit Puranik. I'm an ASP.NET developer and have an experience of 6+ years into web based application development.
In my blog series, I'll be posting about various problems that I've come across in my career and also the new things which I learnt and will be useful to everyone.
My blogs will include technologies like ASP.NET, C#, Team Foundation Server, Hyper V, Build and Release Management etc.

Regards
Ankit Puranik