Monday, December 22, 2008

C# Program to display Prime Number

Program to display the PrimeNumber

public class PrimeNumber
{
public void DisplayPrimeNumberUpTO(string number)
{
int max = int.Parse(number);
List previousPrimes = new List();
previousPrimes.Add(2);
if (max < 2) return; // none
for (int i = 3; i <= max; i++)
{
int maxDivisor = (int)Math.Floor(Math.Sqrt(i));
bool foundDivisor = false;
for (int j = 0; j < previousPrimes.Count; j++)
{
if (previousPrimes[j] > maxDivisor)
break;
if ((i % previousPrimes[j]) == 0)
{
foundDivisor = true;
}
}
if (!foundDivisor)
{
previousPrimes.Add(i);
}
}
for (int i = 0; i < previousPrimes.Count; i++)
{
Console.WriteLine("Prime: {0}", previousPrimes);
}
}
}

Calculate factorial.

C# Program to calculate the factorial.

public class Factorial
{
public long FactorialCalculate(long val)
{
return val == 1 ? val : val * FactorialCalculate(val - 1);
}
}

A constructor can call another overloaded constructor

A constructor can call another overloaded constructer but there is a trick to make this call possible.

So in the following example when you create the instance of CallConstructor class without parameter constructor. This will internally call the constructor with parameter.

below is the code for the same.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InterviewCodePractice.CallConstructor
{
public class CallConstructor
{
public CallConstructor()
: this(5)
{
System.Windows.Forms.MessageBox.Show("Default");
}
public CallConstructor(int i)
{
System.Windows.Forms.MessageBox.Show("parameter");
}
}
}


Output of the above problem will be
1. parameter will be printed in the messagebox.
2. Default will be printed in the messagebox.

Upload File in .net

I was search for uploading the large file in asp.net and got the following article. I found this useful and that is why I am publishing the same on my blog.

Upload larger files
By default, ASP.NET permits only files that are 4,096 kilobytes (KB) (or 4 megabytes [MB]) or less to be uploaded to the Web server. To upload larger files, you must change the maxRequestLength parameter of the section in the Web.config file.

Note When the maxRequestLength attribute is set in the Machine.config file and then a request is posted (for example, a file upload) that exceeds the value of maxRequestLength, a custom error page cannot be displayed. Instead, Microsoft Internet Explorer will display a "Cannot find server or DNS" error message.

If you want to change this setting for all of the computer and not just this ASP.NET application, you must modify the Machine.config file.

By default, the element is set to the following parameters in the Machine.config file:
executionTimeout="90"
maxRequestLength="4096"
useFullyQualifiedRedirectUrl="false"
minFreeThreads="8"
minLocalRequestFreeThreads="4"
appRequestQueueLimit="100"
/>

The Machine.config file is located in the \System Root\Microsoft.NET\Framework\Version Number\Config folder.

Theoretically, the maximum file upload size is fairly large. However, because of ASP.NET health monitoring, you cannot upload very large files in ASP.NET. The ASP.NET worker process has a virtual address space of 2 gigabytes (GB). However, the ASP.NET worker process only uses a little more than 1 GB because of health monitoring and memory fragmentation.

During the upload process, ASP.NET loads the whole file in memory before the user can save the file to the disk. Therefore, the process may recycle because of the memoryLimit attribute of the processModel tag in the Machine.config file. The memoryLimit attribute specifies the percentage of physical memory that the ASP.NET worker process can exhaust before the process is automatically recycled. Recycling prevents memory leaks from causing ASP.NET to crash or to stop responding.

Additionally, other factors play a role in the maximum file size that can be uploaded. These factors include available memory, available hard disk space, processor speed, and current network traffic. With regular traffic of files being uploaded, Microsoft recommends that you use a maximum file size in the range of 10 to 20 megabytes (MB). If you rarely upload files, the maximum file size may be 100 MB.

Note You can upload files that are larger than 100 MB in ASP.NET. However, Microsoft recommends that you follow the maximum file upload sizes that are mentioned in this article. To determine more precise file sizes, perform stress testing on computers that are similar to the ones that will be used in production.

You may notice the following error messages if you encounter file size limits during the file upload process:
• The page cannot be displayed.
• Server Application is Unavailable
In the event log, the error message will be similar to the following:
aspnet_wp.exe (PID:PIDNumber) was recycled because memory consumption exceeded the SizeLimit MB (Percentage percent of available RAM).
• Exception of type System.OutOfMemoryException was thrown.
You may also find that uploads occur very slowly. If you watch the Aspnet_wp.exe process in Windows Task Manager, you will notice that the memory delta changes by 64 KB every 1 to 2 seconds. Depending on the size of the file, this delay may cause the ASP.NET worker process to recycle because of a responseDeadlock error.

Monday, November 10, 2008

Paging Procedure.

I was need to do the paging at run time and get the page specific data.
Below is the procedure for the same i found while surfing the net and i belive this is a grat findings.

CREATE PROCEDURE [dbo].[utilPAGE]
@datasrc nvarchar(200)
,@orderBy nvarchar(200)
,@fieldlist nvarchar(200) = '*'
,@filter nvarchar(200) = ''
,@pageNum int = 1
,@pageSize int = NULL
AS
SET NOCOUNT ON
DECLARE
@STMT nvarchar(max) -- SQL to execute
,@recct int -- total # of records (for GridView paging interface)

IF LTRIM(RTRIM(@filter)) = '' SET @filter = '1 = 1'
IF @pageSize IS NULL BEGIN
SET @STMT = 'SELECT ' + @fieldlist +
'FROM ' + @datasrc +
'WHERE ' + @filter +
'ORDER BY ' + @orderBy
EXEC (@STMT) -- return requested records
END ELSE BEGIN
SET @STMT = 'SELECT @recct = COUNT(*)
FROM ' + @datasrc + '
WHERE ' + @filter
EXEC sp_executeSQL @STMT, @params = N'@recct INT OUTPUT', @recct = @recct OUTPUT
SELECT @recct AS recct -- return the total # of records

DECLARE
@lbound int,
@ubound int

SET @pageNum = ABS(@pageNum)
SET @pageSize = ABS(@pageSize)
IF @pageNum < 1 SET @pageNum = 1
IF @pageSize < 1 SET @pageSize = 1
SET @lbound = ((@pageNum - 1) * @pageSize)
SET @ubound = @lbound + @pageSize + 1
IF @lbound >= @recct BEGIN
SET @ubound = @recct + 1
SET @lbound = @ubound - (@pageSize + 1) -- return the last page of records if -- no records would be on the
-- specified page
END
SET @STMT = 'SELECT ' + @fieldlist + '
FROM (
SELECT ROW_NUMBER() OVER(ORDER BY ' + @orderBy + ') AS row, *
FROM ' + @datasrc + '
WHERE ' + @filter + '
) AS tbl
WHERE
row > ' + CONVERT(varchar(9), @lbound) + ' AND
row < ' + CONVERT(varchar(9), @ubound)
EXEC (@STMT) -- return requested records
END

utilPAGE 'TableName', 'OrderBy', '*', '', 4, 10

@datasrc
- the table (or stored procedure, etc.) name
@orderBy
- the ORDER BY clause
@fieldlis
- the fields to return (including calculated ex-pressions)
@filter
- the WHERE clause
@pageNum
- the page to return (must be greater than or equal to one)
@pageSize
- the number of records per page

Way to bind Command Arguments Value for dynamic value in Html view (aspx page).

Below is the way to bind the CityID and Sname to command arguments.

CommandArgument='<%#Eval("CityID") + ";" +Eval("Sname")%>'

Javascript validation in Grid

In the row Data Bound event of the grid User has to find the Update control which will normally be in the first cell of the every grid row.Then after finding the control user has to add the attributes to the link button of the grid row.

if (e.Row.Cells[0].HasControls())
{
for (int i = 0; i < e.Row.Cells[0].Controls.Count; i++)
{
if (e.Row.Cells[0].Controls[i].ToString() == "System.Web.UI.WebControls.DataControlLinkButton")
{
LinkButton lnkbtnUpdate = (LinkButton)e.Row.Cells[0].Controls[i];
if (lnkbtnUpdate.Text.ToUpper() == "UPDATE")
{
lnkbtnUpdate.Attributes.Add("onclick", "return onUpdateValidation('" + e.Row.FindControl("txtName").ClientID + "');");
break;
}
if (lnkbtnUpdate.Text.ToUpper() == "EDIT")
{
break;
}
}
}
}

Example to filter the DataTable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace Utility
{
public class FilterDataTableForInQuery
{
public DataTable FilterDataTable(DataTable dtLocal, string value)
{
dtLocal.DefaultView.RowStateFilter = DataViewRowState.OriginalRows;
if (value != string.Empty)
{
dtLocal.DefaultView.RowFilter = "ID in( " + value + ")";
return dtLocal.DefaultView.ToTable();
}
else
{
return null;
}
}
}
}

Code to send the e-mail from .NET Code

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Mail;

namespace Mail
{
public class SendMail
{
public void Mail(string strFrom,string strTo,string strBody,string strSubject)
{
MailMessage objMailmsg = new MailMessage();
objMailmsg.To = strTo;
objMailmsg.From = strFrom;
objMailmsg.BodyFormat = MailFormat.Html;
objMailmsg.Subject = strSubject;
objMailmsg.Body = strBody;
SmtpMail.SmtpServer = "";
SmtpMail.Send(objMailmsg);
}
}
}

Transfering file from server to client.

Below code will give user option to
* User can download the file from the server and save it by choosing the save option.
* User can open the file.
* User can cancel the all operation.

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
///
/// Summary description for TransmitFile
///


public class TransmitFile
{
public TransmitFile()
{
}
FileDownloadHelper objFileDownloadHelper = new FileDownloadHelper();
public void Transmit(string filePath,string FileName,string FileID)
{
FileInfo myfile = new FileInfo(filePath);
if (myfile.Exists)
{
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + "(" + FileID + ").doc");
HttpContext.Current.Response.AddHeader("Content-Length", myfile.Length.ToString());
HttpContext.Current.Response.ContentType = objFileDownloadHelper.ReturnExtension(myfile.Extension.ToLower());
HttpContext.Current.Response.TransmitFile(myfile.FullName);
HttpContext.Current.Response.End();
}
}
}

Handling Special Case Like & and > while Genrating Xml

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
namespace Utility
{
class GenrateXML
{
public static string Genrate(string Screen, NameValueCollection nvCollection)
{
StringBuilder strXML=new StringBuilder();
strXML.Append("");

strXML.Append("<");
strXML.Append(Screen);
strXML.Append(">");

for (int i = 0; i < nvCollection.Count; i++)
{
strXML.Append("<");
strXML.Append(nvCollection.GetKey(i));
strXML.Append(">");

string strValue = nvCollection.Get(i).Replace("&", "&");
strValue = strValue.Replace("<", "<");
strValue = strValue.Replace(">", ">");

strXML.Append(strValue);

strXML.Append(" strXML.Append(nvCollection.GetKey(i));
strXML.Append(">");
}
strXML.Append(" strXML.Append(Screen);
strXML.Append(">");
strXML.Append("
");
//strXML.Replace("&", "&");
return strXML.ToString();
}
}
}

Setting the focus on Open form.

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Regularex-pressions;
using System.Windows.Forms;
namespace Utility
{
class Validations
{
//Open Form
public static void OpenForm(Form objForm,MDIMainForm _MAIN)
{
bool isOpened = false;
for (int I = 0; I < Application.OpenForms.Count; I++)
{
if (objForm.GetType().Equals(Application.OpenForms[I].GetType()))
{
isOpened = true;
Application.OpenForms[I].Focus();
objForm = null;
break;
}
}
if (!(isOpened))
{
objForm.MdiParent = _MAIN;
objForm.Show();
}
}
}
}

Thursday, August 21, 2008

Execute sql query with exec or execute and Passing Comma Seprated List of IDs to Store Procedure

Hi,

I was in need to create the query in string variable and execute the same.I found the solution which fits in my situation.

The below mentioned way gives you idea where i need that.As i have the list of values and i want only those records to be retrive from the Database.

EXECUTE(@STRQRY)

ALTER procedure [dbo].[spGetData]
@strDataIDs varchar(max)
as
begin
DECLARE @STRQRY NVARCHAR(MAX)
SET @STRQRY= 'select * from DataMaster where accnum not in (' +@strDataIDs+ ')'
EXECUTE(@STRQRY)
end

Passing Array to Store Procedure in SQL

Passing the array as SQL Parameter is always a concern becuase running the ExceuteQuery for multiple Insert is not a good option through .NET gives you the Implementation of Transaction but this will only serve concurrency issue but somewhere er have to face the performance issue because of this.

So, the need to pass the array to Store Procedure is very comman and the best approch to do this is pass the xml to the Store Procedure in ntext variable.


Create procedure [dbo].[spSendXML]
(
@RecordXML ntext
)
AS

Begin

create Table #tbl (ID int)

DECLARE @idoc int
EXEC sp_xml_preparedocument @idoc OUTPUT, @RecordXML

insert into #tbl
select ID
FROM OPENXML(@idoc,'/Root/Comp', 1)
WITH (ID varchar(50))


End


By doing this you can get all the data in SQL Temp Table.


Calling of the same Store Procedure.

spSendXML ''

Thanks
Dalip Vohra

Custom Text Box with ID and Text in read only mode.

I was having the situation where I have to show the account name in the application and consider accountid in functioning like insert, update.

Point to note here is i don't want to se any kind of list control like dropdown,listbox,etc.

So, I have created my own Text Box control which will provide me the facility to maintain the ID of the text.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication5
{
public class MyTextBox : TextBox
{
private string _valueID;
public string ValueID
{
get
{
return _valueID;
}
set
{
_valueID = value;
}
}
protected override void OnCreateControl()
{
this.ReadOnly = true;
base.OnCreateControl();
}
}
}

Thanks
Dalip Vohra

Fetching Values Of Sql Table as Comma Seprated Values In SQL Variable

Declare @Str varchar(2000)

Begin

(Select @Str=COALESCE(@Str, '','') + Cast([Employee_name] as nvarchar(100)) + ','

from dbo.Employee )

Select substring(@Str,0,len(@str))

End

Thursday, June 12, 2008

Max Length Validation (Display remaining character while typing)

Max Length validation is sometime doesn't give the right impact on the user as user has something in mind to type but at the end he/she came to know becuase of the max length of the field user is not allowed to type that long comment/value. So, better way is to display how many characters left from the total max length which user can enter in the field while he/she is entring the value of the field.

Code for the same is mentioned below.



<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>

<script language="java-script">
function textCounter(field, countfield, maxlimit)
{
if (field.value.length > maxlimit)
{
field.value = field.value.substring(0, maxlimit);
}
else
{
countfield.value = maxlimit - field.value.length;
}
}
</script>

<style
.txtBoxes
{
border:solid 1px DarkGray;
width:100px;
}
</style>

</head>
<body>
<form id="form1" runat="server">
<table border="0">
<tr>
<td>
<textarea "textCounter(areaTxtDetails, remlen, 10);" "textCounter(areaTxtDetails, remlen, 10);"
id="areaTxtDetails" "textCounter(areaTxtDetails, remlen, 10);" "textCounter(areaTxtDetails, remlen, 10);"
name="areaTxtDetails" rows="2" cols="65" class="areaTxtDetails" runat="server"> </textarea>
</td>
</tr>
<tr>
<td>
<span style="font-family:Arial;font-size:78%;">You have</span> <input type="text" id="remlen" cssclass="txtBoxes" width="30px"> <span style="font-family:Arial;font-size:78%;">characters remaining.</span>
</td>
</tr>
</table>

</form>
</body>
</html>

Max Length validation

Max Length validation is generally we use like we dont allow user to enter the anything once the limit is over but most of the time we left with one loop hole in that.

Restrict the user on the keypress but we don't restrict the user on paste and if user paste something he/she can cross the limit event because at that time the key press event doesn't gets fired. So below is the solution for the same.

C# code

txtComments_Demotion.Attributes.Add("onkeypress", "java-script:maxLength('" + txtComments_Demotion.ClientID + "','92');");
txtComments_Demotion.Attributes.Add("onpaste", "java-script:maxLengthPaste('" + txtComments_Demotion.ClientID + "','92');");

Javascript function in aspx page.

function maxLength(fieldName,maxChars)
{
field=document.getElementById(fieldName);
if(field.value.length >= maxChars) {
event.returnValue=false;
return false;
}
}

function maxLengthPaste(fieldName,maxChars)
{
field=document.getElementById(fieldName);
event.returnValue=false;
if((field.value.length + window.clipboardData.getData("Text").length) > maxChars) {
return false;
}
event.returnValue=true;
}

Wednesday, June 11, 2008

Accessing Xls sheet Data Microsoft.Office.Interop.Excel.dll

In my last article about Accessing data from xls from .NET code I used OledbConnection but that was not covering all my needs so for the better control I found another way of calling the Xls sheet data and I have created another component. The component code and the calling code is mentioned below in c# language.

Note: This require the reference for the Microsoft.Office.Interop.Excel.dll which you can find in your local system. Go to Start -> Search -> Search for (Microsoft.Office.Interop.Excel.dll) -> Copy the same to bin folder and reference from there.

Component Code.

/*
* Created by Dalip Vohra
* Date: 07 June 2008 00:09
*/
using System;
using Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.IO;
using System.Data;
using System.Data.OleDb;
namespace ExcelManagement.Direct
{
///
/// Description of TimedAccess.
///

public class ExcelAccess
{
#region Private Variables
ApplicationClass app;
Workbook book = null;
Worksheet sheet = null;
Range range = null;
#endregion
#region Constructor
public ExcelAccess(string _xlsFile, int _xlsFileSheetIndex)
{
app = new ApplicationClass();
app.Visible = false;
app.ScreenUpdating = false;
app.DisplayAlerts = false;
string execPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
book = app.Workbooks.Open(execPath + @"\..\..\" + _xlsFile, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value);
sheet = (Worksheet)book.Worksheets[_xlsFileSheetIndex];
}
#endregion
#region ChangeSheetIndex Method
public void ChangeSheetIndex(int SheetIndex)
{
sheet = (Worksheet)book.Worksheets[SheetIndex];
}
#endregion

#region ChangeSheetToSheetName Method
public void ChangeSheetToSheetName(string NewSheetName)
{
System.Collections.IEnumerator s = ((System.Collections.IEnumerator)book.Worksheets.GetEnumerator());
int i=1;
while (s.MoveNext())
{
if (((Worksheet)s.Current).Name == NewSheetName)
{
sheet = (Worksheet)book.Worksheets[i];
return;
}
i++;
}
}
#endregion
#region Read Range Method(Based on the Starting Cell).
public object[,] ReadRange(string StartingCell)
{
try
{
range = sheet.get_Range(StartingCell, Missing.Value);
range = range.get_End(XlDirection.xlToRight);
range = range.get_End(XlDirection.xlDown);
string downAddress = range.get_Address(
false, false, XlReferenceStyle.xlA1,
Type.Missing, Type.Missing);
range = sheet.get_Range(StartingCell, downAddress);
return (object[,])range.Value2;
}
catch (Exception e)
{
range = null;
sheet = null;
if (book != null)
book.Close(false, Missing.Value, Missing.Value);
book = null;
if (app != null)
app.Quit();
app = null;
return null;
}
}
#endregion
#region Read Range Method.
public object[,] ReadRange(string StartingCell, string EndingCell)
{
try
{
// get a range to work with
range = sheet.get_Range(StartingCell, EndingCell);
return (object[,])range.Value2;
}
catch (Exception e)
{
range = null;
sheet = null;
if (book != null)
book.Close(false, Missing.Value, Missing.Value);
book = null;
if (app != null)
app.Quit();
app = null;
return null;
}
}
#endregion
#region Read Cell Method
public string ReadCell(string cellName)
{
try
{
range = sheet.get_Range(cellName, Missing.Value);
if (range.Value2 != null)
{
return range.Value2.ToString();
}
else
{
return string.Empty;
}
}
catch (Exception e)
{
range = null;
sheet = null;
if (book != null)
book.Close(false, Missing.Value, Missing.Value);
book = null;
if (app != null)
app.Quit();
app = null;
return null;
}
}
#endregion
#region Dispose Method
public void Dispose()
{
range = null;
sheet = null;
if (book != null)
book.Close(false, Missing.Value, Missing.Value);
book = null;
if (app != null)
app.Quit();
app = null;
}
#endregion
}
}

Calling code


ExcelManagement.Direct.ExcelAccess _access = new ExcelManagement.Direct.ExcelAccess("Book1.xls", 2);
MessageBox.Show(_access.ReadCell("b1"));
_access.ChangeSheetIndex(1);
_access.ChangeSheetToSheetName("Sheet1");
object[,] values = _access.ReadRange("A1", "b2");
for (int i = 1; i <= values.GetLength(0); i++)
{
for (int j = 1; j <= values.GetLength(1); j++)
{
if (values[i, j] != null)
{
MessageBox.Show(values[i, j].ToString());
}
else
{
MessageBox.Show("");
}
}
}
_access.Dispose();

Saturday, June 7, 2008

Accessing Xls Sheet Data from .NET Application

Some time back i was in need to fetch some data from the Excel sheet from .NET Application. I have done some R & D on the Net and found some great examples of the same then i created my own sample component which will serve you like the basis component and you can enhance the same futher as per your need.

/*
* Created by Dalip Vohra
*/

using System;
using System.IO;
using System.Data;
using System.Data.OleDb;
namespace ExcelManagement.OleDB
{
///
/// Description of TimedAccess.
///

public class ExcelAccess
{
#region Private Variables
string connString;
OleDbConnection oledbConn;
#endregion

#region Constructor
public ExcelAccess(string _xlsFile, string _xlsFileSheetName)
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=../../Book2.xls;Extended Properties=Excel 8.0";
oledbConn = new OleDbConnection(connString);
try
{
// Open connection
oledbConn.Open();
}
catch
{
throw (new Exception("Connection Exception"));
}
}
#endregion

#region GetSheetData Method
public DataSet GetSheetData(string SheetName)
{
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + SheetName + "$]", oledbConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
DataSet ds = new DataSet();
oleda.Fill(ds, "RecordsTable");
return ds;
}
#endregion

#region GetRangeFromSheet Method

public DataSet GetRangeFromSheet(string SheetName, String StartingCell, String EndingCell)
{
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + SheetName + "$" + StartingCell + ":" + EndingCell + "]", oledbConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
DataSet ds = new DataSet();
oleda.Fill(ds, "RecordsTable");
return ds;
}
#endregion

#region Dispose Method

public void Dispose()
{
connString = null;
oledbConn.Close();
}
#endregion

}
}