Monday, January 9, 2017

Logging in DotNetCore Application

To view any exception raised in the dotnetcore application, these are the steps to do.

Step 1:

First make sure the “web.config” has “stdoutLogEnabled” enabled as “true” and the “stdoutLogFile” path is set correct. Use as shown below. Do not end the path with “\”. The reason is, the application will use the last portion of the name as file prefix along with the timestamp. For example in this case the log file name is something like “stdoutLog_4036_201716232359.log” and this file will be present inside the folder “C:\inetpub\wwwroot\ProjectTest\Logs\”.
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="true" stdoutLogFile="C:\inetpub\wwwroot\ProjectTest\Logs\stdoutLog" forwardWindowsAuthToken="false"/>

Step 2:
Make sure to give write permission to the log folder (in my example ““C:\inetpub\wwwroot\ProjectTest\Logs\”) for the IIS_IUSRS.
 These two steps will ensure logging is happening when an exception is raised in the code.
 I added a “TEST EXCEPTION” in the code like this.
         public void ConfigureServices(IServiceCollection services)       {
            // Add framework services.
            services.AddMvc();
             services.AddTransient<IBizAssign, BizAssign>();
             throw new Exception("TEST EXCEPTION");
        }

This was logged in the log file as per the expectation.
The same log file can be used for non-exception general logging.
Just the follow this article to setup logging. https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging

Simply start logging wherever necessary like shown below.

            logger.LogInformation("Get function entered.");

This will write all the information in the log file.

Wednesday, December 28, 2016

Get FeatureLayer from GIS Layer Name in ArcGIS Explorer Application

Here is the code snippet to get the "FeatureLayer" from the GIS Layer Name in ArcGIS Explorer Application.


        public static FeatureLayer GetFeatureLayer(string GISLayerName)
        {
            FeatureLayer ToGoFeatureLayer = null;
            foreach (MapItem EachMapItem in ESRI.ArcGISExplorer.Application.Application.ActiveMapDisplay.Map.ChildItems)
            {
                if ((EachMapItem is FeatureLayer) && (EachMapItem.Name == GISLayerName))
                {
                    ToGoFeatureLayer = (FeatureLayer)EachMapItem;
                    break;
                }
            }
            return ToGoFeatureLayer;
        }

XML Serialization in C#


Simple Serialize and de-Serialize to and from XML. This sample takes a C# object and serializes to XML file. Also it reads contents from a XML file and de-serializes it.
 
Happy coding.
 
Cheers
Adam

public class CSerializeController
    {
        public bool Serialize(object InData, string FQXMLFileNametoSave)
        {
            bool ToGobool = false;
            StreamWriter sw = new StreamWriter(FQXMLFileNametoSave);
            System.Xml.Serialization.XmlSerializer TheXmlSerializer = new System.Xml.Serialization.XmlSerializer(InData.GetType());
            try
            {
                TheXmlSerializer.Serialize(sw, InData);
                ToGobool = true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString() + " - Error in function Serialize");
            }
            finally
            {
                sw.Close();
                sw.Dispose();
            }
            return ToGobool;
        }
 
        public object DeSerialize(object InEmptyData, string FQXMLFileNametoLoad)
        {
            object ToGoobject = new object();
            StreamReader sr = null;
            try
            {
                sr = new StreamReader(FQXMLFileNametoLoad);
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(InEmptyData.GetType());
                ToGoobject = (object)serializer.Deserialize(sr);
            }
            catch (Exception ex)
            {
                ToGoobject = null;
                throw new Exception(ex.ToString() + " - Error in function DeSerialize");
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                    sr.Dispose();
                }
            }
            return ToGoobject;
        }
}
 
 

Get all file info from the folder using C# code


Here is the code snippet to get all the file information from a folder in the descending order of creation date and time.


var dirInfo = new DirectoryInfo(folderNametoSearch);

FileInfo[] filesInfo = dirInfo.GetFiles().OrderByDescending(p => p.CreationTime).ToArray();

 

Get more details when an Error Exception is thrown in C#

When there is an issue in the C# code, the application will throw exceptions.

All these exceptions can be handled properly and also logged. Using Reflection, we can get the class name and the function name which caused the exception

Simply use the following catch block in all your try-catch functions and pass all the exception to the Utility class to handle it.

catch (Exception ex)
{

MethodBase method = System.Reflection.MethodBase.GetCurrentMethod();

string methodName = method.Name;

string className = method.ReflectedType.Name;

UtilClass.HandleError(className, methodName, ex);

}
 
Happy Coding !

Thursday, November 24, 2016

Download EXCEL file as a BLOB object in the client side


Here is the code snippet where the excel file object from the server can be downloaded as a blob at the client side.


        var xhr = new XMLHttpRequest();
        xhr.open('POST', Config.RemoteServerUrl, true);
        xhr.responseType = 'arraybuffer';
        xhr.onload = function () {
            if (this.status === 200) {
 
                var filename = inFileName; // "ExportResults.xlsx";
                var disposition = xhr.getResponseHeader('Content-Disposition');
                var type = xhr.getResponseHeader('Content-Type');
                var blob = new Blob([this.response], { type: type });
                if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the
// blob for which they were created.These URLs will no longer resolve as the data backing the URL has been freed."
                    window.navigator.msSaveBlob(blob, filename);
                } else {
                    var URL = window.URL || window.webkitURL;
                    var downloadUrl = URL.createObjectURL(blob);
                    if (filename) {
                        // use HTML5 a[download] attribute to specify filename
                        var a = document.createElement("a");
                        // safari doesn't support this yet
                        if (typeof a.download === 'undefined') {
                            window.location.href = downloadUrl;
                        } else {
                            a.href = downloadUrl;
                            a.download = filename;
                            document.body.appendChild(a);
                            a.click();
                        }
                    } else {
                        window.location.href = downloadUrl;
                    }
             setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
             }
           }
        };
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhr.send(dataToGo); 
    }
 
 
Happy Coding.
 
Cheers
Adam

XML to JSON tricks using C#.NET and Newtonsoft JSON Library


// Converting XML to JSON
XmlDocument doc = new XmlDocument();
doc.Load("C:\\Temp\\SampleData.xml");    // Use this line to load XML from file.           
doc.LoadXml(fullXmlContent); // Use this line if there is already XML content in a string.
string jsonText = JsonConvert.SerializeXmlNode(doc);
JObject dataFromSQL = (JObject) JsonConvert.DeserializeObject(jsonText);
 
// At this point the XML is converted to JSON object.
 
//Get Agency Data from JSON object. Assuming "Agency" element is contained inside "MajorAccounts" element.
 
if (dataFromSQL["MajorAccounts"]["Agency"] == null)
throw new Exception("Data missing in XML for [MajorAccounts][Agency].");
 
JObject agencyJObject = (JObject)dataFromSQL["MajorAccounts"]["Agency"] ;
               
Hope this helps !
 
Cheers
Adam

Sunday, June 26, 2016

Find Distinct Column Values in C# DataTable


 Here is the code snippet to find the Distinct Column Values from a C# DataTable.


   DataView tempView = new DataView(tableInfo);
   DataTable distinctValues = tempView.ToTable(true, "ColumnName"); 



Happy Coding !

Monday, May 30, 2016

Convert C# SQL Parameters list to C# DataTable

Here is the code snippet to convert C# SQL parameters list to C# DataTable.

Happy Coding.

        private DataTable GetDataTableFromParamResults(List<SqlParameter> sqlParameterCollection)

        {

            DataTable paramResultsTable = new DataTable("ParamResultsTable");

            foreach(SqlParameter eachParam in sqlParameterCollection)

            {

                DataColumn newCol = newDataColumn(eachParam.ParameterName.TrimStart(new char[] { '@' }), GetDBType( eachParam.DbType) );

                paramResultsTable.Columns.Add(newCol);

            }

            DataRow newRow = paramResultsTable.NewRow();

            foreach (SqlParameter eachParam in sqlParameterCollection)

            {

                string colName = eachParam.ParameterName.TrimStart(new char[] { '@' });

                newRow[colName] = eachParam.Value;

            }

            paramResultsTable.Rows.Add(newRow);

 

            return paramResultsTable;

        }

 

        private Type GetDBType(DbType inDbType)

        {

            Type togoType = null;

            switch (inDbType)

            {

                case DbType.AnsiString:

                    togoType = Type.GetType("System.String");

                    break;

                case DbType.Binary:

                    togoType = Type.GetType("System.Byte");

                    break;

                case DbType.Byte:

                    togoType = Type.GetType("System.Byte");

                    break;

                case DbType.Boolean:

                    togoType = Type.GetType("System.Boolean");

                    break;

                case DbType.Currency:

                    togoType = Type.GetType("System.Decimal");

                    break;

                case DbType.Date:

                    togoType = Type.GetType("System.DateTime");

                    break;

                case DbType.DateTime:

                    togoType = Type.GetType("System.DateTime");

                    break;

                case DbType.Decimal:

                    togoType = Type.GetType("System.Decimal");

                    break;

                case DbType.Double:

                    togoType = Type.GetType("System.Double");

                    break;

                case DbType.Guid:

                    togoType = Type.GetType("System.Guid");

                    break;

                case DbType.Int16:

                    togoType = Type.GetType("System.Int16");

                    break;

                case DbType.Int32:

                    togoType = Type.GetType("System.Int32");

                    break;

                case DbType.Int64:

                    togoType = Type.GetType("System.Int64");

                    break;

                case DbType.Object:

                    togoType = Type.GetType("System.Object");

                    break;

                case DbType.SByte:

                    togoType = Type.GetType("System.SByte");

                    break;

                case DbType.Single:

                    togoType = Type.GetType("System.Single");

                    break;

                case DbType.String:

                    togoType = Type.GetType("System.String");

                    break;

                case DbType.Time:

                    togoType = Type.GetType("System.DateTime");

                    break;

                case DbType.UInt16:

                    togoType = Type.GetType("System.UInt16");

                    break;

                case DbType.UInt32:

                    togoType = Type.GetType("System.UInt32");

                    break;

                case DbType.UInt64:

                    togoType = Type.GetType("System.UInt64");

                    break;

                case DbType.VarNumeric:

                    togoType = Type.GetType("System.Decimal");

                    break;

                case DbType.AnsiStringFixedLength:

                    togoType = Type.GetType("System.String");

                    break;

                case DbType.StringFixedLength:

                    togoType = Type.GetType("System.String");

                    break;

                case DbType.Xml:

                    togoType = Type.GetType("System.String");

                    break;

                case DbType.DateTime2:

                    togoType = Type.GetType("System.DateTime");

                    break;

                case DbType.DateTimeOffset:

                    togoType = Type.GetType("System.DateTimeOffset");

                    break;

                default:

                    throw new Exception("Unable to convert the type  " + inDbType.ToString() +".");

            }

            return togoType;

        }

 

All Blogs so far ...