Change background colour for each var in table using AJAX - ajax

I have gone through the various answers provided on Stackflow, however cannot find the answer I need.
I need to add a different colour for each category that is called in the table. The table uses AJAX in cakePHP. The table calls correctly, but I just need to add a colour for each var.
Here is the code
function showTable() {
//var asset = document.getElementById('filter').value;
var startDate = $(".daterange").attr("data-start-date");
var endDate = $(".daterange").attr("data-end-date");
var asset = document.getElementById('assetSelect').value;
var room = document.getElementById('roomSelect').value;
var object = document.getElementById('checkobject');
var person = document.getElementById('checkPerson');
var tools = document.getElementById('checktools');
var filter = '';
You can see from above there are 5 different object, I need all the assets to be one colour, all the rooms to be another colour and so forth.
If you could help I would greatly appreciate it.

Change the style property of your object should do the job :
asset.style.background-color = '#f3f3f3';

Related

UpdateRelatedObject method only works when the sourceProperty is not collection

I am getting the following error when I try to update tree of object using asp.net webapi OData:
"UpdateRelatedObject method only works when the sourceProperty is not collection."
My code is provided below. I got this error when the mehod "UpdateRelatedObject" is called. Can you please advise what is wrong with my code and how to update tree of objects (meaning object contains collection of child objects) using asp.net webapi odata v4.
var container = new Container(new Uri("http://JohnAlbert.com/MyOdataTest/odata"));
Product product = container.Products.Expand(p=> p.ProductItems).Expand(p=>p.ProductInvoices).Where(p => p.PId == Guid.Parse("28C508B8-F2DC-45C2-B401-7F94E79AB347")).FirstOrDefault();
if (product != null)
{
product.Name = product.Name + "_Modified";
var pitem1 = product.ProductItems[0];
product.ProductItems.Remove(pitem1);
container.UpdateRelatedObject(product, "ProductItems", pitem1);
var pitem2 = product.ProductItems[0];
pitem2.Price = 999;
container.UpdateRelatedObject(product, "ProductItems", pitem1);
var pInv1 = product.ProductInvoices[0];
product.ProductInvoices.Remove(pInv1);
container.UpdateRelatedObject(product, "ProductInvoices", pInv1);
}
container.UpdateObject(product);
container.SaveChanges(SaveChangesOptions.BatchWithSingleChangeset);
What you actually want to delete the relationship between some items in a collection-valued navigation property of an entity and itself. In such case DeleteLink() is the right method to use. In this case the following code should do the work:
if (product != null)
{
var pitem1 = product.ProductItems[0];
var pitem2 = product.ProductItems[0];
var pInv1 = product.ProductInvoices[0];
container.DeleteLink(product, "ProductItems", pitem1);
container.DeleteLink(product, "ProductItems", pitem2);
container.DeleteLink(product, "ProductInvoices", pInv1);
container.SaveChanges();
}
You may think the above way isn't as intuitive as directly removing the navigation items from the entity using .Remove() as you did. For this problem, the entity tracking enabled by using DataServiceCollection<T> can help. You can use this blog post as a tutorial for how to use DataServiceCollection<T>: http://blogs.msdn.com/b/odatateam/archive/2014/04/10/client-property-tracking-for-patch.aspx
To delete a contained navigation property, you can use DataServiceContext.DeleteObject.
To delete a relationship between an entity and its navigation property, you can use DataServiceContext.DeleteLink
To update an object, you can use DataServiceContext.UpdateObject.
So according to your scenario, you could use following code
if (product != null)
{
product.Name = product.Name + "_Modified";
dsc.UpdateObject(product);
var pitem1 = product.ProductItems[0];
//This is to remove relationship
container.DeleteLink(product, "ProductItems", pitem1);
// This is to remove the object
//container.DeleteObject(pitem1);
var pitem2 = product.ProductItems[0];
pitem2.Price = 999;
container.UpdateObject(pitem2);
var pInv1 = product.ProductInvoices[0];
//This is to remove relationship
container.DeleteLink(product, "ProductInvoices", pInv1);
// This is to remove the object
//container.DeleteObject(pInv1);
container.SaveChanges(SaveChangesOptions.BatchWithSingleChangeset);
}

How to format DateTime from DB to be displayed throughout the site, using ASP.Net MVC 3 Razor C#?

I've been looking for an answer since yesterday with no avail. I've tried things like Model binders, layout templates (doesn't apply on my case), etc.
Let me clarify what I actually need.
I have many DateTime fields on many tables in a SQL Server 2008 R2 database. They're stored on the London Timezone.
I've managed (with help from you guys) to convert the DateTime to the user's Timezone and display them correctly.
What I need now is a way to automate this. Everytime the site displays DateTime coming from the database, it needs to be converted beforehand.
The input will stay as it is.
If it was on WebForms development - that I'm used to - I'd just create a handler. But I don't know what's the best practice on MVC 3 Razor.
Does anyone can give me some directions here, please?
Thanks in advance.
Complementing
That's the code that converts the DateTime:
// Timezone data provider
IDateTimeZoneProvider timeZoneProvider = DateTimeZoneProviders.Tzdb;
// Database Timezone = London
var londonTimeZone = timeZoneProvider["Europe/London"];
//// Getting date/time from the database and mapping it as being local to London timezone
//var yourDateFromDb = new DateTime(source.Year, source.Month, source.Day, source.Hour, source.Minute, source.Second, source.Millisecond);
//ZoneLocalMapping map = londonTimeZone.MapLocal(LocalDateTime.FromDateTime(yourDateFromDb));
//// This is the date/time with the correct offset (taking into account DST etc)
//var zonedDbDateTime = map.First();
// Jon Skeet suggestion instead of using the Mapping
// http://stackoverflow.com/questions/16164994/datetime-conversions-using-nodatime-on-asp-net-mvc-3-razor-website-how-to/16178730?noredirect=1#16178730
//
var dateTimeFromDb = new DateTime(source.Year, source.Month, source.Day, source.Hour, source.Minute, source.Second, source.Millisecond);
var zonedDbDateTime = londonTimeZone.AtLeniently(LocalDateTime.FromDateTime(dateTimeFromDb));
// Map the London zoned date/time to the users local date/time (saved on the Session)
var usersTimezoneId = (HttpContext.Current.Session["timezoneid"] != null ? HttpContext.Current.Session["timezoneid"].ToString() : "UTC");
var usersTimezone = timeZoneProvider[usersTimezoneId];
var usersZonedDateTime = zonedDbDateTime.WithZone(usersTimezone);
return usersZonedDateTime.ToDateTimeUnspecified();
I've found a solution going for a DateTime extension:
public static DateTime ToLocalTimeZone(this DateTime dateTime) {
IDateTimeZoneProvider timeZoneProvider = DateTimeZoneProviders.Tzdb;
var londonTimeZone = timeZoneProvider["Europe/London"];
var dateTimeFromDb = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day,
dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond);
var zonedDbDateTime = londonTimeZone.AtLeniently(LocalDateTime.FromDateTime(dateTimeFromDb));
var usersTimezoneId = (HttpContext.Current.Session["timezoneid"] != null ? HttpContext.Current.Session["timezoneid"].ToString() : "UTC"); var usersTimezone = timeZoneProvider[usersTimezoneId]; var usersZonedDateTime = zonedDbDateTime.WithZone(usersTimezone);
return usersZonedDateTime.ToDateTimeUnspecified();
}
Not sure about best practices, because as I've pointed out, I'm totally new to the MVC model. But it's doing the trick.

How to Cache Multiple Versions of a Page using Razor Dynamic Query & WebCache

I decided to implement caching to improve the performance of the product pages.
Each page contains a large amount of the product's images.
I created the following code in a Razor view.
#{
var productID = UrlData[0].AsInt();
var cacheItemKey = "products";
var cacheHit = true;
var data = WebCache.Get(cacheItemKey);
var db = Database.Open("adldb");
if (data == null) {
cacheHit = false;
}
if (cacheHit == false) {
data = db.Query("SELECT * FROM Products WHERE ProductID = #0", productID).ToList();
WebCache.Set(cacheItemKey, data, 1, false);
}
}
I'm using the data with the following code:
#foreach (dynamic p in data)
{
<a href="~/Products/View/#p.ProductID"
<img src="~/Thumbnail/#p.ProductID"></a>
}
The caching code works well, but when passing the new query string parameter (changing the version of the page) the result in browser is the same for the declared cashing time.
How to make caching every version of the page?
Thanks
Oleg
A very simple approach might be to convert your key (productID) to a string and append it to the name of your cacheItemKey.
So you might consider changing the line:
var cacheItemKey = "products";
to read:
var cacheItemKey = "products" + productID.ToString();
This should produce the behavior you are looking for -- basically mimicking a VaryByParam setup.
ps. Please keep in mind I have not added any sort of defensive code, which you should do.
Hope that helps.

How to Update one Sharepoint List (calendar) from Another (custom)?

As part of an EvenReceiver the itemAdded on a custom List (source) creates a Calendar entry in another List (target).
I now want to add an itemUpdated event so that when the the source List is updated the change is filtered through to the target List.
I am using c# in Visual Studio to develop the Event Receiver.
Can anyone please advise the best way to do this and how I create the link between the two Lists to ensure I can update from source to target?
Thank you.
You will have to udpate the target list yourself...
var sourceItem = this.properties.ListItem;
//you can use other properties to search for the item in the targetlist aswell
string query = string.Format("<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>{0}</Value></Eq></Where>", sourceItem.Title);
var spQuery = new SPQuery() { Query = query };
var foundItems = targetList.GetItems(spQuery);
if(foundItems.Count == 1)
{
var foundItem = foundItems[0];
//update the properties you want
foundItem["Property1"] = sourceItem["Property1"];
foundItem["Property2"] = sourceItem["Property2"];
foundItem["Property3"] = sourceItem["Property3"];
foundItem.Update();
}
Note that this piece of code is straight out of my head & untested ;-)

How to set the System.Web.WebPages.WebPage.Model property

I am planning on creating a custom route using ASP.NET Web Pages by dynamically creating WebPage instances as follows:
IHttpHandler handler = System.Web.WebPages.WebPageHttpHandler.CreateFromVirtualPath("~/Default.cshtml");
How can I supply an object to the underlying WebPage object so that it can become the web pages's "Model"? In other words I want to be able to write #Model.Firstname in the file Default.cshtml.
Any help will be greatly appreciated.
UPDATE
By modifying the answer by #Pranav, I was able to retrieve the underlying WebPage object using reflection:
public void ProcessRequest(HttpContext context)
{
//var page = (WebPage) System.Web.WebPages.WebPageHttpHandler.CreateFromVirtualPath(this.virtualPath);
var handler = System.Web.WebPages.WebPageHttpHandler.CreateFromVirtualPath(this.virtualPath);
var field = handler.GetType().GetField("_webPage", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var page = field.GetValue(handler) as System.Web.WebPages.WebPage;
var contextWrapper = new HttpContextWrapper(context);
var pageContext = new WebPageContext(contextWrapper, page, context.Items[CURRENT_NODE]);
page.ExecutePageHierarchy(pageContext, contextWrapper.Response.Output);
}
Unfortunately this is not reliable as it does not work in Medium Trust (BindingFlags.NonPublic is ignored if application is not running in full trust). So while we have made significant progress, the solution is not yet complete.
Any suggestions will be greatly appreciated.
The Model property of a WebPage comes from the WebPageContext. To set a Model, you could create a WebPageContext with the right parameters:-
var page = (WebPage)WebPageHttpHandler.CreateFromVirtualPath("~/Default.cshtml");
var httpContext = new HttpContextWrapper(HttContext.Current);
var model = new { FirstName = "Foo", LastName = "Bar" };
var pageContext = new WebPageContext(httpContext, page, model);
page.ExecutePageHierarchy(pageContext, httpContext.Response.Output);
The model instance should now be available as a dynamic type to you in your page.

Resources