Changes(update) not commited to multiple columns using LINQ to SQL - c#

i am trying the linq to sql query using button but the change does not commit.
here is the code which i am using:
using (Property_dbDataContext context = new Property_dbDataContext())
{
var user = (from a in context.User_profiles
where a.user_id == Convert.ToInt32(Request.QueryString["user_id"])
select a).FirstOrDefault();
user.email = _Email.Text;
user.first_name = _FirstName.Text;
user.last_name = _LastName.Text;
user.phone = _Phone.Text;
user.cell = _Cell.Text;
user.fax = _Fax.Text;
user.address = _Address.Text;
user.zip_code = _ZipCode.Text;
user.country = _Country.SelectedItem.Text;
context.SubmitChanges();
}

Your code seems correct. I think you are missing something else. So i suggest you should try some debugging;
First make sure to wrap your code inside null check always;
if(user !=null)
{
user.email = _Email.Text;
user.first_name = _FirstName.Text;
user.last_name = _LastName.Text;
user.phone = _Phone.Text;
user.cell = _Cell.Text;
user.fax = _Fax.Text;
user.address = _Address.Text;
user.zip_code = _ZipCode.Text;
user.country = _Country.SelectedItem.Text;
context.User_profiles.Attach(user);
context.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
context.SubmitChanges();
}
Secondly, for debugging purposes, write some const string values to see if really you are posting data like this;
user.email = _Email.Text;
user.first_name = "test1";
user.last_name = _LastName.Text;
.........
context.SubmitChanges();
And third, don't forget, debugger is your best friend :)

Did you try this?
using (Property_dbDataContext context = new Property_dbDataContext())
{
var user = (from a in context.User_profiles
where a.user_id == Convert.ToInt32(Request.QueryString["user_id"])
select a).FirstOrDefault();
user.email = _Email.Text;
user.first_name = _FirstName.Text;
user.last_name = _LastName.Text;
user.phone = _Phone.Text;
user.cell = _Cell.Text;
user.fax = _Fax.Text;
user.address = _Address.Text;
user.zip_code = _ZipCode.Text;
user.country = _Country.SelectedItem.Text;
context.User_profiles.Attach(user);
context.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
context.SubmitChanges();
}

Related

Adding attributes for faceting with Algolia C#

I have an attribute that I'd like to add for faceting: ApprovalFL. When I add the facet in the Algolia dashboard, it works fine until I have to reindex which ends up deleting my facets in the dashboard for some reason. I was thinking, maybe adding the attribute in my code would resolve that. I found the documentation about this step here: https://www.algolia.com/doc/api-reference/api-parameters/attributesForFaceting/
Here's the C# example they provide:
index.SetSettings(
JObject.Parse(#"{""attributesForFaceting"":[""author"",""filterOnly(category)"",""searchable(publisher)""]}")
);
If I understand correctly, this code needs to go in my backend reindexing code (found in my AdminController.cs):
public async Task<ActionResult> ReIndexData()
{
var algoliaArtistModels = Tools.BuildAlgoliaArtistModels(EntityDataAccess.GetAllAccountInfoes());
var algoliaUnaffiliatedArtistModels = Tools.BuildAlgoliaArtistModels(EntityDataAccess.GetAllUnaffiliatedAccountInfo());
var algoliaSongModels = Tools.BuildAlgoliaSongModels(EntityDataAccess.GetAllAcceptedSongs());
var artistIndexHelper = HttpContext.Application.Get("ArtistIndexHelper") as IndexHelper<ArtistAlgoliaModel>;
var unaffiliatedArtistIndexHelper = HttpContext.Application.Get("UnaffiliatedArtist") as IndexHelper<ArtistAlgoliaModel>;
var songIndexHelper = HttpContext.Application.Get("SongIndexHelper") as IndexHelper<SongAlgoliaModel>;
await artistIndexHelper.OverwriteIndexAsync(algoliaArtistModels);
await unaffiliatedArtistIndexHelper.OverwriteIndexAsync(algoliaUnaffiliatedArtistModels);
await songIndexHelper.OverwriteIndexAsync(algoliaSongModels);
return View("AlgoliaReIndexData");
}
However, I don't think I put index.setSettings in this block of code, what is the best way to set this attribute for faceting in my backend code? The ApprovalFL attribute is stored in my Song indices.
Possibly it should go somewhere here in my Tools.cs?
public static SongAlgoliaModel BuildAlgoliaSongModel(Song song)
{
var model = new SongAlgoliaModel();
var album = EntityDataAccess.GetAlbumByID(song.AlbumID);
model.AccountImageURL = album.AccountInfo.ImageURL;
model.AccountInfoID = album.AccountInfoID;
model.AccountType = album.AccountInfo.CreatorFL == true ? "Creator" : "Artist";
model.AlbumID = song.AlbumID;
model.AlbumName = album.AlbumName;
model.ApprovalFL = song.ApprovalFL;
model.Artist = album.AccountInfo.DisplayName;
model.BPM = song.BPM;
model.Duration = song.Duration;
model.FeaturedArtist = song.Artist;
model.FreeFL = album.FreeFL;
model.ImageURL = album.ImageURL;
model.iTunesURL = album.iTunesURL;
model.LabelName = album.LabelName;
model.LicenseFL = album.LicenseFL;
model.SongID = song.SongID;
model.Title = song.Title;
model.UploadDate = song.UploadDate;
model.URL = song.URL;
model.UserID = album.AccountInfo.UserID;
return model;
}
public static List<SongAlgoliaModel> BuildAlgoliaSongModels(AccountInfo accountInfo)
{
var list = new List<SongAlgoliaModel>();
var songs = EntityDataAccess.GetSongsByUserID(accountInfo.UserID).Where(x => x.ApprovalFL == true).ToList();
foreach(var item in songs)
{
var model = new SongAlgoliaModel();
model.AccountImageURL = item.Album.AccountInfo.ImageURL;
model.AccountInfoID = item.Album.AccountInfoID;
model.AccountType = item.Album.AccountInfo.CreatorFL == true ? "Creator" : "Artist";
model.AlbumID = item.AlbumID;
model.AlbumName = item.Album.AlbumName;
model.ApprovalFL = item.ApprovalFL;
model.Artist = item.Album.AccountInfo.DisplayName;
model.BPM = item.BPM;
model.Duration = item.Duration;
model.FeaturedArtist = item.Artist;
model.FreeFL = item.Album.FreeFL;
model.ImageURL = item.Album.ImageURL;
model.iTunesURL = item.Album.iTunesURL;
model.LabelName = item.Album.LabelName;
model.LicenseFL = item.Album.LicenseFL;
model.SongID = item.SongID;
model.Title = item.Title;
model.UploadDate = item.UploadDate;
model.URL = item.URL;
model.UserID = item.Album.AccountInfo.UserID;
list.Add(model);
}
return list;
}
OK for those using C# .NET it's as simple as adding it to your Global.asax.cs for example for me:
var songIndexHelper = new IndexHelper<SongAlgoliaModel>(algoliaClient, "Song", "SongID");
songIndexHelper.SetSettings(JObject.Parse(#"{""attributesForFaceting"":[""ApprovalFL""]}"));
Why do you have to re-index by the way? Best practice is to set up your index only initially.

Checking for existing records on database wen i call web api

I am calling a web api and saving the records on the database through the controller, i want each time im calling the api to check if the record exists in the database if yes then dont save, if not then save.
var client = new WebClient();
var text = client.DownloadString("https://www.test.com/api/all-users?name=testusername%20&pass=334432");
var wclients = JsonConvert.DeserializeObject<dynamic>(text);
List<apicli> list1 = new List<apicli>();
var clie = new apicli();
if (wclients.message == "success")
{
var data = wclients.data;
//var account = wclients.account;
ViewBag.test = data;
foreach(var item in ViewBag.test)
{
clie.Email = item.email;
clie.Name = item.name;
clie.Aff = item.affiliated_id;
foreach(var item1 in #item.account.real)
{
clie.Login = item1.login;
clie.password = item1.pass;
}
list1.Add(clie);
db.apiclis.AddRange(list1);
db.SaveChanges();
};
}
I would assume you need something like this, although you need to check what is the unique id of each record:
foreach(var item in data){
var c = new apicli {
Email = item.email,
Name = item.name,
Aff = item.affiliated_id
Login = item.account.real.LastOrDefault()?login??"",
Login = item.account.real.LastOrDefault()?pass??""
}
if(!db.apiclis.Any(a => a.Email == c.Email && a.Name == c.Name && a.Aff == c.Aff)){
db.apiclis.Add(c);
}
}
Here I assume that email+name+aff = unique identificator.

Need to access and edit an attribute in a database

Orders are created and saved in this method
public async Task<ActionResult> FirstClassCreate(FormCollection values)
{
var order = new Order();
TryUpdateModel(order);
var customer = db.Users.FirstOrDefault(x => x.Email == User.Identity.Name);
var cart = ShoppingCart.GetCart(this.HttpContext);
try
{
order.DeliveryDate = DateTime.Now.AddDays(1);
order.DeliveryMethod = "First Class";
order.FirstName = customer.FirstName;
order.LastName = customer.LastName;
order.PostalCode = customer.PostalCode;
order.State = customer.State;
order.City = customer.City;
order.Email = customer.Email;
order.Country = customer.Country;
order.Phone = customer.PhoneNumber;
order.Address = customer.Address;
order.HasPaid = false;
order.Username = customer.Email;
order.OrderDate = DateTime.Now;
var currentUserId = User.Identity.GetUserId();
order.Total = cart.GetFirstClass();
if (order.SaveInfo && !order.Username.Equals("guest#guest.com"))
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var ctx = store.Context;
var currentUser = manager.FindById(User.Identity.GetUserId());
//Save this back
//http://stackoverflow.com/questions/20444022/updating-user-data-asp-net-identity
//var result = await UserManager.UpdateAsync(currentUser);
await ctx.SaveChangesAsync();
await storeDB.SaveChangesAsync();
}
//Save Order
storeDB.Orders.Add(order);
await storeDB.SaveChangesAsync();
//Process the order
cart = ShoppingCart.GetCart(this.HttpContext);
order.Total = cart.GetFirstClass();
order = cart.CreateOrder(order);
return RedirectToAction("FirstClass", "Checkouts", order);
}
catch
{
//Invalid - redisplay with errors
return View(order);
}
}
I need to be access the orders database and change attributes of a specific order, using the email as the Unique Identifier and search for the newest (find the newest using the Order Date where 'haspaid' = false).
using ()//Insert database context here)
{
//Search for order in the database, try using the email as the Unique Identifire and search for the newest where haspaid = false
//Change the haspaid attribute to true
var orders = from o in db.Orders
where o.Email == User.Identity.Name, o.HasPaid = false, //Newest
select o;
order.HasPaid = true;
db.Orders.SaveChanges();
//save database changes
}
If I understand you correctly, you don't know how to query the record you want to update. So you need to use the Where() to filter the record and use the Max() function to get the latest date.
var orderToBeChanged = db.Orders
.Where(o => o.HasPaid == false && o => o.Email == User.Identity.Name)
.Max(o => o.OrderDate);

Search in IQueryable<T>

I am pulling some data from database by this line below:
IQueryable<user> UserList = DatabaseContext.Users.GetAll();
I want to seach something in UserList such as:
foreach (var User in UserList)
{
if (User.type == (int)UserType.SuperUser)
{
IsRecordFound = true;
break;
}
}
Then i do something according to the state of flag:
if (!IsRecordFound)
{
AesCrypto aesCrypto = new AesCrypto();
user newuser = new user();
newuser.username = DEFAULT_SUPER_USER_NAME;
newuser.password = aesCrypto.Encrypt(DEFAULT_SUPER_USER_PASSWORD);
newuser.type = (int)UserType.SuperUser;
newuser.create_date = DateTime.Now;
newuser.last_login = newuser.create_date;
newuser.email_address = DEFAULT_SUPER_USER_EMAIL_ADDR;
newuser.login_count = 1;
DatabaseContext.Users.Add(newuser);
if (!DatabaseContext.Save())
return false;
}
Is there any easy or practical way to seach in IQueryable interface by using LINQ or something else?
if (!UserList.Any(x => x.Type == (int)UserType.SuperUser))
{
AesCrypto aesCrypto = new AesCrypto();
user newuser = new user();
newuser.username = DEFAULT_SUPER_USER_NAME;
newuser.password = aesCrypto.Encrypt(DEFAULT_SUPER_USER_PASSWORD);
newuser.type = (int)UserType.SuperUser;
newuser.create_date = DateTime.Now;
newuser.last_login = newuser.create_date;
newuser.email_address = DEFAULT_SUPER_USER_EMAIL_ADDR;
newuser.login_count = 1;
DatabaseContext.Users.Add(newuser);
if (!DatabaseContext.Save())
return false;
}
You can do it like
bool isSuperUser = UserList.Any(a=>a.type==a.SuperUser)
to search an IQueryable, use where
var foundUsers = UserList.Where( usr => usr.Type == (int)UserTypes.SuperUser );
if( foundUsers == null && foundUsers.Count() == 0 ) // only one of these is required.. I forget which though :s
{
AesCrypto aesCrypto = new AesCrypto();
user newuser = new user();
newuser.username = DEFAULT_SUPER_USER_NAME;
newuser.password = aesCrypto.Encrypt(DEFAULT_SUPER_USER_PASSWORD);
newuser.type = (int)UserType.SuperUser;
newuser.create_date = DateTime.Now;
newuser.last_login = newuser.create_date;
newuser.email_address = DEFAULT_SUPER_USER_EMAIL_ADDR;
newuser.login_count = 1;
DatabaseContext.Users.Add(newuser);
if (!DatabaseContext.Save())
return false;
}
UserList .Where(user => user.Type== (int)UserType.SuperUser);

How do you return A Table with inserted information in LINQ TO SQL?

I want to return a table which I have edited/added information/inserted data to. Here's my code.
using(DbClassesDataContext myDb = new DbClassesDataContext(dbPath)){
PatientInfo patientInfo = new PatientInfo();
patientInfo.Phy_ID = physcianID;
patientInfo.Pat_First_Name = txtFirstName.Text;
patientInfo.Pat_Middle_Name = txtMiddleName.Text;
patientInfo.Pat_Last_Name = txtLastName.Text;
patientInfo.Pat_Gender = cmbGender.Text;
patientInfo.Pat_Marital_Status = cmbMaritalStatus.Text;
patientInfo.Pat_Date_Of_Birth = dtpDOB.Value;
patientInfo.Pat_Home_Add = txtHomeAdd.Text;
patientInfo.Pat_Home_Num = txtPhone.Text;
patientInfo.Pat_Work_Add = txtWorkAdd.Text;
patientInfo.Pat_Work_Num = txtWorkPhone.Text;
patientInfo.Pat_Prim_Physician = txtPrimPhysician.Text;
patientInfo.Pat_Ref_Physician = txtRefePhysician.Text;
}
Where I want to return patientInfo? what data type is it? how would I create a method which returns it like that?
You can just return the patientInfo object directly, it will be of type PatientInfo (exactly like it appears in your code now).
You are not actually using the DB context that you are generating in your code. I assume you want to insert the new PatientInfo to the DB? Something like:
using(DbClassesDataContext myDb = new DbClassesDataContext(dbPath)){
PatientInfo patientInfo = new PatientInfo();
patientInfo.Phy_ID = physcianID;
patientInfo.Pat_First_Name = txtFirstName.Text;
patientInfo.Pat_Middle_Name = txtMiddleName.Text;
patientInfo.Pat_Last_Name = txtLastName.Text;
patientInfo.Pat_Gender = cmbGender.Text;
patientInfo.Pat_Marital_Status = cmbMaritalStatus.Text;
patientInfo.Pat_Date_Of_Birth = dtpDOB.Value;
patientInfo.Pat_Home_Add = txtHomeAdd.Text;
patientInfo.Pat_Home_Num = txtPhone.Text;
patientInfo.Pat_Work_Add = txtWorkAdd.Text;
patientInfo.Pat_Work_Num = txtWorkPhone.Text;
patientInfo.Pat_Prim_Physician = txtPrimPhysician.Text;
patientInfo.Pat_Ref_Physician = txtRefePhysician.Text;
//store to db
myDb.Patients.AddObject(patientInfo);
myDb.SaveChanges();
return patientInfo;
}
Be careful, the object internally stores a reference to the DataContext you created/updated it with. If you use it together with later updates/inserts that you have the same context for all of them or you will get exceptions.

Categories

Resources