IamCalvinBrown.com a Blog Site

Code Examples, Consulting Advice and lots of other cool things

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]
      void getContentInJsonFormat(string id);
}

What the WCF Service looks like:
public class RestService: IRestService
{
     [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle =WebMessageBodyStyle.Bare)]
    public void getContentInJsonFormat(string id)
    {
          string workingString = "some random text or object";  // you should actually put a Json string here or create a class to return

         HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
         HttpContext.Current.Response.Write("[" + JsonConvert.SerializeObject(workingString) + "]");
    }
}

How to call this service:
(when hosted) http://www.IamCalvinBrown.com/restservice/IamCalvinBrown/123
(locally) http://localhost:3242/RestService.svc/IamCalvinBrown/123

The url is unique to your website, so please don't use port 20949 unless it's actually your sites port. RestService is the name of the WCF service. 123 is the input parameter.

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>

How to 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();

        }

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, " "));

}

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>