IamCalvinBrown.com - Blog

Blog Posts for .NET Architects, Devs and Evangelists

Calling JSONP / JSON WCF Service from HTML

The code below allows you to hit a WCF service and return the results. Use any version of jquery.min.


$.ajax({

                        type: "GET",

                        url: "http://www.iamcalvinbrown.com/wcf/Authentication.svc/sayHello",

                        success: function (j) {

                            console.log('inside results');

                            console.log(j);

                        },

                        error: function (j) {

                            console.log('Error');

                            console.log(j);

                        }

                    });

Enabling CORS in WCF

Familiarize yourself with these items:

1. Global.asax - Application_BeginRequest method
2. Exact url that will be requesting data

Note: http://localhost will not work. Please specify the port (ex: http://localhost:234) if you're running in development mode.

By adding this to your Global.asax, you allow the caller to hit your service and get a return. Otherwise, the status will be a 200, but with a readyState of Load.

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:61417");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");

                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }

Creating a Table Variable in SQL

Table variables are excellent for the temporary needs of SQL developers to create a structure (in memory) and select data just as you would from a real table.

Declare @MyTableVar TABLE

(

uniqueRowID   INT IDENTITY(1,1) PRIMARY KEY,

first_name    VARCHAR(35),

last_name   VARCHAR(35)

)

WCF - Return JSON Content (for Angular consumption)

Note: If you use string as a return type, it will not work when consumed directly by Angular.

You need 3 pieces:

  1. WCF Service (ex: RestService.svc)
  2. WCF Interface Class (ex: IRestService.cs)
  3. Newtonsoft.Json (install this package)
What the interface should look like:
public interface IRestService
{
     [OperationContract]
       WebGet(UriTemplate="IamCalvinBrown/{id}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
     System.IO.Stream getContentInJsonFormat(string id);
}

What the WCF Service looks like:
public class RestService: IRestService
{
    public System.IO.Stream getContentInJsonFormat(string id)
    {
          string workingString = string.empty;  // you should actually put a Json string here or create a class to return

         string returnString = JsonConvert.SerializeObject(workingString);
         return new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(returnString)); 
    }
}

How to call this service:
http://localhost:20949/restservice/IamCalvinBrown/123

The url is unique to your website, so please don't put port 20949 as your site unless it's actually your sites port. RestService is the name of the WCF service and the rest of the url (IamCalvinBrown/123) are the values you set in the Interface. The 123 value can change based on what you want to return.

Happy coding.

Generate a Random name from an array using JQuery

We have an array of items, and we want to pull the item out of the array by id. In this case, the id is randomly generated. If found, show the name.

1. There should be a div somewhere in the body of the screen named message_div

2. 

<script type="text/javascript">

$( document ).ready(function() {

var array = [ 

{'id':'1' ,'name':'IamCalvinBrown'} , 

{'id':'2' ,'name':'Calvin'}, 

{'id':'3' ,'name':'Nailah'}, 

{'id':'4' ,'name':'Kendi'},

{'id':'5' ,'name':'Everybody'}, 

];


$("#changeTextButton").click(function ()

{

// generate a random number between 1 and 5 (change the 5 to increase with the size of the array)

var _randomNumber = Math.floor((Math.random() * 5) + 1);

// find the specific item in our list

// findById takes the array from above and the randomNumber generated

$("#message_div").html(findById(array,_randomNumber));

});


function findById(source, id) {

 var _id = id.toString(); // conver the number to text since we are generating random numbers

 

 for (var i = 0; i < source.length; i++) {

if (source[i].id === _id) {

 return source[i].name;

}

 }

 throw "Couldn't find object with id: " + id;

}

});

</script>

Remove special characters from a string in C#

public static string RemoveSpecialCharacters(string str)

        {

            StringBuilder sb = new StringBuilder();

            foreach (char c in str)

            {

                if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '.' || c == '_')

                {

                    sb.Append(c);

                }

            }

            return sb.ToString();

        }

Adding 2 decimal spaces and a dollar sign to a decimal in C#

decimal _someValue = 123.4m;

_someValue.ToString("C").ToString(); // the output is: $123.40

Make all urls lowercase in MVC

The line highlighted in yellow sets all urls to lower case. this is more visually appealing to the users and less confusing with longer urls.

public static void RegisterRoutes(RouteCollection routes)

        {

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


            routes.LowercaseUrls = true;


            routes.MapRoute(

                   "Default",

                   "{action}",

                   new { controller = "Home", action = "Index" }

               );


            routes.MapRoute(

                "Index", // Route name

                "{controller}/{action}/{id}", // URL with parameters

                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults

            );


        }

How to get Angular to display HTML

The important items to note here are two things. 1 is the angular-sanitize.min.js file which manages the html rendering, and the ng-bind-html attribute. It can be added to a div, span, etc, however I used it on a paragraph tag in this example.


The code that's displayed to the users

<div ng-app="myApp" ng-controller="myCtrl">

          <p ng-bind-html="description"></p>

</div>


The code (note: should be enclosed in a <script> tag

var app = angular.module('myApp', ['ngSanitize']);

var _desc = '<b>this is</b> sample html being displayed;

 app.controller('myCtrl', ['$scope' ,function ($scope) {

                $scope.description  = _desc;

            }]);

Get a Querystring parameter in JQuery

 var customerId = getParamByName('id');

 console.log("ID: " + customerId ); // write out the value

  function getParamByName(param) {

          paramparam.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");

          var regex = new RegExp("[\\?&]" + param+ "=([^&#]*)"),

          results = regex.exec(location.search);

          return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));

}

Editing a sub-array in JQuery

If you've used complex array objects like FullCalendar, the you know that it's the subarray values that are mostly used. Here's an example of how to edit the subArray.

This defines the object as an object within an array.

var eventList = {
    events : []
};
eventList.events.push("IamCalvinBrown.com");

Adding a WebMethod to a .cs page

When you want code that can be called by JQuery inside your .cs page, you only need to add the [WebMethod] attribute.

Please note, the name of the method is erroneous, and this method returns no data. Have your function return a complex object (POCO), or a string. The Json below will deserialize it and return it to JQuery.

Namespace

using System.Web.Services;

Code

[WebMethod]

        public static string getSomeDataFromSomePlace()

        {

            try

            {

                // method that returns data from the DB, a webservice, etc

string _objectOrPlainText = string.empty; // clearly this won't return anything -- go fetch data here

            }

            catch (Exception ex)

            {

                log.Error("SalonProfile:getSalonAmenitiesAndDescription", ex);

            }


            string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(_objectOrPlainText);

            return json;

        }

Selecting an item by name in a dropdown in JQuery

<select id="clients">

 <option value="1" >John</option>

  <option value="2">Calvin</option>

  <option value="3">Adjo</option>

</select>

// the list above is named clients, so the code below will select the item by name
$("#clients option:contains('Calvin')").attr('selected', true);

Setting the default page in web.config

Google wants the first page of websites to work with a simple / . To enable your site to be search friendly it's always best to set the default page that you site will render. Below is an example of how to do this:


<system.webServer>
      <defaultDocument enabled="true">    <!-- this line enables default documents for a directory -->
         <files>      
            <clear/>     <!-- removes the existing default document list -->                
            <add value="login.aspx"/>     <!-- login.aspx is now the default document  -->                
            <add value="index.aspx"/>     <!-- 2nd default document in search order -->                
            <add value="iamcalvinbrown.aspx/>     <!-- 3rd default document in search order -->
         </files>
      </defaultDocument>
      <modules runAllManagedModulesForAllRequests="true"/>
   </system.webServer>