Blog Archives
Classic ASP VB Filter File Name Extensions From String EndsWith
Came across a classic ASP VB site recently in my adventures. There was a feature request to filter out some file extensions from existing code logic, and I discovered quickly most of my .Net methods were unavailable, so I came up with this little snippet and had a great blast from the past. 🙂
function FilterExtensions(fn) FilterExtensions=true a_ext = Array(".db",".db") 'place additional extensions here for each ext in a_ext i = InStrRev(fn,ext) if i>0 then FilterExtensions=false end if next end function
If FilterExtensions returns true then there were no matches (extension of filename successfully passed all filters).
C# Event Handlers and Delegates in ASP .Net with Web User Controls
This article should help as a general how to on event handlers and delegates in C# as well as propose a different way to handle cross page methods in your ASP .Net website from a web user control or other page.
Dilemma:
Page contains user control which has some methods and functionality built in. When a particular button click or other generic event is fired in the user control, it needs to call back to the parent page.
Solution:
Create event handlers and their delegates in the user control, fire them from the methods tied to the internal controls protected events, and define the methods that will handle the new events in the page (see code below).
C# (with some VB notes):
//delegate declaration not necessary in VB public delegate void MyCustomHandler(object sender, EventArgs e); public event MyCustomHandler SomethingClicked; protected void btnButton1_Click(object sender, EventArgs e) { //tell our parent page which is listening for the event that something was clicked //this null check and method invoke is the equivalent of raise event in VB if (SomethingClicked != null) { SomethingClicked(sender, e); } //do some other work specific to this button in the user control }
That’s the code for your user control, now for the page.
protected void Page_Load(object sender, EventArgs e) { MyUserControl1.SomethingClicked += new MyUserControl1.MyCustomHandler(MyUserControl1_SomethingClicked); if (!Page.IsPostBack) { //do my other normal work } } protected void MyUserControl1_SomethingClicked(object sender, EventArgs e) { //voila! clicking on the button in your user control will fire this method on the parent page! }
Alternatively instead of declaring your own delegate, you can also simply use:
//in control public event EventHandler SomethingClicked; //and in page load MyUserControl1.SomethingClicked+= new EventHandler(MyUserControl1_SomethingClicked);
If you have no need for custom arguments, this a good quick alternative that may be well liked by VB users where delegate declaration is optional.
References
DeveloperFusion, http://www.developerfusion.com/article/2137/event-handling-in-net-using-c/3/
VBForums, http://www.vbforums.com/showthread.php?t=521089
MSDN (events and delegates), http://msdn.microsoft.com/en-us/library/17sde2xt%28v=vs.71%29.aspx
MSDN (dynamically bind event handlers), http://msdn.microsoft.com/en-us/library/t3d01ft1%28v=vs.80%29.aspx
MSDN (which control raised an event), http://msdn.microsoft.com/en-us/library/zk6b17bs%28v=vs.80%29.aspx
ASP.Net (blog), http://weblogs.asp.net/rweigelt/archive/2005/01/14/353333.aspx
TechRepublic, http://www.techrepublic.com/article/simplify-net-class-communication-with-delegates/1050214
Akadia, http://www.akadia.com/services/dotnet_delegates_and_events.html
Calendar Extender Highlight Current Day in C# .Net
Thanks goes to Karan from asp.net blogs.
<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="tbTarget1" PopupButtonID="btnCalendar" CssClass="calendarposition" OnClientShowing="currentdateactive"> </asp:CalendarExtender>
function currentdateactive(e) { if (!e.get_selectedDate() || !e.get_element().value) e._selectedDate = (new Date()).getDateOnly(); }
.ajax__calendar_active{background-color:#820024;color:#ffffff;border:1px solid #D4D0C8;} /*use your own class to control positioning. careful of nested relative/absolute divs*/ .calendarposition{position:absolute;margin-top:250px;margin-left:250px;background-color:#fff;border:1px solid silver;} /*prepend css class with div to override ms ajax web.resx autogenerated css*/ div.ajax__calendar_day{text-align:center;}
References
ASP.Net (blogs), http://weblogs.asp.net/karan/archive/2010/09/20/calendar-extender-today-s-date.aspx
.Net Thread Safety
Any future posts regarding thread safe calls will go here.
C#: (field)
//place in an event handling label, on edit, click, update, etc if(label1.InvokeRequired) { label1.Invoke(new MethodInvoker(delegate { label1.text = "value"; } )); } else { label1.text = "value"; }
C#: (singleton)
public sealed class ObjType { private static ObjType _ObjInstance; private static readonly object objlock; ObjType() { _ObjInstance=null; objlock = new object(); } public static ObjType ObjInstance { get { lock (objlock) { if (_ObjInstance==null) { _ObjInstance= new Singleton(); } return _ObjInstance; } } } }
URL Encode in .Net
C#: (ASP .Net)
System.Web.HttpUtility.UrlEncode()
C#: (Client/Server Environment)
Uri.EscapeUriString()
References
MSDN, WebUtility Classhttp://msdn.microsoft.com/en-us/library/system.net.webutility.aspx
MSDN, Uri Classhttp://msdn.microsoft.com/en-us/library/system.uri.escapeuristring.aspx
MSDN blogs, http://blogs.msdn.com/b/yangxind/archive/2006/11/09/don-t-use-net-system-uri-unescapedatastring-in-url-decoding.aspx
JQuery Grid Themes
Useful links to JQuery grids utilizing (mostly) standard UI themes and/or very little code.
Google!
http://jquery-ui.googlecode.com/svn/branches/labs/grid/tests/static/grid/default.html
Datatables.Net:
http://www.datatables.net/styling/themes/smoothness
Ke-Cai:
http://www.ke-cai.net/2010/01/theme-your-table-with-jquery-ui.html
Trirand:
http://www.trirand.com/blog/jqgrid/jqgrid.html
Stackoverflow:
http://stackoverflow.com/questions/2613632/jquery-ui-themes-and-html-tables
JQuery and Partial Postbacks
I recently came across an issue where JQuery bindings no longer functioned after a partial postback and stumbled upon some code that was helpful in most cases.
Javascript (JQuery):
Sys.Application.add_load(startJQuery); startJQuery() { //do JQ here }
And alternatively..
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(){});
This code will not always work however, as was the case in my particular scenario, so I resolved using an alternate method.
RegisterStartupScript is great functionality, and can be useful for loading javascript dynamically on an as-needed basis.
The example below, based on prior code selects the correct JS file to use, then loads it using the registerstartupscript function. This is all within a code block which calls an update panel
C#:
int scriptnumber = 1; string FilePath = String.Format("~/Scripts/Script_{0}.js",scriptnumber.ToString()); System.IO.StreamReader sr = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(FilePath)); jqueryfileoutput = sr.ReadToEnd(); upnlBodyContent.Update(); ScriptManager.RegisterStartupScript(this, this.GetType(), "scriptname", "<script type=\"text/javascript\">" + jqueryfileoutput.ToString().Trim() + "</script>", false);
JQuery and Frames
Although there is definitely some room for debate in the web development and design community on where the usage of frames is necessary, there are some situations where they cannot be avoided.
Manipulation of data within these frames can be confusing, and dumping frames to page content using ajax or server side code is not always possible. This is especially true if these pages contain their own sub-site navigation.
In these scenarios, JQuery helps us simplify content management within frames using a combination of the “.contents()” method and “find” functionality to locate and update elements.
If “videoframe” is the id of the iframe, the example below changes the background color of a body inside the frame to a specific color.
JS (JQuery):
$('#videoframe').contents().find("body").css("background-color", "#FFFFFF");
References:
JQuery API, http://api.jquery.com/contents
Get IP Address of Originating Website From a Webservice
The following code was used in a .Net 3.5 web service to retrieve the IP Address of the website consuming it.
This solution may initially escape you since it might seem like the web service should run within an HTTP Context and thus utilize this object to get information from websites calling particular methods.
See MSDN reference(s) for more information.
C#:
RemoteEndpointMessageProperty clientEndpoint = OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; clientEndpoint.Address
References:
MSDN, http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.remoteendpointmessageproperty.aspx
JQuery AJAX Reference
Keep in mind when using code below if requesting a page that requires login/restricted access, users login session is not carried over.
Snippet below is sample code usage illustrating two different methods of achieving similar result. See references for more info and full specifications.
Javscript (JQuery):
$.ajax({ url: 'http://www.websitename.com/', dataType: "text", type: "POST", data: { city: "NewYork"}, error: function(err) { alert("Error:" + err.toString()); }, success: function(data) { //$("#JQuery_modal_p").html(data); alert(data); } });
Javscript (JQuery):
$.ajax({ url: 'http://www.websitename.com/' + data1+ data2, dataType: "text", type: "GET", data: {}, error: function(err) { alert("Error:" + err.toString()); }, success: function(data) { //$("#JQuery_modal_p").html(data); alert(data); } });
References:
JQuery Ajax, http://api.jquery.com/jQuery.ajax/