: +91-265-2775555
 : +1-856-831-0505
 : +44-788-443-25-28
 : +45-4052-3137

 ‭(Hidden)‬ Admin Links

There are currently no favorite links to display.

 Blog image

 Tag Cloud

 Archives

There are currently no favorite links to display.

Open native windows application from web page

Recently I needed to open windows calculator from web page. Different browser has different approach to allow this. Below I have mentioned how to implement this for Internet Explorer 6.0/7.0/8.0 and Mozilla Firefox 3.0/3.5.

Internet Explorer:

In IE you need to create the ActiveX control to open the application. You need to write the following HTML code to do this.

<html>

<head>

</head>

<body>

    <input type="button" id ="buttonOpenCalculator"  value="Open Calculator" />

    <script type="text/javascript">

      function OpenCalculator()

      {

            var commandShell = new ActiveXObject("WScript.Shell");

            commandShell.Run("calc");

            commandShell.Quit;

      }

      document.getElementById("buttonOpenCalculator").attachEvent('onclick', OpenCalculator);

    </script>

</body>

</html>

Here when you click the button “Open Calculater” calculator will be opened.

Note: In order to open calculator you need change browser settings as below.

·         Go to Tools > Internet Options > Security Tab > Local Intranet.

·         Click Custom Level in Security level for this zone.

·         SetInitialize and script ActiveX controls not marked as safe” to prompt in ActiveX Controls and Plug-Ins zone.


 

Mozilla Firefox:

To open the application in web page from Mozilla you need to create an extension (.xpi).

In extension you need to write the following code in JS file.

 

//This is the function that will create a process for an application

eventListener = function(event) {

    // get system32 path for user;

    var userSystemFilePath = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("SysD", Components.interfaces.nsIFile);

    var stringApplicationPath = userSystemFilePath.path + "\\calc.exe";// "c:\\windows\\system32\\calc.exe";

    event.target.setAttribute("IsAddOnInstalled", "true");   

    var stringParameter = "";

    try

    {

        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

        var objectFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);

        objectFile.initWithPath(stringApplicationPath);

        if (objectFile.exists())

        {

            // create an nsIProcess

            var objectProcess = Components.classes["@mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess);

            objectProcess.init(objectFile);

            // Run the process.

            // If first param is true, calling process will be blocked until

            // called process terminates.

            // Second and third params are used to pass command-line arguments

            // to the process.

            var arguments = null;

            var argumentLenth = 0;

            if (stringParameter)

            {

                arguments = [stringParameter];

                argumentLenth = 1;

            }

            objectProcess.run(false, arguments, argumentLenth);

        }

    }

    catch (error)

    {

        alert(error );

    }

}

document.addEventListener("sendEvent", eventListener, false, true);

 

 

 

In the web page you need to write the following code

 

<html>

<head>

</head>

<body>

    <input type="button" id ="buttonOpenCalculator"  value="Open Calculator" />

    <script type="text/javascript">

        var element = document.createElement("ExtensionDataElement");

        element.setAttribute("IsAddOnInstalled", 'false');

        document.documentElement.appendChild(element);

       

        function OpenCalculator()

        {

            var event = document.createEvent("Events");

            event.initEvent("sendEvent", true, false);

            element.dispatchEvent(event);

            if (element.getAttribute("IsAddOnInstalled") == 'false')

            {

                window.open("download url of xpi","calculator","","");

            }

        }

        document.getElementById("buttonOpenCalculator").addEventListener('click', OpenCalculator, false);

    </script>

</body>

</html>

 

If you run the code and click the button for first time you will be prompted to install xpi file. Firefox needs to be restarted after installing the extension. Clicking the button now will open the calculator.

Printing in silverlight

Problem: Printing in silverlight.

Answer: One of the important missing features in Silverlight has been printing support. If you have ever tried to print a web page containing Silverlight content, what you saw on the printed page may be skewed or even missing altogether!  

In one of the projects we are working, we need to print information from silverlight application for a user. We have resolved this problem using HTML Bridge.

First of all, Place one div element in your .aspx or .html page which holds your silverlight object as shown below. Look at printDiv tag. It will hold printing content of silverlight application.

“<div id="silverlightControlHost">

<object data="data:application/x-silverlight-2," type="application/x-silverlight-2"

            width="100%" height="100%">

            <param name="source" value="ClientBin/XXXXX.xap" />

            <param name="onError" value="onSilverlightError" />

            <param name="background" value="white" />

            <param name="minRuntimeVersion" value="3.0.40624.0" />

            <param name="autoUpgrade" value="true" />

            <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" style="text-decoration: none">

                <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight"

                    style="border-style: none" />

            </a>

        </object>

        <iframe id="_sl_historyFrame" style="visibility: hidden; height: 0px; width: 0px;

            border: 0px"></iframe>

    </div>

    <div id="printDiv" style="display: none; height: 0; width: 0; z-index: -1; position: absolute">

    </div>

Add this JavaScript function as below in same aspx or html page. These will pop up a print dialog to print dynamically generated content in printDiv element.

//        Function to print itinarary layout

        function CallPrint() {

            var prtContent = document.getElementById("printDiv");

            var WinPrint = window.open('', '', 'left=0,top=0,width=1,height=1,toolbar=0,scrollbars=0,status=0');

            WinPrint.document.write(prtContent.innerHTML);

            WinPrint.document.close();

            WinPrint.focus();

            WinPrint.print();

            WinPrint.close();

            prtContent.innerHTML = "";

        }

 

Now question is how we can add elements and set values from silverlight in this div tag. Here Is the solution. For HtmlElement and HtmlPage object please add statement

 using System.Windows.Browser;

//get printDiv element of html or aspx page as HTMLElement

HtmlElement printDiv = HtmlPage.Document.GetElementById("printDiv");

 

//setting printDiv's innerHTML property to empty string

printDiv.SetProperty("innerHTML", string.Empty);

 

//creating table and tbody instance

HtmlElement table = HtmlPage.Document.CreateElement("table");

HtmlElement tbody = HtmlPage.Document.CreateElement("tbody");

 

//setting table width and Vertical align properties

table.SetStyleAttribute("width", "70%");

table.SetStyleAttribute("verticalAlign", "top");

 

 

//creating TripName(Header of page) label in top

HtmlElement trTrip = HtmlPage.Document.CreateElement("tr");

 

HtmlElement tdTrip = HtmlPage.Document.CreateElement("td");

tdTrip.SetStyleAttribute("width", "20%");

tdTrip.SetStyleAttribute("verticalAlign", "top");

 

// add input element and set it’s properties and value

HtmlElement tripinput = HtmlPage.Document.CreateElement("input");

tripinput.SetAttribute("value", _dashboard.lblControlName.Text);

tripinput.SetStyleAttribute("width", "100%");

tripinput.SetAttribute("type", "text");

tripinput.SetAttribute("readonly", "readonly");

tripinput.SetStyleAttribute("border", "0");

tdTrip.AppendChild(tripinput);

trTrip.AppendChild(tdTrip);

tbody.AppendChild(trTrip);

 

//adding tbody tablebody to table

table.AppendChild(tbody);

//adding table to printDiv Div

printDiv.AppendChild(table);

 

//call to javascript Function which will fire print command to print Printdiv contents

HtmlPage.Window.CreateInstance("CallPrint", null);

 

That’s it.

 

Thanks,

Posted By: Darshana Rana & Jigar patel

Sql server 2005: OUTPUT Clause

Sql server 2005: OUTPUT Clause

What:    OUTPUT Clause is used to return the rows affected by Insert, Update or Delete Statement on
             Sql table

Why:     to perform an action on the rows which are affected by any of the table manipulation statements
             i.e. Insert, Update and Delete.

Example: suppose, we have a requirement to maintain a log file after any operation on a table. Here             operation refers Insert, Update and Delete operation.

The role of an Output Clause comes here, Instead of using a trigger we could use the OUTPUT clause.

How:     For the example here uses a 2 tables:

1.       tblExternalFile: a parents Table

2.       tblExternalFileBackup : a Backup Table

Structures of these 2 tables are bellow:

1.       tblExternalFile

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE TABLE [dbo].[tblExternalFile](

                  [Id] [int] IDENTITY(1,1) NOT NULL,

                  [FileXml] [xml] NULL,

                  CONSTRAINT [PK_tblExternalFile] PRIMARY KEY CLUSTERED

                  (

                        [Id] ASC

                  )WITH (    

                        PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF,

IGNORE_DUP_KEY = OFF,

                        ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON

                  ) ON [PRIMARY]

) ON [PRIMARY]

2.       tblExternalFileBackup

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

   CREATE TABLE [dbo].[tblExternalFileBackup](

         [Id] [int] IDENTITY(1,1) NOT NULL,

         [FileXml] [xml] NULL,

         CONSTRAINT [PK_tblExternalFileBackup] PRIMARY KEY CLUSTERED

         (

               [Id] ASC

         )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF,

               IGNORE_DUP_KEY = OFF,

               ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON

   ) ON [PRIMARY]

 

Here both tables have same numbers of column,

 

OUTPUT clause with Insert:

                Here is a code that will automatically insert a new record in - tblExternalFileBackup
            table,whenever an insert operation fires on – tblExternalFile table.

            GO

            -- Create Temp Table variable

            DECLARE @MyTableVar table( Id int,

                                       FileXml xml,

                                       ModifiedDate smallDateTime);

 

            -- Insert Operation Fires on tblExternalFile

            INSERT tblExternalFile([FileXml])

                OUTPUT INSERTED.Id,INSERTED.FileXml,GetDate()

                    INTO @MyTableVar

                        VALUES (N'<DatabaseData                               xmlns=""><MappingMeta>123</MappingMeta></DatabaseData>');

 

            -- Insert a newly Added Record to tblExternalFileBackup

            INSERT INTO tblExternalFileBackup(FileXml)

                  SELECT FileXml FROM @MyTableVar

 

            --Display the result set of the table variable.

            SELECT * FROM tblExternalFileBackup;

      GO

OUTPUT clause with Delete:

                                DELETE FROM tblExternalFile

            OUTPUT DELETED.*

            WHERE ID=17

      All Deleted rows will be displayed whose Id is 17.

OUTPUT clause with Update:

                                -- Create Temp Table variable

            DECLARE @MyTableVar table( Id int,

                                       OldFileXml xml,

                                       NewFileXml xml,

                                       ModifiedDate smallDateTime);

 

            -- Update Operation

            UPDATE tblExternalFile

                  SET FileXml = '<Employee xmlns=""><ID>007</ID></Employee>'

                  OUTPUT INSERTED.Id,

                   DELETED.FileXml,

                   INSERTED.FileXml,

                   GETDATE()

            INTO @MyTableVar

            WHERE iD=17;

 

            -- Insert a newly Added/ Updated Record to tblExternalFileBackup

            INSERT INTO tblExternalFileBackup(FileXml)

                  SELECT FileXml FROM @MyTableVar

 

      SELECT * FROM tblExternalFileBackup

 

                @MyTableVar is a table Variable we use it to store the Updated records of a Table.
                            Here an Id Number ‘17’ will be updated with the New Xml String and new row will be
                            added in tblExternalFileBackup table.

Alternative of OUTPUT Clause:

                You can write a trigger on table to manage a log on a table. The benefits/ Limitation of
                            triggers over OUTPUT clause are not in the scope of this blog.

 

 

Ref. Site: http://msdn.microsoft.com/en-us/library/ms177564(SQL.90).aspx


Thanks,

Vivek Shah

MOSS 2007: Server error: http://go.microsoft.com/fwlink?LinkID=96177

While trying to install WSS 3.0 SP1 (http://technet.microsoft.com/en-us/office/sharepointserver/bb735839.aspx) the installation get stuck at task 9 of 10 of SharePoint Products and Technology Configuration Wizard. When tried to access the server, encountered the following error:

 

Server error: http://go.microsoft.com/fwlink?LinkID=96177

 

When look into the “Event Viewer”, found the following error description:

 

The schema version (3.0.149.0) of the database DATA
DATABASE_NAME on DATABA_SESERVER_NAME is not consistent with the expected database schema version (3.X.X.X) on DATABASE_NAME.  Connections to this database from this server have been blocked to avoid data loss.  Upgrade the web front end or the content database to ensure that these versions match.

 

Resolution:

 

The first thing we did was either remove content database from the web application which are having the error or Detach the database. This doesn’t seem to work. So we run the command

 

stsadm –o upgrade –inplace –url Central_Administration_URL –forceupgrade

 

and we were back in the business J.

Integrate Android SDK with Eclipse 3.4 (Ganymede) on Windows OS

To Integrate Android with an Eclipse follow the following Steps:

1.     If you have an Eclipse installed on your window OS, you can ignore this step. If you don’t have. you can download it free from http://www.eclipse.org/downloads/ and install in on you window OS.

 

2.     Download latest Android SDK from http://developer.android.com/ , unzip it to a suitable location on your machine. The unzip folder contains a number of file and folder like docs, samples, tools, usb_driver…etc.

 

3.     Once you have Eclipse installed, follow the steps below to download the Android Development

Tools (ADT) plug-in and install it in your respective Eclipse environment.

 

i.              Start Eclipse, then select Help > Software Updates....

ii.             In the dialog that appears, click the Available Software tab.

iii.            Click Add Site...

iv.            Enter this as the Location:  

 

https://dl-ssl.google.com/android/eclipse/

 

Alternatively, you can use http in the Location URL, if you are having trouble with https (https is preferred for security reasons).

 

http://dl-ssl.google.com/android/eclipse/

 

Click OK.

v.             Back in the Available Software view, you should see the plugin. Select the checkbox next to Developer Tools and click Install...

vi.            On the subsequent Install window, "Android Developer Tools", and "Android Editors" should both be checked. The Android Editors feature is optional, but recommended. If you choose to install it, you need the WST plugin mentioned earlier in this page. Click Next.

vii.           Accept the license agreement and click Finish.

viii.          Restart Eclipse.

 

4.     In Eclipse IDE, go to Windows à Preferences... to open the Preferences panel.

 

5.     Select Android from the left panel.

 

6.     For the SDK Location in the main panel, click Browse... and locate the SDK directory.

 

7.     Click Apply, then OK.

 

Done! If you haven't encountered any problems, then you're ready to begin developing Android application

 

That’s it, if you have in suggestion / comments, mail me on vivekshah@prakashinfotech.com

 

Ref. Site: http://developer.android.com/sdk/1.1_r1/installing.html#installingplugin

http://www.eclipse.org/downloads/

http://developer.android.com/

 

Thanks,

Vivek Shah

How to make CloudTags in static webpages?

Overview :

Nowadays we found all the websites have special type of panel, whether left or right side of the page, with different styled words or phrases. Some of them are more or less styled, like bold and size of the font. These are the nothing but CloudTags, which leads us to the different pages related to that perticular word or phrase.

There are lots of techniques to do such a like stuff. I have searched for all those for Static Webpages and found few links like below.

http://24ways.org/2006/marking-up-a-tag-cloud

http://webdesign.about.com/od/csstutorials/a/aa011407.htm

Etc...

But, all those are not enough for me to do, what I wanted because all of them used to statically apply the CSS. So, when we require making the word or phrase bolder then there would require to change the CSS on each page and it is not the proper way to deal with.

Solution :

So, I have tried to resolve the problem by using following technologies.

1.       XML/XSLT

2.       JavaScript/CSS

 

1.          XML/XSLT

I have created two simple Xml file which contains the projects information, let’s say Projects.xml

Projects.xml

 <?xml version="1.0" encoding="utf-8" ?>

<Projects>

  <Project type="Migration">

    <Item>1</Item>

    <Item>2</Item>

  </Project>

  <Project type="File Upload">

    <Item>1</Item>

    <Item>2</Item>

    <Item>3</Item>

    <Item>4</Item>

    <Item>5</Item>

  </Project>

  <Project type="SharePoint">

    <Item>1</Item>

    <Item>2</Item>

    <Item>3</Item>

    <Item>4</Item>

  </Project>

  <Project type="Silverlight">

    <Item>1</Item>

  </Project>

  <Project type="Cold Fusion">

    <Item>1</Item>

  </Project>

</Projects>

This xml file contains Project nodes, which actually specifies the type of project. Here I have added random types of the projects.

 And each Project node contains the Item, which are the actual name of the projects done, here I have used only numbers, because it just to show you the working and there is nothing concern about the data, I have used here.

But the actual require format of the xml file is something different as below,

NewProjects.xml

<?xml version="1.0" encoding="utf-8"?>

<Projects>

  <Project type="Cold Fusion" Num="1" url="projects.html?projecttype=Cold Fusion">

  </Project>

  <Project type="File Upload" Num="5" url=" projects.html?projecttype=File Upload">

  </Project>

  <Project type="Migration" Num="2" url=" projects.html?projecttype=Migration">

  </Project>

  <Project type="SharePoint" Num="4" url=" projects.html?projecttype=SharePoint">

  </Project>

  <Project type="Silverlight" Num="1" url=" projects.html?projecttype=Silverlight">

  </Project>

</Projects>

In this xml file, we can see that it is simple to understand by developer but it is not easy to maintain by the data entry operator.  The person, who is entering the data, can make mistakes or may enter wrong data and ultimately there would be generated wrong CloudTags .

This xml file is same as Projects.xml file with additional attributes in the Projects node.

Num: This is the number which shows the number of projects done in that particular type(Category).

url: This is the url to redirect to the page which contains the information regarding that particular project type. Here we have taken only a single url and passing project type as a bookmark in the querystring.

To make process simpler for data entry I have used xslt to apply style to the Projects.xml and generates the NewProjects.xml.

Projects.xslt

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"

  <xsl:output method="xml" indent="yes"/>

 

  <xsl:template match="/">

    <xsl:element name="Projects">

      <xsl:for-each select="Projects/Project">

        <xsl:sort select="@type"/>

        <xsl:element name="Project">         

          <xsl:attribute name="type">

            <xsl:value-of select="@type"/>

          </xsl:attribute>

          <xsl:attribute name="Num">

            <xsl:value-of select="count(Item)"/>

          </xsl:attribute>

          <xsl:attribute name="url">

            <xsl:text> projects.html?projecttype=</xsl:text>

            <xsl:value-of select="@type" disable-output-escaping="yes"/>

          </xsl:attribute>

          <!--<xsl:copy-of select="Item"/>-->

        </xsl:element>

      </xsl:for-each>

    </xsl:element>

  </xsl:template>

</xsl:stylesheet>

By using the xslt, we even can generate HTML but that would be seen later on.

In this xslt file I have there is comment

<!--<xsl:copy-of select="Item"/>-->

This is actually to renders the Item nodes under Project nodes, like Projects.xml, which are not required here for me.

2.       JavaScript/CSS

Here is the javascript which actually gets the xml/xslt files and generated the output using DOM.

tagCloud.js

var divTagId;

var xml;

var xsl;

 

var xmlOutput;

 

function loadXMLDoc(fname) {

    var xmlDoc;

    // code for IE

    if (window.ActiveXObject) {

        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");

        xmlDoc.async = false;

        xmlDoc.load(fname);

    }

    // code for Mozilla, Firefox, Opera, etc.

    else if (document.implementation && document.implementation.createDocument) {

    try {      

            xmlDoc = document.implementation.createDocument("", "", null);

            xmlDoc.async = false;

            xmlDoc.load(fname);           

        }

        catch (e) {

            var xmlhttp = new window.XMLHttpRequest();

            xmlhttp.open("GET", fname, false);

            xmlhttp.send(null);

            xmlDoc = xmlhttp.responseXML.documentElement;

        }

    }

    else {

        alert('Your browser cannot handle this script');

    }   

    return (xmlDoc);

}

 

function insertTable() {

    tbl = document.createElement('table');

    tbl.style.width = "100%";

    tbl.style.height = "100%";

    tbl.style.background = 'transparent';

    var row = tbl.insertRow(0);

    var cl = row.insertCell(0);

 

    cl.style.padding = "10px";

    cl.style.align = "justify";

 

    oTableContainer = document.getElementById(divTagId);

    oTableContainer.appendChild(tbl);

 

  

    var doc = xmlOutput.documentElement; //.selectNodes('Project');

   

 

    if (doc.hasChildNodes()) {

        var itemElements = doc.getElementsByTagName("Project")       

        var max = parseInt(itemElements.item(0).getAttribute("Num"));      

        var min = parseInt(itemElements.item(0).getAttribute("Num"));

        for (var i = 1; i < itemElements.length; i++) {

            {

                var tmp = parseInt(itemElements.item(i).getAttribute("Num"));

                if (max < tmp)

                    max = tmp;

                if (min > tmp)

                    min = tmp;

            }

        }

 

        var minFontSize = 11;

        var maxFontSize = 32;

        var diff = max - min;

        var offset = parseInt((maxFontSize - minFontSize) / diff);

        var htmlString = '';

 

        for (var i = 0; i < itemElements.length; i++) {

            {

                var tmp = parseInt(itemElements.item(i).getAttribute("Num"));

                var fontSize = minFontSize + ((tmp - min) * offset);

                htmlString += '&nbsp;<a href="' + itemElements.item(i).getAttribute("url") + '" style="font-size: ' + fontSize + 'px;line-height: ' + (minFontSize + (diff * offset)) + 'px;color: #1E3695;">' + itemElements.item(i).getAttribute("type") + '</a>&nbsp;';

            }         }

        cl.innerHTML = htmlString;

    }

}

 

function displayResult(divTagIdArg, xmlArg, xslArg) {

    divTagId = divTagIdArg;

 

    xml = loadXMLDoc(xmlArg);

    xsl = loadXMLDoc(xslArg);

   

    // code for IE

    if (window.ActiveXObject) {

        xmlOutput = new ActiveXObject("Microsoft.XMLDOM");

        xmlOutput.async = "false";

        xmlOutput.loadXML(xml.transformNode(xsl));

    }

    // code for Mozilla, Firefox, Opera, etc.

    else if (document.implementation && document.implementation.createDocument) {

        xsltProcessor = new XSLTProcessor();

        xsltProcessor.importStylesheet(xsl);

        resultDocument = xsltProcessor.transformToDocument(xml, document);

        var xmlSerializer = new XMLSerializer();

        parser = new DOMParser();

        xmlOutput = parser.parseFromString(xmlSerializer.serializeToString(resultDocument), "text/xml");

    }

    insertTable();

} 

And we only require to call the displayResult() javascript function by passing id of the division tag, relative path of the xml file, and relative path of the xslt file.

Limitations : It is intendended to use and tested in IE7.0, firefox3.0.11, and Opera 9.27 only.

Example :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>Cloud Tags in static pages...</title>

    <script src="Javascripts/tagCloud.js" type="text/javascript"></script>

</head>

<body onload="displayResult('divCloudTag','XmlDataSource/Projects.xml','XmlDataSource/Projects.xslt');">

    <div id="divCloudTag" style="width: 400px;height:200px;vertical-align:top;direction:ltr;display:inline;">

    </div>

</body>

</html>

Output:

CloudTag

Note : Javascrip/CSS guys can make it to work with other browsers and also can simplyfiy the secario.

Thanks,

Ramesh N Vagh,

Software Engineer,

Prakash Software Solutions Pvt. Ltd.

Vadodara

Anti-Patterns and Worst Practices – The Arrowhead Anti-Pattern

It is a common belief that methods should have a single entry and exit point. While this is a noble goal you need to be very aware that you can detract from the readability and comprehensibility of your code simply to uphold that belief. While a single exit point is not an anti-pattern striving to achieve a single exit point can result in deeply nested “arrowhead” code which is an anti-pattern.

My basic advice to you is that you should only strive for a single exit point from your method when it aids in the readability and comprehensibility of that method, if it doesn’t then don’t get caught up in having a single exit point.

Below mentioned link will detailed you the whole concept

http://www.lostechies.com/blogs/chrismissal/archive/2009/05/27/anti-patterns-and-worst-practices-the-arrowhead-anti-pattern.aspx

SQL QUERY OPTIMIZATION

1.    Use Clustered Indexes

Having the clustered index on the primary key is sometimes not the most efficient place for the clustered index to be. A clustered index is the most performant type of index. The whole table is sorted according to the clustered index. If the table is involved in lots of joins based on the primary key, it is probably the USE place for it to be, but if you are continually filtering or grouping on other columns in a table, then you should possibly consider changing the primary key index to Non-Clustered, and putting the clustered index on those filtered or grouped columns.

The following statement removes and existing clustered index on the primary key and replaces it with a non-clustered index:

ALTER TABLE MySchema.SalesOrderHeaderDROP CONSTRAINT PK_SalesOrderHeader

GO

ALTER TABLE MySchema.SalesOrderHeaderADD CONSTRAINT PK_SalesOrderHeaderPRIMARY KEY NONCLUSTERED (SalesOrderID);

Then the following statement adds a new clustered index to a table.

CREATE CLUSTERED INDEX MyClusteredIndexON MySchema.SalesOrderHeader (OrderID)

2.    Use Indexed Views

 

Indexed Views have been around for a while. A view is like a named query, and these days you can add indexes to them. If used correctly, they can cause a massive improvement in execution times, often better than a clustered index with covering columns on the original table. Also, in SQL Server Developer Edition and Enterprise Edition, a view index will also be automatically used if it is the best index even if you don’t actually specify the view in your query!

 

CREATE VIEW MySchema.SalesByCustomer

WITH SCHEMABINDING

AS

SELECT

soh.SalesTerritoryID, soh.CustomerID,   SUM (sod.Quantity * sod.UnitPrice)

FROM

MySchema.SalesOrderHeader soh

INNER JOIN MySchema.SalesOrderDetail sod   ON (soh.SalesOrderID = sod.SalesOrderID)

GROUP BY

soh.SalesOrderTerritory, soh.CustomerID

Note the use of the schema binding attribute. This prevents you from changing underlying tables while this view exists, and is necessary if you want to add an index. Some people avoid indexed views for this reason, as the maintenance becomes more complicated as further dependencies to the view are created. The following statement adds an index:

CREATE UNIQUE CLUSTERED INDEX IdxSalesOrderView ON MySchema.SalesByCustomer (   SalesTerritoryID, CustomerID   )

Use Indexed Views (SCHEMABINDING cannot be specified if the view contains alias data type columns)

3.    Use Covering Indexes

Covering indexes are a feature that was newly added to SQL 2005. Basically, you can create an index optimized for the query itself based on joins, filters and grouping, and then add additional columns that can be retrieved directly from the index for use in select statements, as follows:

CREATE NONCLUSTERED INDEX TestIndex  

ON MySchema.SalesOrderDetail (OrderId) INCLUDE (Quantity, UnitPrice)

The above statement causes a non-clustered index to be created on the SalesOrderDetail table. If queries are executed on the OrderId column, the index will be used, and if the only other columns being retrieved are Quantity and UnitPrice, then the query optimizer doesn’t need to retrieve any extra columns from the underlying table. It can just use the index. Because the query optimizer doesn’t need to query the original table, performance is improved. 

4.    Restrict the queries result set

Try to restrict the queries result set by returning only the particular columns from the table, not all table's columns.

5.    Use views and stored procedures

This can reduce network traffic, because your client will send to server only stored procedure or view name (perhaps with some parameters) instead of large heavy-duty queries text. This can be used to facilitate permission management also, because you can restrict user access to table columns they should not see.

6.    Avoid using cursors, whenever possible.

SQL Server cursors can result in some performance degradation in comparison with select statements. Try to use correlated sub query or derived tables, if you need to perform row-by-row operations.

7.    Use constraints instead of triggers.

Constraints are much more efficient than triggers and can boost performance. So, you should use constraints instead of triggers, whenever possible.

8.    Use table variables instead of temporary tables.

Table variables require less locking and logging resources than temporary tables, so table variables should be used whenever possible.

9.    Include SET NOCOUNT ON

This can reduce network traffic, because your client will not receive the message indicating the number of rows affected by a T-SQL statement.

Include SET NOCOUNT ON statement into your stored procedures to stop the message indicating the number of rows affected by a T-SQL statement.

10. use UNION ALL statement instead of UNION

 

The UNION ALL statement is much faster than UNION, because UNION ALL statement does not look for duplicate rows, and UNION statement does look for duplicate rows, whether or not they exist.

 

11. Avoid data type mismatch for index columns

AVOID

Select

barcode, price

From

products

Where

barcode = 5467;

          USE

Select

barcode, price

From

products

Where

barcode = ‘5467’;

          barcode is a type of CHAR (10)

12. Index Usage and Functions

AVOID

Select COUNT (*)

From products

Where SUBSTR (brand, 1, 3) =’Arr’;

USE

Select COUNT (*)

From products

Where brand like =’Arr%’;

The reason why application of a function renders the index seek operation useless is because the index pages do not store the data after the application of that function and thus the optimizer cannot perform a seek operation.

13. Composite Index

 

AVOID

 

Select

count (*)

From

products

Where

price < 1000

 

USE

Select

count (*)

From

products

Where

brand > ‘0’ AND price < 1000

 

Ensure all columns are specified when using composite index

14. Group By, Having

 

AVOID

 

Select brand, SUM (price)

From products

Group by brand

Having brand = ‘Arrow’

 

USE

 

Select brand, SUM (price)

From products

Where brand = ‘Arrow’

Group by brand

 

Move conditions from having clause to where clause

 

15. Nested Selects

 

AVOID

 

Select

COUNT (*)

From

products

Where

itemcode IN (

Select

itemcode

 from

clothing

 where

material = ‘Cotton’

)

USE

 

SELECT

          COUNT (*)

FROM

          PRODUCTS P

          INNER JOIN CLOTHING C

          ON P.BARCODE = C.BARCODE

          AND C.MATERIAL = 'Cotton'

 

Use joins instead of nested selects, whenever possible

 

16. Multi table join

AVOID

SELECT

          COUNT (*)

FROM

          T-SHIRT T

          INNER JOIN SHIRTS S

          ON T.BARCODE = S.BARCODE

          INNER JOIN CLOTHING C

          ON S.BARCODE = C.BARCODE

          INNER JOIN PRODCUT P

          ON C.BARCODE = P.BARCODE

 

USE

 

SELECT

          COUNT (*)

FROM

          PRODUCTS P

          INNER JOIN CLOTHING C

          ON P.BARCODE = C.BARCODE

          INNER JOIN SHIRTS S

          ON C.BARCODE = S.BARCODE

          INNER JOIN T-SHIRT T

          ON S.BARCODE = T.BARCODE

 

When joining multiple tables the smallest table should be specified last

 

17. NOT IN

AVOID

Select

count (*)

From

Products

Where

barcode NOT IN (

Select

barcode

  From

Clothing

      )

USE

Select

COUNT (*)

 From

Produ cts P

 Where

NOT EXISTS (

Select

C.barcode

 From

Clothing C

 Where

C.barcode = P.barcode

)

Replace NOT IN by NOT EXISTS

18. NOT EQUAL TO

 

AVOID

 

SELECT

          P.BRAND

FROM

          PRODUCTS P

          INNER JOIN CLOTHING C

          ON P.BARCODE = C.BARCODE

          INNER JOIN SHIRT S

          ON C.BARCODE = S.BARCODE

WHERE

          C.MATERIAL! ='COTTON’

          USE

SELECT

          P.BRAND

FROM

          PRODUCTS P

          INNER JOIN CLOTHING C

          ON P.BARCODE = C.BARCODE

          INNER JOIN SHIRT S

          ON C.BARCODE = S.BARCODE

WHERE

          C.MATERIAL < 'COTTON'

UNION

SELECT

          P.BRAND

FROM

          PRODUCTS P

          INNER JOIN CLOTHING C

          ON P.BARCODE = C.BARCODE

          INNER JOIN SHIRT S

          ON C.BARCODE = S.BARCODE

WHERE

          C.MATERIAL > 'COTTON’

Replace “! =” by Union of “<” and “> “

 

19. COUNT(*)

 

AVOID

 

Select

COUNT (*)

From

PRODUCTS

          USE

SELECT

TOP 1 ROWS

FROM

SYSINDEXES

WHERE

ID = OBJECT_ID('PRODUCT') AND INDID < 2

 

 

 

Facebook Application Development

Step 1: Requirements

1.       Download the Facebook LINQ to FQL binaries(DLLs) from http://facebooklinq.codeplex.com/

2.       Create a website or application in VS 2008

3.       Add references of DLL (downloaded in step1) in to the project.

 

Step 2: Facebook Application Setting

               

4.       Login in http://www.Facebook.com with valid user name and password.

5.       Paste the URL http://www.facebook.com/developers/ to support custom application in your account.

6.       Click “Allow” button to allow for custom Facebook application

7.       Click  “Setup New Application” button to validate your custom application

8.       Give the application name – let’s say “My Application” and select “Agree” radio button then click “Save Changes” button.

9.       Facebook generates some credentials for the created application like “API Key”, “Application Secret”,” Application ID” with respective values. See below fig

 

Step 3: Setting the Facebook application credentials in Web.Config

               

1.       Add below values in “appSettings” section;

 <appSettings>

<add key="Facebook.Linq.ApplicationID" value="84057646988" />

<add key="Facebook.Linq.APIKey" value="0e3d1bf9c7b2b665ff30e8fa30bcc2a9" />

<add key="Facebook.Linq.Secret" value="c29cc5998518dc19616e0c6087bf8e9d" />

</appSettings>

 

2.       Add below value in “httpHandlers” section

<add path="FacebookCallback.ashx" verb="*" type="facebook.Web.FacebookCallback, facebook.Linq, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b83f527cfd9d0f78" validate="false"/>

 

Step 4: Accessing Facebook Data

 

3.       Open the webpage (in our case Default.aspx)

4.       Add reference of Facebook dlls using below lines

using facebook;

5.       Authenticate current Facebook Logged in user with below line

bool isAuthenticated = facebook.Web.FacebookContext.Current.TryAuthenticating(true);

6.       After authentication, create the object of FacebookDataContext with below line

var db = new FacebookDataContext();

7.       Now access the properties of db whose type of facebook.Linq.FqlTable indicates the facebook data like;

a.       db.user – user information

b.      db.group – groups information

c.       db.friend_info – friends list etc.

8.       Filter data as per requirements through executing LINQ on the above lists

 

Step 5: Source code listing

a.          ASPX Page

Put the DataList and add item templates in to the datalist as per requirements

 <asp:DataList ID="Example1DataList" runat="server" RepeatDirection="Horizontal" ItemStyle-VerticalAlign="Top">

            <ItemTemplate>

                <asp:Label ID="Label1" runat="server" Text='<%# Eval("name") %>'></asp:Label><br />

                <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("pic") %>'></asp:Image><br />

                <asp:Label ID="Label2" runat="server" Text='<%# Eval("birthday") %>'></asp:Label><br />

            </ItemTemplate>

        </asp:DataList>

b.      C# Code

Write the below code to display the logged in user information like name, birthday and photo of the user.

 protected void Page_Load(object sender, EventArgs e)

    {

try

        {

            if (facebook.Web.FacebookContext.Current.TryAuthenticating(true))

            {

 

                var db = new FacebookDataContext();

                var myUser = from user in db.user where user.uid == db.uid select user;

                var myUser2 = db.user.Where(t => t.uid == db.uid);

                Example1DataList.DataSource = myUser.Take(10);

                DataBind();

            }

        }

        catch (Exception ex)

        {

            throw ex;

        }

    }

 

Thank You,

 

Posted By : Vipul Patel & Poonam Aswani

Sorting a Collection of Customized Objects

When using our own Object model in our projects, we have our own classes for userdefined objects
and collection of these objects to represent the list of these objects.
For example we have a object named Customer and we have a customer collection object. We can directly bind this collection of customer to a datagrid or gridview. But when we have to provide a sorting on columns in grid, the process we follow is a bit tedious. Here is a very simple way to sort our collection of any object without converting into datatable or any other object.
We have a generic comparer class as follows:
 
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Reflection;
 
    /// <summary>
    /// This class is used to compare any
    /// type(property) of a class for sorting.
    /// This class automatically fetches the
    /// type of the property and compares.
    /// </summary>
    public sealed class GenericComparer<T> : IComparer<T>
    {
        public enum SortOrder { Ascending, Descending };
        #region member variables
        private string sortColumn;
        private SortOrder sortingOrder;
        #endregion
        #region constructor
        public GenericComparer(string sortColumn, SortOrder sortingOrder)
        {
            this.sortColumn = sortColumn;
            this.sortingOrder = sortingOrder;
        }
        #endregion
        #region public property
        /// <summary>
        /// Column Name(public property of the class) to be sorted.
        /// </summary>
        public string SortColumn
        {
            get { return sortColumn; }
        }
        /// <summary>
        /// Sorting order.
        /// </summary>
        public SortOrder SortingOrder
        {
            get { return sortingOrder; }
        }
        #endregion
        #region public methods
        /// <summary>
        /// Compare interface implementation
        /// </summary>
        /// <param name="x">First Object</param>
        /// <param name="y">Second Object</param>
        /// <returns>Result of comparison</returns>
        public int Compare(T x, T y)
        {
            PropertyInfo propertyInfo = typeof(T).GetProperty(sortColumn);           
            IComparable obj1 = (IComparable)propertyInfo.GetValue(x, null);
            IComparable obj2 = (IComparable)propertyInfo.GetValue(y, null);
            if (sortingOrder == SortOrder.Ascending)
            {
                return (obj1.CompareTo(obj2));
            }
            else
            {
                return (obj2.CompareTo(obj1));
            }
        }
        #endregion
    }
 
Now following is the code you need to put for sorting any collection of object. I have a collection of customers objects as

Customers[] objCustomers
 
convert this object to a generic list i.e.

List<Customers> lstCustomers = new List<Customers>(objCustomers);
 
lstCustomers.Sort(new GeneriComparer<Customers>(sortColumnName,GenericComparer<Customers>.SortOrder.Ascending));
 
again take the sorted list back to your collection i.e.
 
objCustomers = lstCustomers.ToArray();

This way you can customize sorting of your grid which is binded to a collection of objects. This is preety fast compared to datatable or dataview, where we need to convert and then sort.

Thank You,
 
Poonam Aswani
1 - 10 Next