Blog Archives

Custom DAL Class SQL ORM ASP .NET

(common.DataObject may be of your choosing or may simply replace with dynamic)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Data.SqlClient;

using AIS.Common; //this is a common namespace I use in examples throughout my site
using System.Reflection;
using System.Dynamic;

//TODO: consider returning ienumerable in sp return values for lazy eval vs .tolist immediate eval
namespace AIS.DAL.AppName
{
    public static class StoredProcedures
    {
        public delegate void ErrorHandler(Exception ex);
        /// <summary>
        /// If no custom error handling is bound to this event, exceptions will be thrown back up to the calling function.
        /// If custom handling is bound to this event, ensure it does not perform a redirect or kill the thread unless you intend to abort the procedural
        /// steps following the method/function call which threw the error.
        /// </summary>
        public static event ErrorHandler HandleError;

        #region Unique Procedures
        public static List<Common.DataObject> LoadUserSessions_All(dynamic o)
        {
            return ExecuteRead("an_get_db_fn1", o);
        }

        public static List<Common.DataObject> LoadUserSessionsDetails_LiveStream(dynamic o)
        {
            return ExecuteRead("an_get_db_fn2", o);
        }

        public static List<Common.DataObject> LoadUserSessionsDetails_Live(dynamic o)
        {
            return ExecuteRead("an_get_db_fn3", o);
        }

        public static int LogChat()
        {
            return ExecuteScalar("an_get_db_fn4", null);
        }

        public static int LogError()
        {
            return ExecuteScalar("an_get_db_fn5", null);
        }
        #endregion

        //TODO: consider hiding from external assemblies which would require strong mappings above
        #region Execution Logic
        public static List<Common.DataObject> ExecuteRead(string procedurename, dynamic param)
        {
            try
            {
                SqlDataSource sds = new SqlDataSource();
                sds.ConnectionString = ConfigValues.TrainingPortalConnectionString;
                sds.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
                sds.SelectCommand = procedurename;

                if (param != null)
                {
                    foreach (PropertyInfo pi in param.GetType().GetProperties())
                    {
                        object pval = pi.GetValue(param, null);
                        if (pval != null)
                        {
                            sds.SelectParameters.Add(pi.Name, pval.ToString());
                        }
                    }
                }

                List<Common.DataObject> results = new List<Common.DataObject>();
                //sds.Select(new DataSourceSelectArguments()).Cast<DataRowView>().ToList().ForEach(o => Load_AddResult<dynamic>(o, ref results));
                sds.Select(new DataSourceSelectArguments()).Cast<DataRowView>().ToList().ForEach(o => Load_AddResult<Common.DataObject>(o, ref results));

                return results;
            }
            catch (Exception ex)
            {
                HandleError_Condensed(ex);
                return null;
            }
        }

        public static void Load_AddResult<t>(Common.DataObject o, ref List<t> results)
        {
            try
            {
                t r = (t)Activator.CreateInstance(typeof(t));

                foreach (PropertyInfo pi in typeof(t).GetProperties())
                {
                    object v = o[pi.Name].ToString();
                    Type pt = Type.GetType(pi.PropertyType.FullName);
                    //try { pi.SetValue(r, Convert.ChangeType(v, pt), null); }
                    //catch (Exception ex) { HandleError_Condensed(ex); }

                    o.Add(pi.Name, Convert.ChangeType(v, pt));
                }

                results.Add(r);
            }
            catch (Exception ex)
            {
                HandleError_Condensed(ex);
            }
        }

        //public static void Load_AddResult<t>(dynamic o, ref List<t> results)
        //{
        //    try
        //    {
        //        t r = (t)Activator.CreateInstance(typeof(t));

        //        foreach (PropertyInfo pi in typeof(t).GetProperties())
        //        {
        //            object v = o[pi.Name].ToString();
        //            Type pt = Type.GetType(pi.PropertyType.FullName);
        //            try { pi.SetValue(r, Convert.ChangeType(v, pt), null); }
        //            catch (Exception ex) { HandleError_Condensed(ex); }
        //        }

        //        results.Add(r);
        //    }
        //    catch (Exception ex)
        //    {
        //        HandleError_Condensed(ex);
        //    }
        //}

        public static void ExecuteNonScalar(string procedurename, dynamic param)
        {
            try
            {
                ExecuteScalar(procedurename, param);
            }
            catch (Exception ex)
            {
                HandleError_Condensed(ex);
            }
        }

        public static int ExecuteScalar(string procedurename, dynamic param)
        {
            try
            {
                SqlDataSource sds = new SqlDataSource();
                sds.ConnectionString = ConfigValues.TrainingPortalConnectionString;
                sds.UpdateCommandType = SqlDataSourceCommandType.StoredProcedure;
                sds.UpdateCommand = procedurename;

                if (param != null)
                {
                    foreach (PropertyInfo pi in param.GetType().GetProperties())
                    {
                        object pval = pi.GetValue(param, null);
                        if (pval != null)
                        {
                            sds.SelectParameters.Add(pi.Name, pval.ToString());
                        }
                    }
                }

                return sds.Update();
            }
            catch (Exception ex)
            {
                HandleError_Condensed(ex);
                return 1; //1 signifies error in tsql
            }
        }
        #endregion

        private static void HandleError_Condensed(Exception ex)
        {
            if (HandleError != null) { HandleError(ex); } else { throw new Exception(ex.Message, ex); } 
        }
    }
}
Advertisement

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