I have been sitting on my seat for over an hour not knowing what's the error.. Could someone please assist?
Error is said to be "When converting a string to DateTime, parse the string to take the date before putting each variable into the DateTime object.
The field name "LastLoginTime" is a DATETIME datatype in my database.
These are the codes..
protected void Page_Load(object sender, EventArgs e)
{
AuditNLoggingDAO al = new AuditNLoggingDAO();
int result = 0;
int resultLogout = 0;
DateTime dateTimeOfLatestLogin = DateTime.MinValue;
//Get IP Address of Client's Machine
String externalIP = null;
try
{
externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")).Matches(externalIP)[0].ToString();
}
catch (Exception ex)
{
logManager log = new logManager();
log.addLog("Retrieval of IP Address", "IP Address", ex);
}
if (!Page.IsPostBack)
{
if (!String.IsNullOrEmpty(Session["LoginUserName"].ToString()))
{
String loginUsername = Session["LoginUserName"].ToString();
//Get latest Login time
DataSet ds = new DataSet();
ds = al.getAuditData(Session["LoginUserName"].ToString());
foreach (DataRow r in ds.Tables[0].Rows)
{
dateTimeOfLatestLogin = Convert.ToDateTime(r["LastLoginTime"]);
}
result = al.trackLogout(loginUsername, DateTime.Now, externalIP, Convert.ToDouble(latitudeTB.Value), Convert.ToDouble(longitudeTB.Value));
resultLogout = al.updateLLogoutT(loginUsername, DateTime.Now, externalIP);
}
loginDetails.InnerText = "You logged into your account at " + dateTimeOfLatestLogin.ToString("hh:mm:ss tt dd/MM/yyyy") + " SGT.";
logoutDetails.InnerText = "You logged out from your session at " + (DateTime.Now).ToString("hh:mm:ss tt dd/MM/yyyy") + " SGT.";
}
}
I can't seemt to be able to find the mistake.. I'm guessing it's my dateTimedateTimeOfLatestLogin variable..
al.trackLogout method,
//Track Logout Activity
public int trackLogout(String username, DateTime dateTimeActivity, String ipaddress, Double latitude, Double longitude)
{
int result = 0;
StringBuilder sqlCmd = new StringBuilder();
sqlCmd.AppendLine("INSERT INTO AuditActivity (Username, DateTimeActivity, IPAddressActivity, LatitudeActivity, LongitudeActivity, ActivityType) ");
sqlCmd.AppendLine("VALUES (#addUsername, #addDT, #addIPAddress, #addLat, #addLng, #addActivity)");
try
{
SqlConnection myConn = new SqlConnection(DBConnectionStr);
myConn.Open();
SqlCommand cmd = new SqlCommand(sqlCmd.ToString(), myConn);
cmd.Parameters.AddWithValue("#addUsername", username);
cmd.Parameters.AddWithValue("#addDT", dateTimeActivity);
cmd.Parameters.AddWithValue("#addIPAddress", ipaddress);
cmd.Parameters.AddWithValue("#addLat", latitude);
cmd.Parameters.AddWithValue("#addLng", longitude);
cmd.Parameters.AddWithValue("#addActivity", "Logout");
result = cmd.ExecuteNonQuery();
myConn.Close();
return result;
}
catch (SqlException ex)
{
logManager log = new logManager();
log.addLog("AuditNLoggingDAO.trackLogout", sqlCmd.ToString(), ex);
return 0;
}
}
Not C# but don't have a C# project open to write in, so it is in VB.Net; minor syntax tweaks and changes but otherwise the same:
Public Function trackLogout(username As String, dateTimeActivity As DateTime, ipaddress As String, latitude As Double, longitude As Double) As Integer
Dim result As Integer = 0
Try
Using conn As New SqlConnection(DBConnectionStr)
Dim sb As New StringBuilder
sb.AppendLine("INSERT INTO AuditActivity (Username, DateTimeActivity, IPAddressActivity, LatitudeActivity, LongitudeActivity, ActivityType) ")
sb.AppendLine("VALUES (#addUsername, #addDT, #addIPAddress, #addLat, #addLng, #addActivity)")
Using cmd As New SqlCommand() With {.CommandText = sb.ToString(), .Connection = conn, .CommandType = CommandType.Text}
cmd.Parameters.AddWithValue("#addUsername", username)
cmd.Parameters.AddWithValue("#addDT", dateTimeActivity)
cmd.Parameters.AddWithValue("#addIPAddress", ipaddress)
cmd.Parameters.AddWithValue("#addLat", latitude)
cmd.Parameters.AddWithValue("#addLng", longitude)
cmd.Parameters.AddWithValue("#addActivity", "Logout")
result = cmd.ExecuteNonQuery
End Using
End Using
Catch ex As Exception
result = -1
' Whatever your current implementation is.
End Try
Return result
End Function
Unfortunately, doing inline sql execution requires StringBuilder. You were correct on that. I use Stored Procedures to execute structured SQL Statements, so I do not have to manage the SQL in the application.
My Revised Codes that i'm using right now..
protected void Page_Load(object sender, EventArgs e)
{
AuditNLoggingDAO al = new AuditNLoggingDAO();
int result = 0;
int resultLogout = 0;
//Get IP Address of Client's Machine
String externalIP = null;
try
{
externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")).Matches(externalIP)[0].ToString();
}
catch (Exception ex)
{
logManager log = new logManager();
log.addLog("Retrieval of IP Address", "IP Address", ex);
}
CultureInfo provider = CultureInfo.InvariantCulture;
if (!String.IsNullOrEmpty(Session["LoginUserName"].ToString()))
{
String loginUsername = Session["LoginUserName"].ToString();
//Get latest Login time
DataSet ds = new DataSet();
ds = al.getAuditData(Session["LoginUserName"].ToString());
DateTime dateTimeOfLatestLogin = DateTime.MinValue;
/*foreach (DataRow r in ds.Tables[0].Rows)
{
//dateTimeOfLatestLogin = DateTime.ParseExact(r["LastLoginTime"].ToString(), "dd-MM-yyyy hh:mm:ss", CultureInfo.InvariantCulture);
String dtDBString = r["LastLoginTime"].ToString();
dateTimeOfLatestLogin = Convert.ToDateTime(dtDBString);
//Debug.WriteLine(dateTimeOfLatestLogin);
//"MM-dd-yyyy HH:mm:ss tt"
}*/
String DBConnectionStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
SqlConnection connection = new SqlConnection(DBConnectionStr);
string sql = "select LastLoginTime FROM AuditTrails WHERE Username=#USERID";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#USERID", loginUsername);
try
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string timeTaken = reader["LastLoginTime"].ToString();
dateTimeOfLatestLogin = Convert.ToDateTime(timeTaken);
}
}
connection.Close();
}
catch (SqlException ex)
{
logManager log = new logManager();
log.addLog("LogoutWithDesc.aspx.cs", "PageLoad", ex);
}
resultLogout = al.updateLLogoutT(loginUsername, DateTime.Now, externalIP);
result = al.trackLogout(loginUsername, externalIP, Convert.ToDouble(latitudeTB.Value), Convert.ToDouble(longitudeTB.Value));
loginDetails.InnerText = "You logged into your account at " + dateTimeOfLatestLogin.ToString("hh:mm:ss tt dd/MM/yyyy") + " SGT.";
logoutDetails.InnerText = "You logged out from your session at " + (DateTime.Now).ToString("hh:mm:ss tt dd/MM/yyyy") + " SGT.";
}
}
Related
I am trying to output the print messages from a stored proc that is being execute from SSIS script task. Here is what I have so far:
public event SqlInfoMessageEventHandler InfoMessage;
void myConnection_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFile = "\\fld6filer\\BrsSystems\\Workitems\\TF19816\test_" + datetime + ".log";
/*Dts.Variables[""].Value.ToString() + "\\" + Dts.Variables[""].Value.ToString() + "_" + datetime + ".log";*/
using (StreamWriter writer = new StreamWriter(LogFile))
{
writer.Write(e.Message);
}
}
public void Main()
{
string par1 = "26";
string par2 = "202111";
string par3 = "09";
string par4 = "tblISF09202111";
string par5 = "tblSUFGenericPseudo202111";
string par6 = "tblSUFGenericPseudo202111";
string par7 = "tblSUFGenericPseudo202111";
string par8 = "tblSUFGenericPseudo202111";
string par9 = "tblSUFGenericFF202111";
string par10 = "1";
try
{
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection MyConnection = new SqlConnection();
MyConnection = (SqlConnection)Dts.Connections["ADODB"].AcquireConnection(null);
//MyConnection.Open();
SqlCommand Storproc = new SqlCommand();
Storproc.Connection = MyConnection;
Storproc.CommandTimeout = 7200;
Storproc.CommandType = CommandType.StoredProcedure;
Storproc.CommandText = "[SurveyInterface].[uspCEProcessingMainScriptAllProcesses]";
SqlParameter Parameter1 = new SqlParameter("#InputSurveyGroupCodeId", par1);
SqlParameter Parameter2 = new SqlParameter("#InputReferencePeriod", par2);
SqlParameter Parameter3 = new SqlParameter("#InputSurveyCodeId", par3);
SqlParameter Parameter4 = new SqlParameter("#InputISFTable", par4);
SqlParameter Parameter5 = new SqlParameter("#InputSUFFrameTable", par5);
SqlParameter Parameter6 = new SqlParameter("#InputExtraVarSUFTable", par6);
SqlParameter Parameter7 = new SqlParameter("#InputPreviousPseudoFrameTableName", par7);
SqlParameter Parameter8 = new SqlParameter("#InputPreviousPseudoFrameTableExtra", par8);
SqlParameter Parameter9 = new SqlParameter("#InputFFTable", par9);
SqlParameter Parameter10 = new SqlParameter("#DEBUG_MODE", par10);
Storproc.Parameters.Add(Parameter1);
Storproc.Parameters.Add(Parameter2);
Storproc.Parameters.Add(Parameter3);
Storproc.Parameters.Add(Parameter4);
Storproc.Parameters.Add(Parameter5);
Storproc.Parameters.Add(Parameter6);
Storproc.Parameters.Add(Parameter7);
Storproc.Parameters.Add(Parameter8);
Storproc.Parameters.Add(Parameter9);
Storproc.Parameters.Add(Parameter10);
Storproc.ExecuteNonQuery();
MyConnection.InfoMessage += new SqlInfoMessageEventHandler(myConnection_InfoMessage);
MyConnection.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception ex)
{
Dts.Events.FireError(0, "ERROR", ex.Message, null, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
I don't know why, but when the execution fails, I get all I want in the execution results tab (From Visual Studio), but I don't get anything in my output file. The file is not even being created.
Why not simply moving the write log code into the Catch block. myConnection_InfoMessage is meaningless in your case:
public void WriteToLog(string message)
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFile = "\\fld6filer\\BrsSystems\\Workitems\\TF19816\test_" + datetime + ".log";
using (StreamWriter writer = new StreamWriter(LogFile))
{
writer.Write(message);
}
}
public void Main()
{
string par1 = "26";
string par2 = "202111";
string par3 = "09";
string par4 = "tblISF09202111";
string par5 = "tblSUFGenericPseudo202111";
string par6 = "tblSUFGenericPseudo202111";
string par7 = "tblSUFGenericPseudo202111";
string par8 = "tblSUFGenericPseudo202111";
string par9 = "tblSUFGenericFF202111";
string par10 = "1";
try
{
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection MyConnection = new SqlConnection();
MyConnection = (SqlConnection)Dts.Connections["ADODB"].AcquireConnection(null);
//MyConnection.Open();
SqlCommand Storproc = new SqlCommand();
Storproc.Connection = MyConnection;
Storproc.CommandTimeout = 7200;
Storproc.CommandType = CommandType.StoredProcedure;
Storproc.CommandText = "[SurveyInterface].[uspCEProcessingMainScriptAllProcesses]";
SqlParameter Parameter1 = new SqlParameter("#InputSurveyGroupCodeId", par1);
SqlParameter Parameter2 = new SqlParameter("#InputReferencePeriod", par2);
SqlParameter Parameter3 = new SqlParameter("#InputSurveyCodeId", par3);
SqlParameter Parameter4 = new SqlParameter("#InputISFTable", par4);
SqlParameter Parameter5 = new SqlParameter("#InputSUFFrameTable", par5);
SqlParameter Parameter6 = new SqlParameter("#InputExtraVarSUFTable", par6);
SqlParameter Parameter7 = new SqlParameter("#InputPreviousPseudoFrameTableName", par7);
SqlParameter Parameter8 = new SqlParameter("#InputPreviousPseudoFrameTableExtra", par8);
SqlParameter Parameter9 = new SqlParameter("#InputFFTable", par9);
SqlParameter Parameter10 = new SqlParameter("#DEBUG_MODE", par10);
Storproc.Parameters.Add(Parameter1);
Storproc.Parameters.Add(Parameter2);
Storproc.Parameters.Add(Parameter3);
Storproc.Parameters.Add(Parameter4);
Storproc.Parameters.Add(Parameter5);
Storproc.Parameters.Add(Parameter6);
Storproc.Parameters.Add(Parameter7);
Storproc.Parameters.Add(Parameter8);
Storproc.Parameters.Add(Parameter9);
Storproc.Parameters.Add(Parameter10);
Storproc.ExecuteNonQuery();
WriteToLog("Stored procedure executed successfully");
MyConnection.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception ex)
{
WriteToLog(ex.Message);
Dts.Events.FireError(0, "ERROR", ex.Message, null, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
Update 1
If you are looking to read output messages from the stored procedure, you can alter the stored procedure and add an output parameter to send the message to the C# script:
Return a message from a stored procedure to C# app
If this is not allowed, try using the SqlConnection.InfoMessage properly:
Accessing InfoMessages for SQL Server queries in C#
I want to learn to make and use Methods in C#.
I know how to get the User Name of the currently logged in Windows user. And I know how to query Active Directory to get their full name. But, I'd like to make a reusable Method that I can put into other web applications as needed.
Would someone show me how that should or might be structured?
I've only done it this way, in VB.Net, and I may have a version of this in C# somewhere:
Protected Sub PopulateReviewerDDL()
'Currently logged in user:
iUserName = Right(Request.ServerVariables("AUTH_USER"), (Request.ServerVariables("AUTH_USER").Length - 6)) 'Remove Domain name and backslash.
Dim DBConn As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Dim DBCmd As New SqlCommand("SELECTADISNames", DBConn)
DBCmd.CommandType = Data.CommandType.StoredProcedure
Try
DBConn.Open()
DBCmd.Parameters.Add("#LogonName", SqlDbType.VarChar).Value = iUserName
Dim dr As SqlDataReader = DBCmd.ExecuteReader
dr.Read()
varLastName = dr("LastName").ToString
varFirstName = dr("FirstName").ToString
dr.Close()
ReviewerName = varFirstName & " " & varLastName
lblUserName.Text = ReviewerName
If Not ddlReviewerName.Items.FindByText(ReviewerName) Is Nothing Then
ddlReviewerName.Text = ReviewerName
Else
Response.Redirect("NoAccess.htm", False)
End If
Catch exp As Exception
Response.Write(exp.Message)
End Try
'Close Database connection
DBCmd.Dispose()
DBConn.Close()
DBConn = Nothing
End Sub
public partial class _Default : System.Web.UI.Page
{
protected string ClearDomain(string sItem)
{
int sLoc = (sItem.IndexOf("\\") + 1);
string sOutPut;
sOutPut = sItem.Substring(sLoc);
return sOutPut;
}
protected void Page_Load(object sender, EventArgs e)
{
string usr;
usr = ClearDomain(User.Identity.Name.ToString());
string dpt;
dpt = "";
SqlConnection DBConn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand DBCmd = new SqlCommand("SELECTADISNames", DBConn);
DBCmd.CommandType = System.Data.CommandType.StoredProcedure;
try
{
DBConn.Open();
DBCmd.Parameters.Add("#LogonName", SqlDbType.VarChar).Value = usr;
SqlDataReader dr = DBCmd.ExecuteReader();
dr.Read();
// ContactPerson.Text = dr["FirstName"].ToString() + " " + dr["LastName"].ToString();
// Notes.Text = dr["Email"].ToString(); // usr.ToString() + "#careersourcebroward.com"; // "Note: Your department is " + dr["Department"].ToString();
email01.SelectedValue = dr["Email"].ToString(); // usr.ToString() + "#careersourcebroward.com";
//if (!IsPostBack)
//{
// Department.Text = dr["Department"].ToString();
//}
dpt = dr["Department"].ToString();
dr.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
DBCmd.Dispose();
DBConn.Close();
DBConn = null;
// ############################################################################################ START ACCESS #####################################
// Add and edit access list. deptAccess is department access only. allAccess is all access. Add: IValentin | Use same case as in Active Directory
string[] deptAccess = {
"mbateman",
"rmoffett",
"CCondon",
"rpickett",
"JLloyd",
"rdaniels",
"LKing",
"SBreslin",
"BCevieux",
"bcharles",
"TWeaver",
"SGonzalez",
"VSaget",
"pchernofsky",
"KRedford",
"VSpellsAnderson",
"jconnelly"
};
string[] allAccess = {
"MCJ",
"chylton",
"ykobrin",
"CAzor",
"mklincewicz",
"mmagill",
"tash",
"dmegnin",
"dhmegnin",
"GValme",
"gvalme",
"mwatson",
"lelmore",
"IValentin",
"TThomas",
"AWiner",
"PScott",
"KKangal",
"CCarcillo",
"KHartzog",
"CJohnson"
};
int pos01 = Array.IndexOf(deptAccess, usr);
int pos02 = Array.IndexOf(allAccess, usr);
if (pos01 > -1 && dpt == Department.SelectedItem.ToString() || pos02 > -1) // (AND Department = usr's department) (OR usr in master list for all access) (use position numbers in the array and ElseIf like the color codes for accesses?)
{
//this.GridView1.AutoGenerateDeleteButton = true;
this.GridView1.Columns[0].Visible = true;
Submit.Visible = true;
Label1.Visible = false;
}
else
{
//this.GridView1.AutoGenerateDeleteButton = false; //This adds a new "generated" column and throws off the column index counts.
this.GridView1.Columns[0].Visible = false;
Submit.Visible = false;
Label1.Visible = true;
}
// ############################################################################################ END ACCESS #####################################
/*
*
* The type or namespace name 'Linq' does not exist in the namespace 'System.Data' (are you miss...
* May 26, 2008 01:30 PM
* Hi,
* I hope that you fixed the problem, just in case you did not add this line into web config where other assembly's are
* <add assembly="System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
* */
Label1.Text = "Note: " + usr.ToString() + ", " + pos01.ToString() + ", " + pos02.ToString() + ", " + dpt;
}
protected void Submit_Click(object sender, EventArgs e)
{
// Call InsertNewRecord
InsertNewRecord();
GridView1.DataBind();
Active.Visible = true;
}
Just move your code into methods or classes (whatever fits best) with the required arguments. here is your modified version in C# :
// ConnectionString make it globle access inside this class
private string ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString;
protected void PopulateReviewerDDL()
{
// Currently logged in user:
var iUserName = GetCurrentUser();
try
{
var reviewerName = GetReviewerName(iUserName, ConnectionString);
if(reviewerName != null)
{
lblUserName.Text = reviewerName;
if (!ddlReviewerName.Items.FindByText(reviewerName) == null)
ddlReviewerName.Text = reviewerName;
else
Response.Redirect("NoAccess.htm", false);
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
protected string GetCurrentUser()
{
return Right(Request.ServerVariables("AUTH_USER"), (Request.ServerVariables("AUTH_USER").Length - 6));
}
protected string GetReviewerName(string username, string connectionString)
{
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(connectionString))
throw new ArgumentNullException("Username or ConnectionString is Empty");
string fullName = null;
try
{
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand("SELECTADISNames", connection))
{
command.CommandType = System.Data.CommandType.StoredProcedure;
connection.Open();
command.Parameters.Add("#LogonName", SqlDbType.VarChar).Value = username;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
fullName = reader["FirstName"].ToString() + " " + LastName = reader["LastName"].ToString();
}
}
}
}
catch (SqlException ex) // we need to catch sql errors only
{
throw new Exception(ex.Message);
}
return fullName;
}
I have an upload button that can upload excel file and save it to my database. What I want to happen is that if there's one or more data in that excel file that already existing the other data will also not be uploaded though it's not yet existing. My code for adding it to the database and upload button are below.
Add to database
private void AddNewTrainee(string strdelname, string strrank, string strcomp, string strcourse, string strcenter, string strinst,
string strsdate, string stredate, string strcissued, string strcnumber, string strremark, int recdeleted, string credate, string update, int fromupload)
{
connection.Open();
String checkDateAndName = "Select count(*) from Trainees where StartDate= '" + strsdate + "' and Delegate='" + strdelname + "' and REC_DELETED = 0 ";
SqlCommand cmd = new SqlCommand(checkDateAndName, connection);
int dataRepeated = Convert.ToInt32(cmd.ExecuteScalar().ToString());
bool boolDataRepated;
connection.Close();
if (!(dataRepeated >= 1))
{
boolDataRepated = false;
}
else
boolDataRepated = true;
connection.Open();
string certNumber = "Select * from CertID_Table update CertID_Table set CertificateID = CertificateID + 1 from CertID_Table ";
SqlCommand cmdCert = new SqlCommand(certNumber, connection);
using (SqlDataReader oReader = cmdCert.ExecuteReader())
{
while (oReader.Read())
{
string test1 = oReader["CertificateID"].ToString();
ViewState["certnumber"] = test1;
}
}
connection.Close();
strcnumber = (string)ViewState["certnumber"];
if (boolDataRepated == false)
{
string path = "D:\\Intern\\BASSWeb\\SQLCommands\\AddSQL.txt";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
string sql = sb.ToString();
try
{
connection.Open();
SqlCommand cmd1 = new SqlCommand(sql, connection);
cmd1.Parameters.AddWithValue("#delName", strdelname);
cmd1.Parameters.AddWithValue("#rank", strrank);
cmd1.Parameters.AddWithValue("#comp", strcomp);
cmd1.Parameters.AddWithValue("#course", strcourse);
cmd1.Parameters.AddWithValue("#center", strcenter);
cmd1.Parameters.AddWithValue("#instructor", strinst);
cmd1.Parameters.AddWithValue("#sdate", strsdate);
cmd1.Parameters.AddWithValue("#edate", stredate);
cmd1.Parameters.AddWithValue("#cissued", strcissued);
cmd1.Parameters.AddWithValue("#cnumber", strcnumber);
cmd1.Parameters.AddWithValue("#remark", strremark);
cmd1.Parameters.AddWithValue("#rdeleted", recdeleted);
cmd1.Parameters.AddWithValue("#cdate", credate);
cmd1.Parameters.AddWithValue("#udate", update);
cmd1.Parameters.AddWithValue("#fupload", fromupload);
cmd1.CommandType = CommandType.Text;
cmd1.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert/Update Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}
}
else
{
string script = "alert(\"The data already exists\");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);
}
}
Upload Button
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
string path = Path.GetFileName(FileUpload1.FileName);
path = path.Replace(" ", "");
FileUpload1.SaveAs(Server.MapPath("~/Datas/") + path);
String ExcelPath = Server.MapPath("~/Datas/") + path;
OleDbConnection mycon = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + ExcelPath + "; Extended Properties=Excel 8.0; Persist Security Info = False");
mycon.Open();
OleDbCommand cmdX = new OleDbCommand("select * from [Sheet1$]", mycon);
OleDbDataReader dr = cmdX.ExecuteReader();
while (dr.Read())
{
delegateName = dr[0].ToString();
rankPos = dr[1].ToString();
company = dr[2].ToString();
courseTitle = dr[3].ToString();
trainingCenter = dr[4].ToString();
instructor = dr[5].ToString();
staDa = DateTime.Parse(dr[6].ToString());
string startDate = staDa.ToString("MM/dd/yyyy");
endDa = DateTime.Parse(dr[7].ToString());
string endDate = endDa.ToString("MM/dd/yyyy");
certIssued = dr[8].ToString();
certNum = dr[9].ToString();
remarks = dr[10].ToString();
recDeleted = 0;
dateCreated = DateTime.Now.ToString("MM/dd/yyyy HH:mm");
dateUpdated = string.Empty;
fromUpload = 1;
AddNewTrainee(delegateName, rankPos, company, courseTitle, trainingCenter, instructor,
startDate, endDate, certIssued, certNum, remarks, recDeleted, dateCreated, dateUpdated, fromUpload);
}
}
catch (Exception ex)
{
string errorMessage = "alert(\"ERROR: " + ex.Message.ToString() + " \");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", errorMessage, true);
}
}
else
{
string errorMessage = "alert(\"ERROR: You have not specified a file \");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", errorMessage, true);
}
PopulateData();
}
You have to set the transferMode to 'Streamed', otherwise you will always get one file.
Have a look at this article: https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-enable-streaming
I think there is a few things you'll need to tackle to reach your end goal.
Use a multiselect method and a get a post list of all files required
for upload.
Do your processing requirements in a Transaction
When your done processing, commit or rollback the transaction as necessary and keep the data you want.
Study the link I posted a little bit. At first transaction seem a little bit overwhelming, but they are actually very simple. Maybe I can help you get started in your understandings. There are really only three extra steps;
1.
Initialize a transaction object after you create a command.
SqlTransaction transaction = connection.BeginTransaction();
2.
On all of your Sql Commands (Inserts,updates, deletes ect) attach the transaction.
cmd.Transaction = transaction;
This will allow you to Execute the SqlCommands without actually putting them into your database. Lastly, when you've processed all of your inserts and updates you can do the final step. The using statement is not required, just good practice. That could be the next thing you'll want to understand it is very helpful.
3.
Commit all SqlCommands to the database.
transaction.Commit();
If at any point during your data processing, something goes wrong than you can rollback every transaction like this.
transaction.Rollback();
when i want to run this code I get an error which throws "IndexOutOfRangeException" on for loop condition. I have tried to use breakpoints and after my DataSet populated clicked on magnifying glass on it. The Visualizer says that it was an empty DataSet. I would appreciate it if someone can help me!
My PageLoad function includes if(!IsPostBack) like this: (freeQuery.aspx.cs)
if (!IsPostBack
{
ViewState["sortColumn"] = " ";
ViewState["sortDirection"] = " ";
string pageURL = HttpContext.Current.Request.RawUrl;
DataSet tables = new DataSet();
string queryString2 = "show tables;";
tables = connectHive(queryString2, pageURL);
List<string> list = new List<string>();
for (int i = 0; i < tables.Tables[0].Rows.Count; i++)
{
list.Add(tables.Tables[0].Rows[i][0].ToString());
}
ListBox1.DataSource = list;
ListBox1.DataBind();
ListBox1.Rows = (ListBox1.Items.Count / 2) + 3;
}
and connectHive function in BasePage.cs below:
protected DataSet connectHive(string query, string pageURL)
{ // Hadoop Hive Connection
var page = HttpContext.Current.CurrentHandler as Page;
OdbcConnection DbConnection = new OdbcConnection("DSN=Hive2");
DbConnection.ConnectionTimeout = 20000000;
try
{
DbConnection.Open();
}
catch (OdbcException exep)
{
ScriptManager.RegisterStartupScript(page, page.GetType(), "alert", "alert('Error in Query!');window.location ='" + pageURL.Replace("/", "") + "';", true);
}
OdbcCommand cmd = DbConnection.CreateCommand();
OdbcDataAdapter adapter = new OdbcDataAdapter(query, DbConnection);
adapter.SelectCommand.CommandTimeout = 20000000;
DataSet data = new DataSet();
data.EnforceConstraints = false;
try
{
adapter.Fill(data);
}
catch (Exception ex)
{
List<string> parameters = new List<string>();
string pageName = findNameByUrl(HttpContext.Current.Request.RawUrl);
parameters.Add("UserID:");
parameters.Add(Session["sicil"].ToString());
parameters.Add("Exception:");
parameters.Add(ex.ToString());
string parameterString = castParameters(parameters);
string exception = "";
string[] sep = new string[] { "\r\n" };
string[] lines = ex.ToString().Split(sep, StringSplitOptions.RemoveEmptyEntries);
int position = lines[0].ToString().LastIndexOf("FAILED:");
if (position > -1)
exception = lines[0].ToString().Substring(position, lines[0].Length - position);
Session["Exception"] = exception.Replace("'", "");
Log(query, "Select Table(BasePage)", pageName, "Failed", parameterString);
}
DbConnection.Close();
return data;
}
I have written a c# monitoring program to check values in a database. It runs 4 separate checks then outputs the results (Winform).
It was all running great then last week the first check hit a problem and whole program stopped.
So my question is how would I trap any errors in any of the 4 checks and keep going/ trucking?
Can I do it with try catch or would this halt program?
Code Sample
bool bTestDate;
object LastDataDate;
//-- Check A - Table 1
OdbcConnection DbConnection = new OdbcConnection("DSN=EDATA");
try
{
DbConnection.Open();
}
catch (OdbcException ex)
{
Console.WriteLine("connection to the DSN '" + connStr + "' failed.");
Console.WriteLine(ex.Message);
return;
}
OdbcCommand DbCommand = DbConnection.CreateCommand();
DbCommand.CommandText = "SELECT NAME, UNAME, DATIME_ENDED FROM XPF WHERE NAME='XXXX'";
OdbcDataReader DbReader = DbCommand.ExecuteReader();
int fCount = DbReader.FieldCount;
string myBatch;
string myUser;
string myDate;
while (DbReader.Read())
{
Console.Write(":");
myBatch = DbReader.GetString(0);
myUser = DbReader.GetString(1);
myDate = DbReader.GetString(2);
myDate = myDate.Remove(myDate.Length - 10);
for (int i = 0; i < fCount; i++)
{
String col = DbReader.GetString(i);
Console.Write(col + ":");
}
tbxxx.Text = string.Format("{0:dd/M/yy H:mm:ss}", myDate);
bool TestDate;
TestDate = CheckDate(Convert.ToDateTime(myDate));
CheckVerif(TestDate, lblVerifixxx);
}
//-- Check B - Table 2
string cnStr = setConnectionString();
string mySQL = "Select Max(TO_DATE(TIME_ID, 'DD/MM/YYYY')) FROM table";
OracleConnection cn = new OracleConnection(cnStr);
cn.Open();
OracleCommand cmd = new OracleCommand(mySQL, cn);
LastDataDate = cmd.ExecuteScalar();
cmd.Dispose();
tbLastDate.Text = string.Format("{0:dd MMM yy}", LastDataDate);
bTestDate = CheckDate(Convert.ToDateTime(LastDataDate));
CheckVerif(bTestDate, lblVerif);
//-- Check C - Table 3
mySQL = "Select Max(xxx_DATE) from AGENT";
OracleCommand cmd2 = new OracleCommand(mySQL, cn);
LastDataDate = cmd2.ExecuteScalar();
cmd2.Dispose();
tbxxx2.Text = string.Format("{0:dd MMM yy}", LastDataDate);
bool TestDatex;
TestDatex = CheckDate(Convert.ToDateTime(LastDataDate));
CheckVerif(TestDatex, lblVerif2);
You can use a try catch block with the expected exceptions and a general one, just to be certain you catch them all and not throw the exception, therefore not halting the program.
try
{
string s = null;
ProcessString(s);
}
// Most specific:
catch (ArgumentNullException e)
{
Console.WriteLine("{0} First exception caught.", e);
}
// Least specific:
catch (Exception e)
{
Console.WriteLine("{0} Second exception caught.", e);
}
Check https://msdn.microsoft.com/en-us/library/0yd65esw.aspx