Wednesday, March 31, 2010

Assign datatable to viewstate

//assign datatable to viewstate.
ViewState["dtQues"] = dtQue;

DataTable dt1 = (DataTable)ViewState["dtQues"];

Tuesday, March 30, 2010

HOw to add pager style...

1) Allow Paging =true
2) allow sorting=true.


NextPageText="Next " PreviousPageText="Previous" />


protected void gvrListOfStudent_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvrListOfStudent.PageIndex = e.NewPageIndex;
gvrListOfStudent.DataBind();
}

Wednesday, March 10, 2010

How to pass two values two query string

window.location="ViewMemberDetails.aspx?view_id="+memberid+"&mem_no="+memberno;

Saturday, March 6, 2010

How to automatic REFRESH webpage after few seconds.

Just add Meta tag b4 / after HTML tag on web page.

//** meta http-equiv="Refresh" content="5" ** //

How to fill DROPDOWN LIST on row data bound

protected void Page_Load(object sender, EventArgs e)
{
conn.Open();
da = new SqlDataAdapter("Select User_id,Name,EmailId,City_id,Qualification from tbl_user", conn);
da.Fill(ds,"tbl_User");
GridView1.DataSource = ds;
GridView1.DataBind();
GridView1.Columns[3].Visible = false;
conn.Close();
}



protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType != DataControlRowType.Header)
{
DropDownList drdp1 = new DropDownList();

drdp1 = (DropDownList)e.Row.Cells[4].FindControl("drdp");

//int user_id =Convert.ToInt32(e.Row.Cells[1].Text);

DataSet ds1 = new DataSet();

SqlDataAdapter da1 = new SqlDataAdapter("Select City_name,City_id from tbl_city", conn);

da1.Fill(ds1, "tbl_drdp");

drdp1.DataSource = ds1;

drdp1.DataTextField = ds1.Tables[0].Columns["City_name"].ColumnName.ToString();

drdp1.DataValueField = ds1.Tables[0].Columns["City_id"].ColumnName.ToString();

drdp1.SelectedIndex = Convert.ToInt32(e.Row.Cells[3].Text);

drdp1.DataBind();
}

}
catch(Exception ex)
{
ex = ex;
}
}

Saturday, February 20, 2010

New SEND-MAIL Function

protected void Button1_Click(object sender, EventArgs e)
{
try
{
MailMessage message = new MailMessage();

SmtpClient mailClient = new SmtpClient();

MailAddress frm = new MailAddress(txtmailfrom.Text);

message.To.Add(txtmailto.Text);

message.Subject = txtsubject.Text;

String bodyText = "";

bodyText = " ";
bodyText = bodyText + "Dear" + " " + "firstname" + " " + "lastname" + ",";
bodyText = bodyText + "
";
bodyText = bodyText + "
";
bodyText = bodyText + "Administrator has sent reply on your Registration:";
bodyText = bodyText + " " + "" + txtsubject.Text + "";
bodyText = bodyText + "
";
bodyText = bodyText + "RegistrationDate:";
bodyText = bodyText + " " + "" + DateTime.Now.ToString() + "";
bodyText = bodyText + "
";
bodyText = bodyText + "If you have any queries or want to send nominations, please mail the same to
href='mailto:YOURADMNEMAILID'>YOURADMNEMAILID
" + "
";
bodyText = bodyText + "
";
bodyText = bodyText + "All the best!!";
bodyText = bodyText + "
";
bodyText = bodyText + "
";
bodyText = bodyText + "Regards,";
bodyText = bodyText + "
";

bodyText = bodyText + "WEBSITE";
bodyText = bodyText + "
";

message.Body = bodyText.ToString();

message.IsBodyHtml = true;

message.Priority = MailPriority.High;

NetworkCredential basicAuthenticationInfo = new NetworkCredential(@"YOURGMAILID", "G-MAIL PWD");

mailClient.Host = "smtp.gmail.com";

mailClient.Port = 587;

mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;

mailClient.UseDefaultCredentials = false;

mailClient.EnableSsl = true;

mailClient.Credentials = basicAuthenticationInfo;

message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

//mailClient.Timeout = 60000;

mailClient.Send(message);

lbl_success.Text = "Successsssss";

}
catch(Exception ex)
{
lbl_success.Text = "faillllll.";
}

}

Diffrence between FUNCTIONS AND STORED PROCEDURES

1. Functions are compiled and executed at run time.
Stored procedures are stored in parsed and compiled format in the database.


A Function returns 1 value only. Procedure can return
multiple values (max 1024).


Procedure can return zero or n values whereas function can return one value which is mandatory.

sp takes input,output parameters, function takes only
input parameters.


Functions are basically used to compute values. We passes some parameters to functions as input and then it performs some

operations on the parameter and return output.
Stored procedures are basically used to process the task.


Functions can be called from procedure whereas procedures cannot be called from function.


Function do not return the images, text. Stored Procedure returns all

Monday, February 15, 2010

HOw to see HIDDEN files and folders from windows which cant see due to virusss

(Go to Start --> Run, then type Regedit
2. Navigate to the registry folder HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\
CurrentVersion\Explorer\Advanced\Folder\Hidden\SHOW ALL
3. Find a key called CheckedValue.
4. Double Click CheckedValue key and modify it to 1. This is to show all the hidden files.)

Saturday, February 13, 2010

HOw to delete all the files and folders from the directory

public object delDirectory(string dirPath)
{

if (!(Directory.Exists(dirPath)))
{
return false;
}
string[] fileEntries = Directory.GetFiles(dirPath);
foreach (string fileName in fileEntries)
{
File.Delete(fileName);
}
string[] subdirectoryEntries = Directory.GetDirectories(dirPath);
foreach (string subdirectory in subdirectoryEntries)
{
delDirectory(subdirectory);
}
Directory.Delete(dirPath);
return true;
}

How to change gridview header on row created.

protected void grvUserThread_RowCreated(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow headerRow = e.Row;
Label lb = new Label();
lb = (Label)e.Row.FindControl("lblabc");
lb.Text = "Thread: " + Thread;
}
}

HOw to use CURSOR in PROCEDURE

set ANSI_NULLS OFF
set QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[PROCNAME]
(
@FeedbackIDStr varchar(5000)/*Selected FeedbackID like 2,4,5,6,7 */
)
AS
Declare @TFid int
Declare @tempTblFid TABLE (idx smallint Primary Key, FeedbackID int)

INSERT INTO @tempTblFid SELECT * from fn_Split(@FeedbackIDStr,',')

/*Declare Cursor for getting FeedbackID and update into tblName*/
Declare curTempFeedback Cursor Fast_Forward for
select FeedbackID from @tempTblFid
Open curTempFeedback
fetch next from curTempFeedback into @TFid
While @@Fetch_Status = 0
BEGIN
UPDATE [tblName]
SET IsAddedToFAQ ='True' where FeedbackID=@TFid

INSERT INTO [tblName]
SELECT Subject,Comment,getdate(),'False',FeedbackID from [tblName] where FeedbackID=@TFid;

fetch next from curTempFeedback into @TFid
END
CLOSE curTempFeedback
DEALLOCATE curTempFeedback

HOW TO KILL PROCESS IN FINALLY BLOCK

catch (Exception ex)
{

}
finally
{
System.Diagnostics.Process[] prs = System.Diagnostics.Process.GetProcesses();

foreach (System.Diagnostics.Process proces in prs)
{

if (proces.ProcessName.ToUpper() == "EXCEL")
{
proces.Refresh();
if (!proces.HasExited)
proces.Kill();
}
}
}
}

HOW TO USE SIGNOUT FUNCTION

protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserID"] != null)
{
BLL_Users objUser = new BLL_Users();
objUser.LogOutUser(Convert.ToInt16(Session["UserID"]));
}
FormsAuthentication.SignOut();
Session.Abandon();
Response.Redirect("Login.aspx", false);
}


}

HOW TO PASS/USE MULTIPLE Parameters in BLL and DAL

public void AddUserLogs(int uid, string ip, string UserSessionID, string browser, string os)
{
try
{
DAL_Users.AddUserLogs(uid, ip, UserSessionID, browser, os);
}
catch (Exception ex)
{
ex = ex;
}
}

public static void AddUserLogs(int uid, string ip, string UserSessionID, string browser, string os)
{
try
{
string strCon = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection con = new SqlConnection();
con.ConnectionString = strCon;
SqlHelper.ExecuteNonQuery(con, CommandType.StoredProcedure, "360LMS_AddUserLoginLogs", new SqlParameter("@UserID", uid), new SqlParameter("@IP", ip), new SqlParameter("@Browser", browser), new SqlParameter("@OS", os), new SqlParameter("@SessionID", UserSessionID));
}
catch (Exception ex)
{
ex = ex;
}

}

Friday, February 5, 2010

How to use multilingual feature

ON LOGIN PAGE

Session.Add("Language", DropDownList1.SelectedValue)


THEN create LMSLanguage.resx under Language folder (for english language)






xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">







msdata:Ordinal="1" />

msdata:Ordinal="2" />










msdata:Ordinal="1" />









text/microsoft-resx


1.0.0.0


System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral,

PublicKeyToken=b77a5c561934e089



System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral,

PublicKeyToken=b77a5c561934e089



Home


Logout



AND also for marathi and hindi.......


System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral,

PublicKeyToken=b77a5c561934e089



marathi word


marathi word



THEN ON PAGE LOAD FOR EACH PAGE


If Session("userid") Is Nothing Then
Response.Redirect("../login.aspx")
End If
Try

Dim rm As System.Resources.ResourceManager
Dim s As String
's = ConfigurationSettings.AppSettings("rootPath")
''s = s + "/Languages/"
's = Server.MapPath("wwwroot") ' 'Path.DirectorySeparatorChar
's = "C:\Inetpub\wwwroot\LMS\Languages\"
s = Server.MapPath(rootPath & "/Languages/")
rm = ResourceManager.CreateFileBasedResourceManager("LMSLanguage", s, Nothing)
Dim a As String
a = Session.Item("Language").ToString
Dim cinfo As CultureInfo
cinfo = New CultureInfo(a)
lblMyOption.Text = rm.GetString("lblMyOptions", cinfo)
lblMyCourses.Text = rm.GetString("lblMyCourses", cinfo)
lblPreference.Text = rm.GetString("lblPreferences", cinfo)
lblChangePwd.Text = rm.GetString("btnTxtChangePwd", cinfo)
lblOldPwd.Text = rm.GetString("lblOldPwd", cinfo)
lblNewPwd.Text = rm.GetString("lblNewPwd", cinfo)
lblReNewPwd.Text = rm.GetString("lblReNewPwd", cinfo)
btnAssinAdd.Text = rm.GetString("btnTextSave", cinfo)
btnAssinCancel.Text = rm.GetString("btnTextCancel", cinfo)

Catch ex As Exception

End Try

EXCEL SHEET IMPORT

protected void btnImport_Click(object sender, EventArgs e)
{
try
{
if (ddlCourseName.SelectedValue == "--Select--")
{
lblErrorMsg.Text = "Please select course name.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
}
else if (ddlCourseModule.SelectedValue == "--Select--")
{
lblErrorMsg.Text = "Please select module name.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
}
else if (!(UploadQuestions.HasFile))
{
lblErrorMsg.Text = "Please select file to import.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
}
else if ((UploadQuestions.PostedFile.FileName.Substring(UploadQuestions.PostedFile.FileName.IndexOf(".")).ToLower()) != ".xls")
{
lblErrorMsg.Text = "Please select excel file to import.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
}
else if (UploadQuestions.HasFile)
{
string url = "CreateAssessment.aspx?CourseID=" + Convert.ToInt16(ddlCourseName.SelectedValue) + "&ModuleID=" + Convert.ToInt16(ddlCourseModule.SelectedValue);
string path = Server.MapPath("Questions");
strFile = "QuestionFormat" + System.DateTime.Now.Ticks.ToString() + ".xls";
UploadQuestions.SaveAs(path + "\\" + strFile);
ValidateQuestion(path + "\\" + strFile);
// ValidateQuestion(path + "\\QuestionFormat633952775374218750.xls");
if (flag != 0)
{
Response.Redirect(url, false);
}
}
}
catch (Exception ex)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, ex.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, ex.Source);
LCE.Configuration.ErrorLog("Assessment/ImportQuestions.cs", errorMessage);
}
}


private void ValidateQuestion(string fileName)
{
string QFormat = "OK";
int rows;
try
{
GC.Collect();
// creat a Application object
objXL = new Application();
// get WorkBook object
objWB = objXL.Workbooks.Open(fileName, 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);

// get WorkSheet object
objSheet = (Microsoft.Office.Interop.Excel.Worksheet)objWB.Sheets[1];
rows = objSheet.UsedRange.Cells.Rows.Count;
if (rows < 15)
{
lblErrorMsg.Text = "Please add question in the excel sheet";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
}
else
{
//****************Check for proper data*******************//

for (int i = 16; i <= (rows + 1); i++)
{
string qt = objSheet.get_Range(objSheet.Cells[i, 2], objSheet.Cells[i, 2]).Text.ToString();
if (qt != "")
{
if (Convert.ToInt16(qt) == 1)//for single select
{
if (objSheet.get_Range(objSheet.Cells[i, 3], objSheet.Cells[i, 3]).Text.ToString() == "")
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
else if (objSheet.get_Range(objSheet.Cells[i, 4], objSheet.Cells[i, 4]).Text.ToString() == "")
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;

}
else if (objSheet.get_Range(objSheet.Cells[i, 5], objSheet.Cells[i, 5]).Text.ToString() == "")
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
else if (objSheet.get_Range(objSheet.Cells[i, 6], objSheet.Cells[i, 6]).Text.ToString() == "")
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
else if (objSheet.get_Range(objSheet.Cells[i, 7], objSheet.Cells[i, 7]).Text.ToString() == "")
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
else if (objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() == "")
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
else if ((Convert.ToInt16(objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString()) < 1) || (Convert.ToInt16(objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString()) > 4))//check selected options
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
else if (objSheet.get_Range(objSheet.Cells[i, 9], objSheet.Cells[i, 9]).Text.ToString() == "")
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
}
else if (Convert.ToInt16(qt) == 2)//for multiple select
{
if (objSheet.get_Range(objSheet.Cells[i, 3], objSheet.Cells[i, 3]).Text.ToString() == "")
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
else if (objSheet.get_Range(objSheet.Cells[i, 4], objSheet.Cells[i, 4]).Text.ToString() == "")
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
else if (objSheet.get_Range(objSheet.Cells[i, 5], objSheet.Cells[i, 5]).Text.ToString() == "")
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
else if (objSheet.get_Range(objSheet.Cells[i, 6], objSheet.Cells[i, 6]).Text.ToString() == "")
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
else if (objSheet.get_Range(objSheet.Cells[i, 7], objSheet.Cells[i, 7]).Text.ToString() == "")
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
else if (objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() == "")
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
else if ((objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() != "1") &&
(objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() != "1,2") &&
(objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() != "1,2,3") &&
(objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() != "1,3,4") &&
(objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() != "2") &&
(objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() != "2,3") &&
(objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() != "2,3,4") &&
(objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() != "3") &&
(objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() != "3,4") &&
(objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() != "4") &&
(objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() != "1,3") &&
(objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() != "1,2,4") &&
(objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() != "1,4") &&
(objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() != "2,4") &&
(objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() != "1,2,3,4") &&
(objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() != "3,4")

)//check selected options
{
lblErrorMsg.Text = "Please check multiple choice answer,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
else if (objSheet.get_Range(objSheet.Cells[i, 9], objSheet.Cells[i, 9]).Text.ToString() == "")
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
}
else if (Convert.ToInt16(qt) == 3)//for true false
{
if (objSheet.get_Range(objSheet.Cells[i, 3], objSheet.Cells[i, 3]).Text.ToString() == "")
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
else if (objSheet.get_Range(objSheet.Cells[i, 4], objSheet.Cells[i, 4]).Text.ToString() == "")
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
else if (objSheet.get_Range(objSheet.Cells[i, 5], objSheet.Cells[i, 5]).Text.ToString() == "")
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
else if (objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() == "")
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
else if ((objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() != "1") && (objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString() != "2"))
{
lblErrorMsg.Text = "Please check true/false answer format,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;

}
else if (objSheet.get_Range(objSheet.Cells[i, 9], objSheet.Cells[i, 9]).Text.ToString() == "")
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
}
}
else
{
lblErrorMsg.Text = "Excel sheet format is incorrect,Please download template format of excelsheet.";
lblErrorMsg.ForeColor = System.Drawing.Color.Red;
QFormat = "Incorrect";
flag = 0;
break;
}
}
}
//********************************************************//
//if format is correct then add to ds
//---------------------------------//
if (QFormat == "OK")
{
for (int i = 16; i <= (rows+1); i++)
{
int qt = Convert.ToInt16(objSheet.get_Range(objSheet.Cells[i, 2], objSheet.Cells[i, 2]).Text.ToString());
if (qt == 1)
{
BLL_Assessment AssObj = new BLL_Assessment();
AssObj.QuestionType = qt;
AssObj.CourseID = Convert.ToInt16(ddlCourseName.SelectedValue);
AssObj.ModuleID = Convert.ToInt16(ddlCourseModule.SelectedValue);
AssObj.QuestionText = objSheet.get_Range(objSheet.Cells[i, 3], objSheet.Cells[i, 3]).Text.ToString();
AssObj.OptionA = objSheet.get_Range(objSheet.Cells[i, 4], objSheet.Cells[i, 4]).Text.ToString();
AssObj.OptionB = objSheet.get_Range(objSheet.Cells[i, 5], objSheet.Cells[i, 5]).Text.ToString();
AssObj.OptionC = objSheet.get_Range(objSheet.Cells[i, 6], objSheet.Cells[i, 6]).Text.ToString();
AssObj.OptionD = objSheet.get_Range(objSheet.Cells[i, 7], objSheet.Cells[i, 7]).Text.ToString();
AssObj.CorrectOptions = objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString();
AssObj.AnsExplaination = objSheet.get_Range(objSheet.Cells[i, 9], objSheet.Cells[i, 9]).Text.ToString();
AssObj.AddQuestion();
flag = 1;
}
else if (qt == 2)
{
BLL_Assessment AssObj = new BLL_Assessment();
AssObj.QuestionType = qt;
AssObj.CourseID = Convert.ToInt16(ddlCourseName.SelectedValue);
AssObj.ModuleID = Convert.ToInt16(ddlCourseModule.SelectedValue);
AssObj.QuestionText = objSheet.get_Range(objSheet.Cells[i, 3], objSheet.Cells[i, 3]).Text.ToString();
AssObj.OptionA = objSheet.get_Range(objSheet.Cells[i, 4], objSheet.Cells[i, 4]).Text.ToString();
AssObj.OptionB = objSheet.get_Range(objSheet.Cells[i, 5], objSheet.Cells[i, 5]).Text.ToString();
AssObj.OptionC = objSheet.get_Range(objSheet.Cells[i, 6], objSheet.Cells[i, 6]).Text.ToString();
AssObj.OptionD = objSheet.get_Range(objSheet.Cells[i, 7], objSheet.Cells[i, 7]).Text.ToString();
AssObj.CorrectOptions = objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString();
AssObj.AnsExplaination = objSheet.get_Range(objSheet.Cells[i, 9], objSheet.Cells[i, 9]).Text.ToString();
AssObj.AddQuestion();
flag = 1;
}
else if (qt == 3)
{
BLL_Assessment AssObj = new BLL_Assessment();
AssObj.QuestionType = qt;
AssObj.CourseID = Convert.ToInt16(ddlCourseName.SelectedValue);
AssObj.ModuleID = Convert.ToInt16(ddlCourseModule.SelectedValue);
AssObj.QuestionText = objSheet.get_Range(objSheet.Cells[i, 3], objSheet.Cells[i, 3]).Text.ToString();
AssObj.OptionA = "";
AssObj.OptionB = "";
AssObj.OptionC = "";
AssObj.OptionD = "";
AssObj.CorrectOptions = objSheet.get_Range(objSheet.Cells[i, 8], objSheet.Cells[i, 8]).Text.ToString();
AssObj.AnsExplaination = objSheet.get_Range(objSheet.Cells[i, 9], objSheet.Cells[i, 9]).Text.ToString();
AssObj.AddQuestion();
flag = 1;
}
}
Session["msg"] = "Questions Imported Successfully..";
}
//---------------------------------//
//CLEAN OBJECT-------
objWB.Close(null, null, null);
objXL.Workbooks.Close();
objXL.Quit();
//System.Runtime.InteropServices.Marshal.ReleaseComObject(objRng);
System.Runtime.InteropServices.Marshal.ReleaseComObject(objXL);
System.Runtime.InteropServices.Marshal.ReleaseComObject(objSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(objWB);
objSheet = null;
objWB = null;
objXL = null;
GC.Collect();
//-----------
}
catch (Exception ex)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, ex.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, ex.Source);
LCE.Configuration.ErrorLog("Assessment/ImportQuestions.cs", errorMessage);
}
finally
{
Dispose();

System.Diagnostics.Process[] prs = System.Diagnostics.Process.GetProcesses();

foreach (System.Diagnostics.Process proces in prs)
{

if (proces.ProcessName.ToUpper() == "EXCEL")
{
proces.Refresh();
if (!proces.HasExited)
proces.Kill();
}
}
}
}

HOw to use INLINE JAAVSCRIPT IN .cs file and REFRESH FUNCTION

Response.Write("script language='javascript'>aalert('Time over !!!'); window.close();");


REFRESH function in js


function Refresh()
{
windsow.opener.documesnt.location.reload();
}

Use OnItem Data Bound function

private void gdListOfQuestions_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
try
{
System.Web.UI.HtmlControls.HtmlInputCheckBox chkbx = new System.Web.UI.HtmlControls.HtmlInputCheckBox();

if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
string[] strSelectedQn;
strSelectedQn = selected_qn_ids1.Value.ToString().Split(',');
for (int i = 0; i < strSelectedQn.Length; i++)
{
if ((strSelectedQn[i].ToString() == e.Item.Cells[0].Text))
{
chkbx = ((System.Web.UI.HtmlControls.HtmlInputCheckBox)(e.Item.FindControl("chkAssign")));
chkbx.Checked = true;
}
}
}
}
catch (Exception ex)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, ex.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, ex.Source);
LCE.Configuration.ErrorLog("Assessment/CreateAssessment.cs", errorMessage);
}
}

HOw to use user defined function in sql server 2005

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.Text.RegularExpressions;
using System.Data.SqlTypes;
///
/// Summary description for Reg_exp
///

public partial class Reg_exp
{
[Microsoft.SqlServer.Server.SqlFunction(IsDeterministic=true,IsPrecise=true)]
public static SqlString Reg_exp_function(SqlString expression, SqlString pattern, SqlString replace)
{
if (expression.IsNull || pattern.IsNull || replace.IsNull)
return SqlString.Null;

Regex r = new Regex(pattern.ToString());

return new SqlString(r.Replace(expression.ToString(), replace.ToString()));

}
}

NOW ACCESS THIS FUNCTION FROM SQL SERVER]


1) sp_configure 'clr enabled',1

2) reconfigure

3) select dbo.Reg_exp_function('Remove1All3Letters7','[a-zA-Z]','')

How to use regular expression in sql server 2005

create table Contacts (
FirstName nvarchar(30),
LastName nvarchar(30),
EmailAddress nvarchar(30) CHECK (dbo.RegExMatch('[a-zA-Z0-9_\-]+@([a-zA-Z0-9_\-]+\.)+(com|org|edu|nz)', EmailAddress)=1),
USPhoneNo nvarchar(30) CHECK (dbo.RegExMatch('\([1-9][0-9][0-9]\) [0-9][0-9][0-9]\-[0-9][0-9][0-9][0-9]', UsPhoneNo)=1))

Thursday, February 4, 2010

HOW TO USE IF ELSE IN PROC

ALTER PROCEDURE [dbo].[360LMS_DashBoard]

@UserID int,
@temp int

AS

if @temp=1
begin

Declare @tempUinfo TABLE
(sr smallint IDENTITY Primary Key,
MyFullName nvarchar(50),
CollegeName nvarchar(50),
Faculty nvarchar(50),
EmailID nvarchar(20),
MobileNumber nvarchar(20),
RegistrationDate datetime
)
INSERT INTO @tempUinfo

select FirstName+' '+MiddleName+' '+LastName as MyFullName,CollegeName,Faculty,EmailID,MobileNumber,
RegistrationDate from [360LMS_Users] where UserID=@UserID

select sr,MyFullName,CollegeName,Faculty,EmailID,MobileNumber,Convert(varchar,RegistrationDate,100) as

RegistrationDate from @tempUinfo
end


else if @temp=2
begin

Declare @tempCCStatus TABLE
(sr smallint IDENTITY Primary Key,
CourseTitle nvarchar(50),
ModuleName nvarchar(50),
LastAccessDate nvarchar(50),
TotalAccessTime nvarchar(50),
LessonStatus nvarchar(50)
)
INSERT INTO @tempCCStatus
select'Certified Course In Information Security' as CourseTitle,cd.CourseTitle as ModuleName,
sco.SuspendData as LastAccessDate,sco.TotalTIme as TotalAccessTime,sco.LessonStatus
from [360LMS_Users] as u,[LearnGrid_UserCourses] as uc,[LearnGrid_CourseData] as cd,[LearnGrid_UserSCOData]

as sco
where u.UserID=uc.UserID and uc.CourseID=cd.CourseID and uc.EventID=sco.EventID and u.UserID=@UserID

select sr,CourseTitle,ModuleName,Convert(varchar,LastAccessDate,100) as

LastAccessDate,TotalAccessTime,LessonStatus from @tempCCStatus
end

HOW TO USE TRIGGER ON TABLE OR AFTER TRIGGER (AFTER REGISTRATION ALL COURSES WILL ASSIGNS TO USERS)

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[trigRegUser] ON [dbo].[360LMS_Users]
FOR INSERT AS

declare @intUserID int
declare @intCourseID int
declare @bitDebug bit
declare @dtRegistratioDate datetime
declare @intEventID int

set @bitDebug = 0
set @dtRegistratioDate = GETDATE()
set @intUserID=(select max(UserID) from [360LMS_Users] )
declare @Identifier nvarchar(50)
declare @LessonStatus nvarchar(50)
declare @SCOExit nvarchar(50)
declare @SCOEntry nvarchar(50)
declare @RawScore int
declare @PreTestScore int
declare @PostTestScore int
declare @SuspendData nvarchar(50)
declare @Credit nvarchar(50)
declare @TotalTIme nvarchar(50)

set @Identifier = 1
set @LessonStatus = 'not attempted'
set @SCOExit = NULL
set @SCOEntry = 'ab-initio'
set @RawScore = 0
set @PreTestScore = 0
set @PostTestScore = 0
set @SuspendData = NULL
set @Credit = 'Information Security'
set @TotalTIme = '00:00:00'

/*get all courses*/
DECLARE curTempCourseID Cursor Fast_Forward for
SELECT CourseID from LearnGrid_CourseData
Open curTempCourseID
fetch next from curTempCourseID into @intCourseID
While @@Fetch_Status = 0
BEGIN
exec [360LMS_UserCoursesAdd] @intUserID,@intCourseID,@bitDebug,@dtRegistratioDate set @intEventID =

@@IDENTITY

exec [360LMS_UserSCODataAdd] @intEventID,@Identifier ,@LessonStatus,@SCOExit ,@SCOEntry ,@RawScore

,@PreTestScore , @PostTestScore ,@SuspendData ,@Credit ,@TotalTIme

fetch next from curTempCourseID into @intCourseID
END
CLOSE curTempCourseID
DEALLOCATE curTempCourseID

HOW TO USE VARIABLES IN PROC

ALTER PROCEDURE [dbo].[360LMS_LogOutUser]
(
@UserID int
)
AS
declare @logid int
declare @Ttime int
declare @intime Datetime
set @logid=(Select Max(LogID) from [360LMS_UserLogs] where UserID=@UserID)

set @intime=(Select LoginDateTime from [360LMS_UserLogs] where UserID=@UserID and LogID=@logid)
set @Ttime=(Select Max(TotalTime) from [360LMS_UserLogs] where UserID=@UserID)

set @Ttime=(@Ttime + DATEDIFF(minute, @intime, getdate()))

Update [360LMS_UserLogs] set LogoutDateTime =getdate(),SessionTime=DATEDIFF(minute, @intime, getdate()) ,
TotalTime=@Ttime
where UserID=@UserID and
LogID=@logid;
UPDATE [360LMS_Users] SET LoginFlag='False' where UserID=@UserID
Update [360LMS_tblChatMassages] set IsOnline='False' where UserID=@UserID

HOW TO USe temporary TABLE

set ANSI_NULLS OFF
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[360LMS_SearchUserPaymentDetail]
@username nvarchar(50)
AS


Declare @temppayment TABLE
(srno smallint IDENTITY Primary Key,
UserID int,
fullname nvarchar(50),
CollegeName nvarchar(50),
Faculty nvarchar(50),
CourseTitle nvarchar(50),
TotalAmountPaid int,
balance int,
duration nvarchar(100),
IsActive int,
RoleId int,
UserName nvarchar(50)
)

INSERT INTO @temppayment
SELECT ucp.UserID,
u.FirstName+' '+u.LastName as fullname,
u.CollegeName,
u.Faculty,
'Certified Course In Information Security' as CourseTitle,
ucp.TotalAmountPaid,
(12500 - ucp.TotalAmountPaid) as balance,
ucp.Duration,
u.IsActive,
u.RoleId,
u.UserName
FROM [360LMS_Users] as u,
[360LMS_UserCoursePayment] As ucp
WHERE
u.UserID=ucp.UserID and u.RoleId='3' and u.DeleteFlag <> 'True'
and (u.FirstName like '%'+@username+'%' or u.FirstName like '%'+@username+'%' )
and ucp.TotalAmountPaid = (SELECT MAX(TotalAmountPaid) FROM [360LMS_UserCoursePayment] WHERE UserID = ucp.UserID )

select * from @temppayment;

HOW TO WRITE PROCEDURE FOR INSERT

set ANSI_NULLS ON
set QUOTED_IDENTIFIER OFF
GO
ALTER PROCEDURE [dbo].[360LMS_User_Registration]
(
@college_name nvarchar(50),
@user_name nvarchar(50),
@password nvarchar(50),
@rollnumber nvarchar(10),
@first_name nvarchar(50),
@middle_name nvarchar(50),
@last_name nvarchar(50),
@sex char(1),
@birth_date datetime,
@faculty nvarchar(50),
@qualification nvarchar(50),
@mobile_number nvarchar(15),
@email_id nvarchar(50),
@address nvarchar(50)
)

AS

INSERT INTO

[360LMS_Users](CollegeName,UserName,Password,RollNumber,FirstName,MiddleName,LastName,Sex,BirthDate,Faculty,Qualification,Mob

ileNumber,EmailID,Address,RegistrationDate)

VALUES(@college_name,@user_name,@password,@rollnumber,@first_name,@middle_name,@last_name,@sex,@birth_date,@faculty,@qualific

ation,@mobile_number,@email_id,@address,getdate())


FOR UPDATE

update [360LMS_Users] set

FirstName=@first_name,MiddleName=@middle_name,LastName=@last_name,CollegeName=@college_name,Sex=@sex,BirthDate=@birth_date,Fa

culty=@faculty,Qualification=@qualification,MobileNumber=@mobile_number,EmailID=@email_id,Address=@address where

UserID=@user_id

CHANGE DATA OF ROW AT VALUE BOUND

protected void grvUserThread_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
Label lb = new Label();
lb = (Label)e.Row.FindControl("lblEdit");
string tuid = Convert.ToString(e.Row.Cells[3].Text);
if ((tuid != "UserID") && (lb != null))
{
int temp = Convert.ToInt32(tuid);
if (temp == Convert.ToInt16(Session["UserID"]))
{
lb.Visible = true;
}
}
}
catch(Exception ex)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, ex.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, ex.Source);
LCE.Configuration.ErrorLog("Forum/ReplyToThreads.cs", errorMessage);
}
}

HOW TO CUSTOMIZE DATAHEADER OF GRIDVIEW ?

protected void grvUserThread_RowCreated(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow headerRow = e.Row;
Label lb = new Label();
lb = (Label)e.Row.FindControl("lblabc");
lb.Text = "Thread: " + Thread;
}
}
catch(Exception ex)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, ex.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, ex.Source);
LCE.Configuration.ErrorLog("Forum/ReplyToThreads.cs", errorMessage);
}
}

HOW TO SEND ANY ID THROUGH QUERY STRING IN JS

function DeleteUser(UserId)
{
if(UserId > 0)
{
if(confirm("Do you want to delete this user ?"))
{
window.location="ListOfUsers.aspx?UserID="+UserId;
}
}
}

HOW TO GET QUERYSTRING VALUE

if(Request.QueryString["UserID"] != null)
{
userid = Convert.ToInt16(Request.QueryString["UserID"].ToString());
}


OR
if (!(Request.QueryString["Thread_ID"] == null))
{
threadid = Convert.ToInt32(Request.QueryString["Thread_ID"]);
}

HOW TO USE USER CONTROL IN .ASPX PAGE

<%@ Register TagPrefix="UC" TagName ="RegUser" Src ="~/Include/UserControl/UserRegistration.ascx" %>









OR

<%@ Register TagPrefix ="SUBMENU" TagName ="PreferencesSubMenu" Src ="~/Include/UserControl/PreferencesSubMenu.ascx" %>




SEND MAIL CLASSSSSSSSSSSSSS

public bool sendMail(string fromEmail, string toEmail, string mailSubject, string mailBody, MailFormat mailFormat, string

fromName, string toName)
{

try
{
if (fromName == "")
{
fromName = ConfigurationSettings.AppSettings["siteName"];
}
if (toName == "")
{
toName = toEmail;
}

MailMessage mail = new MailMessage();


mail.From = fromEmail;
mail.To = toEmail;
mail.Subject = mailSubject;
mail.BodyFormat = mailFormat;
mailBody += "";
mail.Body = mailBody;

SmtpMail.SmtpServer = ConfigurationSettings.AppSettings["SmtpServer"];
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername",

ConfigurationSettings.AppSettings["sendemailusername"]);
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword",

ConfigurationSettings.AppSettings["sendemailpassword"]);
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", 2);
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver",

ConfigurationSettings.AppSettings["SmtpServer"]);
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout", 50);
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", 25);

//SmtpMail.SmtpServer = ConfigurationSettings.AppSettings["SmtpServer"];
////SmtpMail.SmtpServer.Insert(0, ConfigurationSettings.AppSettings["SmtpServer"].ToString());
// mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
// mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername",

ConfigurationSettings.AppSettings["sendemailusername"]);
// mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword",

ConfigurationSettings.AppSettings["sendemailpassword"]);


SmtpMail.Send(mail);

return true;
}
catch (Exception ex)
{
return false;
}
}

CHANGE PASSWORD AND SEND MAIL FUNCTION

protected void btnsave_Click(object sender, EventArgs e)
{
try
{
DataTable dt = new DataTable();
int userid = Convert.ToInt16(Session["UserID"].ToString());
BLL_Users objuser = new BLL_Users();
objuser.UserID = userid;
objuser.Password = txtoldpwd.Text.Trim();
objuser.NewPwd = txtnewpwd.Text.Trim();

dt = objuser.ValidateUserByUserID();
if (dt.Rows.Count > 0)
{

if ((Convert.ToInt16(dt.Rows[0]["IsChange"])) > 0)
{
lblsuccess.Font.Bold = true;
lblsuccess.ForeColor = Color.Red;
lblsuccess.Text = "Please enter correct old password.";
txtoldpwd.Text = "";
}
else
{
lblsuccess.Font.Bold = true;
lblsuccess.ForeColor = Color.Green;
lblsuccess.Text = "Password has been changed successfully.";

DataTable dt1 = new DataTable();
BLL_Users objView = new BLL_Users();
objView.UserID = Convert.ToInt32(Session["UserID"].ToString());
dt1 = objView.GetUserInformation();
if (dt1.Rows.Count > 0)
{
String bodyText = "";
bodyText = "";
bodyText = bodyText + "Dear" + " " + dt1.Rows[0]["FirstName"].ToString() + " " +

dt1.Rows[0]["LastName"].ToString() + ",";
bodyText = bodyText + "
";
bodyText = bodyText + "
";
bodyText = bodyText + "Your password has been changed to :";
bodyText = bodyText + " " + txtnewpwd.Text + "";
bodyText = bodyText + "
";
bodyText = bodyText + "
";
bodyText = bodyText + "If you have any queries or want to send nominations, please mail the same to

aatish09@gmail.com " + "
";
bodyText = bodyText + "
";
bodyText = bodyText + "All the best!";
bodyText = bodyText + "
";
bodyText = bodyText + "
";
bodyText = bodyText + "Regards,";
bodyText = bodyText + "
";
bodyText = bodyText + "Learning Organization ";
bodyText = bodyText + "
";
bodyText = bodyText + "Three Sixty Degree Data Research Pvt.Ltd. Pune";
bodyText = bodyText + "
";
//bodyText = String.Empty;
bool check;

BLL_SendMail objmail = new BLL_SendMail();
check = objmail.sendMail(ConfigurationSettings.AppSettings["adminEmail"],

dt1.Rows[0]["EmailID"].ToString(), "Change Password", bodyText, MailFormat.Html, "", "");
if (check == true)
{
lblsendmail.Visible = true;
lblsendmail.Text = "Password has been Mailed to you, Please check mail.";

}
else
{
lblsendmail.Visible = true;
lblsendmail.Font.Bold = true;
lblsendmail.ForeColor = Color.Red;
lblsendmail.Text = "Problem in sending Email.";
}
}
}
}
}
catch(Exception ex)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, ex.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, ex.Source);
LCE.Configuration.ErrorLog("Preferences/ChangePassword.cs", errorMessage);
}
}

HOW TO USE SELECT ALL CHECK BOX FUNCTION



< type="text/javascript" language="javascript">
function CheckData()
{
GetSelected()
if(document.getElementById('<%=selected_qn_ids1.ClientID %>').value == "")
{
alert("No user is selected for enrollment.");
return false;
}
}
function GetSelected()
{
var grdInput;
var strSelectedIds;
var chkLength;
var intLoopCount;
var intarr = 0;
var arr = new Array(100);

grdInput = document.getElementById('<%= dgStudentEnroll.ClientID %>').getElementsByTagName("input");
chkLength = grdInput.length;

for(intLoopCount=0;intLoopCount<)
{
if(grdInput[intLoopCount].type == "checkbox")
{
if(grdInput[intLoopCount].checked == true)
{
if(document.getElementById("<%= selected_qn_ids1.ClientID %>").value == "")
{
var Qid= grdInput[intLoopCount].value;
document.getElementById("<%= selected_qn_ids1.ClientID %>").value = Qid;


}
else
{
var Qid= grdInput[intLoopCount].value;
document.getElementById("<%= selected_qn_ids1.ClientID %>").value =

document.getElementById("<%= selected_qn_ids1.ClientID %>").value + "," + Qid;
var str=document.getElementById("<%= selected_qn_ids1.ClientID %>").value;
}
intarr = intarr + 1;
}
else
{

}
}
}
}

HOW TO USE DATAGRID WITH DATAFILED FROM DATABASE


="#999999" ForeColor="#FFFFFF" HeaderStyle-HorizontalAlign ="Center" >


="#000000" ItemStyle-Width ="40px" ItemStyle-HorizontalAlign="Center" >


="#000000" ItemStyle-Width ="200px" ItemStyle-HorizontalAlign="Center" >


ItemStyle-ForeColor ="#000000" ItemStyle-Width ="300px" ItemStyle-HorizontalAlign="Center" >


ItemStyle-ForeColor ="#000000" ItemStyle-Width ="150px" ItemStyle-HorizontalAlign="Center" >


ItemStyle-ForeColor ="#000000" ItemStyle-Width ="100px" ItemStyle-HorizontalAlign="Center" >


ItemStyle-ForeColor ="#000000" ItemStyle-Width ="100px" ItemStyle-HorizontalAlign="Center" >


="#000000" ItemStyle-Width ="100px" ItemStyle-HorizontalAlign="Center" >


="#000000" ItemStyle-Width ="100px" ItemStyle-HorizontalAlign="Center" >


ItemStyle-ForeColor ="#000000" ItemStyle-Width ="100px" ItemStyle-HorizontalAlign="Center" >


ItemStyle-ForeColor ="#000000" ItemStyle-Width ="150px" ItemStyle-HorizontalAlign="Center" >


ItemStyle-ForeColor ="#000000" ItemStyle-Width ="100px" ItemStyle-HorizontalAlign="Center" >


="#000000" ItemStyle-Width ="150px" ItemStyle-HorizontalAlign="Center" >


HOW TO RETURN RECORDS FROM EXCEL SHEET aND HOW TO USE FINALLY BLOCK

DataSet ds = GetExcel(path + "\\" + strFile);
string chk_reg = "";
int rowCount = ds.Tables[0].Rows.Count;
if (rowCount > 0)
{
for (int z = 0; z < 1; z++)
{
}

public DataSet GetExcel(string fileName)
{
Application oXL;
Workbook oWB;
Worksheet oSheet;
Range oRng;
try
{
// creat a Application object
oXL = new ApplicationClass();
// get WorkBook object
oWB = oXL.Workbooks.Open(fileName, 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);

// get WorkSheet object
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.Sheets[1];
System.Data.DataTable dt = new System.Data.DataTable("dtExcel");
DataSet ds = new DataSet();
ds.Tables.Add(dt);
DataRow dr;

StringBuilder sb = new StringBuilder();
int jValue = oSheet.UsedRange.Cells.Columns.Count;
int iValue = oSheet.UsedRange.Cells.Rows.Count;
// get data columns
for (int j = 1; j <= jValue; j++)
{
dt.Columns.Add("column" + j, System.Type.GetType("System.String"));
}

// get data in cell
for (int i = 1; i <= iValue; i++)
{
dr = ds.Tables["dtExcel"].NewRow();
for (int j = 1; j <= jValue; j++)
{
oRng = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[i, j];
string strValue = oRng.Text.ToString();
dr["column" + j] = strValue;
}
ds.Tables["dtExcel"].Rows.Add(dr);
}
return ds;
}
catch (Exception ex)
{
return null;
}
finally
{
Dispose();
System.Diagnostics.Process[] prs = System.Diagnostics.Process.GetProcesses();
foreach (System.Diagnostics.Process proces in prs)
{
if(proces.ProcessName.ToUpper()=="EXCEL")
{
proces.Refresh();
if (!proces.HasExited)
proces.Kill();
}
}
}
}

HOW TO DOWNLOAD EXCEL SHEET

protected void linkBtnDownLoad_Click(object sender, EventArgs e)
{
DownLoadExcel();
}

private void DownLoadExcel()//function for download excel sheet format.
{
try
{
//b4 download file make sure that file access is not denied ,so set file attribute IsReadonly to false.
string download_filename = Server.MapPath("../Reports") + "\\StudentRegistration.xls";
System.IO.FileInfo fileInfo = new System.IO.FileInfo(download_filename);
fileInfo.IsReadOnly = false;
FileStream fs;
fs = File.Open(Server.MapPath("../Reports") + "\\StudentRegistration.xls", FileMode.Open);
Byte[] bytBytes = new Byte[fs.Length];
fs.Read(bytBytes, 0, Convert.ToInt32(fs.Length));
fs.Close();
Response.AddHeader("Content-disposition", "attachment; filename=StudentRegistration.xls");
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(bytBytes);
Response.End();
}
catch (Exception ex)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, ex.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, ex.Source);
LCE.Configuration.ErrorLog("ManageUsers/ImportFromExcel.cs", errorMessage);
}
}

HOW TO HIDE AND SHOW DIV AT JAVASCRIPT

function ShowDiv()
{

document.getElementById('<%=div_reply_to_thread.ClientID %>').style.display='block';
document.getElementById('<%=td_btn_reply.ClientID %>').style.display='block';
document.getElementById('<%=td_btn_edit.ClientID %>').style.display='none';
}
function HideDiv()
{
document.getElementById('<%=div_reply_to_thread.ClientID %>').style.display='none';
}

HOW TO USE CUSTOMIZE COLUMN FIELD IN GRIDVIEW HOW TO USE HIDDEN FIELD

BorderColor="#999999" ForeColor="#FFFFFF" HeaderStyle-HorizontalAlign="Center"
OnRowDataBound="gvAllThreads_RowDataBound">

ItemStyle-ForeColor="#000000" ItemStyle-Width="40px" ItemStyle-HorizontalAlign="Center">

ItemStyle-Width="700px" ItemStyle-HorizontalAlign="Center">

< href="javascript:GetThreadID('<%# DataBinder.Eval(Container.DataItem,"ThreadID")%>')">
<%# DataBinder.Eval(Container.DataItem,"Subject")%>img




ItemStyle-ForeColor="#000000" ItemStyle-Width="150px" ItemStyle-HorizontalAlign="Center">

ItemStyle-ForeColor="#000000" ItemStyle-Width="50px" ItemStyle-HorizontalAlign="Center">

ItemStyle-ForeColor="#000000" ItemStyle-Width="50px" ItemStyle-HorizontalAlign="Center">

ItemStyle-Width="200px" ItemStyle-HorizontalAlign="Center">

< ID="lblLastPostDate" Text='<%#DataBinder.Eval(Container.DataItem,"LastPostedDate")%>'
runat="server">

< ID="lblPostedUserName" Text='<%#DataBinder.Eval(Container.DataItem,"FirstName")%>'
runat="server"> img1



ItemStyle-Width="75px" ItemStyle-HorizontalAlign="Center" Visible="false">

< href="javascript:Get_ThreadID('<%# DataBinder.Eval(Container.DataItem,"ThreadID")%>')">
img


ItemStyle-HorizontalAlign="Center" Visible="false">


onclick="javascript:SelectAll(this);" />


< id="chkAssign" runat='server' type="checkbox" value='<%#

DataBinder.Eval(Container.DataItem,"ThreadID")%>'
onclick="javascript:SelectedChange(this);" name="chkAssign" />





HOW TO fill installment dropdown list

ds1 = objcheck.CheckPaidInstallment();
if (ds1.Tables.Count > 0)
{
ddlInstallment.DataSource = ds1;
ddlInstallment.DataTextField = ds1.Tables[0].Columns["PaymentType"].ColumnName.ToString();
ddlInstallment.DataValueField = ds1.Tables[0].Columns["PaymentID"].ColumnName.ToString();
ddlInstallment.DataBind();
ddlInstallment.Items.Insert(0, "--Select--");
}

To show users photo, take users Image url from db. then assign image path of disk to ImageUrl.

string ImageUrlFromDB = dt.Rows[0]["ImageUrl"].ToString();
string UserImage = Session["rootPath"] + "/UserImages/" + ImageUrlFromDB.ToString().Trim();
Image1.ImageUrl = UserImage;
Image1.AlternateText = "img";

HOW TO SAVE USERS IMAGE IN DB: STORE ONLY PATH IN DB AND IMAGES IN FOLDER ON SERVER

protected void btnupload_Click(object sender, EventArgs e)
{
try
{
BLL_Users objimage = new BLL_Users();
objimage.UserID = Convert.ToInt16(Session["UserID"].ToString());
string filename = ImageUpload.FileName;//find the extension of the uploaded image.convert it into lower case.


//if following 2 lines(which remove readonly pro of the image) r make enable then images from client m/c will not

save to server
//System.IO.FileInfo fileInfo = new System.IO.FileInfo(ImageUpload.PostedFile.FileName);//first remove readonly

of any image from wher r u uploding
//fileInfo.IsReadOnly = false;

string fileName = Server.HtmlEncode(FileUpload1.FileName);
string ext= System.IO.Path.GetExtension(fileName);

if (ImageUpload.HasFile && ext == ".jpeg" || ext == ".jpg" || ext == ".bmp" || ext == ".png" || ext == ".gif")
{
ImagePath = Server.MapPath("../"); // find LMSBeta
string ImagePath1 = ImagePath + "UserImages"; // attach /LMSBeta/UserImages
objimage.ImageURL = Session["FirstName"].ToString() + Session["LastName"].ToString() + ext; //send

username+ext
objimage.UpdateUserImage();

ImageUpload.SaveAs(ImagePath1 + "\\" + Session["FirstName"] + Session["LastName"]+ ext); //if user register

then only save his image to disk with his username + ext.
Image1.ImageUrl = ImagePath1 + "\\" + Session["FirstName"] + Session["LastName"] + ext;
Response.Redirect("ViewProfile.aspx?action=viewprofile",false);
}
else
{
Session["imgErr"] = "Only .jpeg, .jpg, .bmp, .png, .gif file formats supported.";
Response.Redirect("ViewProfile.aspx?action=viewprofile",false);
}
}
catch(Exception ex)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, ex.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, ex.Source);
LCE.Configuration.ErrorLog("Include/UserRegistration.cs", errorMessage);
}
}

INSERT radiobutton value in db

objReg.Sex = RadioBtnSex.SelectedItem.Text;

select radiobutton value from db

if (Convert.ToString(dt.Rows[0]["Sex"]) == "M")
{
lbl_gender.Text = "Male";
}
else
{
lbl_gender.Text = "Female";
}

INSERT DROPDDOWN LIST value in db

objReg.Faculty = drpdFaculty.SelectedValue;

select DROPDDOWN LIST value from db

if (Convert.ToString(dt.Rows[0]["Faculty"]) == "")
{
drpdFaculty.SelectedValue = "--Select--";
}
else
{
drpdFaculty.SelectedValue = dt.Rows[0]["Faculty"].ToString();
}

HOW TO USE VARIABLE ON ASPX PAGE AT DATA BINDING

< href="javascript:ForgotPwd('<%=userid %>')">
Visible="true">



userid = Convert.ToInt16(Request.QueryString["UserID"].ToString());//this is for sending user id to change password window. // in .cs file

HOW TO CREATE HTML TABLE USING STRING BUILDER ?

StringBuilder strBldr = new StringBuilder();
StringBuilder strFAQ = new StringBuilder();


strFAQ.Append("");


//for(int iTemp = 0 ;i< dsListOfFAQ.Tables[0].Rows.Count;i++)
int Counter = dsListOfFAQ.Tables[0].Rows.Count;

if (Counter > 0)
{
int count = 1;

foreach (DataRow dr in dsListOfFAQ.Tables[0].Rows)
{

//DataRow dr = dsListOfFAQ.Tables[0].NewRow();

strFAQ.Append("");

strFAQ.Append("");
strFAQ.Append("");
count += 1;

}
strFAQ.Append("
");
//strFAQ.Append( Convert.ToInt32(dr["FAQID"].ToString()) +".");
strFAQ.Append(Convert.ToInt32(dr["serial"].ToString()) + ".");

//divFAQList.InnerHtml += "
='"+ Convert.ToInt32(dr["FAQID"].ToString()) +"'>
";


strFAQ.Append("" + dr["Question"].ToString() + "");
//divFAQList.InnerHtml += "
";



strFAQ.Append("

");
strFAQ.Append(dr["Answer"].ToString());

if (count == dsListOfFAQ.Tables[0].Rows.Count)
{
strFAQ.Append("
");
strFAQ.Append("
");
}


strFAQ.Append("Click here

to Edit    ");
//strFAQ.Append(" " + "Approve    " + " ");
strFAQ.Append("Delete");

strFAQ.Append("

");

strFAQ.Append("
");
lblFAQ.Text = strFAQ.ToString();
}
else
{
lblFAQ.Text = "No record found.";
lblFAQ.ForeColor = System.Drawing.Color.Red;
lblFAQ.Font.Bold = true;
}
}

WHAT IS GLOBAL.ASPX PAGE EVENTS AND HOW TO COUNT TOTAL APPLICATION HIT COUNTERS AND SESSION COUNT

<%@ Application Language="C#" %>

HOW TO CHANGE THEME AND MASTER PAGE ON PRE INIT

protected override void OnPreInit(EventArgs e)
{
if (Session["UserID"] != null)
{
string thm;
thm = (string)Session["Theme"];
if (thm != null)
{
Page.Theme = thm;
}
else
{
Page.Theme = "Theme1";
}
if (Convert.ToString(Session["RoleName"].ToString().Trim()) == "SuperAdmin")
{
string masterfile = "../SuperAdmin/SuperAdmin.master";
if (!masterfile.Equals(string.Empty))
{
base.MasterPageFile = masterfile;
}
}
else if (Convert.ToString(Session["RoleName"].ToString().Trim()) == "Administrator")
{
string masterfile = "../Admin/CollegeAdmin.master";
if (!masterfile.Equals(string.Empty))
{
base.MasterPageFile = masterfile;
}
}
else if (Convert.ToString(Session["RoleName"].ToString().Trim()) == "Student")
{
string masterfile = "../Users/UserMasterPage.master";
if (!masterfile.Equals(string.Empty))
{
base.MasterPageFile = masterfile;
}
}
base.OnPreInit(e);
}
else
{
Response.Redirect(LCE.Configuration.GetRootPath().ToString() + "/Login.aspx", false);
}
}

HOW TO GIVE ROOT PATH TO LINKS

< href="<%= rootPath%>/Courses/MyCourses/Default.aspx">Assign Modules



< href="<%= rootPath%>/Assessment/MyAssesments/UserAssessments.aspx">Assign Assessments


public string rootPath = LMSBeta.BLL.Configuration.GetRootPath();
public string role;
protected void Page_Load(object sender, EventArgs e)
{
role = Convert.ToString(Session["RoleName"]);
}

HOW TO OPEN WINDOW IN JS ONCLICK


Sample Certificate


HOW TO CREATE CSS FILE and CLASSSESS

*{margin:0;padding:0}
* html,body{height:100%;width:100%;}
a{color:#000000;text-decoration:none; height :26px;}
a:link{ color: #000000;text-decoration:none; }
a:visited{ color: #0000ff;text-decoration:none;}
a:hover{color: #0000ff; text-decoration:underline; height :26px; padding:0px 0px 0px 0px; }
a:active{ color: #0000ff; text-decoration:none;padding:0px 0px 0px 0px;}

body
{
margin:0px auto;
padding:0px auto;
background-color: #FFFFFF;
text-align:center;

/*min-height:468px; for good browsers*/
/*min-width:916px; for good browsers*/
font-family: verdana, sans-serif;
font-size: 11px;
}
.Outer
{
clear:both;
width:950px;
min-width:950px;
min-height:468px;
margin:0px auto;
margin-top:auto;
margin-bottom:auto;
text-align:center;
border:1px solid #CCCCCC;
position:relative;
top:auto;
display:table;
vertical-align: middle;
}
.Menu
{
clear:both;
width:916px;
height:88px;
margin:0px auto;
/*border:1px solid #000000;min-width:916px;*/

background:url(Images/icon_bg.jpg) no-repeat;
}
.TopHeader
{
clear:both;
width:952px;
height:160px;
background-color: #f9f9f9;
background:url(buttons/Top_Banner.jpg) no-repeat;
}
.LeftSubMenu
{
clear:both;
float:left;
text-align:left;
/*line-height:20px;*/
padding:20px 0px 0px 17px;

width:223px;
vertical-align:middle;
/*background-color:#d6d6d6;

border:1px solid #000000;*/
background-color:#f9f9f9;
min-width:223px;
}
.LeftMenuHeader
{
margin:0px auto;
padding:0px auto;
height:31px;
width:223px;
text-align:center;
background:url(Images/left_menu_top.jpg) no-repeat;
}
.LeftMenuBottom
{
margin:0px auto;
padding:0px auto;
height:31px;
width:223px;
text-align:center;
background:url(Images/left_menu_bottom.jpg) no-repeat;
}
.Separater
{
margin:0px auto;
padding:0px auto;
height:24px;
width:223px;
text-align:center;
background:url(Images/Line_Image.jpg) no-repeat;

}
.RightContent
{
float:right;
padding:20px 5px 0px 0px;
margin:0px auto;
min-height:324px;
width:680px;
background-color:#f9f9f9;

}
.ContentTopBar
{
margin:0px auto;
padding:0px 0px 0px 0px;
height:31px;
width:660px;
text-align:center;
background:url(Images/Content_top_bg.jpg) no-repeat;
}

.Form
{
clear:both;
width:950px;
min-height:340px;
background-color:#FBFBFB;
/*background:url(Home/border.jpg) repeat-y;

border-left:2px solid #cccccc;
border-right:2px solid #cccccc;*/
}
.LeftTop
{
margin:0px auto;
float:left;
vertical-align:middle;
height:150px;
width:730px;


}
.RightTop
{
float:right;
height:150px;
width:200px;

}
.content
{
clear:both;
width:100%;
min-height:340px;
}
.ContentTopBg
{
height:29px;
width:660px;
background:url(buttons/ContentTopBg.jpg) no-repeat;
}
.ContentMidBg
{
width:660px;
background:url(buttons/ContentMidBg.jpg) repeat-y ;
}
.ContentFooterBg
{
height:5px;
width:660px;
background:url(buttons/ContentFooterBg.jpg) no-repeat;
}
.HomeFooter
{
clear:both;
width:952px;
height:80px;
background-color: #f9f9f9;
background:url(buttons/Bottom_Banner.jpg) no-repeat;
}

.Footer
{
text-align:right;
padding:0px 0px 0px 0px;
clear:both;
width:952px;
height:20px;
background-color: #f9f9f9;
/*background:url(buttons/Bottom_Banner.jpg) no-repeat;*/
}
.login_bg
{
margin:0px auto;
margin-top:15px;
width:311px;
height:232px;
background-color: #f9f9f9;
background:url(buttons/Login_Window.jpg) no-repeat;
}
.form_top_bg
{
margin:0px auto;
margin-top:15px;
width:731px;
height:32px;
background-color: #f9f9f9;
background:url(buttons/Form_Topbg.jpg) no-repeat;
}
.form_middle_bg
{
margin:0px auto;
margin-top:15px;
width:731px;
height:18px;
background-color: #f9f9f9;
background:url(buttons/Form_middlebg.jpg) repeat-y;
}
.form_bottom_bg
{
margin:0px auto;
margin-top:15px;
width:731px;
height:20px;
background-color: #f9f9f9;
background:url(buttons/Form_Bottombg.jpg) no-repeat;
}
/*watermark text box*/

.watermarked {
/*height:20px;*/
width:150px;
padding:2px 0px 0px 2px;
border:1px solid #BEBEBE;
background-color:#F0F8FF;
color:gray;
}
/* normal text */
.ContentHeaderTop
{
width:660px;
height:29px;
background:url(buttons/Content_Top_Header.jpg) no-repeat;
}
.ContentMiddleBg
{
width:660px;
background:url(buttons/Content_Middle_BG.jpg) repeat-y;
}
.TextStyle
{
clear:both;
margin :0px auto;
width:90%;
line-height:25px;
text-align:justify;
color :#000000;
}
.CountentFooter
{
width:660px;
height:5px;
background:url(buttons/Content_Bottom_Bg.jpg) no-repeat;
}
/* by Aatish Jadhav on 25 jan 2010 */
/*For Dashboard*/

.Dashboard_top_bg
{
margin:0px auto;
margin-top:15px;
width:248px;
height:44px;
background-color: #f9f9f9;
background:url(buttons/Dashboard_top_bg.jpg) no-repeat;
}
.Dashboard_middle_bg
{
margin:0px auto;
margin-top:15px;
width:248px;
height:20px;
background-color: #f9f9f9;
background:url(buttons/Dashboard_middle_bg.jpg) repeat-y;
text-align:center;
}
.Dashboard_bottom_bg
{
margin:0px auto;
margin-top:15px;
width:248px;
height:15px;
background-color: #f9f9f9;
background:url(buttons/Dashboard_bottom_bg.jpg) no-repeat;
}

HOW TO CREATE ERRORLOG FILE

catch(Exception ex)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, ex.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, ex.Source);
LCE.Configuration.ErrorLog("Payment/PaymentList.cs", errorMessage);
}

CONFIGURATION.CS IN APP_Code folder FOR Database connection and ERROR LOGS and GET ROOT PATH

CREAe ERROR LOGS FOLDER IN ROOT PATH

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;
using System.Collections;



namespace LCE
{
using System.Web.UI;
using System.IO;
using System.Collections;
using System.Web.Security;
using System.Web;
using System.Data;
using System.Configuration;
using System;


public class Configuration
{
public static string GetConnnectionString()
{
return ConfigurationSettings.AppSettings["ConnectionString"];
}

public static string GetCurrentUSerID()
{
return HttpContext.Current.User.Identity.Name;
}
public static string GetRootPath()
{
return ConfigurationSettings.AppSettings["rootPath"];
}
public static void ErrorLog(string sFilename, string sErrMsg)
{
string sPathName="";
sPathName = System.AppDomain.CurrentDomain.BaseDirectory;
sPathName = sPathName + "ErrorLogs" + "\\ErrorLog_";
string sErrorTime;
string sYear = DateTime.Now.Year.ToString();
string sMonth = DateTime.Now.Month.ToString();
string sDay = DateTime.Now.Day.ToString();
sErrorTime = sYear +"_"+ sMonth +"_"+ sDay+".txt";
if (File.Exists(sPathName + sErrorTime))
{
File.SetAttributes(sPathName + sErrorTime, FileAttributes.Normal);//set file attributes readonly to normal.
}
using (StreamWriter objsw = new StreamWriter(sPathName + sErrorTime, true))
{
objsw.WriteLine("*****************Start*****************");
objsw.WriteLine();
objsw.WriteLine("Date/Time: " + System.DateTime.Now.ToString());
objsw.WriteLine("File Name :" + sFilename);
objsw.WriteLine("Error Msg :" + sErrMsg);
objsw.WriteLine();
objsw.WriteLine("******************End********************");
objsw.Flush();
objsw.Close();
}
}
}
}

HOW TO CREATE .sitemap file

for example web.sitemap