Blog Archives

Custom URLRewriting with XML and Global.asax

utilizes my custom DocParser class here http://ronniediaz.com/2013/08/23/parse-xml-to-dynamic-expandoobject-c-net-4-0/

 void Application_BeginRequest(object sender, EventArgs e)
    {
        //string path = Request.Url.ToString();
        string path = Request.Path;

        if (Regex.IsMatch(path.ToLower(), ".*[.](jpg|png|gif|css|js|pdf|ico|woff|svg|eot|ttf)$"))
        {
            //var h = Regex.Replace(path.ToLower(), ".*/(.*)/(.*)$", "~/$1/$2", RegexOptions.Singleline);
            //Context.RewritePath(path);
            return;
        }
        
        //TODO: authorize user/request
 DocParser dp = new DocParser(Server.MapPath("~/rewrite.xml"));
        var rules = dp.GetElements("*/rule");
        
        foreach (var r in rules)
        {
            if (string.IsNullOrEmpty(r.match_url)) {
                Shared.HandleError("Global.asax::null or empty match_url encountered");
            }

            if (string.IsNullOrEmpty(r.action_url))
            {
                Shared.HandleError("Global.asax::null or empty action_url encountered");
            }
            
            if (Regex.IsMatch(path, r.match_url,RegexOptions.IgnoreCase))
            {
                List<object> qsvars = new List<object>();

                foreach (Match m in Regex.Matches(path, r.match_url, RegexOptions.IgnoreCase))
                {
                    for (int i=1;i<m.Groups.Count;i++)
                    {
                        qsvars.Add(m.Groups[i].Value);
                    }
                }
                //Context.RewritePath(string.Format(r.action_url,qsvars.ToArray()) + "&rewrite=1");
                Context.RewritePath(string.Format(r.action_url, qsvars.ToArray()));
            }
        }
}

rewrite.xml examples

<?xml version="1.0" encoding="utf-8" ?>
<rules>
  <rule match_url="^/home" action_url="~/home.aspx" />
  <rule match_url="^/login" action_url="~/default.aspx" />
  <rule match_url="^/register" action_url="~/welcome/register.aspx" />
  <rule match_url="^/logout" action_url="~/logout.aspx" />
  <rule match_url="^/default/(.*)" action_url="~/default.aspx?q={0}" />
  <rule match_url="^/test/(.*)/(.*)" action_url="~/test.aspx?q={0}&amp;r={1}" />
</rules>

Parse XML to Dynamic ExpandoObject C# .NET 4.0

The example below uses the LINQ to XML predecessor System.Xml.XmlDocument simply because I still prefer the regex parsing method. It can easily be adapted to use XDocument instead based on your preference. The end resulting output (IEnumerable) is the same.

code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Dynamic;
using System.Xml.Linq;

namespace AIS.Common
{
    public class DocParser : IDisposable
    {
        public enum DocTypes
        {
            Xml
        };

        private XmlDocument Document { get; set; }
        //private XDocument Document { get; set; }
        private DocTypes DocType { get; set; }

        //constructor
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt">type of document, currently only supports xml</param>
        /// <param name="f">filename and path</param>
        public DocParser(DocTypes dt, string fp)
        {
            try
            {
                switch (dt)
                {
                    case DocTypes.Xml:
                        DocType = DocTypes.Xml;

                        Document = new XmlDocument();
                        Document.Load(fp);

                        //Document = XDocument.Load(fp);
                        break;
                    default:
                        throw new Exception("Constructor::invalid or unknown doc type specified");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Constructor::Error with document load or doc type.",ex);
            }
        }

        public IEnumerable<dynamic> GetElements(string regex)
        {
            return XmlToExpandoObject(regex);
        }

        private IEnumerable<dynamic> XmlToExpandoObject(string regex)
        {
            dynamic eo = new ExpandoObject();
            var dictionary = eo as IDictionary<string, object>;
            XmlNodeList xnl = Document.SelectNodes(regex);
            foreach (XmlNode xn in xnl)
            {
                foreach (XmlAttribute xa in xn.Attributes)
                {
                    dictionary[xa.Name.ToString()] = xa.Value.Trim();
                    //TrySetAttr(xn.LocalName, xn);
                }

                yield return eo;
            }
        }
}
}

sample xml:

<?xml version="1.0" encoding="utf-8" ?>
<robots>
  <robot id="1" age="5" />
  <robot id="2" age="3" />
</people>

usage:

DocParser dp = new DocParser(DocParser.DocTypes.Xml, Server.MapPath("~/xmlfilename.xml")); //can also retrieve xml from external service, etc
        var robots = dp.GetElements("*/robot");
foreach (var r in robots) {
Console.WriteLine("Robot id={0}, age={1}", r.id,r.age); //output. if this is web app you will likely do this differently
}

References
http://msdn.microsoft.com/en-us/magazine/ff796227.aspx

slideshowpro dynamic images xml file output with classic asp

outputxml() 

'--------------------------------
'generates xml file with some static info and some dynamic for use by slideshowpro
'in slideshowpro simply replace images.xml with the name of this file
'--------------------------------

sub outputxml()
Response.ContentType = "text/xml"

outputxmlheader()
outputxmlbody()
outputxmlfooter()
end sub

sub outputxmlheader()
Response.Write("<?xml version=""1.0"" encoding=""UTF-8""?>")
Response.Write("<gallery title=""My Photos"" description="""">")
end sub

sub outputxmlfooter()
Response.Write("</gallery>")
end sub

sub outputxmlbody()
call outputalbumandfiles(Server.MapPath("/myphotos/img/20121031event"),"a1","2012 Event A","Event A Description.","img/20121031event/","ico/eventa.jpg")

call outputalbumandfiles(Server.MapPath("/companyphotos/img/20121120event"),"a2","2012 Event B","Event B Description.","img/20121120event/","ico/eventb.jpg")
end sub

sub outputalbumandfiles(path,id,title,description,lgpath,tn)
Response.Write("<album id=""" & id & """ title=""" & title & """ description=""" & description & """ lgPath=""" & lgpath & """ tn=""" & tn & """>")

set fs = CreateObject("Scripting.FileSystemObject")
    set folder = fs.GetFolder(path)
	
	for each item in folder.Files
	 if FilterExtensions(item.Name) then
	 Response.Write("<img src=""" & item.Name & """ target=""_blank"" />")
		 end if
     next

	 'TODO: set objects = nothing
Response.Write("</album>")
end sub
   
'filter out .db files and any other files you do not want to slideshowpro to load
'alternative you can reverse the logic to allow only jpg, png etc
   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
   next
   end function

References
http://support.microsoft.com/kb/301244

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.

OAuth Specs and Protocol

The OAuth protocol defines a common data structure for communicating between websites.

This relatively new format is increasing in popularity and used in many different sites including Facebook and Google. Microsoft has even added support for it in its latest WCF RIA services. (See my article with silverlight links below).

Read the full spec at IETF or try out some sample code.

References:
IETF, http://tools.ietf.org/html/rfc5849
OAuth.net, http://oauth.net
Quick Silverlight References, http://ronniediaz.com/2011/01/17/quick-silverlight-references/

Import OData / XML / RSS / Webservice Feeds into Excel

If you came here looking for some quick and easy code that you can plug right in and dump data in excel format.. You have come to the wrong spot. :)

Depending on the scenario you may need this functionality for, you may want to check out a cool tool backed by Microsoft called “Powerpivot“.

This code is not hard to write, but there are many points of error and re-implementation for multiple users and/or clients is likely a larger project than you (or your boss) might realize if you haven’t dealt with data conversion processes before or have multiple complex data relationships which may or may not change data structure over time (addition/removal of columns, mappings, etc).

(For an example on some sample code to help you with this task, see one of my older entries on converting datatable to csv. http://ronniediaz.com/2010/03/02/csv-to-datatable/)

However, if you decide to go the power pivot route, this is a cool little plugin for use with Microsoft Excel which allows you to directly import data from various streams and feeds including OData and SQL.

This plugin basically eliminates the steps involved for an end user to “export to csv, then import into excel”, as well as cuts back on the time and potentially error prone task of assigning a developer to create a data export for this same process.

Check it out.
http://www.powerpivot.com/

Follow

Get every new post delivered to your Inbox.