Saturday, December 26, 2015

Using enumerations in C#

Let’s assume we have an enumeration like shown below. I have the integer value of the enumeration and I want to get the enumeration type.

public enum DataTypeCodes
    {
        DATATYPE_1 = 11,
        DATATYPE_2 = 12,
        DATATYPE_3 = 23,
        DATATYPE_4 = 34,
        DATATYPE_5 = 45,
        DATATYPE_6 = 56,
        DATATYPE_7 = 67,
        DATATYPE_8 = 78
    }

Here is the code snippet to achieve this.

Int value = 23;
DataTypeCodes dt = (DataTypeCodes) value;

This should give me 'DATATYPE_3'.

Cheers
Adam

 

 

 

 

Saturday, November 28, 2015

Insert XSL Stylesheet reference in the XML document using C# program



Here is the code snippet to insert the XSL style sheet reference in the XML document.

Thanks
Adam


XmlDocument xmlDoc = new XmlDocument();
using (MemoryStream memStreamXml = new MemoryStream())
{

     XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
     xmlWriterSettings.Encoding =
Encoding.UTF8;
     
XmlWriter xmlWriter = XmlWriter.Create(memStreamXml, xmlWriterSettings);
     xmlSer =
new XmlSerializer(typeof(SomeClass));
     xmlSer.Serialize(xmlWriter, SomeClassObject);

     memStreamXml.Seek(0, SeekOrigin.Begin);
     xmlDoc.Load(memStreamXml);

}
// Now add the stylesheet processing

// instruction to the XML document

XmlProcessingInstruction newPI;
String PItext = string.Format("type='text/xsl' href='{0}'", xslFileName);
newPI = xmlDoc.CreateProcessingInstruction(
"xml-stylesheet", PItext);
xmlDoc.InsertAfter(newPI, xmlDoc.FirstChild);
// Now write the document
// out to the final output stream
using (StreamWriter streamWriter = new StreamWriter(xmlFileName, false, Encoding.UTF8))
{
    using (XmlWriter xmlWriter = XmlWriter.Create(streamWriter)
    {

       xmlDoc.WriteTo(xmlWriter);

    }
}

Saturday, October 10, 2015

XML Document SelectNodes will not give results

 
When I tried to select nodes from the sample XML document shown below, I was not getting any results.
 
The reason is the "namespace".
 
When I select the nodes, I must use the right "namespace".
 
Here is the sample code which can add namespace first and then perform "SelectNodes" operation.
 
 
XmlDocument doc = new XmlDocument();
doc.Load(xmlFileName);
XmlNode docElement = doc.DocumentElement as XmlNode;
XmlNamespaceManager nsman = new XmlNamespaceManager(doc.NameTable);
nsman.AddNamespace("a", docElement.NamespaceURI);
XmlNodeList nodes = docElement.SelectNodes("a:Details/a:Section",nsman);

foreach (XmlNode node in nodes)
{
        // use node variable here.
}





Cheers
Happy Coding !



 

Saturday, September 12, 2015

Bulk Insert C# DataTable into SQL Server

Here is the sample code to insert C# DataTable into SQL.


        public bool BulkInsertDataTable(string ConnectionString , DataTable dataTable)
        {
            bool isSuccuss;
            try
           {
                SqlConnection SqlConnectionObj = new SqlConnection( ConnectionString );
                SqlConnectionObj.Open();
                SqlBulkCopy bulkCopy = new SqlBulkCopy(SqlConnectionObj,
                                                         SqlBulkCopyOptions.TableLock
                                                       | SqlBulkCopyOptions.FireTriggers
                                                       | SqlBulkCopyOptions.UseInternalTransaction
                                                       , null);
                bulkCopy.DestinationTableName = "tableName";
                SQLUtil.SqlTableCreator sqlTabCre = new SQLUtil.SqlTableCreator(SqlConnectionObj);
                sqlTabCre.CreateFromDataTable(dataTable);
                bulkCopy.WriteToServer(dataTable);
                SqlConnectionObj.Close();
                isSuccuss = true;
            }
            catch (Exception ex)
            {
                isSuccuss = false;
                throw new Exception("Error when inserting table " + tableName + " into SQL using connection string '" + ConnectionString + "'. Error Details : " + ex.ToString() + ".");
            }
            return isSuccuss;
        }

The utility to create SQL Table (SqlTableCreator) can be found here.

Hope this saves you some time.

Happy coding.

Cheers
Adam

Saturday, August 1, 2015

ASP.NET Web REST API Settings

I created a new ASP.NET Web API REST Service and I deployed it on the IIS Server. It didn't work.

I made sure that the .NET framework is correct.

Finally I found this link.

http://stackoverflow.com/questions/15622720/net-web-api-404-file-or-directory-not-found

As per the recommendation here, I downloaded the ASP.NET MVC Setup from the following Microsoft Link and installed it on the IIS Server.

http://www.microsoft.com/en-us/download/details.aspx?id=30683

Then it started working.

After few days, I installed Visual Studio 2015 and removed Visual Studio 2013 from my laptop.

In Visual Studio 2015, I created a brand new ASP.NET Web API REST Service and published on the same server. Once again , my application stopped working. At the same time, the old application which I published using Visual Studio 2013 was still working.

Then I started to compare the "Web.Config" file and I realized that Visual Studio 2015 was missing this parameter (runAllManagedModulesForAllRequests).

<system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <modules runAllManagedModulesForAllRequests="true">
        <remove name="FormsAuthentication" />
    </modules>
  </system.webServer>

After adding this settings in the Web.Config, then the HTTP REST services started to work.

Hope these tips will save you some time.

Cheers
Adam


 

Tuesday, July 28, 2015

WCF Service to Internet

 
 
Here are the steps to convert the WCF Service to be accessed from the browser over the internet.
 
1. Add the 'WebGet' parameter to the interface.
2. Add the endpoint binding to the Web config file.
3. Add the endpoint behavior to the Web config file.
 
Now the service should be exposed over the internet.
    
[ServiceContract]
    public interface IServiceSomeName
    {
        [WebGet(UriTemplate = "gettoken", ResponseFormat = WebMessageFormat.Json)]
        [OperationContract]
        string GetToken();
        [OperationContract]
        string GetData(int value);
 
        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);
        // TODO: Add your service operations here
    }
    <services><service name="WcfServiceSomeName.ServiceSomeName">
        <endpoint binding="webHttpBinding" contract="WcfServiceSomeName.IServiceSomeName"  behaviorConfiguration="webHttp"/>
      </service>
    </services>
 
 
 
 
      <endpointBehaviors>
        <behavior name="webHttp">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
 Also I noticed one more interesting fact.
Quote
- WCF Data Services don't support passing parameters in the request body or headers, they have to be present in the URL of the request. This makes it hard to pass long values.

Unquote
I found this info in the below link.
 
 
Hope these tips will come in handy when working with WCF web services.
Cheers
Adam
 
 

Sunday, June 21, 2015

Tips on JSON and SQL Geography


Here is one way to get key and value attributes from a JSON string which contains the Key and Value attributes in JSON string format.


    var regex = new RegExp('"', 'g');
    $.each(jsonValues, function () {
        newhtml += "<tr>";
        newhtml += s + KeyandValue[0].toString().replace(regex ,'') +e;
        newhtml += s + KeyandValue[1].toString().replace(regex ,'') + e;
        newhtml + "</tr>";
    })
 
 

Here is one tip to convert between DBGeography and SQLGeography

//SqlGeography theGeography;
int srid = 4326; // or alternative
DbGeography newGeography = DbGeography.FromText(theGeography.ToString(), srid);

 
//To reverse it:
DbGeography theGeography;
SqlGeography newGeography = SqlGeography.Parse(theGeography.AsText()).MakeValid();


 
Happy coding.
 
 

Monday, May 25, 2015

Using SQL Spatial to create polygon features

I was assigned a task to generate polygon features using SQL Spatial. SQL Spatial has many features to create geometric/geographic features. When I was working on this assignment , for some reason, some of the generated polygons were not appearing correctly. They were too big or it didn't look right.

For example, when I tried to generate all the US state polygons, some states showed up correctly but some was too big and not of the right size.

After doing some searching, I found out that the polygons are not drawn in the right orientation.

I checked the envelope angle of each polygon feature using the following command.

EnvelopeAngle

If the envelope angle is greater than 180 degrees then I re-oriented the polygon using the following command

ReorientObject

After this fix, then all the 'Polygons' showed up correctly.

Hope this tip helps.

Have fun coding.

 

Wednesday, April 29, 2015

Using Open Layers to display Map

Here is a simple example on how to load a map using "Open Layers" open source GIS API.

==== JavaScript Code ========

$(document).ready(function () {

LoadMap();

}); 


function LoadMap() {

var map = new ol.Map({

target: 'map',

layers: [


new ol.layer.Tile({

source: new ol.source.MapQuest({ layer: 'sat' })

})

],


view: new ol.View({

center: ol.proj.transform([37.41, 8.82], 'EPSG:4326', 'EPSG:3857'),

zoom: 4

})

});

}

=================================================

======== Code from Index.html =============================

<link rel="stylesheet" href="http://openlayers.org/en/v3.2.1/css/ol.css" type="text/css">

<script src="http://openlayers.org/en/v3.2.1/build/ol.js" type="text/javascript"></script>

<script src="scripts/mainJavaScript.js"></script>

<div id="map" class="map"></div>

============================================================

These lines should display a "World Map".

Happy Coding.

Cheers
Adam




 

All Blogs so far ...