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;

        }

 

Convert DataTable to C# Class

Here is the code snippet to convert a C# DataTable to an existing C# class. If the column name matches with C# field name, then the class object will be created and pushed out.

public static UserInfo GetUserInfoFromDataTable(DataTable userInfoTable)

        {
  if (userInfoTable.Rows.Count == 0) throw new Exception("No UserInfo records found.");

            if (userInfoTable.Rows.Count > 1) throw new Exception("More than one UserInfo records found.");

            DataRow oneRow = userInfoTable.Rows[0];

            UserInfo togoUserInfo = new UserInfo();

            var props = typeof(UserInfo).GetProperties();

            foreach (var prop in props)

            {
  string propName = prop.Name;
 if (oneRow.Table.Columns.Contains(propName))

                {

                    object propNewValue = oneRow[propName];

                    prop.SetValue(togoUserInfo, propNewValue);

                }

            }

            return togoUserInfo;

        }

Happy Coding.

Cheers
Adam

Friday, April 29, 2016

Log4Net not logging in SQL Server

I was using Log4Net for one of my projects. The idea is to log everything into SQL. For some reason it was not logging. Finally after checking all these items, I was able to make it work. Hope this checklist will help you as well.
 
1. Copy the SQL config files from this example link.
 
2. Check the SQL Database connection string in the config file. Make sure that the Database Name is correct.
 
3. Check the SQL command in the config file. Make sure the table name is right.
 
4. Check the SQL Table in SQL and make sure it has the "Identity Column." Usually for the Id column the "Identity" should be enabled to true.
 
5. Turn on the SQL Server Profiler and examine the command coming into the SQL server.
 
6. If nothing is coming into SQL, then probably the Log4Net configuration file is not loaded. Try to load the configuration file programmatically.
 
Good Luck.
 
Cheers
Adam
 

Saturday, March 26, 2016

Build HTML Email from SQL Table content.


There was a need to create HTML table email body from the contents in the SQL table.

Here is the code snippet to do it.
 
 
Set @body = select
                                         AgencyID AS [TD]
                                    , Name AS [TD]
                                    , IsClient AS [TD]
                           from data.Agencies
                           For XML raw('tr'), Elements
 
I must give credit for the following site which provided this idea and good explanation.
 
 
Happy Coding.
 
Cheers
Adam
 
 

All Blogs so far ...