Technical Insights: Azure, .NET, Dynamics 365 & EV Charging Architecture

Tag: C#

Resolve URL functions

This snippet code is credited to Scott’s Hanselman, This Resolve URL function is used where you want to implement it on your business layer.

Methods:


        #region "Image URL helpers"

        public static string ResolveUrl(string originalUrl)
        {
            if (originalUrl == null)
                return null;
            // *** Absolute path - just return
            if (originalUrl.IndexOf("://") != -1)
                return originalUrl;
            // *** Fix up image path for ~ root app dir directory
            if (originalUrl.StartsWith("~"))
            {
                string newUrl = "";
                if (System.Web.HttpContext.Current != null)
                    newUrl = System.Web.HttpContext.Current.Request.ApplicationPath + originalUrl.Substring(1).Replace("//", "/");
                else  // *** Not context: assume current directory is the base directory
                    throw new ArgumentException("Invalid URL: Relative URL not allowed.");
                // *** Just to be sure fix up any double slashes
                return newUrl;
            }
            return originalUrl;
        }

        /// Works like Control.ResolveUrl including support for ~ syntax
        /// but returns an absolute URL.
        /// 
        /// Any Url, either App relative or fully qualified
        /// if true forces the url to use https
        /// 
        public static string ResolveServerUrl(string serverUrl, bool forceHttps)
        {    // *** Is it already an absolute Url?
            if (serverUrl.IndexOf("://") > -1)
                return serverUrl;
            // *** Start by fixing up the Url an Application relative Url
            string newUrl = ResolveUrl(serverUrl);
            Uri originalUri = System.Web.HttpContext.Current.Request.Url;
            newUrl = (forceHttps ? "https" : originalUri.Scheme) + "://" + originalUri.Authority + newUrl;
            return newUrl;
        }

        /// 
        /// This method returns a fully qualified absolute server Url which includes
        /// the protocol, server, port in addition to the server relative Url.
        ///
        /// It work like Page.ResolveUrl, but adds these to the beginning.
        /// This method is useful for generating Urls for AJAX methods
        /// 
        /// Any Url, either App relative or fully qualified
        /// 
        public static string ResolveServerUrl(string serverUrl)
        {
            return ResolveServerUrl(serverUrl, false);
        }

        #endregion

Usage:

 sb.AppendFormat("

", row.WidgetItemClass); sb.AppendFormat("More Info", ProductsService.GetProductUrl(row.ProductID), ResolveServerUrl("~/GetWhiteLabelFile.aspx?whiteLabelFileID=" + row.WidgetItemLinkImageID.ToString())); sb.AppendFormat("

");

Convert DataTable to CSV Function

This is the class that you can use to create a CSV file from DataTable. Basically what it does is to iterate each column and row in datatable and separate them with comma.

Class/Function:

using System;
using System.Data;
using System.IO;
using System.Text;
using System.Web;

namespace BusinessLayer
{
    public class CSVBuilder
    {
        public static string BuildCSVDocument(DataTable table)
        {
            StringBuilder   builder = new StringBuilder();
            DataColumn      col;

            // append header
            for (int index = 0; index < table.Columns.Count; index++)
            {
                col = table.Columns[index];
                builder.AppendFormat("{0},", col.ColumnName);
            }

            builder.AppendLine();

            // append rows
            foreach (DataRow row in table.Rows)
            {
                object[] values = row.ItemArray;

                for (int index = 0; index < values.Length; index++)
                {
                    object value = row[index];
                    string valueString;

                    if (value is DateTime)
                    {
                        valueString = Convert.ToDateTime(value).ToString("dd/MM/yyyy hh:mm");
                    }
                    else if (value is string)
                    {
                        valueString = value.ToString().Replace("'", "`").Replace(",", "");
                    }
                    else
                    {
                        valueString = value.ToString();
                    }

                    builder.AppendFormat("{0},", valueString);
                }

                builder.AppendLine();
            }

            return builder.ToString();
        }

        public static void StreamCSV(DataTable table, HttpResponse response, string fileName)
        {
            // convert the extract to CSV
            string csv = BuildCSVDocument(table);

            // Send it to browser
            response.ClearContent();
            response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.ContentType = "text/csv";

            // Write to the stream
            StreamWriter sw = new StreamWriter(response.OutputStream);
            sw.Write(csv);
            sw.Close();

            response.Flush();
            response.Close();
        }
    }
}

Usage

 private void GenerateMyCsv()
    {
        lblErrorOrderID.Visible = false;

        try
        {
            tdsReports.MissingBatchNumberSelectDataTable dtBatch =
                ReportFactory.GetMissingBatch(txtOrderID.Text);

            //display no results returned message
            if (dtBatch.Rows.Count != 0)
            {
               CSVBuilder.StreamCSV(dtBatch , Response, "MyCSV.csv");
            }

        }
        catch (ApplicationException ex)
        {
            lblErrorOrderID.Text = ex.Message;
            lblErrorOrderID.Visible = true;
        }
        catch (Exception ex)
        {
            lblErrorOrderID.Text = ex.Message;
            lblErrorOrderID.Visible = true;
        }
    }

Powered by WordPress & Theme by Anders Norén