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.
Related
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;
}
I want to implement an async function. My problem is; I do not know where to put the await key word in the code below:
public async Task<List<ManualReadTag>> GetManuallyReadTags(ParameterManualTags model)
{
var db = new ApplicationDbContext();
using (var cnxn = db.Database.Connection)
{
cnxn.Open();
var cmd = cnxn.CreateCommand();
cmd.CommandText = "GetManualReadForDedicated";
cmd.CommandType = CommandType.StoredProcedure;
var dtFrom = cmd.CreateParameter();
dtFrom.ParameterName = "#DateFrom";
dtFrom.DbType = DbType.Date;
dtFrom.Direction = ParameterDirection.Input;
dtFrom.Value = model.DateFrom;
var dTo = cmd.CreateParameter();
dTo.ParameterName = "#DateTo";
dTo.DbType = DbType.Date;
dTo.Direction = ParameterDirection.Input;
dTo.Value = model.DateTo;
var lane = cmd.CreateParameter();
lane.ParameterName = "#Lane";
lane.DbType = DbType.Int32;
lane.Direction = ParameterDirection.Input;
lane.Value = model.Lane;
var plaza = cmd.CreateParameter();
plaza.ParameterName = "#Plaza";
plaza.DbType = DbType.String;
plaza.Direction = ParameterDirection.Input;
plaza.Value = model.Plaza;
cmd.Parameters.Add(dtFrom);
cmd.Parameters.Add(dTo);
cmd.Parameters.Add(lane);
cmd.Parameters.Add(plaza);
try
{
using (var reader = cmd.ExecuteReader())
{
var result = ((IObjectContextAdapter) db)
.ObjectContext
.Translate<ManualReadTag>(reader)
.ToList();
return result;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
MessageBox.Show(ex.Message);
return null;
}
}
}
This code works I just need to put int the await keyword so I can use the async.
Could you please point me the right way to do this?
You can try ExecuteReaderAsync instead:
await cmd.ExecuteReaderAsync()
Everywhere where there's an asynchronous API. And don't forget to dispose of all your disposables.
public async Task<List<ManualReadTag>> GetManuallyReadTagsAsync(ParameterManualTags model)
{
var db = new ApplicationDbContext();
using (var cnxn = db.Database.Connection)
{
using (var cmd = cnxn.CreateCommand())
{
cmd.CommandText = "GetManualReadForDedicated";
cmd.CommandType = CommandType.StoredProcedure;
var dtFrom = cmd.CreateParameter();
dtFrom.ParameterName = "#DateFrom";
dtFrom.DbType = DbType.Date;
dtFrom.Direction = ParameterDirection.Input;
dtFrom.Value = model.DateFrom;
var dTo = cmd.CreateParameter();
dTo.ParameterName = "#DateTo";
dTo.DbType = DbType.Date;
dTo.Direction = ParameterDirection.Input;
dTo.Value = model.DateTo;
var lane = cmd.CreateParameter();
lane.ParameterName = "#Lane";
lane.DbType = DbType.Int32;
lane.Direction = ParameterDirection.Input;
lane.Value = model.Lane;
var plaza = cmd.CreateParameter();
plaza.ParameterName = "#Plaza";
plaza.DbType = DbType.String;
plaza.Direction = ParameterDirection.Input;
plaza.Value = model.Plaza;
cmd.Parameters.Add(dtFrom);
cmd.Parameters.Add(dTo);
cmd.Parameters.Add(lane);
cmd.Parameters.Add(plaza);
await cnxn.OpenAsync();
using (var reader = await cmd.ExecuteReaderAsync())
{
var result = ((IObjectContextAdapter)db)
.ObjectContext
.Translate<ManualReadTag>(reader)
.ToList();
return result;
}
}
}
}
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
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.