Blog Archives
URL Rewriting/Mapping using Global.asax
Ultimately I wound up using a different method, specified in my other blog post on URL Rewriting on GoDaddy and Shared hosting.
However, the method below is actually very useful if you are trying to do certain validation which cannot be expressed in web.config or RegEx prior to redirect, such as checking if querystring is valid and exists in database values, etc.
//try out various request types such as absolute path and raw url to see differences protected void Application_BeginRequest(object sender, EventArgs e) { string originalPath = HttpContext.Current.Request.Path.ToLower(); //HttpContext.Current.Request.RawUrl.ToLower(); //HttpContext.Current.Request.Path.ToLower(); RewritePaths(originalPath); } private void RewritePaths(string originalPath) { Rewrite(originalPath, "default", "index"); Rewrite(originalPath, "home", "index"); Rewrite(originalPath, "index"); Rewrite(originalPath, "login"); } private void Rewrite(string path, string page) { if (path.Contains("/" + page)) { if (!path.Contains(".aspx")) { //Context.RewritePath(path.Replace("/" + page, "/" + page + ".aspx")); Context.RewritePath(page + ".aspx"); } } } private void Rewrite(string path, string frompage, string topage) { if (path.Contains("/" + frompage)) { if (!path.Contains(".aspx")) { //Context.RewritePath(path.Replace("/" + frompage, "/" + topage + ".aspx")); Context.RewritePath(topage + ".aspx"); } } }
URL Rewriting on GoDaddy and Shared hosting
After doing a lot of searching through google queries, forums and archives, I was finally able to solve the conundrum of using URL rewriting on GoDaddy.
The site in question is also a subdomain in a sub folder off the root site, meaning web.config rules cascade, which complicated things slightly more and was enough to send GD support over the edge.
So my site/domain/DNS setup was as follows:
//--parent www.parentsite.com //--and sub subsite.parentsite.com //--where sub is actually cname of test.othersite.com //--parent points to root folder /web.config /default.aspx //--and sub points to subsite folder /subsite/web.config /subsite/default.aspx //--desired url /subsite/default //--should point to /subsite/default.aspx
I could not find a single article which presented a complete solution, including my own URL Mapping solution I presented in a previous article.
The simple solution in my previous article only works on GoDaddy servers if the mapping specifies a file extension on both the url and mapped url, such as:
<urlMappings enabled="true"> <add url="~/default.aspx" mappedUrl="index.aspx"/> <add url="~/index.html" mappedUrl="index.aspx"/> </urlMappings>
After speaking with GoDaddy support on 3 separate occasions, including callbacks from higher tiers, they informed me the mappings “work” and deferred to the above example..
So I dropped the simple approach of using URL Mappings, and stepped it up to URL Rewriting. According to GoDaddy kbase article, Microsoft URL Rewriting is supported, although for some reason they don’t include any examples..
I was able to at least get this working as intended after a little tweaking and reading through some of the references listed further below.
The configuration I am using is IIS7 with .Net 3.5. Haven’t tested it on 4.0 though this should work as well.
The solution:
(see code snippets above for domain structure in my scenario)
(( make sure you don't place modules or system.webServer in your web.config more than once.. you'll get a server 500 error 😛 )) <modules runAllManagedModulesForAllRequests="true"> <system.webServer> <rewrite> <rewriteMaps> <rewriteMap name="StaticRedirects"> <!-- this is similar to url mapping, but the user would actually see the aspx extension in the url --> <!-- <add key="/subsitefoldername/pagename" value="/pagename.aspx"/> --> </rewriteMap> </rewriteMaps> <rules> <rule name="RedirectRule" stopProcessing="true"> <match url=".*" /> <conditions> <add input="{StaticRedirects:{REQUEST_URI}}" pattern="(.+)" /> </conditions> <action type="Redirect" url="http://test.othersite.com{C:1}" appendQueryString="True" redirectType="Permanent" /> </rule> <rule name="default"> <match url="default" /> <action type="Rewrite" url="default.aspx" /> <!-- this hides the extension as intended --> </rule> <rule name="login"> <match url="login" /> <action type="Rewrite" url="login.aspx" /> </rule> </rules> </rewrite>
Unfortunately however, the above example can break page validation/viewstate, but that’s a topic for another article. 😛
There is one other alternative to note that I also tried which also worked on my local server but not on GoDaddy was using Global.asax context rewrite. To avoid lengthiness, see deferred post on URL Rewriting/Mapping using Global.asax.
References
“Simple URL Rewriting/Mapping in IIS7”, https://ronniediaz.com/2011/04/06/simple-url-rewritingmapping-in-iis7/
Learn IIS, http://learn.iis.net/page.aspx/508/wildcard-script-mapping-and-iis-7-integrated-pipeline/, http://learn.iis.net/page.aspx/465/url-rewrite-module-configuration-reference/, http://learn.iis.net/page.aspx/761/provide-url-rewriting-functionality/
Stackoverflow, http://stackoverflow.com/questions/416727/url-rewriting-under-iis-at-godaddy
Rackspacecloud, http://cloudsites.rackspacecloud.com/index.php/How_do_I_rewrite_URLs_from_ASP/.NET%3F
Godaddy kbase, http://help.godaddy.com/topic/623/article/5443
C# and VB Equivalents
VB:
'shorthand object constructors; assigned initial properties dim p as New Person() With {.FirstName = "john", .LastName="smith"} 'add handler for events AddHandler context.BeginRequest, AddressOf Applicaton_BeginRequest
C#:
//shorthand object constructors; assigned initial properties Person p = new Person() with {FirstName = "john", LastName="smith"} //add handler for events context.BeginRequest += Application_BeginRequest;
IIF in C#
I always find myself referencing my other projects for this one when I jump between languages, so decided to toss it on the web.
Both examples are in the context of ASP .Net, but syntax also applies np to Winforms
In VB:
<asp:label id="lblmessage" runat="server" visible='<%# iif(1=1,"true","false") %>' />
C# Equivalent:
<asp:label id="lblmessage" runat="server" visible='<%# 1 == 1 ? "true" : "false" %>' />
Serialize and Deserialize classes and objects in .Net
Serialization is a powerful tool and a major factor in many intermediate development technologies such as webservices.
Simply call “SerializeObject” and pass in the class name of your object for the “T” parameters, and your object will be serialized as an xml string which can then be stored in DB or written to disk!
To mark a public variable so it is not serialized, such as a decrypted key value or password, simply mark it with the attribute [XmlIgnore].
Enjoy. 😉
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Xml; using System.Xml.Serialization; namespace ApplicationName { /// <summary> /// Contains generic static/shared methods accessible throughout the site /// </summary> public static class XMLSerialization { /// <summary> /// Serialize Object of Type T to XML and return value as string. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="pObject"></param> /// <returns></returns> public static String SerializeObject<T>(T pObject) { /*try */ String XmlizedString = null; MemoryStream memoryStream = new MemoryStream(); XmlSerializer xs = new XmlSerializer(typeof(T)); XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); xs.Serialize(xmlTextWriter, pObject); memoryStream = (MemoryStream)xmlTextWriter.BaseStream; XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray()); return XmlizedString; /*} catch (Exception e) { System.Console.WriteLine(e); return null; }*/ } public static T DeserializeObject<T>(string URL) { /*try */ T returnObject; XmlSerializer xs = new XmlSerializer(typeof(T)); XmlTextReader xmlTextReader = new XmlTextReader(URL); returnObject = (T)xs.Deserialize(xmlTextReader); //xs.Serialize(xmlTextWriter, pObject); return returnObject; /*} catch (Exception e) { System.Console.WriteLine(e); return null; }*/ } public static String UTF8ByteArrayToString(Byte[] characters) { UTF8Encoding encoding = new UTF8Encoding(); String constructedString = encoding.GetString(characters); return (constructedString); } public static Byte[] StringToUTF8ByteArray(String pXmlString) { UTF8Encoding encoding = new UTF8Encoding(); Byte[] byteArray = encoding.GetBytes(pXmlString); return byteArray; } } }
Note:
Any snippets may have been condensed from their original sources for brevity. See references for original articles.
All server side code examples are in C# .Net.
References
Original reference misplaced.
Quick Silverlight References
Most of the links below are relatively introductory, but they do serve as a quick refresher if it has been awhile since you have worked with Silverlight.
Though not all of the links are specific to SL4, I would recommend a path of RIA services in conjunction with ADO .Net Entity framework for your business apps as these new process flows simplify the project structure and are improvements upon their predecessors.
For quick “agile” development, Linq to SQL is still the way to go IMO, but ADO .Net is also great nonetheless.
– Walkthrough creating a silverlight business application (4.0 or later) and retrieve data using WCF service.
http://www.silverlight.net/learn/tutorials/silverlight-4/aspnet-and-silverlight/
– Using ADO .Net Entity Model / Framework with Silverlight (4.0 or later)
http://msdn.microsoft.com/en-us/library/ee796239%28v=vs.91%29.aspx
– Silverlight custom data forms (3.0 or later)
http://www.silverlightshow.net/items/Creating-Rich-Data-Forms-in-Silverlight-3-Customization.aspx
– Basic Animation in Silverlight
http://www.silverlight.net/learn/videos/silverlight-videos/basic-animation-silverlight-3/
– General Reference (all versions)
http://www.silverlight.net/learn/
– Run Silverlight on Desktop (Out of Browser Application)
http://www.silverlightshow.net/items/Silverlight-3-as-a-Desktop-Application-Out-of-Browser-Applications.aspx
Bind Control to an Object in Windows Forms
Simple solution for basic binding in Windows Forms app. This would NOT be recommended if you are using ASP .Net, Silverlight, WCF, RIA or any other services to retrieve the data as these project types have much better support for binding to controls.
C#:
static class dataaccess { static mytype object; } //on app load object = new mytype(); //on form load tbField1.DataBindings.Add("Text", dataaccess.object.property, "Field1")