Here when I select same date and same batch it should give me the alert message with pop-up. I tried try catch method but it's not working.Tell me where I went wrong.
My code so far
using (SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
var fromdate = DateTime.Parse(txtfromdate.Text);
var todate = DateTime.Parse(txttodate.Text);
var datedif1 = (todate - fromdate).Days;
var sqlInsert = new SqlCommand("INSERT INTO datelist ([datedif],[batch],[daywk],[semester],[weekbatch],[subject],[facultyname],[facultyid],[WeekMonth]) SELECT * from (SELECT #datedif as datedif, #batch as batch,#daywk as daywk,#semester as semster,#weekbatch as weekbatch,#subject as subject,#facultyname as facultyname,#facultyid as facultyid,#weekMonth as weekMonth) AS temp WHERE NOT EXISTS (SELECT datedif,batch from datelist where batch=#batch and datedif=#datedif)", con2);
var sqlParamater = sqlInsert.Parameters.Add("#datedif", SqlDbType.Date);
var sqlParameter1 = sqlInsert.Parameters.Add("#batch", SqlDbType.NVarChar);
var sqlParameter2 = sqlInsert.Parameters.Add("#daywk", SqlDbType.NVarChar);
var sqlParameter3 = sqlInsert.Parameters.Add("#semester", SqlDbType.NVarChar);
var sqlParameter4 = sqlInsert.Parameters.Add("#weekbatch", SqlDbType.NVarChar);
var sqlParameter5 = sqlInsert.Parameters.Add("#subject", SqlDbType.NVarChar);
var sqlParameter6 = sqlInsert.Parameters.Add("#facultyname", SqlDbType.NVarChar);
var sqlParameter7 = sqlInsert.Parameters.Add("#facultyid", SqlDbType.NVarChar);
var sqlParameter8 = sqlInsert.Parameters.Add("#WeekMonth", SqlDbType.NVarChar);
con2.Open();
try
{
for (var i = 0; i <= datedif1; i++)
{
var consecutiveDate = fromdate.AddDays(i);
sqlParamater.Value = consecutiveDate;
sqlParameter1.Value = batch1;
sqlParameter2.Value = dayweek;
sqlParameter3.Value = semester;
sqlParameter4.Value = weekbatch;
sqlParameter5.Value = subject;
sqlParameter6.Value = faculty;
sqlParameter7.Value = facultyid;
sqlParameter8.Value = weekmonth;
int s = sqlInsert.ExecuteNonQuery();
}
}
catch
{
Response.Write("<script>alert('Already date is selected.Select another date')</script>");
con2.Close();
}
}
}
1 - Please first check are you going inside catch block put a debugger there.
2 - Put a debugger also on your page load to check when it is happening.
You can use RegisterStartupScript() methodAt Server side
catch
{
string msg="Already date is selected.Select another date";
ScriptManager.RegisterStartupScript(this, GetType(), "myFunction", "myFunction('"+msg+"');", true);
}
At Client side
<script>
function myFunction(a) {
alert(a);
}
</script>
Also it is better to make some store procedure.
Related
I am trying to sort a datatable into a DataSet. I want to sort by the Status Column in "DESC". But I am not aware how to go about this. I have tried the suggested solutions online but I seem not to be doing something right. Here is what I have tried, albeit, I have commented out the sorting lines of the code as they do not work for me. How can I sort my table using the Status column in Desc?
[WebMethod(EnableSession = true)]
public List < TaskListClass > getTasks() {
var userId = Session["UserId"].ToString();
List < TaskListClass > objB = new List < TaskListClass > ();
try {
using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnString"].ToString())) {
connection.Open();
DataSet Myds = new DataSet();
// Myds.Tables[0].DefaultView.Sort = "Status desc";
SqlDataAdapter sqldr = new SqlDataAdapter();
string ProcName = "getTasks";
SqlCommand cmd = new SqlCommand(ProcName, connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#userId", SqlDbType.VarChar, 900).Value = userId;
sqldr.SelectCommand = cmd;
sqldr.Fill(Myds);
DataTable dt = Myds.Tables[0];
// DataTable dt = Myds.Tables[0].DefaultView.ToTable();
for (int i = 0; i < dt.Rows.Count; i++) {
objB.Add(new TaskListClass() {
Id = Convert.ToString(dt.Rows[i]["Id"]),
Subject = Convert.ToString(dt.Rows[i]["Subject"]),
Customer = Convert.ToString(dt.Rows[i]["Customer"]),
Sender = Convert.ToString(dt.Rows[i]["Sender"]),
Receiver = Convert.ToString(dt.Rows[i]["Receiver"]),
Priority = Convert.ToString(dt.Rows[i]["Priority"]),
StartDate = Convert.ToString(dt.Rows[i]["StartDate"]),
EndDate = Convert.ToString(dt.Rows[i]["EndDate"]),
Status = Convert.ToString(dt.Rows[i]["Status"]),
OnProgress = Convert.ToString(dt.Rows[i]["OnProgress"]),
});
}
}
} catch (Exception e) {
msg = e.ToString();
}
return objB;
}
Ok, a few things.
first up, a dataset is a collection of tables - "many tables" possible.
But you have ONE table, so why use a dataset? I see no need. Just use a single data table for this.
And this will reduce the code.
So, I suggest this, or close to this:
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnString"].ToString()))
{
using (var cmd = new SqlCommand("getTasks", connection))
{
connection.Open();
cmd.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
cmd.Parameters.Add("#userId", SqlDbType.VarChar).Value = userId;
dt.Load(cmd.ExecuteReader());
// now sort the datatable
dt.DefaultView.Sort = "Status DESC";
// now fill out our object with each row
foreach (DataRow OneRow in dt.Rows)
{
objB.Add(new TaskListClass()
{
Id = OneRow["Id"].ToString(),
Subject = OneRow["Subject"].ToString(),
Customer = OneRow["Customer"].ToString(),
Sender = OneRow["Sender"].ToString(),
Receiver = OneRow["Receiver"].ToString(),
Priority = OneRow["Priority"].ToString(),
StartDate = OneRow["StartDate"].ToString(),
EndDate = OneRow["EndDate"].ToString(),
Status = OneRow["Status"].ToString(),
OnProgress = OneRow["OnProgress"].ToString(),
}); ;
}
}
}
}
return objB;
The way the current code is written, you could add this after the for-loop:
objB = objB.OrderByDescending(t => t.Status).ToList();
Depending of the datatype of Status, it might be sorted alphabetically.
var dataRow = dt.AsEnumerable().OrderByDescending(x => x.Field<string>("Status")).ToList();
foreach (var item in dataRow)
{
//Enter your Code Here
}
Here dt is your datatable.
dataRow is a set of list.
After get the data list, you can asign it to your "objB".
I have a procedure with 2 input parameters and 2 output parameters. Currently its working fine. However, i want to take the two output parameters of the procedure and store it in a variable. Can anyone guide me how.
Stored procedure code:
create or replace PROCEDURE P_LOGIN_USER
(
USERNAME IN VARCHAR2
, ENCRYPTIONKEY IN VARCHAR2
, OUT_STATUS OUT VARCHAR2
, OUT_STATUS_DESC OUT VARCHAR2
)
------------------------Procedure Code
END P_LOGIN_USER
C# Code where i assign the input parameters. Missing part is getting the output parameters
OracleCommand cmd = new OracleCommand("P_LOGIN_USER", OrCon);
cmd.CommandType = CommandType.StoredProcedure;
OracleParameter in_username = new OracleParameter();
in_username.OracleDbType = OracleDbType.Varchar2;
in_username.Direction = ParameterDirection.Input;
in_username.Size = 500;
in_username.Value = username;
cmd.Parameters.Add(in_username);
OracleParameter in_ecnryptionkey = new OracleParameter();
in_ecnryptionkey.OracleDbType = OracleDbType.Varchar2;
in_ecnryptionkey.Direction = ParameterDirection.Input;
in_ecnryptionkey.Size = 500;
in_ecnryptionkey.Value = password;
cmd.Parameters.Add(in_ecnryptionkey);
OracleParameter out_1 = new OracleParameter();
out_1.OracleDbType = OracleDbType.Varchar2;
out_1.Direction = ParameterDirection.Output;
out_1.Size = 500;
cmd.Parameters.Add(out_1);
OracleParameter out_2 = new OracleParameter();
out_2.OracleDbType = OracleDbType.Varchar2;
out_2.Direction = ParameterDirection.Output;
out_2.Size = 500;
cmd.Parameters.Add(out_2);
try
{
OrCon.Open();
cmd.ExecuteNonQuery();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "P_LOGIN_USER";
cmd.Parameters.Add(new OracleParameter
{
ParameterName = "result",
Size = 1,
Direction = ParameterDirection.ReturnValue,
OracleDbType = OracleDbType.Varchar2
});
}
catch (OracleException ex)
{
Console.Write(ex.Message);
}
OrCon.Close();
You can get the value out output parameter like this.
string outputStatus = Convert.ToString(cmd.Parameters["#OUT_STATUS "].Value);
Put the above line after ExecuteNonQuery()
Stored procedure code:
create or replace PROCEDURE P_LOGIN_USER
(
USERNAME IN VARCHAR2
, ENCRYPTIONKEY IN VARCHAR2
, p_recordset OUT SYS_REFCURSOR) IS
BEGIN
OPEN p_recordset FOR
SELECT OUT_STATUS ,OUT_STATUS_DESC .....
END
C#:
using (var reader = cmd.ExecuteReader())
{
List<ListModel> obj= reader.MapToList<ListModel>();
return obj;
}
## **MapToList** ##
public static List<T> MapToList<T>(this DbDataReader dr) where T : new()
{
if (dr != null && dr.HasRows)
{
var entity = typeof(T);
var entities = new List<T>();
var propDict = new Dictionary<string, PropertyInfo>();
var props = entity.GetProperties(BindingFlags.Instance | BindingFlags.Public);
propDict = props.ToDictionary(p => p.Name.ToUpper(), p => p);
List<string> log = new List<string>();
while (dr.Read())
{
try
{
T newObject = new T();
for (int index = 0; index < dr.FieldCount; index++)
{
var columnname = dr.GetName(index).ToUpper();
if (propDict.ContainsKey(dr.GetName(index).ToUpper()))
{
var info = propDict[dr.GetName(index).ToUpper()];
if ((info != null) && info.CanWrite)
{
try
{
var val = dr.GetValue(index);
info.SetValue(newObject, (val == DBNull.Value) ? null : val, null);
}
catch (Exception ex)
{
var columename= dr.GetName(index).ToUpper();
var val= dr.GetValue(index);
var getype = val.GetType();
log.Add(columename + ":" + val + ":" + getype.ToString());
}
}
}
}
entities.Add(newObject);
}
catch (Exception ex)
{
}
}
return entities;
}
return null;
}
Whenever the code is executed, it always return that the ID value is not supplied that will cause an error. Would someone please show me where is my error? In some queries there is also sqlcommand.Parameters.Clear(); which is not included in this code.
The #ID should be pointing to the first column in the datagridview, where I can also set the match with the ID (primary key) in the table via SQL Management.
using (SqlCommand InsUpd = new SqlCommand(
#"IF EXISTS(SELECT 1 FROM dbo.Bokfuppg WHERE dbo.Bokfuppg.ID = #ID)
UPDATE dbo.bokfuppg
SET fnr = #Fnr, kto = #Kto, Ukto = #Ukto, avd = #Avd, prod = #Prod, proj = #Proj, ant = #Ant, bel = #Bel, Text = #Text, vbel = #Vbel, period = #Period
WHERE dbo.Bokfuppg.ID = #ID
ELSE
INSERT INTO dbo.bokfuppg(Fnr, Kto, Ukto, Avd, Prod, Proj, ant, bel, text, vbel, period) VALUES(#Fnr, #Kto, #Ukto, #Avd, #Prod, #Proj, #Ant, #Bel, #Text, #Vbel, #Period)", con))
{
con.Open();
using (SqlTransaction tr = con.BeginTransaction())
{
InsUpd.Transaction = tr;
InsUpd.Parameters.Add("#ID", SqlDbType.Int);
InsUpd.Parameters.Add("#Fnr", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Kto", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Ukto", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Avd", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Prod", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Proj", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Ant", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Bel", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Text", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Vbel", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Period", SqlDbType.NVarChar);
foreach (DataGridViewRow item in dataGridViewBokfuppg.Rows)
{
InsUpd.Parameters["#ID"].Value = item.Cells[0].Value;
InsUpd.Parameters["#Fnr"].Value = textBox1.Text;
InsUpd.Parameters["#Kto"].Value = item.Cells[1].Value;
InsUpd.Parameters["#Ukto"].Value = item.Cells[2].Value;
InsUpd.Parameters["#Avd"].Value = item.Cells[3].Value;
InsUpd.Parameters["#Prod"].Value = item.Cells[4].Value;
InsUpd.Parameters["#Proj"].Value = item.Cells[5].Value;
InsUpd.Parameters["#Ant"].Value = item.Cells[6].Value;
InsUpd.Parameters["#Bel"].Value = item.Cells[7].Value;
InsUpd.Parameters["#Text"].Value = item.Cells[8].Value;
InsUpd.Parameters["#Vbel"].Value = item.Cells[9].Value;
InsUpd.Parameters["#Period"].Value = item.Cells[10].Value;
InsUpd.ExecuteNonQuery();
}
tr.Commit();
}
}
MessageBox.Show("Record Updated Successfully");`
I want to block the duplicate dates before inserting it into database.If a week with the same date is already exist in the database,when selecting the same date it should pop-up with the error message "this dates are already chosen".
Example:
If Week 1 is 1.1.2015 to 5.1.2015 stored in database and when Week 2 is also selecting the same date from 1.1.2015 to 5.1.2015,it should give the error message.
How to accomplish this,suggest some ideas.
This is my database.
I am using SQL database.Where the selected dates are stored in "datedif" column in database. With the "daywk" column I'm selecting the dates by week wise and displayed in grid.
I want to block the duplicate date when inserting into "datedif" column.
my code so far.
using (SqlConnection con2 = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=Z:\NewTimeTable\NewTimeTable\App_Data\Admindetail.mdf;Integrated Security=True"))
{
var fromdate = DateTime.Parse(txtfromdate.Text);
var todate = DateTime.Parse(txttodate.Text);
var datedif1 = (todate - fromdate).Days;
var sqlInsert = new SqlCommand("INSERT INTO datelist ([datedif],[batch],[daywk],[semester],[weekbatch],[subject],[facultyname],[facultyid],[WeekMonth]) VALUES (#datedif,#batch,#daywk,#semester,#weekbatch,#subject,#facultyname,#facultyid,#weekMonth)", con2);
var sqlParamater = sqlInsert.Parameters.Add("#datedif", SqlDbType.Date);
var sqlParameter1 = sqlInsert.Parameters.Add("#batch", SqlDbType.NVarChar);
var sqlParameter2 = sqlInsert.Parameters.Add("#daywk", SqlDbType.NVarChar);
var sqlParameter3 = sqlInsert.Parameters.Add("#semester", SqlDbType.NVarChar);
var sqlParameter4 = sqlInsert.Parameters.Add("#weekbatch", SqlDbType.NVarChar);
var sqlParameter5 = sqlInsert.Parameters.Add("#subject", SqlDbType.NVarChar);
var sqlParameter6 = sqlInsert.Parameters.Add("#facultyname", SqlDbType.NVarChar);
var sqlParameter7 = sqlInsert.Parameters.Add("#facultyid", SqlDbType.NVarChar);
var sqlParameter8 = sqlInsert.Parameters.Add("#WeekMonth", SqlDbType.NVarChar);
con2.Open();
for (var i = 0; i <= datedif1; i++)
{
var consecutiveDate = fromdate.AddDays(i);
sqlParamater.Value = consecutiveDate;
sqlParameter1.Value = batch1;
sqlParameter2.Value = dayweek;
sqlParameter3.Value = semester;
sqlParameter4.Value = weekbatch;
sqlParameter5.Value = subject;
sqlParameter6.Value = faculty;
sqlParameter7.Value = facultyid;
sqlParameter8.Value = weekmonth;
sqlInsert.ExecuteNonQuery();
}
con2.Close();
}
}
List persons = new List();
using (SqlConnection connection = new SqlConnection("Data Source=(local);Initial Catalog=AdventureWorks2014;Integrated Security=SSPI"))
using (SqlCommand cmd = new SqlCommand("SELECT BusinessEntityID AS ID, FirstName, MiddleName, LastName FROM Person.Person", connection))
{
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
// Check is the reader has any rows at all before starting to read.
if (reader.HasRows)
{
throw new ApplicationExcetion("Data is duplicated");
}
}
}
before insert into database. just query first.
if query have exist data(duplicated data). then throw exception
I have tried this below code, but it throws a unique key constraint error. I would like it as a pop-up message; see my below code.
using (SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
var fromdate = DateTime.Parse(txtfromdate.Text);
var todate = DateTime.Parse(txttodate.Text);
var datedif1 = (todate - fromdate).Days;
var sqlInsert = new SqlCommand("INSERT INTO datelist ([datedif],[batch],[daywk],[semester],[weekbatch],[subject],[facultyname],[facultyid],[WeekMonth]) VALUES (#datedif,#batch,#daywk,#semester,#weekbatch,#subject,#facultyname,#facultyid,#weekMonth)", con2);
var sqlParamater = sqlInsert.Parameters.Add("#datedif", SqlDbType.Date);
var sqlParameter1 = sqlInsert.Parameters.Add("#batch", SqlDbType.NVarChar);
var sqlParameter2 = sqlInsert.Parameters.Add("#daywk", SqlDbType.NVarChar);
var sqlParameter3 = sqlInsert.Parameters.Add("#semester", SqlDbType.NVarChar);
var sqlParameter4 = sqlInsert.Parameters.Add("#weekbatch", SqlDbType.NVarChar);
var sqlParameter5 = sqlInsert.Parameters.Add("#subject", SqlDbType.NVarChar);
var sqlParameter6 = sqlInsert.Parameters.Add("#facultyname", SqlDbType.NVarChar);
var sqlParameter7 = sqlInsert.Parameters.Add("#facultyid", SqlDbType.NVarChar);
var sqlParameter8 = sqlInsert.Parameters.Add("#WeekMonth", SqlDbType.NVarChar);
con2.Open();
try
{
for (var i = 0; i <= datedif1; i++)
{
var consecutiveDate = fromdate.AddDays(i);
sqlParamater.Value = consecutiveDate;
sqlParameter1.Value = batch1;
sqlParameter2.Value = dayweek;
sqlParameter3.Value = semester;
sqlParameter4.Value = weekbatch;
sqlParameter5.Value = subject;
sqlParameter6.Value = faculty;
sqlParameter7.Value = facultyid;
sqlParameter8.Value = weekmonth;
int s = sqlInsert.ExecuteNonQuery();
}
con2.Close();
}
catch(ConstraintException ex)
{
throw new ApplicationException("data are duplicated");
}
}
Here's a screen shot of the error which am getting,
You are catching a ConstraintException, but the insert is throwing a SqlException which is not a subclass of ConstraintException. Change the catch and you will get it handled.