Sunday, December 26, 2010

Cross Table Queries, SQL Server Pivot

In our project we often use Cross table queries, usually for generating statistical data, or even reports.
For Pivoting.

 Pivot was introduced in SQL Server 2005.
It was a surprise to know with Microsoft Access there is a built in option to produce crosstab queries, but not so with SQL Server 2000.

Sunday, November 14, 2010

Reasons for using IDisposable: Cleaning Up Unmanaged Recourses.

About C# Disposal pattern,
How to code Disposal pattern for unmanaged resource.
Difference between Managed and Unmanaged resource.

Wednesday, November 10, 2010

Blogger trick1: Using Template Designer and increasing post Width

Using Template Designer was really cool. zero effort cool. Bu post width used to be so small that it sucked.
Tried to find solution for this problem, found several tricks to increase post width in template, none worked for new templates.
Finally i thought i should use my own head for a bit. This was simple. Then i thought why not restrict height of post and add
scroll bar so viewing multiple post on one page will be easier.
So, following things are covered in this post:
  1. Using Template designer to select template
  2. Adjusting width of layout through template designer.
  3. Adjust post width through HTML in blogger Editor.
  4. Adding scroll bar to post body by restricting height of post.
  • Goto Dashboard –> Design –> Template Designer
  • Select Template you like. Select Background.
  • In Layout tab->Body Layout –>  select layout you like, i prefer 2 column layout like this:
                   image
  • Now, Layout tab-> Adjust Width –> Select max width as 1000px, and adjust left sidebar accordingly.
image
  • Click on “Apply to Blog” button. View blog.
  • You have now created theme for blog. It’s time to increase post width or adjust max width of post.
  • Click on “Back to Blogger” link –> Edit HTML –>
  • In text Area search following text
  • <b:template-skin>
    <b:variable default='930px' name='content.width' type='length' value='1000px'/>

  • replace value=’1000px to size you want say value=’1200px’
  • Now add scroll bars to your post body:
  • Search following text in text Area
  • .post-body {
    position: relative;
    }



  • replace this block of css with following
  • .post-body {
    position: relative;
    height : 700px;
    overflow:auto;
    }



  • 700px is size i preferred you can give any height value you wish. Scroll bar will appear if your post height increases length of 700px.

Friday, October 8, 2010

Type and Search in DropDownList in ASP.NET : Using Ajax and JavaScript

  • Copy following JavaScript code and paste in <head></head> tag.
<script type = "text/javascript">
var ddlItemText //array for ddl text items
, ddlValue //array for ddl item values
, ddlSrchObj; //ddl object

//init op onload
function initItems() {
ddlItemText = new Array();
ddlValue = new Array();
ddlSrchObj = document.getElementById("<%=ddlsSrchInJS.ClientID %>");

//        Get ddl items and values onblur load
for (var i = 0; i < ddlSrchObj.options.length; i++) {
ddlItemText[ddlItemText.length] = ddlSrchObj.options[i].text;
ddlValue[ddlValue.length] = ddlSrchObj.options[i].value;
}
}
window.onload = initItems;

function SearchItem(value) {
ddlSrchObj.options.length = 0;
for (var i = 0; i < ddlItemText.length; i++) {
if (ddlItemText[i].toLowerCase().indexOf(value) != -1) {//if found
AddOption(ddlItemText[i], ddlValue[i]);
}
}
if (ddlSrchObj.options.length == 0) {//if not found
AddOption("No items found.", "");
}
}
// if found create option to show in ddl
function AddOption(text, value) {
var option = document.createElement("option");
option.text = text;
option.value = value;
ddlSrchObj.options.add(option);
}
</script>





  • Copy following line and paste it just after  <%@ Page directive.
    <%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>



  • You need to add reference of Ajaxtoolkit in your webapplication if not added.
  • Copy paste following code in <form></form> tag
<table>
<tr>
<td>
Dropdown Dropdown Search using Javascript 
</td>
<td>

<asp:TextBox ID="txtSearch" runat="server"
onkeyup = "SearchItem(this.value)">
</asp:TextBox>
<br />
<asp:DropDownList ID="ddlsSrchInJS" runat="server" Height="22px" Width="157px" >
</asp:DropDownList>

</td>
</tr>
<tr>
<td >

</td>
<td >
&nbsp;</td>
</tr>
<tr>
<td>
Dropdown Search using AJAX
</td>
<td>

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:DropDownList ID="ddlAjaxSearch" runat="server" Height="22px" Width="156px">
</asp:DropDownList>
<asp:ListSearchExtender ID="ListSearchExtender1" 
TargetControlID="ddlAjaxSearch"
QueryPattern="Contains" 
runat="server">
</asp:ListSearchExtender>

</td>
</tr>
</table>
</form>

  • Following is code to add items to both dropdownlists. I’ve added 10 items and assigned values to items of dropdown to be used with javascript. In this case for dropdown to be used with ajax does not require values for items. I’ve written it on page load, you may do it in anyway you prefer.
string[] strArr = new string[10] { "vishal", "akshay", "bandya", "dilip"
, "gazala", "minal", "ninad", "kunal"
, "ajay", "rizwan" };
int i = 1;
foreach(string s in strArr)
{
ddlAjaxSearch.Items.Add((new ListItem(s)));
ddlsSrchInJS.Items.Add((new ListItem(s)));
ddlsSrchInJS.Items[ddlsSrchInJS.Items.Count - 1].Value = Convert.ToString(++i);
}

  • QueryPattern="Contains"  attribute is necessary, else by default   QueryPattern is “StartsWith”.
  • ListSearchExtender works same with ListBox too.
image image
  • Hope this helps you. Suggestions if any are welcome..

Saturday, September 18, 2010

Adding Ajax Seadragon to ASP.net aspx Page: using javaScript Part2

Before going through this post you need to check how to create and add deepzoom content and dzc/dzi file for image and add it in your VS project.
You can find how to create and add deepzoom content and dzc xml file here and here.
Now Download AjaxControlToolkit from here. And add reference of AjaxControlToolkit.dll to your project.
In your apsx page add following line to register ajax toolkit.
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="ajaxToolkit" %>




Copy paste following code inside <HTML></HTML> tag.
Change name of dsc/dzi xml file from “dzc_output.xml” to name you are using.
<head runat="server">
<style type="text/css">  
.hidden_seadragon  
{  
position: absolute;  
top: -100000px;  
display: none;  
}  
</style>  
</head>
<body>
<form id="form1" runat="server">
<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</ajaxToolkit:ToolkitScriptManager>
<ajaxToolkit:Seadragon runat="server" ID="dummy" Width="0" Height="0" CssClass="hidden_seadragon">  
</ajaxToolkit:Seadragon>  

<div id="container" style="width: 640px; height: 480px; color: White; background-color: Black;">  
</div>  

<script type="text/javascript">  
//<![CDATA[ 
var seadragon = null; 
function init() {
seadragon = Sys.Component.create(Sys.Extended.UI.Seadragon.Viewer,
{ "controls": []
, "overlays": []
, "prefixUrl": "/"
, "xmlPath": ""
}
, null
, null
, $get("container"));
seadragon.openDzi("dzc_output.xml"); 
} 
Sys.Application.add_init(init); 

function handle(delta, Px, Py) { 
var bounds = Sys.UI.DomElement.getBounds($get("container")); 
var RegMinX = bounds.x; 
var RegMaxX = bounds.x + bounds.width; 
var RegMinY = bounds.y; 
var RegMaxY = bounds.y + bounds.height; 
if (Px >= RegMinX && Px <= RegMaxX && Py >= RegMinY && Py <= RegMaxY) { 
if (seadragon.viewport) { 
if (delta >= 0) { 
seadragon.viewport.zoomBy(seadragon.config.zoomPerClick / 1.0); 
} else if (delta < 0) { 
seadragon.viewport.zoomBy(1.0 / seadragon.config.zoomPerClick); 
} 
seadragon.viewport.applyConstraints(); 
} 
return true; 
} 
return false; 
} 

/* 
          The mouse wheel script Reference from: http://adomas.org/javascript-mouse-wheel/ 
           I just make a little modification to meet the requirement. 
        */ 
function wheel(event) { 
var delta = 0; 
if (!event) /* For IE. */ 
event = window.event; 
if (event.wheelDelta) { /* IE/Opera. */ 
delta = event.wheelDelta / 120; 
/** In Opera 9, delta differs in sign as compared to IE. 
                */ 
if (window.opera) 
delta = -delta; 
} else if (event.detail) { /** Mozilla case. */ 
/** In Mozilla, sign of delta is different than in IE. 
                * Also, delta is multiple of 3. 
                */ 
delta = -event.detail / 3; 
} 
/** If delta is nonzero, handle it. 
            * Basically, delta is now positive if wheel was scrolled up, 
            * and negative, if wheel was scrolled down. 
            */ 
if (delta) { 
var prv = handle(delta, event.x ? event.x : event.clientX, event.y ? event.y : event.clientY); 
/** Prevent default actions caused by mouse wheel. 
                * That might be ugly, but we handle scrolls somehow 
                * anyway, so don't bother here.. 
                */ 
if (prv) { 
if (event.preventDefault) 
event.preventDefault(); 
event.returnValue = false; 
} 
} 
} 
/** Initialization code.  
        * If you use your own event management code, change it as required. 
        */ 
if (window.addEventListener) 
/** DOMMouseScroll is for mozilla. */ 
window.addEventListener('DOMMouseScroll', wheel, false); 
/** IE/Opera. */ 
window.onmousewheel = document.onmousewheel = wheel; 
//]]>  
</script>  
</form>
</body>

Let me know if this has helped you. Please do share if you know better way to do the same.

Sunday, September 12, 2010

Adding Ajax Seadragon to ASP.net aspx Page: using javaScript Part1

Before we start to learn “How to add Seadragon to your ASP.NET aspx page” you need to know how  to create DZI/DZC xml file and deepzoom content. You can see how to create the same at my prior blog Using Expression Web 3 and Deepzoom Composer for Silverlight and Ajax Seadragon.
  • Create ASP.NET website if you have not created one yet.
  • Create deepzoom content and DZC xml file, and drag drop content to your website’s Solution Explorer.
image You will see Content folder “dzc_output_files” and dzc output xml file “dzc_output.xml” added to your website. image
  • Now add “aspx” page to your website.
  • Copy and paste following code in <Head></Head> tag. Name of file “dzc_output.xml”. may change if you give some other name in your DZC project in DeepZoom composerChange name in JS function openDzi(<DZI output xml file>) accordingly.
    <%--cssStyle for the container that will hold your seadragon--%>
    <style type="text/css">
    #container
    {
    width: 500px;
    height: 400px;
    background-color: black;
    border: 1px solid black;
    color: white;   /* for error messages, etc. */
    }
    </style>
    <%--you can download following js file and use it from your project folder.
    This file also contents handler for mouse wheel tracker for image zoom and zoomout effects
    that you won't get directly if you use seadragon from ajaxtoolkit xml based syntax in asp.net
    My opinion is that, you should download it/copy it and then use so you can work even when you are not connected to internet.--%>
    <script type="text/javascript" 
    src="http://seadragon.com/ajax/0.8/seadragon-min.js">
    </script>
    
    <script type="text/javascript">
    function init() {
    var viewer = new Seadragon.Viewer("container");
    viewer.openDzi("dzc_output.xml");
    }
    Seadragon.Utils.addEvent(window, "load", init);
    </script>
    
    

  • Now copy paste following code in <body></body> tag in your page
<form id="form1" runat="server">
<div id="container">
<%--you will get seadragon here--%>    
</div>
</form>
  • Thats it you are ready to Go.
  • Open the page in browser.

Saturday, September 11, 2010

SQL SERVER 2005/2008: Concatenation of column data using ‘FOR XML’

Concatenation of a column data, say for table TAB1.  Yaa! its easy..
Select convert(varchar,col1) +’ ’+ convert(varchar,col1)+’ ’ + convert(varchar,col1) from TAB1 

Hmm..! but that’s not what i am talking about. Say you have table temp2 with columns [d] and [e].

[d] is repeated multiple times for different values of  [e] . Now, to add more complexity [d] is foreign key to column [a] in table temp1.
yaa temp1 [1---M] temp2 .Now temp1 also has column [b].

Following are contents of both tables :
image

Now. the requirement, you need rowset { temp1.[a]   temp2[Concatenated e] }.

Q : How to do it?..
A1 : Write a table values function that returns concatenated [e] and [b] for temp2, then join this output with temp1 for the required rowset.
A2: write complex CTE for [e] and concatenated [b] in temp2  and join it with temp1  for required rowset.

I know this two easy solutions. There might be other approaches too. But what we are going to look at is ‘FOR XML PATH’.


  • know more about ‘FOR XML’ in SQL SERVER 2005 here
    I found lot of resources that explained same thing, but in too complex way. the simplest and best i found was here.
I am further making it more easier, i guess…! :) I have created small snippet for explain the scenario i had mentioned prior in this post and it’s solution. Following snippet is created in SQL SERVER 2008.

Copy paste following code in your management studio query window and observe the results :)

  • 1st result is contents of temp1

  • 2nd result is content of temp2

  • 3rd result is concatenation of column [b] in temp1 - - - additional example not discussed above.

  • 4th result is for scenario i am talking about.
    BEGIN
    CREATE TABLE temp1
    (
    a  int IDENTITY(1,1)  PRIMARY KEY ,
    b  varchar(10)
    )
    CREATE TABLE temp2
    (
    d  int ,
    e varchar(5)
    )
    ALTER TABLE temp2
    ADD CONSTRAINT tempp 
    FOREIGN KEY(d)REFERENCES temp1(a)
    
    insert into temp1 values (1)
    insert into temp1 values (2)
    insert into temp1 values (3)
    insert into temp1 values (4)
    insert into temp1 values (11)
    insert into temp1 values (5)
    insert into temp1 values (1)
    insert into temp1 values (3)
    insert into temp1 values (2)
    insert into temp1 values (4)
    insert into temp1 values (12)
    
    insert into temp2 values (1,'fdg')
    insert into temp2 values (2,'ghg')
    insert into temp2 values (3,'hgh')
    insert into temp2 values (4,'l;kl')
    insert into temp2 values (11,'gfh')
    insert into temp2 values (5,'rtr')
    insert into temp2 values (1,'khgj')
    insert into temp2 values (3,'dfd')
    insert into temp2 values (2,'ghfg')
    insert into temp2 values (4,'fghfg')
    insert into temp2 values (4,'vishu')
    insert into temp2 values (1,'opop')
    
    --1st table
    Select * from temp1
    --second table
    Select * from temp2
    
    --Get comma separated string of the whole column (only one column) from table using fox xml path
    Select top 1 stuff(b,1,2,'')
    from 
    (
    SELECT     
    (    SELECT 
    ', '+b
    FROM temp1 
    FOR XML PATH('') 
    ) as b 
    FROM temp1 
    ) T
    --following query gives result for the scenario i am talking about 
    Select
    a,
    stuff(
    coalesce((    SELECT     ' ~ '+e
    FROM temp2
    where a=d
    FOR XML PATH('') 
    ), '---')
    ,1,3,''
    )as e 
    from temp1     
    DROP table temp2
    drop table temp1
    END
    




 image Let me know if it helps you.. Would appreciate if you share your knowledge and experience about same.

Sunday, September 5, 2010

Using Expression Web 3 and Deepzoom Composer for Silverlight and Ajax Seadragon




Deepzoom Composer and Expression Web 3 studio. Though i will consider “Seadragon Ajax” control only, but Deep zoom Silverlight is similar. Also I am writing about this control first coz of all controls in ASP,Ajax toolkit or silverlight this was first i liked the most. Now lets start…

1. The DZI file:

      This is actually a xml file also known as deep zoom source file. You can use a tools to create a Deep Zoom source file (for example, Deep Zoom Composer or Photosynth, i guess DeepZooom Composer is pretty eazy). If you are interested in learning more about schema of this file visit here. You can also download its xsd from here.
      In simple words, Idea is, if you zoom the picture, not whole picture is required to be seen in the window. Images in Deep Zoom are represented by a tiled image pyramid. After creating dzi file in Deepzoom composer you will find many(10) folders in it with pieces of the picture and same picture in different sizes in those folders.  Those folders have numbers that specifies levels. Now, Levels specify resolution of picture. Ok enough for DZI and image pyramid level details now. We have got enough info needed to create dzi file.

Creating dzi or dzc in DeepZoom Composer :

  • Install deepzoom composer, download it from here. Mentioned link provide the required info to install and use composer to create deep zoom content, I am using same content to explain. but i will explain with images here :P .
  • Go to deep zoom composer and create a project.
  • Select the Import tab and add the image file you want to convert to a DZI or DZC image by clicking “Add” and browsing for image file.
image image
  • Select the Compose tab and drag the source image from the Images below to the layout area.
image image 
  • Select the Export tab.
image
  • Select output type in right panel as Seadragon or Silverlight Deep Zoom as required, Name the content, select location whre you want to place the content by clicking on “Browse” . In Export option we are not conserned with use of multiple images so single image composition will be selected by default.
  • Click the Export button.
image You can preview same in browser by clicking on Preview option once export is complete. Now the deep zoom content is ready to be used.

Using Expression Web Dev3 Studio : Expression Web Dev 3 studio you need to purchase … :( …
  • If you are new to Expression Web studio, you’ll have to know how to create website project directory, before reading further.  Easiest way to do it is watch this.
  • Create Website, or in existing website, Open page in design mode now, Expand “Media” tree in Toolbox tab.
  • Drag and Drop “Deep Zoom” on page, browse window will open where you will have to select deep zoom content source file, the xml file we create earlier.
image image
  • Insert Deep zoom options window will appear.
  • Select “Seadragon Ajax only” option for Seadragon Ajax. For Silverlight Deep zoom you will have to select “Silverlight only” option.
  • Click ok.
  • Now click on “Code” view in dev studio.
   1:  <head>
   2:  <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
   3:  <link href="Untitled_1.css" rel="-stylesheet" type="text/css" /> ignore this
   4:  <script type='text/javascript' src='javascript/deepzoom/seadragon-min.js'></script><script type='text/javascript'
   5:   src='javascript/deepzoom/silverlight.js'></script>
   6:  </head>
   7:   
   8:  <body>
   9:  <div id="deepzoomcontainer">
  10:      <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" style="width:640px; height:480px;">
  11:          <param name="source" value="deepzooms/dzc_output4/deepzoomproject.xap"/>
  12:          <param name="onerror" value="onSilverlightError"/>
  13:          <param name="background" value="white" />
  14:          <param name="minRuntimeVersion" value="2.0.31005.0" />
  15:          <param name="autoUpgrade" value="true" />
  16:          <param name="initparams" value="zoomIn=5"/>
  17:  <a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
  18:              <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none;"/>
  19:          </a>
  20:      </object>
  21:      <iframe id="I1" style='visibility:hidden;height:0;width:0;border:0px;' name="I1">
  22:      </iframe></div> ignore this
  23:   
  24:  </body>

  • This is Generated code in Expression Web studio.

  • You will also find deepzoom content added to your website automatically, don’t have to worry about that work.
image

Let me know if you like the post….. :)