i want to insert my data into temporary in mvc
I dont want to store data directly into database
For an example, as u visit to a mall and buy 5-6 things, so first it wont store all data in database, instead it stores into somewhere in application.
Like this what logic may i use to make this type of site
public ActionResult Education_Detail(Education objEducation)
{
sp.Reg_Can_Education(ref objEducation);
objEducation.CorColl = (CourseCollection)TempData["objCourseColl"];
TempData["objCourseColl"] = objEducation.CorColl;
for (int item = 0; item < objEducation.CorColl.Count; item++)
{
if (objEducation.CorColl.Item(item).CourseId.ToString() == objEducation.objCourse.CourseId)
{
objEducation.objCourse.CourseNm = objEducation.CorColl.Item(item).CourseNm.ToString();
}
if (objEducation.objCourse.CourseNm != null)
{
break;
}
}
Thank you
Store your data in cookie or session and when user check out store it to database.
Related
I Want to clear one session Data but it's clearing both Sessions data. below is my 2 MVC action methods which are used to clear Session data.
1)
public int Clearsesson()
{
int i = 0;
List<Wish_Product> products = new List<Wish_Product>();
if (**Session["WishItem"]** != null)
{
Session.Clear();
i = 1;
}
else
{
i = 0;
}
return i;
}
2)
public int Clearsesson2()
{
int i = 0;
List<Cart_Product> products = new List<Cart_Product>();
if (**Session["CartItem"]** != null)
{
// Session.Remove("CartItem");
Session.Clear();
i = 1;
}
else
{
i = 0;
}
return i;
}
So like this I am storing Data in two Sessions but when I run this asp.net MVC Action method to clear One session data, it automatically clears second one Session Data too.
Why so like this? Please make it clear to me why it's happening.
Or what I've to do to solve this problem?
The short answer is yes, on the current collection.
According to ASP.NET documentation, HttpSessionState.Clear method removes all keys and values from currently active session state collection (it doesn't destroy user's session state base), so that both Session["WishItem"] & Session["CartItem"] values are cleared together from collection when the method is executed, but the session state base kept alive.
There are 2 different session collection keys in this case & actually both of them using same session state. To clear single session data, there are 2 different ways:
1) Remove session key using Session.Remove.
Session.Remove("WishItem");
2) Assign null value to the session state based with its key.
Session["WishItem"] = null;
The difference between them is that the former deletes both keys and values so that it won't appear as key-value pair in session collection anymore, and the latter overwrites current collection value with specified key but the key name still unchanged.
Therefore, you can remove each session data separately without clearing another session key like this:
public int ClearSession()
{
int i = 0;
// other code logic
if (Session["WishItem"] != null)
{
// only WishItem key has cleared
Session.Remove("WishItem");
i = 1;
}
// other code logic
}
public int ClearSession2()
{
int i = 0;
// other code logic
if (Session["CartItem"] != null)
{
// only CartItem key has cleared
Session.Remove("CartItem");
i = 1;
}
// other code logic
}
Note that each authenticated user always be assigned with one session state base, hence using Session.Clear removes all existing key-value pairs stored in session collection for current user (doesn't affect other user's session state).
I am getting rss feed from a another website and in case that website shut down, I don't want to get an error. So in order to avoid from error I am trying to save rss feeds to database and if the rss server shuts down I will be able to get feed from my database.
I also want to keep only 6 feed in database. If new feed comes I want to delete the last feed by PublishDate
public static List<Rss.News> GetRssFeed(ApplicationDbContext db)
{
try
{
XDocument feedXml = XDocument.Load("http://www.gib.gov.tr/
rss/haberguncel.php");
var feeds = from feed in feedXml.Descendants("item")
select new Rss.News
{
Title = feed.Element("title").Value,
Link = feed.Element("link").Value,
Description = feed.Element("description").Value,
PublishDate=feed.Element("pubdate").Value
};
int counter = 0;
var itemE = db.News.FirstOrDefault();
if (itemE != feeds.First())
{
foreach (var itemC in feeds)
{
if (!db.News.Contains(itemC))
{
db.News.Add(itemC);
db.SaveChanges();
counter += 1;
}
else
{
break;
}
if (counter == 6) { break; }
}
}
return feeds.ToList();
}
catch (Exception)
{
// i will get data from database here.
}
}
I am getting this error when I run this code:
Unable to create a constant value of type
'...Models.Rss+News'. Only primitive types or enumeration
types are supported in this context.
The error is resulting from this line:
if (!db.News.Contains(itemC))
In order to do this type of evaluation at the database level, Entity Framework must be able to convert item being compared (itemC) into a constant value, which it cannot do with this type, hence your error. You can try casting db.News to a list, first, which would switch the evaluation over to in-memory instead at the the database, i.e.:
var news = db.News.ToList();
if (news.Contains(itemC))
However, you'll have to evaluate how that might affect your application's performance. Alternatively, you simply query on a particular value that you determine as the "key" for lookup. For example, you might say that Link will only ever match if it's the same item, so based on that:
if (!db.News.Any(m => m.Link == itemC.Link))
Is there an equivalent of Rails ActiveRecord::Callbacks in ASP MVC?
http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
I'm in a situation where we are not using identities for our primary key. We do this for reasons specific to our DB sharding design. Because of this we have a lookup table to find the next ID for a specific table. I'd like to automatically get this value and set it in an abstract class whenever a model is created/updated and before it is saved. I also need to update the lookup table with an incremented 'nextID' after the save is successful.
I'm open to other solutions on how to do this without callbacks as well.
So you need the callback just to increment ID in the lookup table? AFAIK there is no equivalent in ASP.NET, may be you could try with Async Controllers (http://msdn.microsoft.com/en-us/library/ee728598%28v=vs.100%29.aspx) and wait for a state change from the successful save, but I would prefer use a service specifically for this like Snowflake (https://github.com/twitter/snowflake/).
I found a solution using overrides as opposed to callbacks. It's my hope that ASP mvc adds support for callbacks as the framework continues to mature because callbacks allow for cleaner code by allowing the OnSave event to exist in the model[s] that the event is concerned with rather than the centralized DbContext class (separation of concerns).
Solution:
The SaveChanges method can be overridden in the Context Class (Entity Framework Power Tools creates the Context class is the 'Models' directory).
public override int SaveChanges()
{
// create a cache for id values in case their are multiple added entries in the dbcontext for the same entitytype
Dictionary<string, UniqueID> idCache = new Dictionary<string, UniqueID>();
IEnumerable<DbEntityEntry> changes = this.ChangeTracker.Entries();
foreach (var entry in changes)
{
//check if this is a new row (do nothing if its only a row update because there is no id change)
if (entry.State == System.Data.EntityState.Added)
{
//determine the table name and ID field (by convention)
string tableName = entry.Entity.GetType().Name;
string idField = entry.Entity.GetType().Name + "ID";
UniqueID id = null;
//if we've already looked this up, then use the cache
if (idCache.ContainsKey(tableName))
{
id = idCache[tableName];
}
//if we havn't looked this up before get it and add it to the cache
else
{
id = this.UniqueIDs.Find(tableName, idField);
//if it doesn't already exist in the lookup table create a new row
if (id == null)
{
id = new UniqueID(tableName, idField, 1);
// since this is a new entry add it
this.UniqueIDs.Add(id);
}
else
{
// set the state to modified
this.Entry(id).State = System.Data.EntityState.Modified;
}
}
entry.CurrentValues[tableName + "ID"] = id.NextID;
id.NextID = id.NextID + 1;
}
}
return base.SaveChanges();
}
how to check the duplicate in Application state
My problem scenario:
I stored the username and password in the application[""] variable.
another user enters the username password i want to check for each and every user.
i tried for for loop but hard to find the count..
could you help me check the duplicate
for (int j = 0; j < (int)System.Web.HttpContext.Current.Application["Userlogin"].ToString().Length - 1; j++)
{
if (System.Web.HttpContext.Current.Application[i].ToString() == sKey)
{
Session["duplicateuser"] = "logout";
Returnmsg = "-3";
}
}
but it shows the string length of the application[]
Thank in Advance
I stored the username and password in the application[""] variable
Wow, don't. The Application state is shared among all users of your application. Never store user specific data in application state. Use Session state instead.
UPDATE:
If you want to check for concurrent user access you could store a collection of users into the application state such as IEnumerable<string>. Then you could check if a user is already logged in easily:
public bool IsUserLoggedIn(string username, HttpApplicationStateBase application)
{
var users = application["users"] as IEnumerable<string>;
if (users == null)
{
users = new ConcurrentBag<string>();
application["users"] = users;
}
return users.Any(u => u == username);
}
I am making an MVC4 web application using Entity Framework 5 (Database-first with generated POCOs) for data access.
In the app, the user goes through several screens, creating or editing a document (called a 'case study'). When they arrive at the final screen, their document exists as a CaseStudy POCO in memory, and everything is great until it is time to save this structure to the database.
To store the document, I have defined several database tables, which in turn map to EF POCOs used by the business layer, which is then consumed by the MVC controllers. As such, short-lived DbContexts are used to retrieve POCOs and store them in session between requests.
As a result, the save screen must save the contents of this POCO that has navigational properties to existing table data (Category, Layout, and Sections tables), and also added or updated data (CaseStudySections and the CaseStudy itself). So all of the POCOs are either new, or the context used to retrieve them has long been disposed. In other words, they are all 'detached'.
What is unusual about this post is that I already have a working solution in hand. The problem is that it is bulky, brittle, and inelegant. I am posting the code below. Note the iteration through sub-collections, the explicit adds and attaches, having to get an entry object and mark individual properties as modified just so they will be updated, and the awful song and dance at the end to get the AdditionalMaterials collection synced up. If this is what is required to deal with detached POCOs in EF5 I will be disappointed.
Am I missing something here? Is this consistent with best practices? Is there a more graceful and/or concise way to attach a structure of POCOs and insert/update?
The code to save a case study:
public void SaveCaseStudy(CaseStudy caseStudy)
{
foreach (var s in caseStudy.CaseStudySections)
{
this.Entities.Sections.Attach(s.Section);
if (s.CreatedByRefId == default(Guid))
{
s.CreatedByRefId = this.UserRefId;
s.CreatedTime = DateTime.Now;
this.Entities.CaseStudySections.Add(s);
}
else
{
this.Entities.CaseStudySections.Attach(s);
var entry = this.Entities.Entry(s);
entry.Property(e => e.TextData).IsModified = true;
entry.Property(e => e.BinaryData).IsModified = true;
}
s.LastModifiedByRefId = this.UserRefId;
s.LastModifiedTime = DateTime.Now;
}
foreach (var m in caseStudy.AdditionalMaterials)
{
if (m.CreatedByRefId == default(Guid))
{
m.CreatedByRefId = this.UserRefId;
m.CreatedTime = DateTime.Now;
this.Entities.AdditionalMaterials.Add(m);
}
else
{
this.Entities.AdditionalMaterials.Attach(m);
}
m.LastModifiedByRefId = this.UserRefId;
m.LastModifiedByTime = DateTime.Now;
}
this.Entities.Layouts.Attach(caseStudy.Layout);
this.Entities.Categories.Attach(caseStudy.Category);
if (caseStudy.CreatedByRefId != default(Guid))
{
this.Entities.CaseStudies.Attach(caseStudy);
var entry = this.Entities.Entry(caseStudy);
entry.Property(e => e.CaseStudyName).IsModified = true;
entry.Property(e => e.CaseStudyTitle).IsModified = true;
}
else
{
this.Entities.CaseStudies.Add(caseStudy);
caseStudy.CreatedByRefId = this.UserRefId;
caseStudy.CreatedTime = DateTime.Now;
}
caseStudy.LastModifiedByRefId = this.UserRefId;
caseStudy.LastModifiedTime = DateTime.Now;
if (caseStudy.CaseStudyStatus != (int)CaseStudyStatus.Personalized)
{
caseStudy.CaseStudyStatus = (int)CaseStudyStatus.PendingApproval;
}
caseStudy.ApprovedByRefId = null;
caseStudy.ApprovedTime = null;
this.Entities.SaveChanges();
var existingAdditionalMaterialRefIds = caseStudy.AdditionalMaterials
.Select(m => m.AdditionalMaterialRefId)
.ToArray();
var additionalMaterialsToRemove = this.Entities.AdditionalMaterials
.Where(m =>
m.CaseStudyRefId == caseStudy.CaseStudyRefId &&
!existingAdditionalMaterialRefIds.Contains(m.AdditionalMaterialRefId))
.ToArray();
foreach (var additionalMaterialToRemove in additionalMaterialsToRemove)
{
this.Entities.AdditionalMaterials.Remove(additionalMaterialToRemove);
}
this.Entities.SaveChanges();
}
In general it is what you have to do. You must tell EF about each change you want to perform when attaching detached object graph. I don't say that your code cannot be simplified but you will still have to deal with every entity and setting its state if you want it to be added or modified.
Here is little bit older but still valid answer about the topic - in short nothing has changes since I wrote it, only new DbContext API was created which still sits on top of the old API. The best description of this topic I have seen so far is in book Programming Entity Framework: DbContext.
How about just doing:
db.CaseStudies.Attach(caseStudy);
db.Entry(caseStudy).State = EntityState.Modified;
db.SaveChange();
That will save all changes in your model to the db.