Monday, September 23, 2013

Debugging Windows service while developing in Visual Studio 2010

1. Set your windows service project as the start up project.

2. Go to Project --> Properties --> Debug section --> set Configuration as "Debug"

3. Go to Project --> Properties --> Debug section --> Check "Enable unmanaged code debugging" checkbox.

4. Go to Project --> Properties --> Debug section --> set required paramenters (to be used in service OnStart())

5. Go to Project --> Properties --> Build section --> set required platform targets (in case of oracle database (oracle.dataaccess.dll), we need to set the platform target as similar to the oracle client version installed in the machine. You can install 32bit oracle client in 64 machine.)

Thursday, August 1, 2013

Log Parser Lizard


Log Parser Lizard

Log Parser is a very powerful and versatile query software tool that provides universal query access to text-based data, such as log files, XML files, and CSV files, as well as key data sources on the Microsoft Windows operating system, such as the event log, IIS log, the registry, the file system, and the Active Directory services. Because the command-line interface is not very intuitive, we have created Log Parser Lizard, a free GUI tool for managing queries and exporting results to Excel and charts. 
  
 

Tuesday, July 30, 2013

Understanding char, nchar, varchar and nvarchar

What they store?

  • nchar and nvarchar can store Unicode characters.
  • char and varchar cannot store Unicode characters.
  • char and nchar are fixed-length which will reserve storage space for number of characters you specify even if you don't use up all that space.
  • varchar and nvarchar are variable-length which will only use up spaces for the characters you store. It will not reserve storage like char or nchar.
  • nchar and nvarchar will take up twice as much storage space, so it may be wise to use them only if you need Unicode support.

Sizes they need

  • char    =  fixed-length character data with a maximum length of 8000 characters.
  • nchar  =  fixed-length unicode data with a maximum length of 4000 characters.
  • Char   =  8 bit length
  • NChar =  16 bit length

Summary

First, char and nchar will always use a fixed amount of storage space, even when the string to be stored is smaller than the available space, whereas varchar and nvarchar will use only as much storage space as is needed to store that string (plus two bytes of overhead, presumably to store the string length). So remember, "var" means "variable", as in variable space.

The second major point to understand is that, nchar and nvarchar store strings using exactly two bytes per character, whereas char and varchar use an encoding determined by the collation code page, which will usually be exactly one byte per character (though there are exceptions, see below). By using two bytes per character, a very wide range of characters can be stored, so the basic thing to remember here is that nchar and nvarchar tend to be a much better choice when you want internationalization support, which you probably do.

Now for some some finer points.

First, nchar and nvarchar columns always store data using UCS-2. This means that exactly two bytes per character will be used, and any Unicode character in the Basic Multilingual Plane (BMP) can be stored by an nchar or nvarchar field. However, it is not the case that any Unicode character can be stored. For example, according to Wikipedia, the code points for Egyptian hieroglyphs fall outside of the BMP. There are, therefore, Unicode strings that can be represented in UTF-8 and other true Unicode encodings that cannot be stored in a SQL Server nchar or nvarchar field, and strings written in Egyptian hieroglyphs would be among them. Fortunately your users probably don't write in that script, but it's something to keep in mind!

Another confusing but interesting point that other posters have highlighted is that char and varchar fields may use two bytes per character for certain characters if the collation code page requires it. (Martin Smith gives an excellent example in which he shows how Chinese_Traditional_Stroke_Order_100_CS_AS_KS_WS exhibits this behavior. Check it out.)


UPDATE: As of SQL Server 2012, there are finally code pages for UTF-16, for example Latin1_General_100_CI_AS_SC, which can truly cover the entire Unicode range.

Thursday, May 30, 2013

Dependency Injection

Basically, instead of having your objects creating a dependency or asking a factory object to make one for them, you pass the needed dependencies in to the constructor, and you make it somebody else's problem (an object further up the dependency graph, or a dependency injector that builds the dependency graph). A dependency as I'm using it here is any other object the current object needs to hold a reference to.

One of the major advantages of dependency injection is that it can make testing lots easier. Suppose you have an object which in its constructor does something like:

public SomeClass() {
myObject = Factory.getObject();
}

This can be troublesome when all you want to do is run some unit tests on SomeClass, especially if myObject is something that does complex disk or network access. So now you're looking at mocking myObject but also somehow intercepting the factory call. Hard. Instead, pass the object in as an argument to the constructor. Now you've moved the problem elsewhere, but testing can become lots easier. Just make a dummy myObject and pass that in. The constructor would now look a bit like:

public SomeClass (MyClass myObject) {
this.myObject = myObject;
}

Most people can probably work out the other problems that might arise when not using dependency injection while testing (like classes that do too much work in their constructors etc.) Most of this is stuff I picked up on the Google Testing Blog, to be perfectly honest...


http://stackoverflow.com/questions/130794/what-is-dependency-injection

Tuesday, April 17, 2012

Going to work on Visual Studio 2010, .Net Framework 4.0

Are you going to work on Visual Studio 2010, .Net Framework 4.0?

Have a look on these links first.

Breaking changes in .NET 4.0:  http://msdn.microsoft.com/en-us/library/ee855831%28VS.100%29.aspx

Breaking changes in ASP.NET 4.0:  http://www.asp.net/whitepapers/aspnet4/breaking-changes

Things we need to be aware of when using named parameters and optional parameters:  http://msdn.microsoft.com/en-us/vstudio/hh913013.aspx

Wednesday, March 7, 2012

Why doesn't C# support multiple inheritance?

This answer is from Chris Brumme via the following post. I've copied the text in here in case the post disappears.
There are a number of reasons we don't implement Multiple Implementation Inheritance directly. (As you know, we support Multiple Interface Inheritance).
However, I should point out that it's possible for compilers to create MI for their types inside the CLR. There are a few rough edges if you go down this path: the result is unverifiable, there is no interop with other languages via the CLS, and in V1 and V1.1 you may run into deadlocks with the OS loader lock. (We're fixing that last problem, but the first two problems remain). The technique is to generate some VTables in RVA-based static fields. In order to deposit the addresses of managed methods (which probably haven't been JITted yet), you use the VTFixup construct. This construct is a table of triplets. The triplets consist of a token to a managed method, an address in your image that should be fixed up (in this case, a slot of the VTable you are creating in the RVA-based static), and some flags. The possible flags are described in corhdr.h and they allow you to specify 32- vs. 64-bit pointer sizes, control over virtual behavior, and whether some reverse-PInvoke behavior should be applied in the form of a thunk that eventually dispatches to the managed method. If we are performing an unmanaged->managed transition, you also have some control over which AppDomain should be selected for us to dispatch the call. However, one of these options (COR_VTABLE_FROM_UNMANAGED_RETAIN_APPDOMAIN) doesn't exist in V1. We added it in V1.1.
There are several reasons we haven't provided a baked-in, verifiable, CLS-compliant version of multiple implementation inheritance:
1. Different languages actually have different expectations for how MI works. For example, how conflicts are resolved and whether duplicate bases are merged or redundant. Before we can implement MI in the CLR, we have to do a survey of all the languages, figure out the common concepts, and decide how to express them in a language-neutral manner. We would also have to decide whether MI belongs in the CLS and what this would mean for languages that don't want this concept (presumably VB.NET, for example). Of course, that's the business we are in as a common language runtime, but we haven't got around to doing it for MI yet.
2. The number of places where MI is truly appropriate is actually quite small. In many cases, multiple interface inheritance can get the job done instead. In other cases, you may be able to use encapsulation and delegation. If we were to add a slightly different construct, like mixins, would that actually be more powerful?
3. Multiple implementation inheritance injects a lot of complexity into the implementation. This complexity impacts casting, layout, dispatch, field access, serialization, identity comparisons, verifiability, reflection, generics, and probably lots of other places.
It's not at all clear that this feature would pay for itself. It's something we are often asked about. It's something we haven't done due diligence on. But my gut tells me that, after we've done a deep examination, we'll still decide to leave the feature unimplemented.
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
Now come to the actual implementation part. 


What happens when we implement tow interfaces which are having same signature for a method? Most the developers think this will give compilation error. Some people would say, we should give the interface name as the prefix in the method signature while implementing in the class. 
First of all compiler will not give compilation error. And it is not necessary that you should give the interface name as the prefix. If you just use the same signature, compiler will understand that you are giving the implementation.
But if you give the interface name as the prefix, you cannot access the method directly. You should typecast the object as the interface type to use method.


If you see the following example, you can understand this. 


public class Emp : IA, IB
{
    //1. Either dont mention the interface
    public string methodA()
    {
        return "Class Emp's output";
    }
    string IA.methodA()
    {
        return "Interface IA's output";
    }
    string IB.methodA()
    {
        return "Interface IB's output";
    }
}

Now invoking code looks like

Emp emp = new Emp();
emp.methodA();
IA a = (IA)emp;
a.methodA();
IB b = (IB)emp;
b.methodA();

Now if you print the output of the three method calls you wiil get

Class Emp's output 
Interface IA's output 
Interface IB's output

Thursday, February 16, 2012

ASP.NET Response.Redirect to new window

Method1

You need to add the following to your server side link/button:

OnClientClick="aspnetForm.target ='_blank';"

My entire button code looks something like:

<asp:LinkButton ID="myButton" runat="server" Text="Click Me!" OnClick="myButton_Click" OnClientClick="aspnetForm.target ='_blank';"/>

Method 2


In the server side OnClick I do a Response.Redirect("MyPage.aspx"); and the page is opened in a new window.

The other part you need to add is to fix the form's target otherwise every link will open in a new window. To do so add the following in the header of your POPUP window.

<script type="text/javascript">
        function fixform() {
            if (opener.document.getElementById("aspnetForm").target != "_blank") return;

            opener.document.getElementById("aspnetForm").target = "";
            opener.document.getElementById("aspnetForm").action = opener.location.href;
            }
</script>

and

<body onload="fixform()">

Tuesday, November 15, 2011

Test If Date Ranges Overlap

Test If Date Ranges Overlap

A commonly-used idiom for determining if one range of dates overlaps with another range of dates

Problem: Given two date ranges, each with start and end dates (and possibly times), how do you determine if the ranges overlap?

Solution:

Testing the range "start1 to end1" against the range "start2 to end2" is done by testing if...

	( start1 <= end2 and start2 <= end1 )
If TRUE, then the ranges overlap.

If the ranges do not include the "end" value itself, then use "<" instead of "<=" in the comparisons.

Important Assumption:

This assumes that start date <= end date in each range. This can also be stated as...

	( start1 <= end1 and start2 <= end2 )
For discussion of what to do if this is not true, see below.

Applicability: Is not limited to date/time comparisons; can also be used for ranges of numbers, names, and any other data type where ranges are meaningful.

Alternate Expression:

	not (end1 < start2 or end2 < start1)



The expression in brackets is true when one range is entirely to the left or right of the other. This condition is pretty easy to visualize. The ranges overlap if and only if it is false.
Implementation: See MartinFowler's RangePattern for implementation details. http://www.martinfowler.com/ap2/range.html

[CategoryPattern]

 

Check the original post http://c2.com/cgi/wiki?TestIfDateRangesOverlap for more information

Friday, November 11, 2011

SecurityTrimmingEnabled Issue

We Faced a weird issue in our application today. We have a horizontal menu in the header portion of our application.

In development environment all menu items are getting rendered.

WithAllMenu

Some of the menu items refered the web links which links are part of another application.

But when we drop the executables to the QA environment, above mentioned menu items are not rendered.

WithoutAllMenu

The QA environment is SSL enabled application and the outside application is non-SSL enabled.

So we found that, when the Webmenu.Sitemap constructs the menu,
it does not show the non-SSL links when those links are invoked from SSL enabled.

We did not get any warning messages. After analyzed a lot, we understand that, we have to switch off the setting

SecurityTrimmingEnabled to false since we are not using windows accounts for roled based menu.

code

To know more about that visit the following links.

http://blogs.msdn.com/b/dannychen/archive/2006/03/16/553005.aspx

Friday, October 21, 2011

Drupal


Drupal
Drupal is an open source content management platform powering millions of websites and applications. It’s built, used, and supported by an active and diverse community of people around the world.


Why Choose Drupal?
Use Drupal to build everything from personal blogs to enterprise applications. Thousands of add-on modules and designs let you build any site you can imagine.
Drupal is a free software package that allows you to easily organize, manage and publish your content, with an endless variety of customization.

Drupal's History
Dries Buytaert began the Drupal software as an message board in 1999. Within a year or so, more people became interested using and contributing to Drupal, so the project was made open source.
Drupal.org came online in 2001, and the Drupal community gained momentum in 2005 with several code sprints and conferences. Read more about the full history of Drupal and Druplicon.


Commercial Services
As well as the community, there are many dedicated companies in the Marketplace to help with your Drupal project. Providing expertise and a deeper understanding, they can help with design, development, hosting, spam blocking, theming, training, and more.


Who's Using Drupal
From local businesses to global corporations, diverse organizations use Drupal

Friday, September 23, 2011

Disabling Script Debugging

If you are using IE8+, you have to use a command line to disable script debugging.  Disabling script debugging can speed up your debugger a lot, so you might want to have it disabled unless you need it.

If you’re on a 64-bit Windows, make a batch file disable:

c:\windows\syswow64\reg add HKLM\SOFTWARE\Microsoft\VisualStudio\9.0\AD7Metrics\Engine\{F200A7E7-DEA5-11D0-B854-00A0244A1DE2} /v ProgramProvider /d {170EC3FC-4E80-40AB-A85A-55900C7C70DE} /f

enable:

c:\windows\syswow64\reg add HKLM\SOFTWARE\Microsoft\VisualStudio\9.0\AD7Metrics\Engine\{F200A7E7-DEA5-11D0-B854-00A0244A1DE2} /v ProgramProvider /d {4FF9DEF4-8922-4D02-9379-3FFA64D1D639} /f

For 32-bit windows, just remove the c:\windows\syswow64\ part.

I added these two batch files to my External Tools  in VS (Tools->External Tools) for quick access.

12

 

Hopefully you find this useful!

Friday, August 19, 2011

The 101 Most Useful Websites

 

most useful websitesAs we quickly approach the dawn of a new year, here are my picks for the 101 most useful websites of the year 2010.

The list primarily highlights the lesser-known or undiscovered websites and misses out all-time favorites like Google Docs, Wikipedia or IMDB that most of us are already aware of.

 

Useful Websites Worth a Bookmark!

The sites mentioned below, well most of them, solve at least one problem really well and they all have simple web addresses (URLs) that you can easily learn by heart thus saving you a trip to Google.

In a hurry? Download this list as a PDF eBook and read it anywhere.

01. screenr.com – record movies of your desktop and send them straight to YouTube.
02.
bounceapp.com – for capturing full length screenshots of web pages.
03.
goo.gl – shorten long URLs and convert URLs into QR codes.
04.
untiny.me – find the original URLs that's hiding behind a short URLs.
05.
localti.me – know more than just the local time of a city
06.
copypastecharacter.com – copy special characters that aren't on your keyboard.
07.
topsy.com – a better search engine for twitter.
08.
fb.me/AppStore – search iOS app without launching iTunes.
09.
iconfinder.com – the best place to find icons of all sizes.
10.
office.com – download templates, clipart and images for your Office documents.
11.
woorank.com – everything you wanted to know about a website.
12.
virustotal.com – scan any suspicious file or email attachment for viruses.
13.
wolframalpha.com – gets answers directly without searching  - see more wolfram tips.
14.
printwhatyoulike.com – print web pages without the clutter.
15.
joliprint.com – reformats news articles and blog content as a newspaper.
16.
isnsfw.com – when you wish to share a NSFW page but with a warning.
17.
e.ggtimer.com – a simple online timer for your daily needs.
18.
coralcdn.org – if a site is down due to heavy traffic, try accessing it through coral CDN.
19.
random.org – pick random numbers, flip coins, and more.
20.
mywot.com – check the trust level of any website - example.
21.
viewer.zoho.com – Preview PDFs and Presentations directly in the browser.
22.
tubemogul.com – simultaneously upload videos to YouTube and other video sites.
23.
truveo.com – the best place for searching web videos.
24.
scr.im – share you email address online without worrying about spam.
25.
spypig.com – now get read receipts for your email.
26.
sizeasy.com – visualize and compare the size of any product.
27.
whatfontis.com – quickly determine the font name from an image.
28.
fontsquirrel.com – a good collection of fonts – free for personal and commercial use.
29.
regex.info – find data hidden in your photographs – see more EXIF tools.
30.
tineye.com – this is like an online version of Google Googles.
31.
iwantmyname.com – helps you search domains across all TLDs.
32.
tabbloid.com – your favorite blogs delivered as PDFs.
33.
join.me – share you screen with anyone over the web.
34.
onlineocr.net – recognize text from scanned PDFs and images – see other OCR tools.
35.
flightstats.com - Track flight status at airports worldwide.
36.
wetransfer.com – for sharing really big files online.
37.
pastebin.com – a temporary online clipboard for your text and code snippets.
38.
polishmywriting.com – check your writing for spelling or grammatical errors.
39.
awesomehighlighter.com – easily highlight the important parts of a web page.
40.
typewith.me – work on the same document with multiple people.
41.
whichdateworks.com – planning an event? find a date that works for all.
42.
everytimezone.com – a less confusing view of the world time zones.
43.
warrick.cs.odu.edu – you'll need this when your bookmarked web pages are deleted.
44.
gtmetrix.com – the perfect tool for measuring your site performance online.
45.
imo.im - chat with your buddies on Skype, Facebook, Google Talk, etc. from one place.
46.
translate.google.com – translate web pages, PDFs and Office documents.
47.
youtube.com/leanback – enjoy a never ending stream of YouTube videos in full-screen.
48.
similarsites.com – discover new sites that are similar to what you like already.
49.
wordle.net – quick summarize long pieces of text with tag clouds.
50.
bubbl.us – create mind-maps, brainstorm ideas in the browser.
51.
kuler.adobe.com – get color ideas, also extract colors from photographs.
52.
followupthen.com – setup quick reminders via email itself.
53.
lmgtfy.com – when your friends are too lazy to use Google on their own.
54.
tempalias.com – generate temporary email aliases, better than disposable email.
55.
pdfescape.com – lets you can quickly edit PDFs in the browser itself.
56.
faxzero.com – send an online fax for free – see more fax services.
57.
feedmyinbox.com – get RSS feeds as an email newsletter.
58.
isendr.com – transfer files without uploading to a server.
59.
tinychat.com – setup a private chat room in micro-seconds.
60.
privnote.com – create text notes that will self-destruct after being read.
61.
flightaware.com – live flight tracking service for airports worldwide.
62.
boxoh.com – track the status of any shipment on Google Maps – alternative.
63.
chipin.com – when you need to raise funds online for an event or a cause.
64.
downforeveryoneorjustme.com – find if your favorite website is offline or not?
65.
example.com – this website can be used as an example in documentation.
66.
whoishostingthis.com – find the web host of any website.
67.
google.com/history – found something on Google but can't remember it now?
68.
errorlevelanalysis.com – find whether a photo is real or a photoshopped one.
69.
google.com/dictionary – get word meanings, pronunciations and usage examples.
70.
urbandictionary.com – find definitions of slangs and informal words.
71.
seatguru.com – consult this site before choosing a seat for your next flight.
72.
sxc.hu – download stock images absolutely free.
73.
zoom.it – view very high-resolution images in your browser without scrolling.
74.
wobzip.org – unzip your compressed files online.
75.
vocaroo.com – record your voice with a click.
76.
scribblemaps.com – create custom Google Maps easily.
77.
buzzfeed.com – never miss another Internet meme or viral video.
78.
alertful.com – quickly setup email reminders for important events.
79.
encrypted.google.com – prevent your ISP and boss from reading your search queries.
80.
formspring.me – you can ask or answer personal questions here.
81.
snopes.com – find if that email offer you received is real or just another scam.
82.
typingweb.com – master touch-typing with these practice sessions.
83.
mailvu.com – send video emails to anyone using your web cam.
84.
ge.tt – quickly send a file to someone, they can even preview it before downloading.
85.
timerime.com – create timelines with audio, video and images.
86.
stupeflix.com – make a movie out of your images, audio and video clips.
87.
aviary.com/myna – an online audio editor that lets record, and remix audio clips online.
88.
noteflight.com – print music sheets, write your own music online (review).
89.
disposablewebpage.com – create a temporary web page that self-destruct.
90.
namemytune.com – when you need to find the name of a song.
91.
homestyler.com – design from scratch or re-model your home in 3d.
92.
snapask.com – use email on your phone to find sports scores, read Wikipedia, etc.
93.
teuxdeux.com – a beautiful to-do app that looks like your paper dairy.
94.
livestream.com – broadcast events live over the web, including your desktop screen.
95.
bing.com/images – automatically find perfectly-sized wallpapers for mobiles.
96.
historio.us – preserve complete web pages with all the formatting.
97.
dabbleboard.com – your virtual whiteboard.
98.
whisperbot.com – send an email without using your own account.
99.
sumopaint.com – an excellent layer-based online image editor.
100.
lovelycharts.com – create flowcharts, network diagrams, sitemaps, etc.
101.
nutshellmail.com – Get your Facebook and Twitter streams in your inbox.

Also see: Best of the Web

Tuesday, August 9, 2011

Identifying value changed controls while submitting

Most of the application developers face the common requirement of giving alert message or showing a popup when particular set of controls are

changed. Consider the following example.

 

Requirement: The alert message or a popup should be shown only when the Language, Timezone and Country controls are changed. If those controls are not

changed, just save the imformation submitted.

 

 

<table cellspacing="0" cellpadding="0" border="0">

        <tr>

            <td>

                <asp:Label ID="Label1" runat="server" Text="Language:" AssociatedControlID="LanguageDropDownList"

                    EnableViewState="False" />

            </td>

            <td>

                <asp:DropDownList ID="DropDownList1" runat="server" EnableViewState="False">

                </asp:DropDownList>

            </td>

        </tr>

        <tr>

            <td>

                <asp:Label ID="Label2" runat="server" Text="Timezone:" AssociatedControllID="TimeZonesDropDownList"

                    EnableViewState="False" />

            </td>

            <td>

                <asp:DropDownList ID="DropDownList2" runat="server" EnableViewState="False">

                </asp:DropDownList>

            </td>

        </tr>

        <tr>

            <td>

                <asp:Label ID="CountryLabel" runat="server" Text="Country:" EnableViewState="False" />

            </td>

            <td>

                <asp:TextBox ID="CountryTextBox" runat="server" Text="">

                </asp:TextBox>

            </td>

        </tr>

    </table>

    <table cellspacing="0" cellpadding="0" border="0">

        <tr>

            <td>

                <asp:Label ID="NameLabel" runat="server" Text="Name:" EnableViewState="False" />

            </td>

            <td>

                <asp:TextBox ID="NameTextBox" runat="server" Text="">

                </asp:TextBox>

            </td>

        </tr>

        <tr>

            <td>

                <asp:Label ID="RoleLabel" runat="server" Text="Role:" AssociatedControlID="RoleDropDownList"

                    EnableViewState="False" />

            </td>

            <td>

                <asp:DropDownList ID="RoleDropDownList" runat="server" EnableViewState="False">

                </asp:DropDownList>

            </td>

            <tr>

    </table>

 

 

Logic 1: Setting a flag when control value changed

 

1. To address this requirement, developers used the logic of setting a flag to true whenever any of the required controls is changed.

 

var isChanged = false;

 

function changeStatus()

{

      if(!isChanged) isChanged=true;

}

 

The javascript method changeStatus() will be called for Language, Timezone and Country controls. Based on the flag value, the decision of

showing the alert/popup or not is taken. This logic has some flaws. When the user changes the control value and immediately set back to the old

value, the flag is still set to true. The logic fails. Then we need to find out the solution for not setting true while the value is set back to old.

 

Logic 2: Compare the populated value and current value

 

There is another different  logic for the given requirement. On server side page_load (..) method, while populating the controls get the values of

required controls and store it in a hidden field.

 

if(!IsPostback)

{

      PopulateControls();

}

 

private populateControls()

{

..

..

 

    initialValueHiddenField.Value = LanguageDropDownList.SelectedValue + TimeZonesDropDownList.SelectedValue + CountryTextBox.Text;

}

 

 

At the time of submitting, on client side get the concatenated values and compare with the populated values to decide showing the popup.

 

function SubmitButtonClientClick()

{

      var actualValue = document.getElementById('LanguageDropDownList').options ......

                  + document.getElementById('TimezonDropDownList').options ......;

                  + document.getElementById('CountryTextBox').value;

 

      if(document.getElementById('initialValueHiddenField').value == actualValue)

      {

            return ShowPopup();

      }

}

 

Logic 3: Check the initial value and current value using JQuery

 

Set an Id attribute to the table where the required controls are there.

 

<table cellspacing="0" cellpadding="0" border="0" id="settingsTable">

 

Now the following client side methods should be written.

 

$(document).ready(function() {

      initialState = getState();

}

function getState()

        {

              var state = "";

              $('#settingstable input, #settingstable select).each( function() {

                      //for checkbox controls val() method always returns "on" irrespective of the checked/unchecked state.

                      //so get the checked/unchecked value only for checkboxes. For other controls, get the val()

                      if($(this).val()=="on"){

                          state += $(this).is(':checked');

                      }

                      else{

                          state += $(this).val();

                      }

              });

              return state;

        }

function SubmitButtonClientClick()

{

      if(initialState  == getState())

      {

            return ShowPopup();

      }

}

 

Since we did not use the ID property of the controls, when new controls are introduced, we should just add to the settingstable.

So this logic will be more effective. As we are using JQuery no need to worry about the browser compatibility.

Thursday, July 28, 2011

Quick Test Professional (QTP)

Introduction

Quick Test Professional (QTP) is an automated functional Graphical User Interface (GUI) testing tool that allows the automation of user actions on a web or client based computer application.

It is primarily used for functional regression test automation. QTP uses a scripting language built on top of VBScript to specify the test procedure, and to manipulate the objects and controls of the application under test.

Contents:

Wednesday, June 29, 2011

An OLE DB Provider was not specified in the ConnectionString. An example would be, 'Provider=SQLOLEDB;'.


We are using typed dateset in DataAccess layer. I faced a weird issue while trying to add a new column with some of the datatables in the typed dataset for eg. USER table. But I can edit datatables of some other typed datasets which are also resides in the same location.

To add the column, I right-clicked on the DataTable. In the quick menu, i have selected the Add->columns. Entered new column name. When i pressed the save option in the Visual Studio, i got the following message.
"An OLE DB Provider was not specified in the ConnectionString.  An example would be, 'Provider=SQLOLEDB;'."

Finally. we resolved this issue by simply removing some annotaion tags in the dataset. Following are the steps to do that.

1. Open the typed dataset in Xml editor( Right click the *.axd file --> open with --> Xml Editor (default))
2. Find for <xs:annotation> tag.
3. Remove entire tag.(There will be some inner tags. if you want take a back up of those lines, do it)
4. Save the file.
5. Close the Xml view.
6. Once again open the typed dataset in the Dataset designer.
7. Try to add the columns.
Now you will be able to add/edit columns. I don't know what actually happens!!

Thursday, May 19, 2011

Different ways to create excel files

I Just analyzed the methodologies used to read/write excel files and listed the pros and cons below.

OpenXML (Office 2007 .XLSX)

Pros:

  • Reliable as this is a Microsoft’s product.
  • Native Excel format
  • Supports all Excel features
  • Do not require an install copy of Excel
  • Open XML SDK 2.o Productivity tool to generate code.

Cons:

  • Limited compatibility outside Excel 2007
  • Complicated unless you're using an expensive third party component

NPOI

Pros:

  • Easy to use and similar to existing SyncFusion code.
  • Do not require an install copy of Excel
  • Excel Chart, Pivot Table, Auto filter on columns, Insert images in header or footer are supported in NPOI 1.2.3 and later versions.
  • Supports Office Open Xml (OOXML) format also.(using ExcelPackage)

Cons:    

COM Interop

Pros:

  • Uses native Microsoft libraries
  • Read support for native documents

Cons:

  • Very slow
  • Dependency/version matching issues
  • Concurrency/data integrity issues for web use when reading
  • Scaling issues for web use (different from concurrency): need to create many instances of heavy Excel app on the server
  • Requires Windows

SpreadSheetML (open format XML)

Pros:

  • Supports most Excel features: formatting, styles, formulas’, multiple sheets per workbook
  • Excel does not need to be installed to use it
  • No third party libraries needed - just write out your xml
  • Documents can be opened by Excel XP/2003/2007

Cons:

  • Lack of good documentation
  • Not supported in older versions of Excel (pre-2000)
  • Write-only, in that once you open it and make changes from Excel it's converted to native Excel.
  • Apart from these, there are some more third party tools available.
  1. Spreadsheetgear http://www.spreadsheetgear.com (License required)

They are claiming that it is faster than Open XMl SDK 2.0.  We can find a testimonial from MSN project manager saying MSN is using spreadsheetgear in the home page.

  1. Aspose (http://www.aspose.com/categories/.net-components/aspose.total-for-.net/default.aspx)  (License required)
  2. MyXlshttp://sourceforge.net/projects/myxls/ (Freeware)

Monday, May 2, 2011

Nullable Types in C#

Nullable types are instances of the System.Nullable<T> struct.

In C# 2.0 and above, you can store null value in any of your datatypes. But the datatype is little bit different.

We know that bool type will hold either true or false. But nullable bool will allow you to assign null also.

Characteristics:

Value Type

Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)

Assign a value to a nullable type in the same way as for an ordinary value type, for example

         int? i = 10;

         double? d1 = 3.14;

         bool? flag = null;

         char? letter = 'a';

         int?[] arr = new int?[10];

 

GetValueOrDefault

Use the System.Nullable.GetValueOrDefault property to return either the assigned value, or the default value for the underlying type if the value is null, for example

int x? = 10;

int j = x.GetValueOrDefault();

HasValue & Value

Use the HasValue and Value read-only properties to test for null and retrieve the value, for example

if (x.HasValue) j = x.Value;

The HasValue property returns true if the variable contains a value, or false if it is null.

The Value property returns a value if one is assigned, otherwise a System.InvalidOperationException is thrown.

The default value for a nullable type variable sets HasValue to false. The Value is undefined.

Conversions

Explicit Conversions:

A nullable type can be cast to a regular type, either explicitly with a cast, or by using the Value property. For example:

         int? n = null;

 

         //int m1 = n;      // Will not compile.

         int m2 = (int)n;   // Compiles, but will create an exception if x is null.

         int m3 = n.Value;  // Compiles, but will create an exception if x is null.

 

Implicit Conversions:

The conversion from an ordinary type to a nullable type, is implicit.

         int? n2;

         n2 = 10;  // Implicit conversion.

Operators

The predefined unary and binary operators and any user-defined operators that exist for value types may also be used by nullable types.

         int? a = 10;

         int? b = null;

 

         a++;         // Increment by 1, now a is 11.

         a = a * 10;  // Multiply by 10, now a is 110.

         a = a + b;   // Add b, now a is null.

 

 

?? operator

Use the ?? operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type.

Example 1

         int? c = null;

         // d = c, unless c is null, in which case d = -1.

         int d = c ?? -1;

 

   Example 2

         int? e = null;

         int? f = null;

 

         // g = e or f, unless e and f are both null, in which case g = -1.

         int g = e ?? f ?? -1;

 

 

 Boxing Nullable Types

                Keep in mind that nullable types are value types and can hold null values whereas Reference types hold null value by default.

Objects based on nullable types are only boxed if the object is non-null. If HasValue is false, the object reference is assigned to null instead of boxing. For example:

bool? b = null;

      object o = b;

// Now o is null.

If the object is non-null -- if HasValue is true -- then boxing occurs, but only the underlying type that the nullable object is based on is boxed. Boxing a non-null nullable value type boxes the value type itself, not the System.Nullable<T> that wraps the value type. For example:

bool? b = false;

      int? i = 44;

      object bBoxed = b; // bBoxed contains a boxed bool.

      object iBoxed = i; // iBoxed contains a boxed int.

The two boxed objects are identical to those created by boxing non-nullable types. And, just like non-nullable boxed types, they can be unboxed into nullable types, as in the following example:

bool? b2 = (bool?)bBoxed;    

      int? i2 = (int?)iBoxed;

Identifying Nullable Types

We can identify the nullable types using the following methods.

         1. System.Type

         2. System.Reflection

        3. is operator

Using System. Type

We can use the C# typeof operator to create a Type object that represents a Nullable type:

         System.Type type = typeof(int?);

Using System.Reflection

You can also use the classes and methods of the System.Reflection namespace to generate Type objects that represent Nullable types.

 

int? i = 5;

Type t = i.GetType();

      Console.WriteLine(t.FullName); //"System.Int32"

The C# is operator also operates on a Nullable's underlying type. Therefore you cannot use is to determine whether a variable is a Nullable type.

  static void Main(string[] args)

        {

            int? i = 5;

            if (i is int) // true

            {

                //

            }

        }