Saturday, October 30, 2010

Odd or even

Last couple of weeks were comparatively cool in the office because we had delivered a stable build of our application to QA team.Like in any other software company, the free hours turned into the learning sessions.Some peoples started learning new technologies and some utilized the time to strengthen their basics in programming.

Our circle is into refreshing the programming logics.Everybody were into screen development in the project and started forgetting the real coding which does problem solving using logics.The refreshing session started with famous sql questions such as how to find out the duplicates in a table,how to insert values into table without duplication using single line query etc…After some time it reached to .net coding.The first question was simple.

Display the string “Odd” or “Even” for a given number without using any conditional operators,looping and built-in or custom methods .NO GOOGLING!!!

Oh its simple…The first response was this.But after sometime people recognized that they forget even how to find whether a number is odd or even..ie they forgot the operator “%”.Remember that they are the senior developers who are designing their tracks.

If one person learns how to ride a bicycle or learns swimming he will not forget it in his life time.In his older ages he may not perform due to health problems.But the knowledge will be there with him.The same principle applies in the case of programming too…It took some time to get answers.

The first answer was the traditional one.Use an array.

MessageBox.Show(new string[] { "Even", "Odd" }[inputVale % 2]);


Next answer was to use enumeration


public enum Result
{
Even=0,
Odd=1
}
MessageBox.Show(((Result)(inputVale % 2)).ToString());


There is a small confusion…ToString() is a built in function???The next answer was also using function.


MessageBox.Show((inputVale % 2).ToString().Replace("0","Even").Replace("1","Odd"));



A humble request to all developers who are working on the screen development, please don’t spoil your real coding skills…

Tuesday, October 19, 2010

C# to write custom Windows PowerShell cmdlet to get ipaddress

After a long time ,I am little bit free from the office works…So obviously started learning new things.One of the pending item was Windows PowerShell which I started some time back.There is no need to explain what is Windows Power Shell.If you don’t know just google it :-)
Being developers,just running a command or writing a script file is not our aim.We need to extend the functionality for the power shell for the end users.How to extend the functionality? It is by writing commandlets.

What is cmdlet (commandlet) ?

The exact definition of CmdLet ,can be obtained from msdn.If we think from a developer perspective CmdLet is
A sub class of PSCmdlet class compiled into a .net dll, with some overridable methods encapsulating the command implementation which can be invoked through power shell command or power shell apis.

Steps to create a CmdLet

  1. Create a class library
  2. Add References
    1. System.Configuration.Install.dll
    2. System.Management.Automation.dll located at C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\
  3. Write classes for Installer by sub classing PSSnapIn and Cmdlet by subclassing PSCmdlet
  4. Compile the code and install the cmdlet using InstallUtil.exe present here C:\Windows\Microsoft.NET\Framework\v4.0.30319\
  5. In the Power shell window, register your cmdlet by using the command Add-PSSnapIn <snapinname>
  6. Run the cmdlet from power shell command window.

Telling these steps is very simple…I found the same in so many sites.But when I tried to create my first sample I faced so many issues…So try to create the cmdlet by yourself using these steps else read the rest of this article.If you create a cmdlet by just reading till here ,I will say you have got excellent googling skills.

Writing C#  to create cmdlet

There is no question in creating a class library and adding references if the path is known.Below is the code for installer class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Management.Automation;
namespace GetIPAddress
{
[RunInstaller(true)]
public class IPSnapIn : PSSnapIn
{
public IPSnapIn()
: base()
{
}
public override string Name
{
get { return "IPSnapIn"; }
}

public override string Vendor
{
get { return "Joymon"; }
}

public override string Description
{
get { return "This snapin contains a cmdlet to get IPAddress of the machine"; }
}
}
}



All the functionalities are wrapped into the base class.So here we just need to give the name and other details only.If you reflect the codes of its base classes you can see the code which does all the installation.



Now coming to the real cmdlet class.




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Management.Automation;
using System.Net;
namespace GetIPAddress
{
[Cmdlet(VerbsCommon.Get, "IP", SupportsShouldProcess = true)]
public class IP : PSCmdlet
{
protected override void BeginProcessing()
{
base.BeginProcessing();
}
protected override void ProcessRecord()
{
base.ProcessRecord();
}
protected override void EndProcessing()
{
WriteIPAddress();
base.EndProcessing();
}
private void WriteIPAddress()
{
string strHostName;
strHostName = Dns.GetHostName();
IPAddress[] addr = Dns.GetHostByName(strHostName).AddressList;
for (int i = 0; i < addr.Length; i++)
WriteObject(string.Format("IP Address {0}: {1} ", i, addr[i].ToString()));
}
}
}



There are 3 methods which are overriding base class methods.Among those, the ProcessRecord is the one which we need.We can write the code to output the ip from here.The WriteIPAddress method writes the ipaddress using WriteObject method.


Now coding done.Compile the dll and get the copy of that dll to your desired location say c:\cmdlets.Now here is the cmd to install the snap in.



InstallUtil c:\cmdlets\IPCmdLet.dll



Now we need to register using the command

add-pssnapin IPsnapin



All set run the command get-ip to get the ipaddress



Note :

1.For running installutil,you may need to give the full path to that exe file


2.add-pssnapin expects the parameter which is same what you have given in the Name property of the installer class IPSnapIn.If you have any confusion on the name use the command get-pssnapin –registered to find out the snapin names.

Saturday, October 16, 2010

Resolve first issue in SSRS 2008

After you install SSRS 2008 and run/deploy your first report there is 99% chance that you will get an error message as follows.

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

If we google it, we will get directions like check your settings of IIS where the service is hosted…But this is mainly for SSRS 2005 which uses IIS for hosting the services.SSRS 2008 is not using IIS, as it has its on server mechanism which overrides 80 port of IIS.

Confused???When an request comes to the system through the port 80, SSRS 2008 will process it before IIS gets the request.That means there is no web.config of IIS to change the SSL settings.But there is another file rsreportserver.config located at the below location to configure the settings.

[Install drive]:\Program Files\Microsoft SQL Server\MSRS10.MSSQLSERVER\Reporting Services\ReportServer

This file contains an entry keyed as “SecureConnectionLevel” defaulted to 2.Change this to 0 to disable SSL.

http://social.msdn.microsoft.com/Forums/en-US/sqlreportingservices/thread/91ba429e-8bc4-4181-b7a3-f5082c80d51e

Enjoy reporting…

Wednesday, October 13, 2010

Reading and writing files in StoredProcedure

I don’t know why I didn’t thought about reading a text file from a stored procedure until I came across a requirement in SSRS.First I searched for something like usp_OpenFile and usp_ReadFile as usual.But no results.After that I realized that I can interact with system from SQL Server only through the Ole Automation.

It was another new thing to me.I have never used Ole Automation through SQL Server.It is not enabled in SQL server by default.We need to enable through the statement sp_configure.

First I tried to see the status of Ole Automation using the query

EXEC sp_configure 'Ole Automation Procedures';
GO


But this returned error saying that this is an advanced option.Then I turned on the advanced options by the below query


sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO


After this I turned on Ole Automation.


sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO


Now the environment is ready for Ole Automation.Just need to execute the SQL which opens and reads a file using COM objects.


DECLARE 
@strPath VARCHAR(255),
@objFileSystem int,
@objTextStream int,
@strRead Varchar(8000),
@strCommand varchar(1000),
@HRESULT int,
@YesOrNo INT
--Initialize variables
select @strPath='c:\temp\test.txt'
select @strRead=''

--Creating the COM File System Object'
EXECUTE @HRESULT = sp_OACreate '
Scripting.FileSystemObject' , @objFileSystem OUT
--HRESULT will be 0 on success
if @HRESULT=0 select @strCommand=@strPath
--Open file
if @HRESULT=0 execute @HRESULT = sp_OAMethod @objFileSystem , '
OpenTextFile', @objTextStream OUT, @strCommand,1,false,0
--Checking for EOF
if @HRESULT=0 execute @HRESULT = sp_OAGetProperty @objTextStream, '
AtEndOfStream', @YesOrNo OUTPUT
--Reading file
IF @YesOrNo=0 and @HRESULT=0 execute @HRESULT = sp_OAMethod @objTextStream, '
ReadAll', @strRead OUTPUT
--Displays the read text.
select @strRead

-- Closing the file "'

if @HRESULT=0 execute @HRESULT = sp_OAMethod @objTextStream, 'Close'
EXECUTE sp_OADestroy @objTextStream



Its not easy if you are not from the COM world.It’s VB equivalent code can be found here in msdn.



You can use the same Ole Automation to write into file as well. Make it as function by returning the variable @strRead.If you just want to run this, copy above code  into a query window of SQL Server Management Studio and press F5.I am not sure whether this will work in other databases except SQL server 2008.



Happy scripting…

Saturday, October 9, 2010

Route in ASP.Net 4

According to MSDN ASP.Net routing is

ASP.NET routing enables you to use URLs that do not have to map to specific files in a Web site.

What does that mean? Simple you can have a url like below in your application.

http://localhost:51174/Day/6/10/2010

Normally the url comes with a .aspx extension such as Default.aspx.This gives the user a clear understanding of which file will process the request.But the above URL doesn’t tell anything about the file which is going to process it.Also there is no file called 2010 without any extension.But we know without a request processor the ASP.Net cannot return anything back to the client. So how this is handled internally?
Here comes the Routing feature of ASP.Net.We can easily specify the URL format and the corresponding file which is going to handle the request as follows in the Global.asax.cs file.

protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapPageRoute("",
"Day/{Day}/{Month}/{Year}",
"~/Default.aspx");
}


Very simple.It defines the pattern which routes to the default.aspx.Now only thing remaining is how the Default.aspx.cs is going to handle the data.ie how it process the particular request considering the parameters.


public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (this.RouteData != null &
this.RouteData.Values.ContainsKey("Day") &
this.RouteData.Values.ContainsKey("Month") &
this.RouteData.Values.ContainsKey("Year"))
{
int day = Convert.ToInt32(this.RouteData.Values["Day"]);
int month = Convert.ToInt32(this.RouteData.Values["Month"]);
int year = Convert.ToInt32(this.RouteData.Values["Year"]);

DateTime dt = new DateTime(year, month, day);
Response.Write(dt.DayOfWeek.ToString());
}
else
{
Response.Redirect(string.Format("~/Day/{0}/{1}/{2}", DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year));
}
}
}


Self explanatory…Get the data through the property RouteData which belongs to the Page class.The sample uploaded here is to show the Day of the week if you request with the day,month and year as integers.ie the request http://localhost:51174/Day/6/10/2010 will give Wednesday.

There are lot more things you can achieve using the Route feature.Refer the MSDN article.http://msdn.microsoft.com/en-us/library/cc668201.aspx

Don’t think that this was not possible in earlier versions of ASP.Net.It was possible using HttpModules and the common name was URL rewriting.Refer the below links to get more information.

http://www.dotnetfunda.com/articles/article550-url-rewriting-with-http-module-in-aspnet.aspx

http://msdn.microsoft.com/en-us/library/ms972974.aspx

I am seriously looking for the differences between the old HttpModule implementation and this new Route feature except for the ease of use of Route.

Tuesday, October 5, 2010

Starting jQuery

I have been hearing about jQuery from the day it is introduced. My thought was ,it is just a  javascript library and who wants it, where I have my favorite Silverlight with C# support & Flash. They served all the needs at client side / browser and I didn’t even cared about creating a sample using jQuery.

But now things changed with the arrival of HTML 5.It has so many capabilities which I thought a RIA can only support.What does that mean? Death of RIA technologies such as Silverlight & Flash? Most probably they will.If the normal HTML page is capable of rendering the rich web contents who will go for a third party RIA application?

That is about the UI.The story never ends with UI alone.What about the interactivity? That is the main attraction of RIA technologies.When HTML 5 comes how the interaction will take place? Obviously we need to write code to get the interaction.So in those days the hero will be javascript which is a good friend of HTML from the very beginning.

Next question.How much code we need to write to accomplish UI interactions like what Silverlight and Flash giving to us right now? Its a big .So what a normal developer will do? He just creates a library which is reusable in all his projects.That is what jQuery javascript library means.

If you still didn’t understand the importance of jQuery, here is the last sentence.Once the HTML 5 is in place we need javascript to make the page interactive and jQuery will help us to write less code to achieve more functionalities.We can also expect ASP.Net 5/6 emitting HTML 5 contents with stunning animations :-)

The main motivation to write this post is a seminar conducted in our company about jQuery.One of my colleagues explained it very well.

What is jQuery

jQuery is just a javascript library ie a .js file containing some functions and classes which helps the developer to write minimal code. For example lets consider the scenario of changing the width of a div on a button click.

The normal js code.

<script type="text/javascript">
   1: function btnIncrease_Click() {
   2:     div1.style.width = "400px";
   3: }
</script>
<body>
<div id="div1" style="width:100px;height:63px; background-color:Red" ></div>
<input type="button" name="btnIncrease" value ="Increase size" onclick="btnIncrease_Click()" />
</body>


The jQuery equivalent

<script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
   1:  
   2: btn1<script type="text/javascript">$(document).ready(function () {
   3:         //$("#div1").fadeOut("normal", function () { });
   4:         $("#btn1").click(function () {
   5:             jQuery("#div1").width("400px");
   6:         });
   7:     });
</script>
<div id="div1" style="width:100px;height:63px; background-color:Red" ></div>
<input type="button" id="btn1" name="btnIncrease" value ="Increase size"/>



Its very simple in the first look if you are good in javascript.We are including a js file which is the jQuery library and using the ‘$’ symbol. We are calling the functions inside the library.The event subscription of the button.click,we are doing in the documentReady event.#btn1 will translate to the btn1 object and on its click we are changing the size of the div.

Ok.Let us think in another way.If you have 10 divs which are using same style class how will you change the size of all those divs? The jQuery implementation is given below.




<script type="text/javascript">
   1:  
   2:     $(document).ready(function () {
   3:         //$("#div1").fadeOut("normal", function () { });
   4:         $("#btn1").click(function () {
   5:             jQuery(".divStyle").width("200px");
   6:         });
   7:     });
</script>



Its very simple use .divStyle as the parameter and its done.

Visual Studio & Intellisense


I am from the Visual studio environement and I would like to be in it.So I obviously look for the VS intellisense support .And it is there if you use the vs specific version of jQuery.

jquery-1.4.1-vsdoc.js

In VS2010 if you create a new ASP.Net project you can find the jQuery library in the scripts folder.The above picture shows 3 js files for jQuery which does the same job.If you use jquery-1.4.1-vsdoc.js you will the the intellisense as shown in the image.


Don’t confuse with the $ symbol which is there in the jQuery like me.Its just a variable.You may use jQuery instead of $.See the js file if you want to change it to your name.

if you are non Visual Studio developer download the jQuery library from http://docs.jquery.com/Downloading_jQuery