ICodeFactory Labs

ASP.NET AJAX 4.0 Templates Simple Demo - Step by Step

by Sergio 27. November 2009 02:59

This quick step by step tutorial is made with Visual Studio 2010 beta2
and ASP.NET AJAX 4.0 Preview 6.
It is possible that some properties and/or methods will be changed in future versions, but so far this is the way to use client side templates in ASP.NET AJAX 4.0.

 

Downloads

First you should download appropriate software:

  1. Microsoft .NET Framework 4.0
  2. Microsoft Visual Studio 2010
  3. ASP.NET Ajax Library

Project

For your first project you should use web site or web project visual studio templates, create new project and add appropriate scripts to a project.

For this example I’ve created a new web site and added all the AJAX scripts we need to a folder named “MicrosoftAJAX” (look at the picture).

 

WebSiteProjectFiles

 

Also I have created a simple demo xml web service to be used from client side to read data for our template.

 

   1:  <%@ WebService Language="C#" Class="DemoService" %>
   2:   
   3:  using System;
   4:  using System.Web;
   5:  using System.Web.Services;
   6:  using System.Web.Services.Protocols;
   7:   
   8:  [WebService(Namespace = "http://icodefactory.com/", 
   9:     Description="Demo web service used by client side templates")]
  10:  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  11:  // To allow this Web Service to be called from script, 
  12:  // using ASP.NET AJAX, uncomment the following line. 
  13:  [System.Web.Script.Services.ScriptService]
  14:  public class DemoService  : System.Web.Services.WebService {
  15:   
  16:      [WebMethod(Description="Returns Demo Contacts data")]
  17:      public Contact[] GetContacts() {
  18:          Contact[] contacts = new Contact[3] {
  19:              new Contact(){ Id=1, Name = "John", Lastname="Doe" },
  20:              new Contact(){ Id=2, Name = "Joan", Lastname="Smith" },
  21:              new Contact(){ Id=3, Name = "Brad", Lastname="Forbs" }
  22:          };
  23:          return contacts;
  24:      }
  25:      
  26:  }

 

Pay attention that you have to set the ScriptService attribute so your web service can be used from JavaScript.

 

Finally we have to add some simple html (yes, pure html) file and import appropriate scripts:

  • MicrosoftAjax.js
  • MicrosoftAjaxTemplates.js

for AJAX client side libraries and

  • DemoService.asmx/jsdebug

for access to the xml web service.

 

   1:  <script src="MicrosoftAJAX/MicrosoftAjax.debug.js" 
   2:          type="text/javascript"></script>
   3:  <script src="MicrosoftAJAX/MicrosoftAjaxTemplates.debug.js"
   4:          type="text/javascript"></script>
   5:   
   6:  <script src="DemoService.asmx/jsdebug" 
   7:          type="text/javascript"></script>

 

We also need some styling on the page. Class ‘sys-template’ is used to hide empty table before data is bound from the service by using AJAX DataView client side control.

 

   1:  <style type="text/css">
   2:          /*Used to hide empty table*/
   3:          .sys-template
   4:          {
   5:              display: none;
   6:          }
   7:          /* Style of table that shows data*/
   8:          .table_style
   9:          {
  10:              background-color: Olive;
  11:              padding: 5px 5px 5px 5px;
  12:          }
  13:      </style>

 

Now, time for JavaScript that should load the data from the xml web service, fill the DataView object and bind the data to the html template.

 

<script type="text/javascript">
        // ASP.NET Ajax client side control - DataView
        var contactsView;
        
        // Triggers on page load
        function pageLoad() {
            // Create Contacts DataView
            contactsView = 
                      $create(Sys.UI.DataView, {}, {}, {}, $get("contactsBody"));

            // Load Contacts from web service
            DemoService.GetContacts(ContactsLoaded);
        }
        
        function ContactsLoaded(contactsData) {
            // Display data in Contacts DataView
            contactsView.set_data(contactsData);
        }
    </script>

 

The pageLoad function creates the DataView client side object and calls the xml web service to populate the object with data.

On successful service call the data is bound to the html with a simple call to the set_data() function.

 

This is how your template should look:

 

   1:  <table class="table_style" border="0" cellpadding="4" cellspacing="4">
   2:          <thead>
   3:              <tr>
   4:                  <th>
   5:                      Name
   6:                  </th>
   7:                  <th>
   8:                      Lastname
   9:                  </th>
  10:              </tr>
  11:          </thead>
  12:          <!-- tbody tag id is used to identify tag in DOM that are going to be
  13:               used by the DataView. Class is set to 'sys-template' in order to
  14:               hide empty table -->
  15:          <tbody id="contactsBody" class="sys-template">
  16:              <tr>
  17:                  <td>
  18:                      {{ Name }}
  19:                  </td>
  20:                  <td>
  21:                      {{ Lastname }}
  22:                  </td>
  23:              </tr>
  24:          </tbody>
  25:      </table>

 

<tbody> tag is used to become a template for the data in the DataView object.

DataView will change HTML with appropriate tags and generate table rows for every data row from the xml web service method call.

{{ Name }} and {{ Lastname }} parts will be replaced with actual data.

 

At the end you have your data.

 

DemoSite_Result

 

Hope this will help you start with the new templates. Web development is moving to client side and everyone should embrace the client side because of its many benefits, like responsiveness, bandwidth and UI patterns.

 

Demo Solution may be downloaded from our public download section.

Currently rated 4.0 by 3 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,

ASP.NET

FCKEditor with ASP.NET - Fix “The server did not send back a proper XML response error”.

by Sergio 7. July 2009 10:47

I like FCKEditor. Our company is using it on several projects, and it mainly works fine, it has a number of different functionalities and it integrates well.

Recently we integrated FCKEditor with an asp.net 3.5 web application. We wanted to allow the client to update some contents on the web site and upload/manipulate images, but we faced a strange exception that stated:

The server didn’t send back a proper XML response. Please contact your system administrator.
XML request error: Ok (200)

 

xmlrequesterror_image1

Response text looked scrambled and messy.

Our first reaction was to search for the same bug on net, but after a few days I did not find anything barely useful!

That’s about when I realized I’ll have to investigate it by myself.

First of all I supposed I should blame some response mime type or format, so I dived into the FCKEditor project source code and found a class named XmlResponseHandler.

This class is used to clear the response object, set the content encoding and content type.

It all looked well. It was time to put some break points and investigate what is going on there.

I monitored two methods: SetupResponse and SendResponse.

private static void SetupResponse( HttpResponse response )

{

// Cleans the response buffer.

response.ClearHeaders();

response.Clear();

// Prevent the browser from caching the result.

response.CacheControl = "no-cache";

// Set the response format.

response.ContentEncoding = System.Text.UTF8Encoding.UTF8;

response.Charset = "utf-8";

response.ContentType = "text/xml";

}

public void SendResponse()

{

SetupResponse();

Response.Write( Xml.OuterXml );

Response.End();

}

Let’s put some break points and check what is going on while looking for the xml response from the server.

code_with_break_points_image2

My attention was drawn to data.

xmldata_image3

SendResponse method has a well formed xml. Let’s go further through the code.

Oops!

The server didn’t send back a proper XML response. Please contact your system administrator.

XML request error: Ok (200)

 

The same error again. Good. That means it is not about the data. Response looks like it is scrambled or packed when it comes to the client side!

That is a clue. Let’s investigate an interesting property of the Response object. It is the Filter property.

Response.Filter is a stream that is used to process data before it is sent to browsers, so if you, for example like to convert all cases to upper this is the place for your custom stream.

I investigated that property and found its value interesting.

deflatestream_image4

There was a DeflateStream object. This means response is compressed by server and sent to client as a compressed stream. This is why I got and strange encoded characters as error.

Fix was easy. I added one line of code:

Response.Filter = null;

private static void SetupResponse( HttpResponse response )

{

// Cleans the response buffer.

response.ClearHeaders();

response.Clear();

response.Filter = null;

// Prevent the browser from caching the result.

response.CacheControl = "no-cache";

// Set the response format.

response.ContentEncoding = System.Text.UTF8Encoding.UTF8;

response.Charset = "utf-8";

response.ContentType = "text/xml";

}

Build the solution and run it again. It works.

It was simple fix, but a very hard one to find. What is most amazing for me is that it was not found by other members of the community so far. I hope this article will help. Does it?

Currently rated 4.8 by 4 people

  • Currently 4.75/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

ASP.NET

UAC Revealed ~ .elevation of rights from .NET as commonly misunderstood.

by Sergio 8. June 2009 09:19

Recently we had a project that involves impersonification of windows users.

Idea was to create a tool that will allow non admin domain user to start single executable that requires administrative rights without need to add domain user to administrators group.
So, we were planning to create command prompt tool that may process parameters, impersonate some other user (administrator) and starts another process with new user’s credentials.

We made a small proof of concept and it all worked well. Nice, I sad, let’s test it with Vista’s User Access Control. Whoops!

Newly started process, starts as admin user, but without elevated rights. That means user is administrator, but run with rights of regular user!

So we got “this process needs elevation” error in console window.

After some investigation on internet we found ProcessStartInfo.Verb property as point of interest in this case.
According to number of articles, you just need to set this property’s value to ‘runas’ and new process will be started with elevated rights. As if.
This approach would not help you in this case. Actually there is no solution for UAC!

We contacted Microsoft’s forums, and after number of posts and responses we discovered the awful truth.
There is no way to start another process from .net code, impersonate another user to execute that code and elevate rights for that user.
Actually there is no way to do it with UAC enabled. It is constraint of UAC itself. UAC will not allow you to do this.
Microsoft claims that this is security measure, but in my opinion it does not have too much sense since my code already knows administrator user’s credentials!
So, what kind of protection is this anyway?
Next thing that was really strange to me is why so many articles claim opposite?
(Take a look at: http://victorhurdugaci.com/using-uac-with-c-part-1/ for example.)

Problem is that there are some administrative users that are not controlled by UAC!
Built in local administrator user or build in domain administrator user are not constrained by UAC.

This means that you may start another process from your .net code, impersonate built in administrator user and new process will start elevated!
So this code snippet:

ProcessStartInfo processInfo = new ProcessStartInfo();
SecureString securePassword = new SecureString();
foreach (char ch in “testpass”)
{
securePassword.AppendChar(ch);
} // foreach
processInfo.UserName = “administrator”;
processInfo.Password = securePassword;
processInfo.Verb = “runas”;
processInfo.FileName = @”c:\windows\system32\cmd.exe”;
processInfo.UseShellExecute = false;
Process.Start(processInfo);

Will run cmd.exe elevated on Vista, because this user is not run as regular user, but as full rights administrator!
But, if you try to use any other member of administrators group as as new process user it will not work!

Unfortunately it has been an ‘show stopper’ for our project. Too bad.

By my first investigation it will  be possible by default on Windows 7! Now, that is interesting.

I wonder did we found a bug in UAC design or .NET implementation? Maybe. The World will know;-)

 

Currently rated 4.4 by 7 people

  • Currently 4.428571/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

.NET

Test Driven Development ~ Yes or No

by Sergio 24. May 2009 18:24

Currently as being in Germany and working on client's site I met an interesting project.

Product that our team is working on with the client is developed on TDD practices.

NUnit, CruiseControl.NET and NCover are used to support development.

I now wonder why TDD is not used more on other projects. There are a number of common reasons people exposes.

“It takes too much time to write tests. I code faster without it.”

This is I guess number one complaint voiced by developers. It is untrue. And it is simple.

Many people view testing of any sort as something that happens at the end of a project. And it is somehow true, but not completely.

It is more related to acceptance tests for example. If you try to add unit test at the end of project, you will fail,

but if you use "pay as you go" logic and start with tests at the beginning, you will get solid, tested code, and will definitely have less bugs.

This means that you will not produce 2 lines of code daily at the end of project just because you are searching for an tricky bug.

This is especially true for "heavy to debugg" issues in nearly finished projects when deadline is so close that you feel dizzy.

There are a number of other excuses for not using TDD, but this one is somehow first one to beat. 

Currently rated 3.0 by 3 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,

State of Mind