Asp.net MVC real time application performance - c#

i'm trying to create an asp.net mvc web application ,some pages need to show the data in "real time" ,this data is on a sql server database ,the data is changing always
i created a stored procedure in sql server , i call this procedure in my controller using Entity framework linq and send the result to the browser using ajax
i used outputcashing to minimize the number of execution of the stored procedure ,
in the same controller there is multiple methode that use the same stored procedure ,every methode execute the same procedure ,
how to emprove the performance of my application ,
is there a way to execute the stored procedure only one time for all the controller ??
this is my controller my objective is to minimize the use of the database
[OutputCache(Duration = 20, VaryByParam = "*")]
public class JobsETLController : Controller
{
private ETL_REP_MAUIEntities db = new ETL_REP_MAUIEntities();
public ObjectResult<BIOGetETLJobs_Result> ETLJobs;
public JobsETLController()
{
ETLJobs =db.BIOGetETLJobs();
}
public ActionResult Indexp()
{
var y = from xx in ETLJobs
where xx.etat!="Completed"
orderby xx.etat ascending
select xx;
return PartialView(y);
}
public ActionResult IndexpAll()
{
var y = from xx in ETLJobs
where xx.etat == "Completed"
select xx;
return PartialView(y);
}

If your server is not in a web farm (multiple servers) then you can cache the data in the Asp.net Cache (this is not output cacheing, it's data cacheing). You simply set a 5 minute time limit on the expiration of the data (you say the data needs to update every 5 minutes) so that when a controller needs the data it first checks the cache, and if it's not there it will then execute the stored procedure.
MyData items;
items = (MyData)Cache["MyData"];
if(items == null)
{
items = DoQueryToReturnItems();
Cache.Add("MyData", items, null, DateTime.Now.AddMinutes(5), ..);
}
It's even possible to setup the cache item to be dependent upon a SqlDependency so that when the data changes, the cache can be updated.

Related

How to use variable static list when multi user access

this variable works fine if used by one user, but when used by two or more users then the "static" variable will be read by the next user, the first user instance when filling the gridview there are 5 rows of data and I try to access through other browser when entering the page, gridview on the second user already filled 5 rows of data in input by the first user. then how the solution to this problem? please see my code and give me an solutions. thanks.
static List<ServicesModels> _gridPackageDetail = new List<ServicesModels>();
private void AddListAction(string alfa, string beta)
{
ServicesModels data = new ServicesModels()
{
id_service_detail = Guid.NewGuid(),
scope_name = alfa,
detail_name= beta
};
_gridPackageDetail.Add(data);
}
public ActionResult GridPackageDetail()
{
ViewBag.DataListPackage = _gridPackageDetail.OrderBy(a => a.scope_name).ToList();
return PartialView();
}
my code in mvc3 controller.
The code is working fine, because this is what intended by "static", to have the same data for multi users. In your case you need to create a list or dictionary or multi-dimensional array (any data structure you are comfortABLE with) and save the data per use in it, and then retrieve the data when needed based on the user id.
static List<ServicesModels> _gridPackageDetail = new List<ServicesModels>();
private void AddListAction(string alfa, string beta)
{
ServicesModels data = new ServicesModels()
{
id_service_detail = Guid.NewGuid(),
scope_name = alfa,
detail_name= beta,
user_id = getTheID()// Get the id of the user
};
_gridPackageDetail.Add(data);
}
public ActionResult GridPackageDetail()
{
ViewBag.DataListPackage = _gridPackageDetail.OrderBy(a => a.scope_name && user_id ==getTheID()).ToList();
return PartialView();
}
replace getTheID() by your way of getting the id of the user.
This is used if you want to keep the data of all users. else you should remove the static keyword.

ASP.NET OData v3 vs Excel 2013: ignoring pagination?

I'm trying to integrate an OData Web Api with Excel 2013 but I'm facing some troubles
Scenario:
Large database view with ~40 millions rows (MySQL)
Database-first EDMX on top of it (Entity Framework 6.1.0)
EntitySetController.Get() to supply data to the clients (WebApi 2.1)
Excel 2013 to consume OData feed
My server side code had to take into account the huge data that is behind, so I decorated my Get() with [Queryable(PageSize=50)]
public class SerieValuesController : EntitySetController<SerieValue, int>
{
#region DB Property
private EDMWarehouseViewsContainer _DB = null;
public EDMWarehouseViewsContainer DB
{
get
{
if (_DB == null)
_DB = new EDMWarehouseViewsContainer();
return _DB;
}
}
#endregion
[Queryable(PageSize=50)]
public override IQueryable<SerieValue> Get()
{
var options = this.QueryOptions;
IQueryable results = DB.SerieValues;
if (options.Filter != null)
{
results = options.Filter.ApplyTo(results, new ODataQuerySettings());
}
if (options.Top != null)
{
results = options.Top.ApplyTo(results, new ODataQuerySettings());
}
return results as IQueryable<SerieValue>;
}
protected override SerieValue GetEntityByKey(int id)
{
SerieValue entity = DB.SerieValues.Find(id);
return entity;
}
}
If I try to get data in a browser, with these URLs
http://mymachine.lan/odata/SerieValues (this gets correctly the first 50 rows in the view, along with a oData.nextLink node)
http://mymachine.lan/odata/SerieValues?$skip=50 (this get correctly the next 50 rows)
When I try to consume this feed from Excel 2013, it starts downloading the data automatically, page by page, until the memory blows.
So I changed my [Queryable] decoration as this
[Queryable(PageSize=50, MaxSkip=5000)]
After checking in the browser ($skip=4999 works, $skip=5000 works, $skip=5001 gives an error), I tried to download the data in excel again.
Unfortunately Excel stops at 5000 giving a Server Error and no data is displayed.
How can I make it work?
Yes, Excel will ignore paging when achieving data from OData service.
Since you set MaxSkip=5000, it will fail when the excel tries to get the 5001th record. So what is your expected behavior? If you wanna control the amount of return, you can combine $skip and $top in your query, and set MaxSkip and MaxTop in service to control the maximum value.

Populate dropdownlist - avoid multiple database calls

I am using a Asp.Net MVC application.
In the following code how can I avoid the two database calls for populating a dropdown?
[HttpGet]
public ActionList Upload(){
// do something
//For populating drop downlist take data from db
Return View("Upload");
}
[HttpPost]
public ActionList Upload(){
//do something
//again take data from db for populating dropdown
Return View("Upload");
}
Any other way than jQuery ajax method? Thanks
It depends on the size of the data and how often it's likely to change, but a common solution is just to use the HttpContext's Cache property.
public List<items> GetDropdownlistItems()
{
string cacheKey = "dropdownlistItems";
if (HttpContext.Current.Cache[cacheKey] != null)
{
return (List<items>)HttpContext.Current.Cache[cacheKey];
}
var items = GetItemsFromDatabase();
HttpContext.Current.Cache.Insert(cacheKey, items, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);
return items;
}
I tend to cache data that is rarely changed such as this.
Checkout EntLibs Caching Application Blocks.
You can load all data into the cache on first use, and set an expiry time depending on how quickly you want changes in the db to be made effective.
Basically, add a layer between your Controller and the Database, that runs code something like this:
MyData myData = null;
myData = (MyData )cacheManager.GetData("myData");
if (myData == null)
{
myData = dataProvider.GetData();
cacheManager.Add("myData", myData, CacheItemPriority.Normal, null, timeToExpire);
}
return myData;
Where myData is the data you need for a dropdown.

MVC 2.0 C# ModelUpdate wont update

I'm having trouble getting a ModelUpdate or TryModelUpdate to work in my code.
I'm using the default Role Manager and Login system created by MVC when running the ASP.Net configuration tool. What I'm trying to do is add another column to the Users table so I can record if my users are also customers. So I want to record their CustomerID there.
I used the ADO Entity Data Model to generate all my model code based off my database. The code it created for the field I want to update is here:
public string CustomerID
{
get
{
return this._CustomerID;
}
set
{
this.OnCustomerIDChanging(value);
this.ReportPropertyChanging("CustomerID");
this._CustomerID = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true);
this.ReportPropertyChanged("CustomerID");
this.OnCustomerIDChanged();
}
}
private string _CustomerID;
partial void OnCustomerIDChanging(string value);
partial void OnCustomerIDChanged();
In my controller Im trying to update the CustomerID field with this code:
var userToUpdate = dbu.aspnet_Users.First(u => u.UserName == User.Identity.Name);
UpdateModel(userToUpdate, new string[] { "CustomerID"}, txtID);
dbu.SaveChanges();
But I get an error saying the overload method has some invalid arguments.
I get that the issue is in assigning txtID to CustomerID based off the error, but whats the correct way to do it?
If I need to add more info please let me know.
I figured it out. Apparantly ModelUpdate won't let me pass in custom data and it needs to be passed in from the Form Collection. So using UpdateModel(userToUpdate, new string[] {"CustomerID"}, form.ToValueProvider()); worked.

manually updating database table values are not reflecting in webpage - aspnet mvc

i noticed some wierd problem i.e i have built a web page on which information comes from database table named "school", when i change some data in that table manually from mssql the web page data is still same as previous, its not gettin' changed, i dn't know how it is possible.
this is my action controller
public ActionResult SchoolDetails(string id,_ASI_School schoolDetails)
{
schoolDetails = SchoolRepository.GetSchoolById(id);
return View(schoolDetails);
}
This is my view
=Html.Encode(Model.SchoolName)
= Html.Encode(Model.SchoolAddress)
= Html.Encode(Model.SchoolEmail)
code for GetSchoolById()..
private static ASIDataContext db = new ASIDataContext();
public static _ASI_School GetSchoolById(string schoolId)
{
return db._ASI_Schools.SingleOrDefault(x => x.SchoolId == schoolId);
}
try putting this above your SchoolDetails ActionResult
[OutputCache( Duration=0)]
MVC does some really nice server side caching as well that clearing the cache on the browser does not fix.

Categories

Resources