Blog Archives

Common functions asp .net static shared library

references custom encryption class here https://ronniediaz.com/2011/01/13/quick-net-encryption-reference/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Security;
using System.Text;
using System.Net;
using System.IO;

namespace AIS.Common
{
    public static class Shared
    {
        //TODO: add local, dev, prd
        public static string basehref { get { return HttpContext.Current.Request.ApplicationPath; } }

        //TODO: change to json serialized object reference to prevent manipulation of pipe delimeters
        public static string SetSecureQueryString(object o)
        {
            string ct = Crypto.Rijndael.Encrypt(o.ToString(), "static_or_dynamic_string");
            return HttpUtility.UrlEncode(ct);
        }

        //TODO: change to json (same as above)
        public static string SetSecureQueryString(object a, object b, object c, object d, object e, object f, object g, object h)
        {
            string ct = Crypto.Rijndael.Encrypt(a.ToString() + "|" + b.ToString() + "|" + c.ToString() + "|" + d.ToString() + "|" + e.ToString() + "|" + f.ToString() + "|" + g.ToString() + "|" + h.ToString(), "livestream");
            return HttpUtility.UrlEncode(ct);
        }

        public static string GetSecureQueryString(string q)
        {
            try
            {
                //automatically decodes querystring in request
                return Crypto.Rijndael.Decrypt(q, "static_or_dynamic_string");
            }
            catch (Exception ex)
            {
                return "";
            }
        }

//retrieves content from web url and returns as string
        public static string DownloadString(string url, NetworkCredential nc=null)
        {
            System.Net.WebClient wc = new WebClient();
            if (nc != null)
            {
                wc.UseDefaultCredentials = true;
                wc.Credentials = nc;
            }

            return wc.DownloadString(url);
        }

        //http://mayur.gondaliya.com/programming-languages/c-sharp/samples/fetching-url-contents-into-a-string-using-httpwebrequest-72.html
//same as above function, different approach with more detail
        public static string DownloadPage(string url)
        {

            const int bufSizeMax = 65536; // max read buffer size conserves memory
            const int bufSizeMin = 8192; // min size prevents numerous small reads
            StringBuilder sb;

            // A WebException is thrown if HTTP request fails
            try
            {

                // Create an HttpWebRequest using WebRequest.Create (see .NET docs)!
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                request.Method = WebRequestMethods.Http.Get;

                // Execute the request and obtain the response stream
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();

                // Content-Length header is not trustable, but makes a good hint.
                // Responses longer than int size will throw an exception here!
                int length = (int)response.ContentLength;

                // Use Content-Length if between bufSizeMax and bufSizeMin
                int bufSize = bufSizeMin;
                if (length > bufSize)
                    bufSize = length > bufSizeMax ? bufSizeMax : length;

                // Allocate buffer and StringBuilder for reading response
                byte[] buf = new byte[bufSize];
                sb = new StringBuilder(bufSize);

                // Read response stream until end
                while ((length = responseStream.Read(buf, 0, buf.Length)) != 0)
                    sb.Append(Encoding.UTF8.GetString(buf, 0, length));

                return sb.ToString();

            }
            catch (Exception ex)
            {
                sb = new StringBuilder(ex.Message);
                return sb.ToString();
            }

        }

//one approach using filesystem. will only work depending on permissions otherwise url parsing is needed
        public static string GetCurrentPageName()
        {
            string spath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
            System.IO.FileInfo oInfo = new System.IO.FileInfo(spath);
            string spagename = oInfo.Name;
            return spagename;
        }

//get titlecase string
        public static string GetTitleCase(object str)
        {
            try
            {
                return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToString().ToLower());
            }
            catch (Exception ex)
            {
                Shared.HandleError(ex);
                return "Other";
            }
        }

        #region handleerror
        public static void HandleError(Exception ex)
        {
            HandleError(ex.ToString());
        }

        //TODO: send error to error handler
        public static void HandleError(string details)
        {
            SendEmail(details);
        }

        public static void HandleError(Page p, Exception ex)
        {
            HandleError(p, ex.ToString());
        }

        public static void HandleError(Page p, string details)
        {
            //MessageBox.Show(hwnd, details);
            SendEmail(details);
        }

        //TODO: replace with call to error manager or hook to event for compatibility
        public static void SendEmail(string details)  {
        //throw new HttpUnhandledException(details);
            if (Shared.GetCurrentPageName().Replace("/", "") != "error.aspx") //TODO: remove. temporary resolution for unhandled session timeouts. PROTOTYPE
            {
                //HttpContext.Current.Response.Redirect("~/error.aspx");
                //TODO: global error log and local
            }
        }
        #endregion
    }
}
Advertisement