Thursday, March 25, 2010
Copy Generic Collection List in DotNet
Anyway Coming to the Collection List Addition,
I would like to explain you with the following collection object.
EG:
Product - Object which has properties (ProductID, ProductName, ProductDescription, DateSold, DaysOnMarket and e.t.c)
SoldProductList - Generic collection object of type Product
PendingProductList - Generic collection object of type Product
ActiveProductList - Generic collection object of type Product
TotalProductList - Generic collection object of type Product
The business logic is to add all the three SOLD, PENDING and ACTIVE list collections to a single collection TOTALPRODUCT list object.
Initially I had my code to loop through each items of the 3 Collection List and add it to the TotalProductList. I was very much sure there should be some other efficient way to make it. As I googled, I found a solution for it. I implemented the following and this helped me in drastically reducing my code and increased the performance of the application flow.
Code:
TotalProductList.getRange(ActiveProductList.ToArray());
TotalProductList.getRange(PendingProductList.ToArray());
TotalProductList.getRange(SoldProductList.ToArray());
Interesting Right!!! Well to fundamentally explain this, DotNet framework has as inbuilt method (getRange) for each collection to copy Array of elements of SAME TYPE. Here we are converting the ActiveProductList generic collection to an Array ( here the Array will be created of same type Product ) and then appending to TotalProductList collection which is also of same Product type.
I hope this helps you do better coding. Please let me know your thoughts and comments on this post.
Happy coding. Have a great time.
Tuesday, January 12, 2010
Importing data to SQL Server from Excel file
This is all about exporting the Excel sheet to SQL Data source. You will need this in many instances to manipulate datas present in the sheet. These were the steps to be followed.
Step 1:
You have to check some basic configurations in your Surface Area Configuration of the SQL Server.
Please refer the following link to do these configurations:
http://www.kodyaz.com/articles/enable-Ad-Hoc-Distributed-Queries.aspx
Step 2:
Install Microsoft.ACE.OLEDB.12.0 component from this following link:
http://www.microsoft.com/downloads/details.aspx?FamilyID=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en
Step 3:
The DB script for importing datas from .xlsx(Excel) file to SQL Server 2005 is mentioned below.
Simple Importing:
SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;Database=C:\TestExcel.xlsx', 'SELECT * FROM [Sheet1$]');
Importing Data to Table:
SELECT * INTO [dbo].[ExcelTempTable] FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;Database=C:\TestExcel.xlsx', 'SELECT * FROM [Sheet1$]');
Note: This doesn't mean that the [ExcelTempTable] should be predefined. Its a table created dynamic with the columns from Excel sheet.
This would suffice for exporting data from .xlsx file to SQL Server. Happy coding.
Tuesday, December 8, 2009
Application Level Error Handling in .NET
The event Application_Error in the Global.asax file deals with this. You can add this Global.asax file in the root of your web application. Inside that place the following code.
void Application_Error(object sender, EventArgs e)
{
Server.Transfer("~/CustomErrors/ErrorHandlingPage.aspx?error=" + Server.GetLastError().Message);
}
This code will fetch the last error occurred in the application and redirects to the ErrorHandlingPage.aspx. Here you can get the error message from the query string 'error'. This is how it works.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String ErrorMsg;
ErrorMsg = Request.QueryString["error"].ToString();
LitError.Text = "Sorry for the inconvenience caused. We regret the situation. Please try after some time. The following exception occured - " + ErrorMsg;
//The below line is for publishing the error to the Exception Log - Specific to the application
ExceptionManager.Publish(ErrorMsg);
}
}
Its upto you to decide, whether to show the message to the user or make in entry in the exception log and notify user with custom error message. Thats it.
Happy coding. Have a good day.
Monday, October 19, 2009
AJAX implementation using POST method in .NET
The real implementation of the AJAX happens only with the JavaScript functions. Here you can really send the partial contents to the server and get back the desired results. There were two ways for the AJAX form posting.
1. GET method and
2. POST method.
Most people tend to go for the GET method since its easier to implement.(Particularly beginners). As you grow you have to be able to identify the instance where you are going to use(GET or POST method). In a simple way,
GET - should be used when a minimum amount of data is going to be passed to the server and collect all the information in a single AJAX call.
POST - when the request is going to be updated frequently and also the server data is going to be changed with the AJAX call then you have to go for POST. Also POST is secured compared to GET method since it doesn't expose the parameters(Query String values).
Here is the example where the POST implementation for simple Login.
EG:
Java script Function
function ajaxPOSTFunction(email,password)
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
if (xmlhttp.status == 200)
{
if(xmlhttp.responseText.match("success"))
{
window.location = '<%= ResolveClientUrl("../profile.aspx") %>';
}
else
{
document.getElementById("validateTips").innerHTML = xmlhttp.responseText;
}
}
}
}
//GET METHOD IMPLEMENTATION - Same implementation using GET - commented
//xmlhttp.open("GET","login.aspx?email=" + email + "&password=" + password,true);
//xmlhttp.send(null);
//POST METHOD IMPLEMENTATION
var params = "email="+email+"&password="+password;
xmlhttp.open("POST",'<%= ResolveClientUrl("../login.aspx") %>',true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
And here is the code for the login.aspx page - PageLoad() and Private method
Login.aspx
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim email As String = Request.Form("email")
Dim password As String = Request.Form("password")
AuthenticateUser(email, password)
Catch ex As Exception
Response.Write(ex.ToString())
End Try
End Sub
Public Sub AuthenticateUser(ByVal userName As String, ByVal password As String)
Dim ErrorBuilder As New StringBuilder
Dim responseStatus As Integer
Dim responseText As String = String.Empty
responseStatus = Me.Controller.AuthenticateUser(userName, password)
If responseStatus = Constants.ServiceResponseStatus.Success Then
responseText = "success"
End If
Select Case responseStatus
Case Constants.ServiceResponseStatus.Success
Response.Write(responseText)
Response.End()
Case Constants.ServiceResponseStatus.Failure
Response.Write("failure")
Response.End()
Case Constants.ServiceResponseStatus.Exception
Response.Write("There has been an internal error. Please try to login again!")
Response.End()
Case Else
Response.Write("The username or the password you provided was not a valid. Please login with valid username and password.")
Response.End()
End Select
End Sub
Wednesday, October 14, 2009
Printer Friendly Button in JS
Here we go.
EG: In the anchor tag just call the javascript function window.print().
javascript:window.print();
Click on the Print this page link to check out.
Print this Page
Really small piece of code right..
Friday, September 25, 2009
Text Formatting made Easy in ASP.NET
I initially thought I have to insert the '-' symbol at the index values. But my goodness, this was made so easy in .Net String Formatting.
For Example:
Dim phone as Integer = 123456890
String.Format("{0:###-###-####}", phone)
This will be displayed as 123-456-7890
Be a smart coder. Let me know if its useful. Happy Coding.
Wednesday, September 2, 2009
Reseed Identity Column in a Table
Resetting Current Identity Value to New Value
use DBNAME
go
dbcc checkident(TABLENAME, reseed,seed value)
For Eg:
dbcc checkident(dbo.[User],reseed,1342)
which served my purpose.
To Get Current Identity Value
Also this seems to be useful. This gives the current identity value of the table.
use DBNAME
go
dbcc checkident(TABLENAME, noreseed)
For Eg:
dbcc checkident(dbo.[User],noreseed)
Please let me know your thoughts. Have a good day.