how to show database changes in web pages(whiteout reloading page)? - ajax

i am working on simple hotel reservation system that users enter their info, like hotel or room. in every page i have footer bar that show feedback of system when user do something. for example when user add hotel , after doing this,when he redirect to any pages, in footer bar, immediately, display , "hotel added successfully".
|----------------------------------------|
| |
| GridView |
| |
| |
|----------------------------------------|
|hotel added successfully ! |
|----------------------------------------|
the solution that i am using is :
when users log something , i log it
and i define div[id=notification] in shared/_layout, and using a worker to call a function that check log database and get new ones.
// i use worker to repeatedly invoke function to check db
var worker = new Worker('../Scripts/worker.js');
worker.addEventListener('message', function (e)
{
if (e.data != "")
{
var result = e.data;
var results = result.split("##");
if ($("#notificationID").val() != results[1])
{
$("#notificationID").val(results[1]);
}
}
}, false);
and the function to check db is
public string GetNewTrans()
{
string userName = Membership.GetUser().UserName;
using (var context = new jobEntities())
{
var query = from p in context.Logs where p.UserName==userName && p.IsNew == null orderby p.ID_Log descending select p;
if (query.Count() > 0)
{
var log = query.FirstOrDefault();
DateTime c= DateTime.Parse(log.RefreshDate.ToString());
var sec = DateTime.Now.Subtract(c).Seconds;
if( sec> 2)
{
log.IsNew = "false";
context.SaveChanges();
}
var result = log.Section + " : " + log.Action +"##"+log.Success.ToString()+"##"+log.ID_Log.ToString();
return result;
}
return null;
}
}
now i think that when number of users increase , the load of check db increase and cause to make pages slower.
so do you have any better solution ?
and my framework in asp mvc 3.5 and use EF 4.1

The better solution to get some data from db its using JsonResult action controller to get json data and than modified on the client.
As for info messages you can add TempData["message"] object in your controller and in redirecting View

Related

Zend 1 ajax with dojo informatiom person

I'm working with Zend 1 with dojo and do not know how to use ajax . In my particular case that when selecting a select , whether made ​​in consultation ajax back from the database information. To enter a ID from user print the information from user by ajax.In my work I can't use jquery.
Good question!
Not is very productive work with dojo, but is possible make exactly how do you want. You will create p element with information captured in data base
In your form, add attribute 'onChange'
$form->setAttrib('onChange', 'recoveryData()');
In js file do you have a function recoveryData(), something as:
dojo.require("dojo.html");
// clean data
var myNewElement = dojo.byId('myNewElement');
if (myNewElement != null) {
dojo.empty("myNewElement");
}
dojo.xhrPost({
content: {id: dojo.attr(dojo.byId("myElement"), "value")},
url: 'your-base-path/recovery-data/',
load: function (response) {
if (response != false) {
// converte to obj
var obj = dojo.fromJson(response);
// creat new element
var node = dojo.create("span", {
innerHTML: obj.NomeServidor,
id: "myNewElement",
'class': 'row'
}
);
dojo.place(node, dojo.byId("myElement"), "after");
}
}
});
Now, you need create an Action "recoveryDataAction()" in your Controller like this:
$data = $this->getrequest()->getPost();
$id = $data['id'];
if ($this->getrequest()->isXmlHttpRequest()) {
// disable layout
$this->_helper->layout()->disableLayout();
// disable view render
$this->_helper->viewRenderer->setNoRender();
$yourTable = new Project_Model_YourTable();
$row = $yourTable->fetchRow($id);
if ($infos != null) {
echo Zend_Json::encode($row);
return;
}
echo false;
}

Calculating age by birthdate field in crm 2013

I need to write a global javascript code that calculates age by birthday field and call the function from a diffrent javascript file to the specific entity.
from some reason i get error message "CalculateAge is undefined" after i loaded my entity javascript file to the form.
This is what i write in the global file:
CalculateAge: function (birthd)
{
if (birthd == null) {
return;}
var today = new Date().getFullYear();
year1 = birthd.getFullYear();
return (today-year1);
}
This is what i write in my entity file that i am loading to the form:
function onLoad() {
var birthDate = Xrm.Page.getAttribute("el_birth_date").getValue();
Xrm.Page.getAttribute("el_age").setValue(CalculateAge(birthDate));
}
I am new in Javascript.. Can ypu please help?
The JavaScript code you are using to calculate the age is not correct, it doesn't consider the month and the day.
A correct version is this one:
function CalculateAge(birthday, ondate) {
// if ondate is not specified consider today's date
if (ondate == null) { ondate = new Date(); }
// if the supplied date is before the birthday returns 0
if (ondate < birthday) { return 0; }
var age = ondate.getFullYear() - birthday.getFullYear();
if (birthday.getMonth() > ondate.getMonth() || (birthday.getMonth() == ondate.getMonth() && birthday.getDate() > ondate.getDate())) { age--; }
return age;
}
and can be used as:
var birthday = Xrm.Page.getAttribute("new_birthday").getValue();
var age = CalculateAge(birthday);
alert(age);
// age on 1st January 2000, JavaScript Date() object contains months starting from 0
var testdate = new Date(2000, 0, 1, 0, 0, 0);
var testage = CalculateAge(birthday,testdate);
alert(testage);
If you get CalculateAge is not defined, probably you didn't include the webresource containing your function inside the form. If you have two JS web resources (one containing the function, the other one containing the onLoad event) both need to be included inside the form.
If you are in a CRM version that has the issue of the asynchronous javascript loading, it's better to include the CalculateAge function in the same file as the onLoad event, but if you prefer keep them separate check this blog post: Asynchronous loading of JavaScript Web Resources after U12/POLARIS
The JavaScript function comes from my blog post: Calculate age in Microsoft Dynamics CRM 2011

Many-To-Many Entity Framework Update

I have an object that has a many-to-many relationship with another object. I am trying to write an update statement that doesn't result in having to delete all records from the many-to-many table first.
My data is:
StoredProcedure - StoredProcedureId, Name
Parameter - ParameterId, Name
StoredProcedure_Parameter - StoredProcedureId, ParameterId, Order
I have a UI for updating a stored procedured object (adding/removing parameters or changing the order of the parameters).
When I save, I end up at:
var storedProcedure = context.Sprocs.FirstOrDefault(s => s.SprocID == sproc.StoredProcedureId);
if (storedProcedure == null)
{
//do something like throw an exception
} else
{
storedProcedure.Name = sproc.Name;
//resolve Parameters many to many here
//remove all Params that are not in sproc.Params
//Add any params that are in sproc.Params but not in storedProcedure.Params
//Update the Order number for any that are in both
}
I know I could simply call .Clear() on the table and then reinsert all of the values with their current state (ensuring that all parameters that were removed by the UI are gone, new ones are added, and updated Orders are changed). However, I feel like there must be a better way to do this. Do many-to-many updates with EF usually get resolved by deleting all of the elements and reinserting them?
Here there is my code that I use and it works. The difference is that instead o having your 3 tables( StoredProcedure, StoredProcedure_Parameter and Parameter ) I have the following 3 tables: Order, OrdersItem(this ensure the many-to-many relation) and Item. This is the procedure that I used for updating or add an order, or after I change an existing OrderItem or add a new one to the Order.
public void AddUpdateOrder(Order order)
{
using (var db = new vitalEntities())
{
if (order.OrderId == 0)
{
db.Entry(order).State = EntityState.Added;
}
else
{
foreach (var orderItem in order.OrdersItems)
{
if (orderItem.OrderItemsId == 0)
{
orderItem.Item = null;
if (order.OrderId != 0)
orderItem.OrderId = order.OrderId;
db.Entry(orderItem).State = EntityState.Added;
}
else
{
orderItem.Order = null;
orderItem.Item = null;
db.OrdersItems.Attach(orderItem);
db.Entry(orderItem).State = EntityState.Modified;
}
}
db.Orders.Attach(order);
db.Entry(order).State = EntityState.Modified;
}
SaveChanges(db);
}
}

Refresh MVC View

I have a little app that initially requests a user id. This user id is then sent as a parameter to a stored procedure that returns values from a database. What I would like for this app to do is to refresh those same values every 30 seconds. My issue is that when I refresh, I lose the user id. Is there something simple that I'm missing here?
public ActionResult Report()
{
string operatorCode = Request.Form.GetValues("txtOperator")[0].ToString();
ViewBag.operatorName = (from e in db.employees
where e.operator_code == operatorCode
select e.name).Max().ToString();
ViewData["operatorCode"] = operatorCode;
var results = db.lex_sp_Select_Paintline_FinRew_Operator(operatorCode);
Response.AddHeader("Refresh", "10");
return View(results.ToList());
}
I think the main reason for the null value is due to the fact that you are trying to refresh an HttpPost, rather than a request (the refresh header is not intended for POSTS). I'd suggest as an alternative, that you change your process to be a request, which would result in only needing to change the invoking code (to a get) and changing the Report action to:
string operatorCode = Request.QueryString["txtOperator"];
this should give you the desired result, tho at the expense of the action now being a get rather than a post. You could also store the operatorCode in Session (tho this may not scale very well). The final option that I can see, would be to run an ajax request on a setInterval() and use that process to send a POST to the controller action.
How about storing in temp session and then using it from there when you lost it?
string operatorCode = Request.Form.GetValues("txtOperator")[0].ToString();
TempData["operatorCode"] = operatorCode;
if (!String.IsNullOrEmpty(operatorCode))
{
TempData["operatorCode"] = operatorCode;
ViewBag.operatorName = (from e in db.employees
where e.operator_code == operatorCode
select e.name).Max().ToString();
ViewData["operatorCode"] = operatorCode;
var results = db.lex_sp_Select_Paintline_FinRew_Operator(operatorCode);
Response.AddHeader("Refresh", "10");
return View(results.ToList());
}
else
{
var tempCode = TempData["operatorCode"]
ViewData["operatorCode"] = tempCode;
var results = db.lex_sp_Select_Paintline_FinRew_Operator(tempCode);
Response.AddHeader("Refresh", "10");
return View(results.ToList());
}

Invoke Webservice with yield return on windows phone

i'm developing a Windows Phone 7 app and I use Windows Live authentication to access the user contacts. I have a webservice, with the following method:
public IEnumerable<LiveIDContact> GetContactsInformationYield(string LocationID, string DelegationToken)
{
string uriTemplate = "https://livecontacts.services.live.com/#L#{0}/rest/LiveContacts/Contacts";
var xdoc = WindowsLiveContactAPIRequest(LocationID, DelegationToken, uriTemplate);
var contacts = (from contact in xdoc.Descendants("Contact")
select contact).ToArray();
foreach (var con in contacts)
{
RetrieveCID(LocationID, DelegationToken, con);
LiveIDContact c = new LiveIDContact()
{
ID = con.Element("ID").Value,
DisplayName = con.Element("Profiles").Element("Personal").Element("DisplayName").Value,
CID = (con.Element("CID") != null ? con.Element("CID").Value : "")
};
yield return c;
}
}
How i invoke the methode in the app:
public void GetContactInformationAsync()
{
LiveIDClient.GetContactsInformationYieldAsync(LocationID, ConsentToken);
}
Here is the problem, when I invoke this methode and i wait on the complete event. It takes 4 to 5 minutes to update the list of contacts in my app.(Performance issue). Is there any way that an event occurs on every yield return ? So i can update my list from that event?
I couldn't find the answer anywhere so lets hope somebody knows the answer.
Is this making a separate HTTP call for every single contact? If so, then I think you simply need to redesign the webservice so that it makes a call for, say, every hundred contacts.

Resources