1,775 articles and 14,011 comments as of Tuesday, November 23rd, 2010

Tuesday, April 13, 2010

jQuery vs Webparts solution

Guest Author: Jason MacKenzie
Intelligence Among Us

As I mentioned in my last post, I had to come up with a simple way of fetching an employee’s phone number and allowing them to update it through SharePoint. I contemplated developing a web part that would interact with the HR system but with the length of time a deployment can take I thought that it might be simpler to use jQuery. This way I don’t have to develop and deploy any custom .Net code. I simply have to write some HTML and jQuery and embed that into the page.

A few caveats. Security is not really an issue here. There is no requirement to ensure that people can only update their own phone number. Although since there is a mapping between a user’s AD account and their HR Employee ID that logic could easily be handled in the web services if required. The other is the fact that cross-domain scripting is not supported so your HTML page will need to be on the same server as the web services.

The last caveat is that the page is hideous and logic is sketchy – this was only a POC to demonstrate a different approach to tackling these types of problems.

How the page works is that a user loads the page and is presente d with a textbox and a button. They enter their Employee ID into the text box and click the button. This uses ajax to call a .Net ASMX web service called EmployeeInfo which accepts the Employee ID in the form an integer and returns an Employee object.  We then simply render that on the screen, hide that button and show another one.  The user can then enter a new phone number in the textbox, click the button which calls the UpdatedEmployee Web Service.  This web service accepts the Employee ID and Phone Number and returns a Response object that has a property called ResponseStatus which we can check in our client code.

This first thing if of course to add a reference to our jQuery library which is stored in a SharePoint library.

<script type=”text/javascript” src=”<url>/jquery-1.3.2.min.js”></script>	

What follows is the HTML code which is simple – and hideous.

<div id="instructions">Enter Employee ID</div>
<div id="controls">
<input id="txtEmployeeID" type="text" />
<input type="button" value="Search" id="Button1" onclick="CallWebService('http://<url>/Service.asmx/EmployeeInfo', document.getElementById('txtEmployeeID').value, '')" />
<input type="button" value="Update Phone Number" id="btnUpdate" onclick="CallWebService('http://<url>/Service.asmx/UpdateEmployee', _employeeid, document.getElementById('txtEmployeeID').value, '')"
style="display:none;" />
</div>
<div id="loadingDiv" style="display:none"><img src="http://jaymoss/PublishingImages/ajax-loader.gif" /></div>
<div id="ResultSet"></div>	

It’s very straightforward. A textbox to enter the Employee ID and a button to request the employee information. Another button to submit the phone number back for updating and a few DIV tags to control formatting.  You can see  in the onclick events of the buttons that we are calling the same Javascript function and passing in different parameters.  Below is the code that int.eracts with the .Net web services.

I don’t want to spend too much time on the simple logic so I’ll focus on the Ajax piece.  All you need to do is call the AJAX function and pass in the correct parameters.  The url parameter is the actual url of your web service.   The data is returned in JSON.  More information on decorating your web services to be compatible with this format is located here: http://stackoverflow.com/questions/211348/how-to-let-an-asmx-file-output-json.

var data;

function CallWebService(url, employeeid, phonenumber)

if (phonenumber.length == 0)

{

data = “{‘employeeid’:'” + employeeid +”‘}”;

_employeeid = employeeid;

}

else

{

data = “{‘employeeid’:'” + employeeid + “‘, ‘phonenumber’: ‘”+ phonenumber +”‘}”;

$(‘#ResultSet’).attr(’style’, ‘display:none’);

$(‘#loadingDiv’).attr(’style’, ‘display:block’);

$(‘#controls’).attr(’style’, ‘display:none’);

}

$.ajax({ 

type: “POST”,

url: url,

contentType: “application/json; charset=utf-8?,

data: data,

dataType: “json”,

success: success,

error: ajaxFailed

});

}	

Since our web services accept parameters we pass them in the data parameter.  All you really need to know is that the format is {‘parameter’:’value’}.  Multiple parameters are separated by commas.  You can pass arrays as well which is well documented online.

The last two parameters are the function to be called if the call is successful and if it fails.  In our case the success function is creatively named “success” and the error function is called “ajaxFailed”  below are the functions themselves.

Side note:  I’m having a hard time concentrating on this post because I’m watching all the pre-fight hype of the GSP vs Dan Hardy fight.  This is going to be ugly.  Dan Hardy doesn’t have a prayer but I digress.  Update:  I can’t believe it went the distance.

function success(data, status)

{

hideLoader();

if (data.d['ResponseStatus'] == “Success!”)

{

alert(‘Employee Phone Number Successfully Updated’);

$(‘#controls’).attr(’style’, ‘display:none’);

}

else

{

$(‘#ResultSet’).html(data.d['EmployeeName'] + ‘ <br>
‘ + data.d['PhoneNumber']);

$(‘#txtEmployeeID’).attr(‘value’, ”);

$(‘#Button1').attr(’style’, ‘display:none’);

$(‘#btnUpdate’).attr(’style’, ‘display:block’);

}

}

function ajaxFailed(xmlRequest)

{

hideLoader();

alert(xmlRequest.status);

}

Data is the JSON object is returned where you can check the properties of the object returned by your web services.  Easy as pie!

Upload the HTML to the web server the web services reside on and you’re golden.  You can then use a simple Page Viewer Web Part to display your masterpiece inside SharePoint and your users will never be the wiser.

Obviously, there are many situations when a custom developed web part is required but my intention has been to demonstrate an alternative approach to accomplish a specific problem without writing custom .Net code.

Enjoy and all comments are always welcome!

Guest Author: Jason MacKenzie
Intelligence Among Us

Jason has been an IT professional for 12 years and has worked in a variety of roles from software development to managing business solutions for a large international automotive supplier. He has developed mission critical software solutions for the manufacturing industry and has experience in the government and educational fields as well.

Jason is a social networking enthusiast and is currently working as an independent SharePoint architect. Jason helps organizations with strategy and implementation guidance related to  architecture, governance, processes as well as hand-holding and facilitating a good group cry every now and again. Jason’s goal is to actively participate in the community and share what he has learned in order to help people and business leverage their investment in this critical platform.

 

Please Join the Discussion

15 Responses to “jQuery vs Webparts solution”
  1. Jay says:

    Nice work, lets publish more garbage on the internet for newbies to find. Lets not promote this garbage, if your going to write an article that has anything like:

    ‘Security is not really an issue here’

    or

    ’so your HTML page will need to be on the same server as the web services’

    you know its a major hack. People already have governance issues around SharePoint and custom development, lets not spread more bad practices. Your only doing the SharePoint community harm.
    This site has become a cesspool of bad practices, you can do better !

    • Paul Galvin says:

      Such a weird thing to say …

      Sure it’s a hack, but so what? The author took pains to hightlight the caveats and then provided the kernel of a solution.

      It would be more constructive to explain how to tighten up the solution than use words like “cesspool.”

    • Shereen says:

      I’ll second that Paul. Jay, I think we’d all be interested to hear your approach to this POC, keeping in mind the author’s intent of demonstrating an alternative approach to this problem.

      It’s not helpful nor constructive to point out flaws, but make no recommendations of your own.

    • eric says:

      Probably a disgruntled .Net developer that got let go from somewhere, but I digress.

      Caveats for a PoC were laid out, no qualms with that. Going into production, you would probably do some sort of LDAP lookup to ensure that the number entered corresponds to your number and proceed with the update if true like he said.

      Lots of great client side solutions provided on this website. If you are looking for GAC deployment and strict governance for Sharepoint applications, this is not the place to paruse.

  2. brunosworld says:

    Jay must be a hardcore purist programmer, and he has his opinions, and that’s ok. But shame on him to provide false information about this site by calling it a “Cesspool” of bad practices.

    The security issue would surely be handled within the governance documentation to make sure that this type of solution would not make it to production. The author was very clear about it’s implications and the decision is made by each individual person to use this approach or not. If my governance/company policy states that a user can only change her information and no one else’s, then I can’t use this. But if it doesn’t, and this solution helps, why not.

    There are tons of solutions on this site that aid the SharePoint community on a daily basis and just because someone does not like the way a solution is implemented, does not make any site for that matter a cesspool. That is the difference in the SharePoint community. A true SharePoint Community member would of looked at this solution and wrote a second article explaining the why and why not’s of implementing this solution and then would have tried to make it more secure, maybe follow some best practices, just like Paul said above me. A true Sharepoint Community member would of not bashed people’s work, but worked on improving it so everyone can benefit.

  3. Louis says:

    This specific example (updating employee information) would indeed probably not end up in production anywhere. Still, the intent was to demonstrate that you can do that without a lot of code, and it IS indeed possible to start from this example, add a more secure, authenticated web service, and end up with production code.

    Maybe there were not enough disclaimers. If you ever find a SP site where you can take all of the posted resources as-is and put them on any production server, please tell us.

  4. Every tool, project and/or application has its own requirements, and if this solution meets those requirements then it is just that, a solution. Jason pointed out, clearly, that this solution might not apply to everyone, and addressed the pros and cons. Articles here are often not about complete solutions, but rather piece parts which not only help to educate on how SharePoint is built as a platform, but also what the capabilities are and to further that knowledge and understanding so that people can apply the knowledge in their everyday use.

    I’m not going to take that comment and give it too much attention, but there’s something to be said for someone that brings nothing but negativity to the party. If you really see the discussions here as bad practices then maybe you should take some of that negativity and flip it around as a positive contribution. I’m sure we’d be all happy to read, discuss and contribute in a civilized way. Bashing an author who took time out of his personal life to share his answer to a solution is not the way to do it.

  5. Hmm…Jason mentions the caveats, and the fact that this was just a POC (”Proof of Concept”)…seems to me like a perfectly fine example of alternative approaches to a given problem.

    If you dont agree with these types of articles (those that tend more towards the “creative” approach…I have plenty of them myself)…fine, thats your right, and you can have your opinion…nothing wrong with that, but dont attack a community (yes, EUSP is more than just a “Site”, it is a community of people from many many different levels) based on such an obviously misinformed point-of-view.

    Open a dialog with us, express your concerns, let us know what you feel is innappropriate information shared to the community…I’m sure that any and all of us that have contributed in any way, or have learned something along the way, or have seen that “Aha!!” moment while reading an article or forum thread would be more than happy to answer any question you may have regarding the validity of the knowledge being shared out by EUSP.

    “Dont hate…Collaborate” :)

    - Dessie

  6. Matt B. says:

    Did I just read my favorite site is a “Cesspool”? /FACEPALM
    This is the same site that has brought you:
    (Well I was going to punch in a bunch of links but this sums it up very well)

    http://www.endusersharepoint.com/2010/04/14/best-of-eusp%E2%80%A6-and-a-few-of-my-own/

    It’s also interesting to see what is posted on the internet without ever identifying yourself… Anonymous blurbs w/o anything to back up the claims, is my #1 pet peeve of the interwebs.

  7. Jay says:

    You guys don’t get it, this passes for revolutionary development?

    Seriously, when did SharePoint turn into Microsoft Access? five years from now we’ll be migrating apps en-mass like we did converting access applications. All you business ‘IT’ guys who know nothing about enterprise development, love to hack around and cut / paste some JavaScript you’ve found on the web and know nothing about. Before long real devs have to support your crap, and not long after that the business is held hostage to change for fear of breaking brittle systems.

    The SharePoint community has attracted a whole bunch of people who don’t have any tangible IT skills, but who think that shoving some code into a page constitutes creating an ‘enterprise solution’, your still not adding any value.

    [Personal attack edited out by Mark Miller]

    OK, so I didn’t expand on my first criticisms enough. So here goes:
    1. This is still source code, how about you write articles on how this code can be managed throughout a proper SDLC.
    2. Security is everything in the enterprise, this means that being able to impersonate other users is a major flaw. Period. Secondly because security is a major issue, servers are isolated … for security … so a HR or ERP system is unlikely to be on the infrastructure as your MOSS instance, so assuming that cross domain scripting won’t be an issue is naive at best.
    3. You all people defend this article saying that there is no harm in letting this tripe get put onto the internet. But people will read this and think its OK. Just because the author took a great deal of time to write this article up doesn’t justify it’s value. It’s simple stuff and any web developer could come up with it (oh thats right, your all business people turned IT people for the extra money).

    You all probably wonder why IT people lock you out, it’s because you have no clue. Go become something useful, find another career, you all do a disservice to the IT industry and cause long term harm.

    • eric says:

      If you feel that way then this site and community is definately not up your alley. You’ve not been reading the proper blog for your area of expertise. This community is designed for end users and power users to build quick win solutions with client side scripting that generally, does not harm to the OOTB Sharepoint deployment. As such, there is no need for a full fledged SDLC process for a script that does nothing but alter CSS or convert literal text into HTML.

      While I can understand your concern and criticisms, your distain for the author and the site is unwarranted. If you would have stated those points in your initial post and not done it so condescending, we may have had a better discussion about the script and the process.

      Remeber the scope of the community here, this is not a .net/feature receiver/deploy to the GAC arena.

  8. Jay says:

    OK, so maybe cesspool was a little strong,

    articles like this add a huge amount of value:
    http://www.endusersharepoint.com/2010/04/08/moss-2007-css-and-you-the-non-developer-%E2%80%93-part-5-the-topnavigation-and-the-siteactions-menus/

    This article on the other hand does harm.

  9. This “discussion” is over. I will not tolerate personal attacks against members of this community. Jay’s responses have been nothing more than troll bait. End of discussion.

Trackbacks

Check out what others are saying about this post...
  1. Preparing for Hosted SharePoint 2010; Failures Don’t Faze Google; Mobile Social Networking…

    Top News Stories Web Hosts Prepare for Release of Hosted SharePoint 2010 (Web Host Industry Review) With…

  2. [...] week EUSP was accused of being a “cesspool of bad practices“. Rather than argue the point, I decided to fully embrace the concept of cesspoolism. I put [...]




Notify me of comments to this article: