How call stored procedure to insert value in a table - insert

Please provide me sample code for inserting values in a table using stored procedure in NHibernate.
Regards
Jcreddy

Here is a nice example from Ayende demonstrating insert using NHibenate.

Check if this code does what you want. First you need to create the stored procedure in db.
ALTER procedure [dbo].[ninsert]
(#header AS int,#subtype AS varchar(50),#title AS varchar(50),
#description AS
VARCHAR(50)) as insert into
dbo.news(nid,title,subtitle,description) values
(#header,#subtype,#title,#description)
then you must access this code via your data layer in the program....
public class datacheck
{
public SqlConnection con = new SqlConnection(#"Data Source=xxx\SQLEXPRESS;Initia Catalog=eyepax;Integrated Security=True");
public int SQLSP(string strSQL, int headerid, string subtype, string title,string descrip) // stored procedure
{
if (con.State.ToString() == "Closed")
{
con.Open();
}
//con.Open();
SqlCommand sqlCmd = new SqlCommand(strSQL, con);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#header", headerid);
sqlCmd.Parameters.AddWithValue("#subtype", subtype);
sqlCmd.Parameters.AddWithValue("#title", title);
sqlCmd.Parameters.AddWithValue("#description", descrip);
int results = sqlCmd.ExecuteNonQuery();
//sqlCmd.Dispose();
//con.Close();
return 0;
}
public DataSet executeSql()
{
DataSet ds = new DataSet();
if (con.State.ToString() == "Closed")
{
con.Open();
}
string sqlcmd1 = "select * from news";
SqlCommand cmd = new SqlCommand(sqlcmd1, con);
SqlDataAdapter sqlAda = new SqlDataAdapter(cmd);
sqlAda.Fill(ds,"news");
return ds;
}
public DataSet executeSql(sqlcmd)
{
DataSet ds = new DataSet();
if (con.State.ToString() == "Closed")
{
con.Open();
}
SqlCommand cmd = new SqlCommand(sqlcmd, con);
SqlDataAdapter sqlAda = new SqlDataAdapter(cmd);
sqlAda.Fill(ds,"news");
return ds;
}
for insert, update delete
public int SQLC(string strSQL) // for insert, update.delete
//{
// if (con.State.ToString() == "Closed")
// {
// con.Open();
// }
// SqlCommand sqlCmd = new SqlCommand(strSQL, con);
// int result = sqlCmd.ExecuteNonQuery();
// return result;
//}

Related

ObjectContext.Translate not working in oracle 19 version

this is my function that translate result from db to object classe.
public static List<T> GetListBySP<T>(string pSPName, params object[] pParamArray)
{
List<T> res = null;
//string connStr = ConfigurationManager.ConnectionStrings[sConnStr].ConnectionString;
string connStr = DbFactory.ConnStr;
using (OracleConnection conn = new OracleConnection(connStr))
{
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandText = pSPName;
cmd.CommandType = CommandType.StoredProcedure;
FillParameters(cmd.Parameters, pParamArray);
cmd.Parameters.Add("pCursor", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
using (var db = DbFactory.CreateRo())
{
try
{
cmd.Connection.Open();
var reader = cmd.ExecuteReader();
res = ((IObjectContextAdapter)db).ObjectContext.Translate<T>(reader).ToList<T>();
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Connection.Close();
}
}
}
}
return res;
}
after update oracle version to 19.
exaption throw on line
res = ((IObjectContextAdapter)db).ObjectContext.Translate<T>(reader).ToList<T>();
the exeption is:
An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.
the project run on .net framework 4.6.2

How do i convert OracleDataReader to a List object that i can store in my model MVC

I have managed to connect to the OracleDb and use the OracleDataReader to retrieve the data from the DB. The problem i have is that i now want to insert the retrieved data in my model (Invoice). The problem right now is that i cant convert the retrieved data to a type that is accepted by the model. Is there a way to convert the OracleDataReader reader to a type that is accepted by the model so i can fil the model (IEnumerable) with data?
public ViewResult search_btn(object sender, EventArgs e, string docno){
OracleConnection OC = new OracleConnection("SOMECONNECTIONSTRING");
OracleCommand getBlobRecord = new OracleCommand("select * from xx where invoice_no=:invoiceId", OC);
getBlobRecord.Parameters.Add(new OracleParameter("invoiceId", docno));
OC.Open();
using (OracleDataReader reader = getBlobRecord.ExecuteReader(CommandBehavior.SequentialAccess))
{
try
{
while (reader.Read())
{
var x = reader["invoice_no"];
var y = reader["supplier_id"];
new Invoice
{
Invoice_No = (int)x,
Supplier_Id = (int)y
};
}
reader.Close();
reader.Dispose();
return View("Index");
}
finally
{
reader.Close();
OC.Close();
}
}}

Handling Null in MVC Model

I am facing DateTime null Error. My data comes from SQL server through stored procedures in MVC project. In MVC, Employee model receive the data in List and pass it to the View through the Employee Controller. Following is the code:
public List<Employee> GetEmployeesByUserName(string username)
{
SqlConnection conn = new SqlConnection(Startup.MTSConn);
List<Employee> empList = new List<Employee>();
using (conn)
{
using (SqlCommand cmd = new SqlCommand("spRetrievEmployeesByUserName", conn))
{
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("#Username", username);
DataTable dt = new DataTable();
conn.Open();
adapter.Fill(dt);
//Convert Data to List
foreach (DataRow row in dt.Rows)
{
employeesList.Add(new Employee
{
UserName = row["UserName"].ToString(),
KOCNo = row["KOCNo"].ToString(),
Name = row["Name"].ToString(),
Designation = row["Designation"].ToString(),
**DOB = row["DOB"]==DBNull ? DBNull : Convert.ToDateTime(row["DOB"])**
Here I want to check if the field is null then return null otherwise convert it to DateTime. In employee model it is already set to null 'public DateTime? DOB { get; set; }'
});
}
}
return empList;
}
}
I advise you to use entity to get the data from the database. However, to tackle this issue try do something like this
foreach (DataRow row in dt.Rows)
{
if (row["DOB"] != null)
employeesList.Add(new Employee
{
UserName = row["UserName"].ToString(),
KOCNo = row["KOCNo"].ToString(),
Name = row["Name"].ToString(),
Designation = row["Designation"].ToString(),
**DOB = row["DOB"].Convert.ToDateTime()**
}
else
{
employeesList.Add(new Employee
{
UserName = row["UserName"].ToString(),
KOCNo = row["KOCNo"].ToString(),
Name = row["Name"].ToString(),
Designation = row["Designation"].ToString(),
DOB = null
}

ALTER TABLE doesn't work

I'm trying to change my column datatype in the table item. Now it has just 0(it's int now). What will happen when I run it? I tried to use int num = cmd.ExecuteNonQuery() but didn't work, it came an error. With this code I don't see changes. I found that LONGBLOB is the particular datatype for saving images in the database. This is my code:
public partial class alterOneSec : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection con = DAL.GetConnection();
con.Open();
if(con.State == ConnectionState.Open)
{
string sql = "ALTER TABLE item ALTER COLUMN picture LONGBLOB NOT NULL";
OleDbCommand cmd = DAL.GetCommand(con, sql);
}
con.Close();
Response.Redirect("homepage.aspx?err=case3");
}
}
The GetCommand method is this:
public static OleDbCommand GetCommand(OleDbConnection con, string sql)
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
return cmd;
}

Load Database Values in Ajax Cascading DropDown

This is the first time I have used Ajax, and this is also my first C#.NET project, so I am very new. I am using .NET 4.0.
I have succesfully implemented the Ajax cascading dropdown, and upon submit, the data is stored in the database. However, this page also has an "Edit" feature, meaning if there is a value for said dropdown already populated in the database, it "should" display, and allow the user to change it. This is where I get stuck. If there is already a value for these dropdowns in the db, how can I display that?
I do have a try/catch for my other non-Ajax fields, and I have tried that on these, to no avail. I'll list that as well.
Code Behind:
public partial class Research : System.Web.UI.Page
{
//Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
/Create data table to populate fields with values from the selected record.
DataTable dt = new DataTable();
dt = selectDetails();
//Call Try/Catch Blocks to load fields.
tryRootCauseCategoryDD(cboRootCauseCategory, dt.Rows[0]["rootCauseCategory"].ToString());
tryRootCauseDD(cboRootCause, dt.Rows[0]["rootCause"].ToString());
}
}
protected void tryRootCauseCategoryDD(DropDownList cboRootCauseCategory, string ddSelected)
{
try
{
cboRootCauseCategory.SelectedValue = ddSelected;
}
catch
{
cboRootCauseCategory.SelectedIndex = 0;
}
}
protected void tryRootCauseDD(DropDownList cboRootCause, string ddSelected)
{
try
{
cboRootCause.SelectedValue = ddSelected;
}
catch
{
cboRootCause.SelectedIndex = 0;
}
}
protected DataTable selectDetails()
{
DataTable dt = new DataTable();
dt = dataAccess.ExecuteDataTable
(
"spRecordDetails", dataAccess.DEV, new SqlParameter[1]
{
new SqlParameter ("#vRecID", Request.QueryString["recID"].ToString())
}
);
return dt;
}
ASPX:
<asp:DropDownList ID="cboRootCauseCategory" runat="server"></asp:DropDownList>
<ajaxToolkit:CascadingDropDown ID="ccdRootCauseCategory" runat="server" Category="RootCauseCategory"
TargetControlID="cboRootCauseCategory" PromptText="(Please select:)" LoadingText="Loading.."
ServiceMethod="BindRootCauseCategoryDetails" ServicePath="CascadingDropDown.asmx">
</ajaxToolkit:CascadingDropDown>
<asp:DropDownList ID="cboRootCause" runat="server"></asp:DropDownList>
<ajaxToolkit:CascadingDropDown ID="ccdRootCause" runat="server" Category="RootCause" ParentControlID="cboRootCauseCategory"
TargetControlID="cboRootCause" PromptText="(Please select:)" LoadingText="Loading.."
ServiceMethod="BindRootCauseDetails" ServicePath="CascadingDropDown.asmx">
</ajaxToolkit:CascadingDropDown>
Web Service:
[WebService(Namespace = "http://microsoft.com/webservices/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//To allow this Web Service to be called from script, using ASP.NET AJAX.
[System.Web.Script.Services.ScriptService()]
public class CascadingDropDown : System.Web.Services.WebService
{
//Database connection string
//private static string strconnection = ConfigurationManager.AppSettings["DEV"].ToString();
private static string strconnection = System.Configuration.ConfigurationManager.ConnectionStrings["DEV"].ConnectionString;
//database connection
SqlConnection conCategory = new SqlConnection(strconnection);
public CascadingDropDown()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
/// WebMethod to Populate Root Cause Category Dropdown
[WebMethod]
public CascadingDropDownNameValue[] BindRootCauseCategoryDetails(string knownCategoryValues, string category)
{
conCategory.Open();
SqlCommand cmdRootCauseCategory = new SqlCommand
("Select Distinct RootCauseCategory From RootCause", conCategory);
cmdRootCauseCategory.ExecuteNonQuery();
SqlDataAdapter daRootCauseCategory = new SqlDataAdapter(cmdRootCauseCategory);
DataSet dsRootCauseCategory = new DataSet();
daRootCauseCategory.Fill(dsRootCauseCategory);
conCategory.Close();
//create list and add items in it by looping through dataset table
List<CascadingDropDownNameValue> RootCauseCategoryDetails = new List<CascadingDropDownNameValue>();
foreach (DataRow dtrow in dsRootCauseCategory.Tables[0].Rows)
{
//string recID = dtrow["recID"].ToString();
string RootCauseCategory = dtrow["RootCauseCategory"].ToString();
string RootCauseCategoryValue = dtrow["RootCauseCategory"].ToString();
RootCauseCategoryDetails.Add(new CascadingDropDownNameValue(RootCauseCategory,RootCauseCategoryValue));
}
return RootCauseCategoryDetails.ToArray();
}
/// WebMethod to Populate Root Cause Dropdown
[WebMethod]
public CascadingDropDownNameValue[] BindRootCauseDetails(string knownCategoryValues, string category)
{
string rootCauseCategory;
//This method will return a StringDictionary containing the name/value pairs of the currently selected values
StringDictionary rootCauseCategoryDetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
rootCauseCategory = (rootCauseCategoryDetails["RootCauseCategory"]);
conCategory.Open();
SqlCommand cmdRootCause = new SqlCommand("select recID, rootCause from RootCause where rootCauseCategory= #vRootCauseCategory", conCategory);
cmdRootCause.Parameters.AddWithValue("#vRootCauseCategory", rootCauseCategory);
cmdRootCause.ExecuteNonQuery();
SqlDataAdapter daRootCause = new SqlDataAdapter(cmdRootCause);
DataSet dsRootCause = new DataSet();
daRootCause.Fill(dsRootCause);
conCategory.Close();
//create list and add items in it by looping through dataset table
List<CascadingDropDownNameValue> rootCauseDetails = new List<CascadingDropDownNameValue>();
foreach (DataRow dtrow in dsRootCause.Tables[0].Rows)
{
string recID = dtrow["recID"].ToString();
string rootCause = dtrow["rootCause"].ToString();
rootCauseDetails.Add(new CascadingDropDownNameValue(rootCause, recID));
}
return rootCauseDetails.ToArray();
}
}
I decided to scrap the idea of a web service, and opted for an updatepanel instead. There is likely a less redundant way to do this, but it's working.
Final Solution:
Markup page:
<asp:TableCell Width="500">
<asp:UpdatePanel ID="UpdatePanel" runat="server">
<ContentTemplate>
<p><asp:DropDownList ID="cboRootCauseCategory" runat="server" AutoPostBack="True" onselectedindexchanged="cboRootCauseCategory_SelectedIndexChanged"></asp:DropDownList>
<asp:DropDownList ID="cboRootCause" runat="server" AutoPostBack="true"></asp:DropDownList></p>
</ContentTemplate>
</asp:UpdatePanel>
</asp:TableCell>
Code Behind:
if (!IsPostBack)
{
//Create data table to populate fields with values from the selected record.
DataTable dt = new DataTable();
dt = selectDetails();
//Call Try/Catch Blocks to load fields.
tryRootCauseCategoryDD(cboRootCauseCategory, dt.Rows[0]["rootCauseCategory"].ToString());
tryRootCauseDD(cboRootCause, dt.Rows[0]["rootCause"].ToString());
}
protected void tryRootCauseCategoryDD(DropDownList cboRootCauseCategory, string ddSelected)
{
try
{
//Load Root Cause Category Drop Down
DataTable RootCauseCategories = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DEV"].ConnectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("Select recID, rootCauseCategory From RootCauseCategory", con);
adapter.Fill(RootCauseCategories);
cboRootCauseCategory.DataSource = RootCauseCategories;
cboRootCauseCategory.DataTextField = "RootCauseCategory";
cboRootCauseCategory.DataValueField = "recID";
cboRootCauseCategory.DataBind();
}
cboRootCauseCategory.Items.Insert(0, new ListItem("(Please select:)", "0"));
cboRootCauseCategory.SelectedValue = ddSelected;
}
catch
{
//Load Root Cause Category Drop Down
DataTable RootCauseCategories = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DEV"].ConnectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("Select recID, rootCauseCategory From RootCauseCategory", con);
adapter.Fill(RootCauseCategories);
cboRootCauseCategory.DataSource = RootCauseCategories;
cboRootCauseCategory.DataTextField = "RootCauseCategory";
cboRootCauseCategory.DataValueField = "recID";
cboRootCauseCategory.DataBind();
}
cboRootCauseCategory.Items.Insert(0, new ListItem("(Please select:)", "0"));
cboRootCauseCategory.SelectedIndex = 0;
}
}
protected void tryRootCauseDD(DropDownList cboRootCause, string ddSelected)
{
try
{
string cboRootCauseCategoryID = Convert.ToString(cboRootCauseCategory.SelectedValue);
DataTable RootCauses = new DataTable();
using (SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["DEV"].ConnectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("Select recID, rootCause, rootCauseCategory From RootCause Where rootCauseCategory = '" + cboRootCauseCategoryID + "'", con2);
adapter.Fill(RootCauses);
cboRootCause.DataSource = RootCauses;
cboRootCause.DataTextField = "RootCause";
cboRootCause.DataValueField = "recID";
cboRootCause.DataBind();
}
cboRootCause.SelectedValue = ddSelected;
}
catch
{
cboRootCause.SelectedIndex = 0;
}
}
protected void cboRootCauseCategory_SelectedIndexChanged(object sender, EventArgs e)
{
string cboRootCauseCategoryID = Convert.ToString(cboRootCauseCategory.SelectedValue);
DataTable RootCauses = new DataTable();
using (SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["DEV"].ConnectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("Select recID, rootCause, rootCauseCategory From RootCause Where rootCauseCategory = '" + cboRootCauseCategoryID + "'", con2);
adapter.Fill(RootCauses);
cboRootCause.DataSource = RootCauses;
cboRootCause.DataTextField = "RootCause";
cboRootCause.DataValueField = "recID";
cboRootCause.DataBind();
}
cboRootCause.Items.Insert(0, new ListItem("(Please select:)", "0"));

Resources