Monday, December 16, 2013

Sending javaScript array to server side c# via web service call

Sending javaScript array to server side c# via web service call

I wanted to send a collection of attributers for a set of textbox input html controls to the server side via an AJAX call:

Collect the desired elements and place certain properties in an array:
var inputs = new Array();

    $("[class^=txtEdit]").filter(":input").each(function () {

        var i = { 'ClassName': $(this).attr("class"), 'Id': $(this).attr("id"), 'Val': $(this).val() };

        inputs.push(i);

    });






Make the AJAX call:

var serviceUrl = '..//Tools.asmx/SaveEdits';
    $.ajax({
        type: "POST",
        //data: JSON.stringify(inputs),
        data: '{ "elements":' + JSON.stringify(inputs) + '}',
        contentType: "application/json; charset=utf-8",
        url: serviceUrl,
        dataType: "json",
        success: function (response) {
            if (response.d) {
                //TODO: rebind
            }
            else {
                alert("Save Edits Failed");
            }
        },
        error: function (response) {
            alert("failed service call" + serviceUrl);
        }
 
 
    });






Container class on server:

public class HtmlInput
{
    public string ClassName { getset; }
    public string Id { getset; }
    public string Val { getset; }
 
    public HtmlInput()
    {
 
    }
 
    public HtmlInput(string className, string id, string val)
    {
        this.ClassName = className;
        this.Id = id;
        this.Val = val;
    }
 
}




The web method:
/// 
    /// Saves all the inputs (items, appOverdies) using services
    /// 
    /// colecton of html inputs
    /// error string
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string SaveEdits(HtmlInput[] elements)
    {
 
 
        string ret = string.Empty;
 
        try
        {
 
            foreach (HtmlInput txt in elements)
            {
                //DO some stuff
            }
 
 
            return ret;
 
        }
        catch (Exception e)
        {
            //TODO:  log e.message etc.
 
            return ret += e.Message;
        }
 
    }


Jquery: Displaying Object Property Names and Values

Jquery Displaying Object Property Names and Values

Here is one way to display a JSON object’s property name and value.  I used this to display the results of a test service call to a paging service.

C# class:
 /// 
    /// Container class to hold results of paging service calls
    /// 
    public class PagerComm
    {

        public string Address { getset; }
        public string Domain { getset; }
        public string ElaspedTime { getset; }
        public string Env { getset; }
        public string Error { getset; }
        
        
        public PagerComm()
        {

        }

        public PagerComm(string address, string domain, string elaspedTime, string env,string error)
        {
            this.Address = address;
            this.Domain = domain;
            this.ElaspedTime = elaspedTime;
            this.Env = env;
            this.Error = error;

        }





    }


Asmx method returning the class:

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public PagingTools.PagerComm SendTestPage(string tstTyp, string pgrId, string pgrTyp)
    {
        PagingTools.PagerComm ret = new PagingTools.PagerComm();
 
        try
        {
 
            PagingTools.ETestPageService svc = new PagingTools.ETestPageService("local:dxf""test");
 
            ret = svc.TestEpicPaging(tstTyp, pgrId, pgrTyp);
            
            
            return ret;
        }
 
 
        catch (Exception e)
        {
            //TODO:  log e.message etc.
 
            return ret;
        }
 
 
    }
    




Service call:

function SendTestPage() {
    var serviceUrl = '..//Tools.asmx/SendTestPage';
    var tstTyp = $("#tstTypDdl option:selected").val();
    var pgrId = $("#pgrIdTxt").val();
    var pgrTyp = $("#pgrTypTxt").val();
 
    $.ajax({
        type: "POST",
        data: "{'tstTyp':'" + tstTyp + "', 'pgrId':'" + pgrId + "', 'pgrTyp':'" + pgrTyp + "'}",
        contentType: "application/json; charset=utf-8",
        url: serviceUrl,
        dataType: "json",
        success: function (response) {
            ParsePageComm(response.d);
        },
        error: function (response) {
            alert("failed service call" + serviceUrl);
        }
 
 
    });
 
}


Call back function:

function ParsePageComm(result) {
    if (result) {             
        $("#resultsDiv").html('');
        $.each(result, function (prpNm, prpVl) {
            if (prpNm.indexOf("_") < 0)
                $("#resultsDiv").html($("#resultsDiv").html() + prpNm + ": " + prpVl + "
");
        });
 
    }
    else {
        alert("Error with Service ");
    }
 
 
}




Example UI:

Address:
Domain:
ElaspedTime: 1004.805
Env:
Error: Failed to execute E3C command.


Wednesday, December 11, 2013

Adding a simple custom section in App.config c#

In App.config: you need to set up a configSections / sectionGroup sections, then you can add your custom sections below appSettings:

xml version="1.0"?>
<configuration>
  <configSections>
    <sectionGroup name="EpicSettings">
      <section name="EpicVersions" type="System.Configuration.DictionarySectionHandler"/>
    </sectionGroup>
  </configSections>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
  <appSettings>
    <add key="rootLevel" value="C:\Program Files (x86)\Epic"/>
    
    <add key="drFltr" value="Interconnect-*"/>
    <add key="DevVersion" value="Interconnect-DEV"/>

    <add key="CmdBldr" value="CommandBuilder.exe"/>
    <add key="CnfgEdt" value="ConfigEditor.exe"/>
    <add key="TrcVw" value="TraceViewer.exe"/>

    <add key="GnrlCnfg" value="\Web\App_Data\Config\General.config"/>

    <add key="WbSvPxyBldrSubDir" value="\Tools\"/>
    <add key="WbSvPxyBldr" value="WebServiceProxyBuilder.exe"/>

    <add key="PhsGenSvcSubDir" value="\Web\bin\"/>

  </appSettings>
  
  <EpicSettings>
    <EpicVersions>
      <add key="v7.9" value="Epic 2012"/>
      <add key="v8.1" value="Epic 2014"/>
    </EpicVersions>
  </EpicSettings>

</configuration>



In code:  Here is one way to access your custom section in the code:  Here we’re trying to determine the Epic Version based on if the directory path contains a string matching one of the config keys.

private string getEpicVersion(string vrsnpth)
        {
            string ret = string.Empty;
 
            var epicVersions = (ConfigurationManager.GetSection("EpicSettings/EpicVersions"as System.Collections.Hashtable)
                 .Cast()
                 .ToDictionary(n => n.Key.ToString(), n => n.Value.ToString());
 
            foreach (System.Collections.Generic.KeyValuePair<stringstring> vrsn in epicVersions)
            {
                if (vrsnpth.ToLower().Contains(vrsn.Key.ToLower()))
                {
                    ret = vrsn.Value;
                    break;
                }
 
            }
 
            return ret;
        }