Binding a KendoUI ComboBox to a remote datasource

In .NET land, you can use WCF or Web API for making a web service. I went with WCF because it was “what I ‘knew’ but I will be experimenting with Web API just to become more knowledgeable. The biggest pain in the butt with WCF is figuring out the right items to put into the web.config file! It didn’t help matters that I wanted a REST-like setup which isn’t how WCF is set up to do out of the box. After a lot of trial and error, I got it working. Here’s how.

The Web Service Setup:

  • Add a WCF Service Application to your Visual Studio solution. My Visual Studio solution contains 3 projects: main .NET app, one project for unit testing, and the 3rd was the service application.
    • Add all necessary references to this new project. In my case, I had to add my .NET app’s DLL as a reference since I was making use of classes referenced there.
    • I also had to re-add System.Data.Entity to this new project but YMMV. Read the error output when you compile the new project and act accordingly.
    • If you added a WCF Service Library instead of a WCF Service application, you *might* need to change the project’s properties to make sure the target framework is set to (in my case) .NET 4.0 instead of the default .NET Client Profile.
  • If you want to be able to invoke your URLs via the browser (HTTP), you’ll have to make some changes to your interface & implementing class.
    • Add [WebGet] or [WebInvoke] decorations to your service implementation. I went with [WebInvoke] for flexibility.
    • Implement your interface and add the [WebInvoke] property as well but specify some additional attributes. Here’s what mine looked like: [WebInvoke(UrlTemplate = “Users/{id}”, Method=”Get”,ResponseFormat=WebMessageFormat.Json,BodyStyle = WebMessageBody.Bare)]
      • UriTemplate – allows you to specify the URL to invoke your method! So, I could do something like http://serviceUrl/Users/1. Make sure that the value inside the curly braces matches the parameter name exactly.
      • Method – I went with GET since I was primarily just retrieving data FROM the service. You can specify other types there e.g. “POST”, etc.
      • ResponseFormat – I went with JSON for flexibility. The only other option is XML.
      • BodyStyle – I went with bare becayse I wanted the returned data to be returned as-is.
    • Please note if you are expecting to pass parameters to your methods which will be invoked via HTTP, you will need to make those parameters of the string type. If you don’t, you’ll get an exception message. If you get this message,it’s actually a good sign that you’re on the right path! It was for me, anyway. :)
    • Open up your WCF Service Application’s web.config file and make the following changes
      • Create an <endpointBehaviors> tag like this: <endpointBehaviors><behavior name=”blah”><webHttp/></endpointBehaviors>and stick that into the <system.serviceModel> tag.
      • Inside the <system.serviceModel> tag, create a <services> tag like this: <services></services>
      • Inside the <services> tag, create a <service> tag like this: <service name=”NameSpace.ImplementingClassName” behaviorConfiguration=”MyServiceBehavior”></service> where ImplementingClassName means exactly that: the name of the class that implements your interface.
      • Inside the <service> tag, create an <endpoint> tag like this:<endpoint address=”” binding=”webHttpBinding” behaviorConfiguration=”blah” contract=”NameSpace.InterfaceName” /> where InterfaceName means exactly that: the name of the interface.
      • Make sure the <endpoint> behaviorConfiguration value matches the behavior name value put into the <endpointBehaviors> tag.
      • Inside the <serviceBehaviors> tag, add a “name” attribute to the <behavior> tag and make sure the value matches the behaviorConfiguration value specified in the <service> tag.
      • If you’re connecting to some DB, don’t forget to add your connection string inside the <configuration> tag.
      • At this point, you probably want to launch the service to give it a whirl. You should open up the service in a browser and be able to invoke your methods following the UriTemplate you specified.
    • I really hope my word salad makes sense. I will attempt to put up the web.config file so you can see what it looks like. Of course, you’re free to tell me how much I suck as writing tutorials as well. This is really more of a loosey goosey guide for my benefit mostly. :)

If you’ve come this far, you have a working service which you should test out by doing something like this: http://localhost:YYY/MyService.svc/Users/1 and since you specified the output of that method to be JSON, you should get a valid json response. You can verify the validity by pasting the output into JSONlint.com. Note that IE will try to download a file since it can’t display it. Use Firefox or Chrome to see the output directly in the browser.

The KendoUI ComboBox Setup:

Once I confirmed my web service was returning the correct data,I felt confident moving to this part of the problem. I’ve been used to working with the MVC wrappers for KendoUI widgets so there was a bit of a learning curve switching to the HTML/JS version. After much trial and error, I figured out the exact incantation which allowed me to use my remote datasource.

So, if you have a KendoUI combobox that needs a remote datasource and your remote datasource returns JSON, then your datasSource declaration should like similar to this:

dataSource: {
    type:"jsonp",
    transport:{
        read:{
            url: "http://serviceUrl/Service.svc/Users/All"
        }
    },
    error:function(e){
        console.log(e)
    }
}

Hope this helps someone.

Code quality

This developer’s work is never ‘done’. Despite sending off my project into Phase 1 of pilot testing, I am constantly worried that some showstopper will be discovered. To that end, I’ve taken it upon myself to test as much as I can; which is learned behavior from my coursework. I always worry about efficiency and as new features are added, I am making a conscious effort to not repeat myself and redactor where it makes sense.

As a relatively new C# developer, I’m constantly learning new ways of doing things. I recently got ReSharper installed on my workstation and I’ve already seen changes to how I code. In fact, thanks to ReSharper’s comforting presence, I was able to refactor some awful code I’d written in way less time. :)

Not sure where I was going with this lost but TL:DR -
(a) test, test, test your code.
(b) there’s always a better mousetrap. Replace yours if it makes sense to do so.

Adding a new column with contextual buttons to an ajax grid (KendoUI)

I recently had to add a new column to my KendoUI ajax grid which would have buttons representing actions possible on the row item based on the status of the row item. In my case, the row items were forms that were submitted which could have any of these actions possible: Approve/Reject/Remove/Create. This new column needed to have any combination of these buttons present based on the status of the row item and the role of the person viewing the list. So, an Approver could be looking at that list and see “Approve” and “Reject” buttons for newly submitted forms or no buttons at all for forms that have had an action (Approve/Reject) taken. Another role (Actor) could be viewing the list of form submissions and have “Create” present on forms that have been approved or “Remove” for forms that haven’t had any action taken. Simple enough, right?

Well, I started out using custom grid commands but it wasn’t the right solution for me because I needed the buttons to be present or absent based on the row object’s state. With the grid commands, the buttons would be present all the time. With the custom commands, it was trivial to get access to things like the row item ID and perform client-side validation. View an example of a custom command using JavaScript on Telerik’s website. I have a bare-bones version for MVC as a gist.

To add the new column to my ajax grid, I simply did this:

columns
    .Template(@<text></text>)
    .ClientTemplate(
    "# if (is_approved == 2) { #" +
        "<button onclick=\"clickMe('#=param1#','#=param2#');\">Approve</button>" + 
    "# } #"
    );

Where is_approved is an attribute of my Form object which I can now use to display which buttons when & where I want! Now this is pretty easy when you’re dealing with simple attributes in your object e.g. primitive datatypes like ints, strings, etc.

For part of my project, I needed to have the buttons clicks trigger an action based on the content of the one of the form object’s attributes which was a list of objects. With the custom command, it was as easy as accessing the name of the list of objects from the dataItem object [see below]

var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
//dataItem.object_list;

When I switched away from the custom command, I had to think of a new way to pass my list of objects as a parameter for the clickMe function referenced earlier and I instantly thought of making the list of objects into a JSON array! My plan was to add another attribute to my Form Object Data Transfer Object (DTO) which would be a string that could be parsed into JSON when received on the client.

To get started, I declared the ToString method in my Form Object DTO and wrote this:

public override string ToString(){
    return "[\\\'" + id + "\\\',\\\'"  + state + ""\\\']";
}

This ToString method when invoked would cause the object to be displayed as: [‘8′,’Approved’].sidenote: that’s not valid JSON but I did this to enable the string representation of the list of form objects to be displayed properly on the page.

Then, I created a list of strings where each element of the list would be the string representation of the form object and converted the list of strings to a massive string by using the String.Join method.

string massivestring = "[" + String.Join(",",objectList) + "]";

At this point, if I had a list containing 2 form objects, it would become a string that looked like this: [[‘4′,’New’],[‘5′,’Approved’]]. Again, this isn’t valid JSON but I did this to prevent parsing errors.

So, once clickMe got invoked (when the user clicks on the button), the string representation of the form objects was converted to a valid JSON string (inside the clickMe function) by replacing the single quotes with double quotes and I could do whatever I wanted to the JSON object.

function convertStringToJSON(str){
    var re = /'/g //the g makes the regex apply globally instead of just the first occurrence of the ' character
    var newStr = str.replace(re,"\"");
    try{
        var jsonResult = JSON.parse(newStr);
        return jsonResult;
    }catch(e){
        return JSON.parse("[]");
    }
} 

Hope this helps someone! Lord knows I’ve stood on the backs/research of others and I’m more than happy to do a little bit for someone else. Enjoy.

KendoUI and MVC

For a work related project, I’ve had to learn to use a tool by Telerik called KendoUI. KendoUI is a framework for building widgets (very simply put). For a .NET MVC app I am building, I ran into an issue where I needed to modify the datasource on the server side. I didn’t really find any documentation online on doing this server side but thanks to Intellisense, I was able to discover the presence of an enumerator on the DataSourceResult. A few Google results later, I was able to iterate through the enumerator from the DataSourceResult and directly modify items that the Kendo Grid would display on my View.

If you must know, it was code for displaying a changelog for the item being viewed; I needed to display a user-friendly version of items like the field name and values where I was storing the ‘raw’ values in my logging table such as the item ids and the database field names.

The sourcecode is up as a gist because the WordPress.com code formatting thing sucks. :(

 

 

 

 

LinkedIn Launches Volunteer Marketplace, Adds Unpaid Work To Its Recruitment Platform, Posting For A Fee

Originally posted on TechCrunch:

LinkedIn, the social network for the working world, has gained a reputation as a place to go when you’re looking for a job, or a person to fill a vacant role. Now the company is expanding on that idea with the launch of a Volunteer Marketplace — a place people can go to post and look for unpaid positions. The site is live now, with openings ranging from asking for help with web development at nonprofits like Hire Our Heroes through to a request for a voluntary board member (with fundraising experience) at the United Way of San Luis Obispo.

But even if the marketplace will focus on unpaid work and is currently limited to U.S. 501c3 nonprofits, posting in the marketplace will not be free: I went through the process of posting a job on the marketplace a moment ago, and in the UK (where I am based and LinkedIn automatically…

View original 651 more words

WHY YOU SHOULD BE WORRIED ABOUT NIGERIA’S ANTI-GAY LAW | BY AYO SOGUNRO

Originally posted on Ayo Sogunro:

Before You Proceed

Two guiding premises underlie this article. The first is this: this article does not support or reject homosexuality as a sexual orientation. The purpose of this article is not to plead the cause of homosexuality as a lifestyle—there are many who have done that, and this is no place to rehash the argument. This article instead recognises the existence of homosexuals as a distinct sub-culture—a minority, if you prefer—within a larger culture, and is concerned, instead, about a philosophy of hate and prejudice against this minority which is about to be set in motion in the guise of legislation.

The second premise is this: that you, the reader, are not entrenched in some belief system that supersedes any attempt at reason. And so, this article is not for those who rely on prejudice, and by “prejudice”, I mean the bigots, the fanatics, the fundamentalists and all those…

View original 1,984 more words

Dev links #3

  1. CSS guide from InsertHTML.com
  2. Technical limits of Google Fusion Tables (max. 5 layers)

Aside: I’m unhappy with the current incarnation of DawgTransit. It is the very definition of hacked together and it was my very first “big” web application. So, in the time honored tradition of developers everywhere, I’m embarking on a re-imaging/overhaul of the site. I *just* got started so I don’t have anything major to show. 

The first change to happen will be an overhaul of the homepage. Based on the stats (h/t StatCounter.com), most people arrive at dawgtransit.com by searching for specific bus routes which often leads them directly to the specific bus route page. So, the screenshow below is an example of an interface that will allow the focus to be on the bus routes.Image

 

For displaying information about the routes, I would like the map to be the focal point of the page and I’ll be working on some ideas for that. 

Follow

Get every new post delivered to your Inbox.

Join 1,075 other followers