Monday, 30 April 2012

ASP.net Maintain scrollbar position after asynchronous post back


In order to maintain scrollbar position after asynchronous post back it is not at all enough to include the MaintainScrollPositionOnPostBack in the page directive alone. We need to include the below JavaScript code just below ScriptManager tag. Because during asynchronous post back, only code within the ScriptManager tag will be executed within aspx page and after that the below JavaScript will be executed and it maintain the scrollbar position.


1. First include the maintain scroll bar position as in the below code.
<pages maintainScrollPositionOnPostBack="true" />

2. Second Include the JavaScript code below the ScriptManager tag

 <script type="text/javascript">
       window.scrollTo = function () { }
</script>

Sunday, 29 April 2012

SQL Execute SP using output parameters


In SQL when we think only function can return value that is not at true. Even stored procedure can return value using out parameters. Out parameter are so useful in stored procedure for returning values. It can be performed by introducing OUT keyword in the parameter list in an SP.

Consider this below sample example,

Stored Procedure
CREATE PROCEDURE Get_Customer_Order @orderID  INT, @customerName VARCHAR(100) OUTPUT
AS
SELECT customerName FROM CustomerOrderDetail
WHERE
OrderID = @orderID  

Execution
DECLARE @Name varchar(100)
Exec Get_Customer_Order 178623300, @Name OUT
Print @Name

Friday, 27 April 2012

ASP.net Copy using File Stream

This below code snippet will be so useful for copying the file from one physical location to another physical location in a server.  ASP.net has inbuilt classes IO.Filestream that is so useful for various file manipulation function.
Code
Public Shared Sub CopyFiles(ByVal srcPath_File As String,ByVal dstPath_File As String)

        Dim oFile As System.IO.FileInfo

        Dim oFileStream As System.IO.FileStream = Nothing
        Dim oFileStreamR As System.IO.FileStream = Nothing
        Try
            oFile = New System.IO.FileInfo(srcPath_File)
            oFileStream = oFile.OpenRead()

            Dim lBytes As Long = oFileStream.Length
            Dim fileData(lBytes) As Byte
            oFileStream.Read(fileData, 0, lBytes)

            If File.Exists(dstPath_File) ThenFile.Delete(dstPath_File)
            oFileStreamR = New System.IO.FileStream(dstPath_File, System.IO.FileMode.OpenOrCreate)
            oFileStreamR.Write(fileData, 0, fileData.Length)
            oFileStreamR.Flush()
            oFileStreamR.Close()
            oFileStreamR.Dispose()
        Catch ex As Exception
            Throw ex
        Finally
            oFileStream.Close()
            oFile = Nothing
            If oFileStreamR IsNot Nothing Then
                oFileStreamR = Nothing
            End If
        End Try
End Sub
Explanation of the code as below,
  1. Use System.IO namespace
  2. Create an instance for the fileinfo class to get the file information of the source file.
  3. Create two instances of filestream one for reading and other for writing the file.
  4. Find the length of the filestream object and store in a byte variable.
  5. Check to see the file already exist in the destination location. If file already exist in the location then delete the file.
  6. Using the filestream read instance read the content of the file and write the content in the target location using the filestream write instance.
  7. Flush and close the filestream write instance.
  8. Finally close the filestream instances.

ASP.net Dynamic MS Word Document creation from Word Template

1.  Create a Word document as per the need and place the bookmark for the text that need to be changed dynamically and save it in a location
2.  Add the Microsoft Object Library to the code
3. Imports Word = Microsoft.Office.Interop.word
4. Use the below code snippet in your asp.net application to create word document on a fly

Dim oWord As Word.Application
Dim oDoc As Word.Document
oWord = CreateObject("Word.Application")
oDoc = oWord.Documents.Open("<FILE LOCATION>")
With oDoc.Bookmarks
  .Item("<BOOKMARK NAME IN WORD DOC>")Range.Text = "<Either value from front end or value form database")
End With
oDoc.Save()
oDoc = Nothing
oWord = Nothing


Please post your queries incase of any doubts.

ASP.net Error Insufficient Privilege


Some time when we invoke a web page in browser may end up in this Server Unavailable error. Same code code execute fine from the visual studio but it wont work after deploying in the server. In this situation please check to see the eventviewer for the error in the deployed server.

Web page Error: Server Unavailable
Event Viewer: aspnet_wp.exe could not be launched because the username and/or password supplied in the processModel section of the config file are invalid.

Resolution:
1)      Open the “Machine.Config” in C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG
2)      Add the UserName=”SYSTEM’ in <ProcessModel> tag.

This worked fine for me and I have resolved this error.

Excel VLookup


At times we may end in searching a value in column of a sheet with other column in the same sheet or a different sheet. Here VLookup is function that is so useful to identify the value.  The most common definition available in internet is “Searches for a value in the first column of a table array and returns a value in the same row from another column in the table array”. The meaning of the sentence is we need to identify a value of a cell in one column from the other column in the same row. VLookup represents vertical lookup.

Syntax
VLOOKUP(<lookup value>,<table array>,< Column index number>,<range lookup>)
  • Lookup value is the value to search in the first column of the table array. Lookup_value can be a value or a reference. If lookup_value is smaller than the smallest value in the first column of table_array, VLOOKUP returns the #N/A error value.
  • Table array may contain two or more columns of data. Use a reference to a range or a range name. The values in the first column of table array are the values searched by lookup value. These values can be text, numbers, or logical values. Uppercase and lowercase texts are equivalent.
  • Column index number    The column number in table_array from which the matching value must be returned. A Column index number of 1 returns the value in the first column in table_array; a Column index number of 2 returns the value in the second column in table array, and so on. If Column index number is:Less than 1, VLOOKUP returns the #VALUE! error value.Greater than the number of columns in table_array, VLOOKUP returns the #REF! error value.
  • Range lookup    A logical value that specifies whether you want VLOOKUP to find an exact match or an approximate match:If TRUE or omitted, an exact or approximate match is returned. If an exact match is not found, the next largest value that is less than lookup_value is returned.The values in the first column of table array must be placed in ascending sort order; otherwise, VLOOKUP may not give the correct value.If FALSE, VLOOKUP will only find an exact match. In this case, the values in the first column of table_array do not need to be sorted. If there are two or more values in the first column of table_array that match the lookup_value, the first value found is used. If an exact match is not found, the error value #N/A is returned.


Example:
Here in this example I will use a sample Order Table with the Product table. Our intention is used to find the Product name from the product id from the Order table for Order Detail table.

A
B
C
Order
Customer Name
Order ID
Product Code
Cameron White
1
AT123
James Peterson
2
BG456
Andrew Thomas
3
BT456
James Peterson
4
CY956
Jason Taylor
5
DR098
James Peterson
6
BT456
Michel Adams
7
CY956

A
B
Product
Product Code
Product Name
AT123
Amber Light
BG456
Big Plug
BT456
Big Tatoo
CY956
Crimson yarn
DR098
Digital Diary
BG456
Big Plug
CY956
Crimson yarn

From the both these table we need to achieve the below result
A
B
Order Detail
Customer Name
Product Code
Cameron White
Amber Light
James Peterson
Big Plug
Andrew Thomas
Big Tatoo
James Peterson
Crimson yarn
Jason Taylor
Digital Diary
James Peterson
Big Tatoo
Michel Adams
Crimson yarn

Type the formula “=VLOOKUP (C4, A14:B21, 2, FALSE)” this Formula (fx) textbox in the excel document
C4 – Lookup value
A14:B21 – It is the table array in the order detail table
2 – Column Index
False – It is the exact match of the lookup value.
Then drag the cell till the end of the row and see the result.
Please your queries on this post and I will get to this very soon.

Thursday, 26 April 2012

Excel Short cut to generate MS SQL query from excel data

Just few days back I use to receive lot of raw data in excel to migrate into MS SQL server. I used some features in MS SQL management studio to upload the data from excel to target tables. It was so problematic that I could not able to migrate all the data from excel to MS SQL. Because some data got truncated, data type excel found to be mismatching, transferred data are not placed in correct target column in the target table, etc.   


To overcome this problem, I formatted the input Excel document as below,
  1. Arrange column in the excel document as that of the columns in the SQL table.
  2. Modify the data types of the columns in the excel document as that of columns in SQL table using some of the predefined functions available in excel. Some time it is not necessary to use the predefined function to format columns.
  3. Place the insert query [insert into <table_name> values (”] in one of the column in excel and drag it till the end where there is no record for that row.
  4. Similarly place the ['','] & ['')] in two separate columns and you should use two single codes in the beginning then only excel will recognize as a single quotes.
  5. Finally frame the formula in the order of columns to form a sql query.
  6. Go to the Function (fx) and type “=”
  7. Hold the control key (block plus symbol appears) and press on the cell and type “&”. Report the process until you form the SQL query.
  8. The formula appears as this “=A1&B1&C1&D1&F1&G1” Or else you predefined concatenate function as this “=CONCATENATE(A1,B1,C1,D1,F1,G1)”
  9. Drag the formula column till the end where there is no record for that row. Copy all formula cells and paste in sql management studio and execute it.
This is found be more helpful and less time consuming for preparing the query.

Please post me your queries if you have doubt in this post.

Wednesday, 25 April 2012

Excel Simple Short Cut to generate Macro code without writing


During many occasions I use to write macro code in excel and it will be so time consuming process or at some time it was so problematic to remember all the syntax and keywords used while writing the code.

Very often I use to notice an option in Excel called “Record Macros” But I don’t find any time to dig into this menu choice. Later I find out that there is an existing feature in excel (in all the versions 2003/2007/2010) underneath “Record Macros” to generate the macro code for whatever operation we process in excel document. Here I will show the sample which is developed in Excel 2007 version.

For all clarification or doubt please post your comment s and I will get back to you very soon.

Create an Excel Macro document <filename>.xlsm in the local path.

I will show a small sample dummy sales data as an example for populating macro
1. Please refer the data as in the below screen shot


2. Click on the developer tab -> Records Macros, it will pop up a small window as in the below screen shot and Click OK

3. Then I will select data and create a line chart as below.

4. Click on the developer tab -> Stop Record, it will pop up a small window as in the below screen shot and Click OK

5. In developer tab Click on the Visual Basic Editor icon and click on the Module item under tree menu in the visual basic editor window to see the generate code.


Tuesday, 24 April 2012

JavaScript Event Handlers


Event Handlers is one of the most important features of JavaScript. I came across a situation where I need to attach even to controls dynamically using JavaScript. So Event Handler helped me to finish of the task.  Different methods can be invoked from the same event handler and we can remove it whenever it is not necessary.

Types of Event Handlers as follows,

The addEventListener() Method
It actually allow you to specify a function to be executed for the event

Syntax: 
element.addEventListener('event_type', function_name, true_or_false);

Sample Eg:
var mypage= "http://www.ajaal.com";
var varCtrl = document.getElementById("btnRedirect");
varCtrl.addEventListener('click', function() { window.location = mypage;
}, false);

The removeEventListener()  Method
To remove an event whenever we don’t need we can use the removeEventListener() method.

Syntax:
element.removeEventListener('event_type', function_name, 
true_or_false);

The attachEvent() Method
The attachEvent() method works in a similar way to addEventListener(). However, it only
works with event bubbling.

Syntax
element.attachEvent(event_handler, function_name);

Sample Eg:
var mypage = " http://www.ajaal.com ";
var varCtrl = document.getElementById("btnRedirect");
varCtrl.attachEvent(onclick, function() { window.location = mypage; } );

Notice that this method does use the name of the event handler (onclick). Also, it does not
have the third option; it just uses event bubbling.

The detachEvent() Method
To remove an event, you would use the detachEvent() method:

Syntax
element.detachEvent(event_handler, function_name)

Please comment your suggestion on this post for further improvement.

Monday, 23 April 2012

Javascript Exception Handling

Exception Handling is one of the most important and essential while programming in JavaScript.  If the exception is not handled properly then we may end up in exclamatory mark that will appear in the left bottom corner of the page. This is due to some exception or error that is available in the executed page. These JavaScript is a client side script so execution failure occur only in the browser from the client end and not in server

There are two ways of handling exception.


1.  Placing the code between the try and catch block. It is the most the easiest approach for error such as “Object not Found” exception/error.
Eg:
try
{
//JavaScript Code
}
catch (e)
{
}
Code:
<HTML>
<HEAD>
<TITLE>Javascript Eg.</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function getValue() {
try{
var servervalue = "two";
for(var i=0; i<document.getElementById("ItemLists").options.length; i++) {  
if ( document.getElementById("ItemLists").options[i].text == servervalue )
{   
  document.getElementById("ItemLists").selectedIndex = i;       break;
}
}
}
catch(e){ alert('Control Not Found!!!');}
}
</SCRIPT>
</HEAD>
<BODY>
<P>
Sample Dropdownlist
<SELECT NAME="ItemList" onchange="Javascript:getValue();">
<OPTION VALUE="one">one
<OPTION VALUE="two">two
<OPTION VALUE="three">three
<OPTION VALUE="four">four
</SELECT></P>
</BODY>
</HTML>


2.  Another option is using null check, check to see a control available in the rendered page in the browser.
Eg:  If(Document.all("ItemLists") != null)


Code: 
<HTML>
<HEAD>
<TITLE>Javascript Eg.</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function getValue() {
var servervalue = "two";
//null check to see the control "ItemLists" available     in the html page
if (document.getElementById("ItemLists")!=null){
for(var i=0;  i<document.getElementById("ItemLists").options.length; i++)
{  
if (document.getElementById("ItemLists").options[i].text == servervalue )
 {   
  document.getElementById("ItemLists").selectedIndex = i;    
  break;  
 }
}
}
}
</SCRIPT>
</HEAD>
<BODY>
<P>
Sample Dropdownlist
<SELECT NAME="ItemList" onchange="Javascript:getValue();">
<OPTION VALUE="one">one
<OPTION VALUE="two">two
<OPTION VALUE="three">three
<OPTION VALUE="four">four
</SELECT></P>
</BODY>
</HTML>