Creating any entity record with mvc 3 - asp.net-mvc

im trying to save a record on a sql server 2008 DB using entityframework and mvc3.
{
using(entities store = new entities())
{
login log = new login() {
Username=username,
Thumbprint=thumbprint
};
store.login.AddObject(log);
store.SaveChanges();//crashes on this line of code
}
}
The code crashes and teh error is I cant save null in the Username column. My DB table does not allow null and im assigning values to the log entity object(username). If you do not understand what im trying to say, please ask.

Related

Reading from a textfile in MVC

I have recently tried to read from a textfile and populate the db and then display the populated data onto my MVC application. Reason for all of this is because I want my desktop application to be able to pass data to my MVC application and save it into my MVC db.
This is what I have:
public ActionResult Index([Bind(Include = "location_id,location_name")] Location location)
{
string full_path = Request.MapPath("~/App_Data/TestText.txt");
if (System.IO.File.Exists(full_path))
{
if (new System.IO.FileInfo(full_path).Length > 0)
{
string[] text_file = System.IO.File.ReadAllLines(HostingEnvironment.MapPath(#"~/App_Data/TestText.txt"));
foreach (string record in text_file)
{
string[] record_cell = record.Split('~');
location.location_name = record_cell[1];
db.Locations.Add(location);
db.SaveChanges();
}
System.IO.File.WriteAllText(HostingEnvironment.MapPath(#"~/App_Data/TestText.txt"), "");
}
}
ViewBag.location_id = new SelectList(db.Locations, "location_id", "location_name");
return View();
}
I have the code above which is placed in my home controller so that everytime the page loads it looks into the textfile for new data and stores it in the db, and at the same time returns a view to display the index page.
Everything works fine on localhost however when hosted I am getting the following error:
I have my textfile located in App_Data, I however feel as though placing the code in the controller under Index is causing this. Can you please help me out to show me where to place the code so that on startup of the website it checks for updated datab in the textfile.
Update:
I have found the error causing the site not to load. Somehow the following line of code from the view, which is populating a dropdown list with data from the db is not working:
#Html.DropDownList("location_id", null, htmlAttributes: new { #class = "form-control"})
Any solutions on fixing this?

Time out 500 error on Edmx

I developed a website using Asp.Net MVC and Edmx database and I published this website on azure and my database is also on azure and I've a functionality on website that uploads excel record into database and that excel sheet contain almost 18000 records every time I upload that sheet it throw Timeout error after some time so what should I do.
Initially I was not using any command Timeout but after doing some research I'm using this in constructor
public ProfessionalServicesEntities()
: base("name=ProfessionalServicesEntities")
{
this.Database.CommandTimeout = 10000;
//this.Database.CommandTimeout = 0; //I tried this too.
//((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 3600;
}
Here is the code of
function :-
public void SaveEquipments(IEnumerable<EquipSampleEntity> collection)
{
using (ProfessionalServicesEntities db = new ProfessionalServicesEntities())
{
string modelXml = XmlSerialization.ListToXml(collection.Where(x=>x.Type == Model).ToList());
string accessoryXml = XmlSerialization.ListToXml(collection.Where(x => x.Type == Accessory).ToList());
db.ImportEquipmentFile(modelXml, accessoryXml);
}
}
here is context file code for SP:-
public virtual int ImportEquipmentFile(string modelXml, string accessoryXml)
{
var modelXmlParameter = modelXml != null ?
new ObjectParameter("ModelXml", modelXml) :
new ObjectParameter("ModelXml", typeof(string));
var accessoryXmlParameter = accessoryXml != null ?
new ObjectParameter("AccessoryXml", accessoryXml) :
new ObjectParameter("AccessoryXml", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("ImportEquipmentFile", modelXmlParameter, accessoryXmlParameter);
}
You may be processing the excel on upload itself and processing it row by row. You have two options, one is to schedule a background job to pickup the upload file and insert it to DB and complete the request.
Next option is to read the whole file in one go and do a single bulk insert into the DB.
There are too many things that can cause this. In Azure App Service there is a Front-end which has a timeout of 240 seconds. If your application takes more time, then you might run into this. This could be one of the probable causes.
In order to understand what is happening. Enabled Web Server Logging and Failed Request Tracing.
See this for how to proceed further: https://learn.microsoft.com/en-us/azure/app-service-web/web-sites-enable-diagnostic-log

SubmitChanges doesn't always update database

I am using ASP.NET MVC 4 (.NET framework 4.5) with LINQ-to-SQL and SQL Server 2008 R2
This function returns always true if I run it through debug mode, but when I run it without debug, it returns false. I once got this error: http://i.imgur.com/HydhT.png
I tried googling this, some similiar problems came up but I checked them all:
UserProfiles table has a primary key
The datacontext is in sync with the database
I've tried putting ConflictMode.ContinueOnConflict as an argument in SubmitChanges()
I've tried to put above the facebookID in LINQ designer: UpdateCheck=UpdateCheck.Never
Nothing works. I have never experienced anything like this before. Does anyone have any idea?
Code:
facebookID field in SQL Server is varchar(50) NULL with default value NULL
public static bool changeFacebookIDByEmail(string email, string facebookID)
{
UserProfile profile = (from s in _dc.Users
join u in _dc.Memberships on s.UserId equals u.UserId
join i in _dc.UserProfiles on u.UserId equals i.userID
where u.Email == email
select i).SingleOrDefault();
profile.facebookID = facebookID;
ChangeSet cs = _dc.GetChangeSet();
_dc.SubmitChanges();
if (cs.Updates.Count <= 0)
return false;
else
return true;
}
It seems like you are executing a manual SQL statement:
UPDATE UserProfiles SET facebookID = NULL WHERE userID = '85A6D951-15C8-4892-B17D-BD93F3D0ACBB'
This will set the facebookID to null. Entity framework does not know this, though. It cannot interpret raw SQL. So it still thinks the facebookID is set to some value. When you later set it to that value in changeFacebookIDByEmail EF thinks nothing changed.
Sou you probably should not execute raw SQL strings. Use EF to change the value to null.
Change .singleordefault to .single I think your problem will be revealed pretty soon after that.
Basically anything found by your query with be in the datacontext. Anything new eg default will not.
You need to rewrite your routine to insert the new user in the case where it's not found.
EDIT
This is some code from a project I have been working on. I've cut out a bunch of stuff to demonstrate how it should work.
// add the identity as necessary
var found = dB.Identities.SingleOrDefault(q => q.UserName == userName);
if (found == null)
{
found = new Identity
{
Domain = domain,
Password = User.Identity.AuthenticationType,
Salt = "",
UserName = userName,
LastUpdatedDateTime = DateTime.Now
};
dB.Identities.InsertOnSubmit(found);
}
dB.SubmitChanges(null);

Query with ROWID via data provider

I am looking to query a table like the following sql:
select * from itd093 where rowid='Cumn99AAAAMzAAAAAJ'
It could find a unique record in the ADS architect client. However, when this query was sent from the code level through the .NET data provider, it return none result from the database server.
Does anyone have ideas on how I can make the sql above return the result through the .NET data provider?
Some sample code here:
public void DataProviderTest()
{
using (AdsConnection conn = new AdsConnection(#"Data Source=D:\Development\FDDB;ServerType=ADS_LOCAL_SERVER;TableType=ADS_CDX;TrimTrailingSpaces=TRUE;"))
{
conn.Open();
AdsCommand cmd = new AdsCommand("select * from itd093 where rowid='Cumn99AAAAMzAAAAAJ'", conn);
AdsDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
if (!reader.Read())
throw new Exception("no records");
}
}
Thanks Mark for pointing out that the .NET data provider and the Advantage Data Architect should return the same result.
The problem to be the different connection strings. From the help documentation, it says,the first six characters of the ROWID represent the database ID. It is based on the connection path.
I was mistakenly copy a rowid from the data architect to test with data provider, and the connection strings are different. That's why I couldn't get a result returned from the data provider as it does from the data architect.

How to stop WCF data Service to fetch data when SavingChanges (during update)

I am trying to update an entity from a WCF client as follows:
Ctxt.MergeOption = MergeOption.NoTracking;
var q = Ctxt.Customers.Where(p => p.MasterCustomerId == "JEFFERSON").Select(o => o);
//DataServiceCollection<Customer> oCustomers = new DataServiceCollection<Customer>(q, TrackingMode.None);
DataServiceCollection<Customer> oCustomers = new DataServiceCollection<Customer>(q);
oCustomers[0].FirstName = "KEFFERSON";
//Ctxt.SaveChanges(SaveChangesOptions.ReplaceOnUpdate);
//ctxt.SaveChangesDefaultOptions = SaveChangesOptions.ReplaceOnUpdate;
Ctxt.SaveChanges();
When I try to save the modified entity, it first tries to load that entity using a select query (to database) and then issues update statement to database.
In my case, I simply want to have the entity to be directly updated in the database without fetching it first. I don't mind if it overwrites the data in database
I tried the following at WCF service:
protected override EF.Model.DataModel.PersonifyEntities CreateDataSource()
{
var ctxt = new EF.Model.DataModel.PersonifyEntities();
ctxt.Customers.MergeOption = System.Data.Objects.MergeOption.NoTracking;
ctxt.ContextOptions.ProxyCreationEnabled = false;
ctxt.ContextOptions.LazyLoadingEnabled = false;
return ctxt;
}
But, no luck. Can anyone help me on this?
For WCF DataServices, the client can only update entities that it tracks. So it has to have the entity downloaded in the client before it can make any changes and save it back. Thats why you see the fetch (I am assuming that this is the first fetch that you are seeing for that specific entity) before the update. Hope this helps.

Resources