Handling Null in MVC Model - model-view-controller

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
}

Related

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();
}
}}

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"));

How to get the userID of a logged in user?

I'm trying to get the userid of the currently logged in user. Here is my code:
public int GetUserID(string _UserName)
{
using (var context = new TourBlogEntities1())
{
var UserID = from s in context.UserInfoes
where s.UserName == _UserName
select s.UserID;
return Int32.Parse(UserID.ToString()); //error is showing here
}
}
I'm calling the method from my controller using this:
public ActionResult NewPost(NewPost model)
{
var Business = new Business();
var entity = new Post();
entity.PostTitle = model.PostTitle;
entity.PostStory = model.PostStory;
entity.UserID = Business.GetUserID(User.Identity.Name);
Business.NewPost(entity);
Business.ViewPost(entity);
return View("ViewPost", model);
}
The error is showing as "input string is not in correct format". Please help. Thanks.
Your query returns an IEnumerable. You need to get only the single record:
using (var context = new TourBlogEntities1())
{
var userIds = from s in context.UserInfoes
where s.UserName == _UserName
select s.UserID;
return userIds.Single();
}
By the way the .Single() method will throw an exception if there are more than 1 records matching the criteria. Hopefully you have an unique constraint on the Username field inside your database.
CreatedBy = this.HttpContext.User.Identity.Name,

using LINQ update particular column in asp.net mvc 3

I have following code for updating user's column
public void UpdateLastModifiedDate(string username)
{
using (AppEntities db = new AppEntities())
{
var result = from u in db.Users where (u.UserName == username) select u;
if (result.Count() != 0)
{
var dbuser = result.First();
dbuser.LastModifiedDate = DateTime.Now;
db.SaveChanges();
}
}
}
I have other's 2 function of almost same of above function for UpdateLastLogOutDate, UpdateLastLoginDate. So, I decided to define single function for all to update Last Date like:
public void UpdateLastDate(string username, string ColumnName);
Here, I can not put ColumnName variable like this:
dbuser.ColumnName = DateTime.Now;
Is there any other way to do this using LINQ
You could define the method like this:
public void Update(string username, Action<User> action)
{
using (AppEntities db = new AppEntities())
{
var result = from u in db.Users where (u.UserName == username) select u;
if (result.Count() != 0)
{
var dbuser = result.First();
action(dbuser);
db.SaveChanges();
}
}
}
And now there could be different usages of this method:
Update("john", user => user.LastModifiedDate = DateTime.Now);
Update("smith", user => user.UpdateLastLogOutDate = DateTime.Now);
Update("admin", user =>
{
user.LastModifiedDate = DateTime.Now;
user.UpdateLastLogOutDate = DateTime.Now;
});
But if the expression is not known at compile time you may take a look at dynamic LINQ.
You could write your code this way also by sending an instance of your entity as parameter:
public void UpdateLastModifiedDate(Entityclassname ent) //[like if table name is item then Entityclassname should be items etc..]
{
using (AppEntities db = new AppEntities())
{
var result = from u in db.Users where (u.UserName == ent.username) select u;
if (result.Count() != 0)
{
var dbuser = result.First();
dbuser.LastModifiedDate = DateTime.Now;
dbuser.UpdateLastLogOutDate=ent.UpdateLastLogOutDate ;
db.SaveChanges();
}
}
}

How call stored procedure to insert value in a table

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;
//}

Resources