Saturday, October 17, 2020

View SQL Table Names in Alphabetical Order

 When you have a SQL table with multiple fields and if you want to view the fields in alphabetical order, use this script.

SELECT 

    COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE, ORDINAL_POSITION

    FROM INFORMATION_SCHEMA.COLUMNS

        WHERE TABLE_NAME = <Your Table Name inside quotes>

        ORDER BY COLUMN_NAME ASC 

Saturday, March 9, 2019

Steps to secure ArcGIS Server REST Endpoints


These are the steps to secure ArcGIS Server REST Endpoints

1.      Go to ArcGIS Manager. Go the services you want to secure and click on the 'Lock' icon to Lock it. This will lock the application.


2.      Download the 'DotNet' proxy folder from ESRI github (https://github.com/esri/resource-proxy/) and install it in the wwwroot folder.

3.      Inside this 'DotNet' folder edit the proxy.config file add an entry like shown here.
<serverUrl url="http://localhost:6080/arcgis/rest/services" matchAll="true" username="<ArcGIS Site Username>" password="<ArcGIS Site Password>"/>

4.      Perform a ping operation like shown here and make sure you are getting results. If not double-check the above steps.
https://<Server Domain Name>/dotnet/proxy.ashx?ping
The reply should be like this.

{ "Proxy Version": "1.1.2", "Configuration File": "OK", "Log File": "Not Exist/Readable"}

5.      Now the site is secure and the proxy is ready for communication.

6.      In your JavaScript API code. Add these lines in the beginning.

        urlUtils.addProxyRule({
            urlPrefix: "https://<Server Domain Name>",
            proxyUrl: "https://<Server Domain Name>/DotNet/proxy.ashx"
        });

7.      Now all your JavaScript REST endpoint calls will go through proxy and your services will remain protected.

Happy Coding !

Visual Studio Code Icon Names


When writing an extension for Visual Studio Code, there might be a need to know the Visual Studio Icon names.

Here is the link which shows all the available icon names.

Hope this helps.

Cheers
Adam

How to call your own Javascript Function from Angular 4 Typescript Application


To call your own JavaScript Function from Angular 4 Typescript Application follow this technique.

In file .angular-cli.json

      "scripts": [
        "../node_modules/adam-scripts/core.js"
      ],

The core.js file contains this function.

function ShowMessage(inMessage) {
    alert(inMessage);
}

In the Typescript file refer and call it like this.

declare var ShowMessage: any;

  ngOnInit() {
    ShowMessage('Working');
  }


XML to C# Objects using JSON - Translate List of Objects


Let’s presume that there is an XML Array like this.

<Books>
<Book>
 <Name>Book Name 1</Name>
 <Author>Author 1</Author>
</Book>
<Book>
 <Name>Book Name 2</Name>
 <Author>Author 2</Author>
</Book>
<Book>
 <Name>Book Name 3</Name>
 <Author>Author 3</Author>
</Book>
</Books>

You can extract the data into C# objects using XML serialization. But XML Serialization will only work if the outer most element is like this.

<ArrayOfBook></ArrayOfBook>

For some reason, if your XML from the SQL server is not like this then you have to use XML attributes in the class definition of “Book” correctly and also create a collection class for the Book List.

The other alternative is to use Newtonsoft JSON. Here is the function to do it.

if (!string.IsNullOrEmpty(inXMLString))
{
    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
    doc.LoadXml(inXMLString); // Use this line if there is already XML content in a string.
    string jsonText = JsonConvert.SerializeXmlNode(doc);
    dynamic dynObject = JsonConvert.DeserializeObject(jsonText);
    foreach (dynamic innerContents in dynObject.Books)
    {
        List<Book> listOfBooks = new List<Book>();
        string jstring = JsonConvert.SerializeObject(innerContents.Value);
        if (innerContents.Value is JArray)
        {
            listOfBooks = JsonConvert.DeserializeObject<List<Book>>(jstring);
        }
        if (innerContents.Value is JObject)
        {
            Book oneBook = JsonConvert.DeserializeObject<Book>(jstring);
            listOfBooks.Add(oneBook);
        }
       togoBooks.AddRange(listOfBooks);
    }
}

return togoBooks;

Hope this helps. Happy coding.

Saturday, November 18, 2017

JSON to Dictionary Conversion


Here is the tip to convert JSON Object to Dictionary.


private static Dictionary<string, object> GetDictFromJObject(JObject inJObject)
{
        if (inJObject == null) return new Dictionary<string, object>();
        return ((JObject)inJObject).ToObject<Dictionary<string, object>>();
}

JavaScript Function to get a Valid Number from String


Here is the function to get a numeric value from a string value.


    function GetValidNumberValue(inValue)
   {
        if (inValue == null) return 0.0;
        if (inValue == undefined) return 0.0;
        if (isNaN(inValue) == true) return 0.0;
        let togoNumber = parseFloat(inValue);
        if (isNaN(togoNumber) == true) return 0.0;
        return togoNumber;
    }

JavaScript functions to handle cookies


Here are the functions to handle cookies using JavaScript.

    function SetCookie(cookieName, cookieValue, exdays) {
        let d = new Date();
       d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        let expires = "expires=" + d.toUTCString();
        document.cookie = cookieName+ "=" + cookieValue+ "; " + expires;
    }

    function GetAllCookie() {
        return document.cookie;
    }

    function DelCookie(cname) {
        let name = cname + "=";
        document.cookie = cname + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
        return "";
    }

    function GetCookie(cname) {
        let name = cname + "=";
        let ca = document.cookie.split(';');
        for (let i = 0; i < ca.length; i++) {
           let c = ca[i];
           while (c.charAt(0) == ' ') c = c.substring(1);
           if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
        }
        return "";
    }


JavaScript Function to get the website URL Value


This JavaScript function will return the URL name along with the protocol ('http' or 'https') value.

function GetHost() {

        if (typeof location.protocol == 'undefined') {

            alert('location.protocol is undefined');

        }

        if (typeof location.host == 'undefined') {

            alert('location.protocol is undefined');

        }

        let host = location.protocol + '//' + location.host + '/';

        return host;

    }

Get JSON string from XML

Here is the function to convert XML string to JSON string.

string GetJSONStringFromXML(string inXMLString){
XDocument xDoc = XDocument.Parse(inXMLString); //orXDocument.Load(xmlfilepath)
string jsonString = JsonConvert.SerializeXNode(xDoc);
return jsonString;
}

Sunday, February 12, 2017

Alternate approach to build Geographic Information Systems (GIS) Applications


GIS based Web Applications are very powerful and used extensively to make significant business decisions. Building a GIS based Web Application can be a challenge as it involves many client and server side technologies. In recent days, open source GIS has become very popular. Since some shops have already invested in Microsoft SQL Server, this can be used effectively for building powerful GIS solutions along with open source GIS tools.
Microsoft SQL Server supports various spatial functions. Detailed documentation can be found here.
SQL Server supports two spatial data types: the geometry data type and the geography data type.
  • The geometry type represents data in a Euclidean (flat) coordinate system.
  • The geography type represents data in a round-earth coordinate system.
Pick the right type based on your business needs. Write simple C# code to manipulate the data stored in SQL Server. You can export the stored SQL spatial data to GeoJSON files using tools like GeoJSON.NET. You can also use QGIS to connect directly to SQL Server and export the data to GeoJSON format. At the end we need GeoJSON format files which can be loaded and viewed in Google Maps using Google Maps JavaScript API.




The SRID (Spatial Reference System Identifier) value 4326 works well all across from SQL Server to Google Maps. For more details check here. In SQL Server Spatial, there are functions to check envelope angle and reorient the polygon if necessary.
Google Maps JavaScript API will allow you to load GeoJSON files and details can be found here. Google Maps JavaScript API also has an excellent Geometry Library which has several functions like a  given point falls inside a polygon or on the edge, etc.,
To summarize, a powerful GIS Web application can be built using SQL Server, QGIS, and Google Maps API.

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;
        }
}
 
 

All Blogs so far ...