Script not running in google chrome - asp.net

I have a page in aspx which uses the following code. The issue is that it fetches the values from SQL and put into boxes using internet explorer but not doing using chrome
var element = document.getElementById("ctl00$pagecontent$Flexibleselect_Reol$ctl01");
//alert(element);
//alert('<%=Flexibleselect_Reol.Controls[1].ClientID %>');
element.onchange = (function(onchange) {
return function(evt) {
// reference to event to pass argument properly
evt = evt || event;
// new code "injection"
var puselectobj = document.getElementById('ctl00$pagecontent$Flexibleselect_Reol$ctl01');
var paramVal = puselectobj.value;
// alert(paramVal);
var newUrl = updateURLParameter('ProcessUnit', paramVal);
theForm.action = newUrl;
if (onchange) {
onchange(evt);
}
}
})(element.onchange);
// alert(element.onchange);
function updateURLParameter(param, value) {
var url = theForm.action;
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL) {
tempArray = additionalURL.split("&");
for (i = 0; i < tempArray.length; i++) {
if (tempArray[i].split('=')[0] != param) {
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
var paramVal = value;
var rows_txt = temp + "" + param + "=" + paramVal;
var querystr = "?" + newAdditionalURL + rows_txt;
return baseURL + querystr;
}
I am getting the following error when running in chrome
"Uncaught TypeError: Cannot read properties of null (reading 'onchange')"

Related

Write custom plugins/extensions like kendoui and telerik for asp.net mvc razor

Telerik and kendoUI offers a number of html controls like grids, charts etc. to enhance the ui in asp.net mvc. More interesting thing is they are used as html extensions and hence we can bind some model to the controls which also makes it somewhat strongly typed. It also uses javascript libs to handle client side interactions. I need to get some gist over how can we write custom plugins like kendo and telerik like building my own grid component. What is the proper pattern that i should follow?
This is not good example but i think it is good start.
This method generates dataTable
public static string GenerateTableHtml<TValue>(IEnumerable<TValue> model, string DeleteUrl, string EditUrl)
{
StringBuilder Table = new StringBuilder();
Table.AppendLine("<script type='text/javascript'> $(document).ready(function () {"
+ "$('.btnDelete').click(function () {"
+ "var url = $(this).attr('dropzone');"
+ "$('#dialog-form').attr('action', url);})"
+ "})</script>");
Table.AppendLine(" <div class=\"dataTables_wrapper\"><div class=\"\">");
string TableButtonsTemplate = "<td><div class=\"table_buttons\">"
+ "<img src=\"../Images/icons/dark/pencil.png\")\" title=\"რედაქტირება\" />"
+ "<a href=\"#\" id=\"opener\" class=\"btnDelete\" dropzone=\"{1}\">"
+"<img class=\"\" src=\"../Images/icons/dark/close.png\")\" title=\"წაშლა\" /></a>"
+ "</div></td>";
string TableButtons = String.Empty;
bool HaveActionButtons = false;
string rowID = string.Empty;
if (String.IsNullOrEmpty(DeleteUrl) == false || string.IsNullOrEmpty(EditUrl) == false)
{
HaveActionButtons = true;
}
Table.AppendLine("<table class=\"display dTable\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">");
Table.AppendLine("<thead>");
Table.AppendLine("<tr>");
int ColumnIndex = 0;
int rowIndexer = 0;
var fType = model.GetType().FullName;
var startIndex = fType.IndexOf("[[") + 2;
var type = fType.Substring(startIndex, fType.Length - startIndex - 2);
foreach (var item in model)
{
if (ColumnIndex == 0)
{
var properties = item.GetType().GetProperties();
foreach (var prop in properties)
{
var metaData = ModelMetadataProviders.Current.GetMetadataForProperty(null,
Type.GetType(type), prop.Name);
if (metaData.DisplayName != null)
{
Table.AppendLine("<th class=\"ui-state-default\" rowspan=\"1\" colspan=\"1\">" + metaData.DisplayName + "</th>");
}
else
{
Table.AppendLine("<th class=\"ui-state-default\" rowspan=\"1\" colspan=\"1\">" + prop.Name + "</th>");
}
}
Table.AppendLine("<th></th>");
Table.AppendLine("</tr>");
Table.AppendLine("</thead>");
Table.AppendLine("<tbody>");
}
foreach (var value in item.GetType().GetProperties().Select(x => x.GetValue(item, null)))
{
int rowCount = item.GetType().GetProperties().Select(x => x.GetValue(item, null)).Count();
rowIndexer++;
if (rowIndexer != rowCount)
{
if (rowIndexer == 1)
{
Table.AppendLine("<tr class=\"gradeA odd\">");
}
if (value != null)
{
string val = value.ToString();
Table.AppendLine("<td>" + val + "</td>");
rowID = item.GetType().GetProperty("ID").GetValue(item, null).ToString();
}
else
{
Table.AppendLine("<td></td>");
}
}
else
{
if (value != null)
{
Table.AppendLine("<td>" + value.ToString() + "</td>");
}
else
{
Table.AppendLine("<td></td>");
}
if (HaveActionButtons == true)
{
Table.AppendLine(String.Format(TableButtonsTemplate, EditUrl + rowID, DeleteUrl + rowID));
}
Table.AppendLine("</tr>");
if (rowIndexer != item.GetType().GetProperties().Count())
{
Table.AppendLine("<tr class=\"gradeA odd\">");
}
}
}
rowIndexer = 0;
ColumnIndex++;
}
Table.AppendLine("</tbody></table></div></div>");
Table.AppendLine(String.Format(Resources.MainResources.ModalDialogConfirm, "Confirmation",
"<strong>Warning!</strong><br /> Are you sure you want to delete user?", ""));
return Table.ToString();
}

google maps api v3 directions_changed event inside a loop

I have a route that is a combination of multiple sub routes. (By sub routes i mean multiple DirectionsRenderer objects)
I also have a loop where i go throught all of the DirectionsRenderer objects and attach "directions_changed" event to all of them.
Unfortunatelly only that last DirectionsRenderer object fires the event when i try to test what happens when i drag the polyline.
Here is a part of my code:
for(var k=0; k<directionsRenderers.length; k++)
{
var directionsRenderer = directionsRenderers[k];
var a = registerDirectionsChangedEvent(k,directionsRenderer);
}
function registerDirectionsChangedEvent(index, directionsRenderer)
{
this.index = index;
this.directionsRenderer = directionsRenderer;
var that = this;
var a = google.maps.event.addListener(this.directionsRenderer, "directions_changed", function()
{
var newStopPoint;
var directionsResult = that.directionsRenderer.getDirections();
var route = directionsResult.routes[0];
var legs = route.legs;
var legsIndex = 0;
for(var i=0; i<legs.length; i++)
{
var cLeg = legs[i];
var viaWaypoints = cLeg.via_waypoints;
if(viaWaypoints.length > 0)
{
newStopPoint = viaWaypoints[0];
if(that.index === 1) legsIndex += 9;
else if(that.index === 2) legsIndex += 18;
break;
}
legsIndex++;
}
addNewStopPoint(newStopPoint,legsIndex);
});
return a;
}
As i have mentioned above not only the last DirectionsRenderer object get fired but the ones before the last event do not implement the default behaviour.
Maybe you have noticed that i use:
this.index = index;
this.directionsRenderer = directionsRenderer;
var that = this;
event without it it still does not work.
I also tried to use a function created inside the loop like this:
(function someFunction(a,b){//do something here})(a,b);
but still no luck!
any advice how to make it works?
Use function closure, this is probably a duplicate (not tested):
for(var k=0; k<directionsRenderers.length; k++)
{
var directionsRenderer = directionsRenderers[k];
var a = registerDirectionsChangedEvent(k,directionsRenderer);
}
function registerDirectionsChangedEvent(index, directionsRenderer)
{
var a = google.maps.event.addListener(directionsRenderer, "directions_changed", function()
{
var newStopPoint;
var directionsResult = directionsRenderer.getDirections();
var route = directionsResult.routes[0];
var legs = route.legs;
var legsIndex = 0;
for(var i=0; i<legs.length; i++)
{
var cLeg = legs[i];
var viaWaypoints = cLeg.via_waypoints;
if(viaWaypoints.length > 0)
{
newStopPoint = viaWaypoints[0];
if(index === 1) legsIndex += 9;
else if(index === 2) legsIndex += 18;
break;
}
legsIndex++;
}
addNewStopPoint(newStopPoint,legsIndex);
});
return a;
}

Resize iframe - do have access to external url code

I have seen lots of questions about resizing iframes but all of those do not have access to the external url. In this case I do. I can insert a script into the head tag. I was trying to use this script inserted into the main page header containing the iframe (i know the opening and closing frame tags are wrong - it would not let me leave them in:
iframe id="frame-one" scrolling="no" frameborder="0" src="yoursitehereexample" onload="FrameManager.registerFrame(this)" /iframe
and this the js in the header (linked FrameManager.js file)
var FrameManager =
{
currentFrameId : '',
currentFrameHeight : 0,
lastFrameId : '',
lastFrameHeight : 0,
resizeTimerId : null,
init : function()
{
if (FrameManager.resizeTimerId == null)
{
FrameManager.resizeTimerId = window.setInterval(FrameManager.resizeFrames, 500);
}
},
resizeFrames : function()
{
FrameManager.retrieveFrameIdAndHeight();
if ((FrameManager.currentFrameId != FrameManager.lastFrameId) ||
(FrameManager.currentFrameHeight != FrameManager.lastFrameHeight))
{
var iframe = document.getElementById(FrameManager.currentFrameId.toString());
if (iframe == null) return;
iframe.style.height = FrameManager.currentFrameHeight.toString() + "px";
FrameManager.lastFrameId = FrameManager.currentFrameId;
FrameManager.lastFrameHeight = FrameManager.currentFrameHeight;
window.location.hash = '';
}
},
retrieveFrameIdAndHeight : function()
{
if (window.location.hash.length == 0) return;
var hashValue = window.location.hash.substring(1);
if ((hashValue == null) || (hashValue.length == 0)) return;
var pairs = hashValue.split('&');
if ((pairs != null) && (pairs.length > 0))
{
for(var i = 0; i < pairs.length; i++)
{
var pair = pairs[i].split('=');
if ((pair != null) && (pair.length > 0))
{
if (pair[0] == 'frameId')
{
if ((pair[1] != null) && (pair[1].length > 0))
{
FrameManager.currentFrameId = pair[1];
}
}
else if (pair[0] == 'height')
{
var height = parseInt(pair[1]);
if (!isNaN(height))
{
FrameManager.currentFrameHeight = height;
FrameManager.currentFrameHeight += 15;
}
}
}
}
}
},
registerFrame : function(frame)
{
var currentLocation = location.href;
var hashIndex = currentLocation.indexOf('#');
if (hashIndex > -1)
{
currentLocation = currentLocation.substring(0, hashIndex);
}
frame.contentWindow.location = frame.src + '?frameId=' + frame.id + '#' + currentLocation;
}
};
window.setTimeout(FrameManager.init, 300);
Then...I put this in the framed page header ResizeFrame.js as a link:
//orig frame mgr script
$.getScript("http://www.yoursitehereexamle.com/js/FrameManager.js", function(){
});
// external heights load
function publishHeight()
{
if (window.location.hash.length == 0) return;
var frameId = getFrameId();
if (frameId == '') return;
var actualHeight = getBodyHeight();
var currentHeight = getViewPortHeight();
if (Math.abs(actualHeight - currentHeight) > 15)
{
var hostUrl = window.location.hash.substring(1);
hostUrl += "#";
hostUrl += 'frameId=' + frameId;
hostUrl += '&';
hostUrl += 'height=' + actualHeight.toString();
window.top.location = hostUrl;
}
}
function getFrameId()
{
var qs = parseQueryString(window.location.href);
var frameId = qs["frameId"];
var hashIndex = frameId.indexOf('#');
if (hashIndex > -1)
{
frameId = frameId.substring(0, hashIndex);
}
return frameId;
}
function getBodyHeight()
{
var height;
var scrollHeight;
var offsetHeight;
if (document.height)
{
height = document.height;
}
else if (document.body)
{
if (document.body.scrollHeight)
{
height = scrollHeight = document.body.scrollHeight;
}
if (document.body.offsetHeight)
{
height = offsetHeight = document.body.offsetHeight;
}
if (scrollHeight && offsetHeight)
{
height = Math.max(scrollHeight, offsetHeight);
}
}
return height;
}
function getViewPortHeight()
{
var height = 0;
if (window.innerHeight)
{
height = window.innerHeight - 18;
}
else if ((document.documentElement) && (document.documentElement.clientHeight))
{
height = document.documentElement.clientHeight;
}
else if ((document.body) && (document.body.clientHeight))
{
height = document.body.clientHeight;
}
return height;
}
function parseQueryString(url)
{
url = new String(url);
var queryStringValues = new Object();
var querystring = url.substring((url.indexOf('?') + 1), url.length);
var querystringSplit = querystring.split('&');
for (i = 0; i < querystringSplit.length; i++)
{
var pair = querystringSplit[i].split('=');
var name = pair[0];
var value = pair[1];
queryStringValues[name] = value;
}
return queryStringValues;
}
// window load
window.onload = function(event)
{
window.setInterval(publishHeight, 300);
}
But no luck on getting it to work - can anyone see where I went wrong. The iframe still appears but does not scale. Many Thanks!
Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.
local (iframe) page: just insert a code snippet
remote (external) page: you need a "body onload" and a "div" that holds all contents. And body needs to be styled to "margin:0"
Local:
<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>
<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>
You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).
Remote:
You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).
<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>
So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.
The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".
Hope this helps. Sorry for my english.

load symbol of flash in flex at runtime

Hey people, I've this huge problem loading a symbol from a swf file in the application at runtime. I want to load it and pass it as a argument to another class where it could be used further. The symbol name is passed on from the array collection from the "o" object. Can anybody please tell me what's the right way to go about it.. Thanks in advance..!!
Following is the code for reference..
public override function Show(o:ObjectProxy):void
{
var _this:Weather;
var _super:ContentItem;
var item:WeatherItem;
var items:ArrayCollection;
var widgetCount:Number;
var headlineFontSize:int;
var conditionsIconThemeLoader:Loader;
this.m_weatherWidgetContainer = new HBox();
super.Show(o);
_this = this;
_super = super;
(undefined == o["HeadlineFontSize"]) ? headlineFontSize = 20 : headlineFontSize = o["HeadlineFontSize"];
if (undefined != o["direction"])
this.m_textDirection = o["direction"];
if (o.LargeUrl.Forecast is ArrayCollection)
items = ArrayCollection(o.LargeUrl.Forecast);
else
items = new ArrayCollection([o.LargeUrl.Forecast]);
widgetCount = this.m_computeWidgetSpace(items.length);
conditionsIconThemeLoader = new Loader();
conditionsIconThemeLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event):void
{
for(var i:uint = 0; i < widgetCount; i++)
{
var symbolClass:Class = e.currentTarget.loader.contentLoaderInfo.applicationDomain.currentDomain.getDefinition(int(items[i].condition)) as Class;
var symbolInstance:Sprite = new symbolClass();
item = new WeatherItem();
item.Show(items[i], headlineFontSize, symbolInstance, widgetCount);
_this.m_weatherWidgetContainer.addChild(item);
}
});
conditionsIconThemeLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void
{
Alert.show("Failure loading " + WidgetStylesheet.instance.Weather_Widget_Theme + ".swf");
});
// Attempt to load theme weather icon file
conditionsIconThemeLoader.load(new URLRequest("assets/animation/" + WidgetStylesheet.instance.Weather_Widget_Theme + ".swf"));
super.media.addChild(this.m_weatherWidgetContainer);
}
Heres the answer
public override function Show(o:ObjectProxy):void
{
var _this:Weather;
var _super:ContentItem;
var conditionsIconThemeLoader:Loader;
var loaderContext:LoaderContext;
this.m_weatherWidgetContainer = new HBox();
this.m_weatherWidgetContainer.percentHeight = 100;
this.m_weatherWidgetContainer.percentWidth = 100;
super.Show(o);
_this = this;
(undefined == o["HeadlineFontSize"]) ? this.m_headlineFontSize = 20 : this.m_headlineFontSize = o["HeadlineFontSize"];
if (undefined != o["direction"])
this.m_textDirection = o["direction"];
if (o.LargeUrl.Forecast is ArrayCollection)
this.m_items = o.LargeUrl.Forecast;
else
this.m_items = new ArrayCollection([o.LargeUrl.Forecast]);
conditionsIconThemeLoader = new Loader();
loaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
conditionsIconThemeLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.m_loaderSuccess);
conditionsIconThemeLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.m_loaderFail);
// Attempt to load theme weather icon file
conditionsIconThemeLoader.load(new URLRequest("assets/animation/" + WidgetStylesheet.instance.Weather_Widget_Theme + ".swf"), loaderContext);
this.m_weatherWidgetContainer.addEventListener(FlexEvent.CREATION_COMPLETE, this.m_drawHorizontalLine);
super.media.addChild(this.m_weatherWidgetContainer);
}

How to get a substring from a string variable which is having HTML tags

I have a string variable assigned with some Content in HTML format.
Some thing like this var strLabel:String = "This is <b>Test</b>;
But in run time i have get the first 10 characters of the string and display it in another control.
For this, what did was
txtLabelName.Text = String(strLabel).substr(0,10) + ' ...';
But in the output i am getting as This is <b. Basically it considering HTML related tags also as text. But my code has to omit the HTML tags while calculating sub string.
Please anybody help me to do this?
Use this regexp to strip html tags (more or less):
txtLabelName.text = strLabel.replace(/\<.+?\>/g, '').substr(0, 10) + ' ...';
It's a very simple regexp to strip all tags so it won't work on more complex tags (probably).
I got this code from some blog. This is working Perfectly
public static function stripHtmlTags(html:String, tags:String = ""):String
{
var tagsToBeKept:Array = new Array();
if (tags.length > 0)
tagsToBeKept = tags.split(new RegExp("\\s*,\\s*"));
var tagsToKeep:Array = new Array();
for (var i:int = 0; i < tagsToBeKept.length; i++)
{
if (tagsToBeKept[i] != null && tagsToBeKept[i] != "")
tagsToKeep.push(tagsToBeKept[i]);
}
var toBeRemoved:Array = new Array();
var tagRegExp:RegExp = new RegExp("<([^>\\s]+)(\\s[^>]+)*>", "g");
var foundedStrings:Array = html.match(tagRegExp);
for (i = 0; i < foundedStrings.length; i++)
{
var tagFlag:Boolean = false;
if (tagsToKeep != null)
{
for (var j:int = 0; j < tagsToKeep.length; j++)
{
var tmpRegExp:RegExp = new RegExp("<\/?" + tagsToKeep[j] + "( [^<>]*)*>", "i");
var tmpStr:String = foundedStrings[i] as String;
if (tmpStr.search(tmpRegExp) != -1)
tagFlag = true;
}
}
if (!tagFlag)
toBeRemoved.push(foundedStrings[i]);
}
for (i = 0; i < toBeRemoved.length; i++)
{
var tmpRE:RegExp = new RegExp("([\+\*\$\/])","g");
var tmpRemRE:RegExp = new RegExp((toBeRemoved[i] as String).replace(tmpRE, "\\$1"),"g");
html = html.replace(tmpRemRE, "");
}
return html;
}

Resources