ASP.NET: Add a serial number in GridView
1. Add a template field tag in your GridView markup
2. Add Container.DataItemIndex + 1 code
3. Enjoy






Happy coding!

Advertisements

Couple of articles ago, I did write about new dynamic type feature in C# 4.0

Some what related to the dynamic is the ExpandoObject.

Yep I know it does sound like an eight armed sea creature, but don’t worry – its just an object that comes with .NET 4.0. Dont know what Microsofties think whenever they come up with such a name.

MSDN says, ExpandoObject “represents an object whose members can be dynamically added and removed at run time.”

Add a property:

sampleObject.test = "Dynamic Property";
Console.WriteLine(sampleObject.test);
Console.WriteLine(sampleObject.test.GetType());

Output:

// This code example produces the following output:
// Dynamic Property
// System.String

Remove a property:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
((IDictionary)employee).Remove("Name");

Associate and call events dynamically:

class Program
{
static void Main(string[] args)
{
dynamic sampleObject = new ExpandoObject();

// Create a new event and initialize it with null.
sampleObject.sampleEvent = null;

// Add an event handler.
sampleObject.sampleEvent += new EventHandler(SampleHandler);

// Raise an event for testing purposes.
sampleObject.sampleEvent(sampleObject, new EventArgs());
}

// Event handler.
static void SampleHandler(object sender, EventArgs e)
{
Console.WriteLine("SampleHandler for {0} event", sender);
}
}

Output:

// This code example produces the following output:
SampleHandler for System.Dynamic.ExpandoObject event.

Cons of ExpandoObject:

Though the usage of dynamic keyword seems quite interesting; but it could become very hard to catch errors. For instance, a new developer who doesn’t know much about it adds a property that was not required; the compiler won’t show an error – only, probably runtime will. This means, typos won’t be picked up during compile time because you can just declare about anything anywhere.

Plus, this code gives an impression that it type-safe, which it clearly, is not.

Even the tools like ReSharper would not be able to grab that error.

Anyway, you may also want to look into the unusual uses of Expando Object.

Happy coding!

How to view arabic in Console apps?

You cant;

The Console applications do not support Arabic Text for input and output due to a limitation in the operating system console support. MSDN

Reason might be because Console is not set to handle multi-byte character-sets or 16-bit Unicode.

So, how to view Arabic numbers in WinForms or WebForms?

It seems that generally Arabic numerals are used in English. Though, the Date controls are culture-aware, the numbers are not 🙂

This means you will have to convert the numerals to arabic manually, at least so it seems.

So, you can write an extension method to achieve that:

public static string ToArabicEx(this string str)
{
if (!string.IsNullOrEmpty(str))
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("ar-AE");
string[] nativeDigits = Thread.CurrentThread.CurrentCulture.NumberFormat.NativeDigits;

return str.Replace('0', nativeDigits[0].ToCharArray()[0])
.Replace('1', nativeDigits[1].ToCharArray()[0])
.Replace('2', nativeDigits[2].ToCharArray()[0])
.Replace('3', nativeDigits[3].ToCharArray()[0])
.Replace('4', nativeDigits[4].ToCharArray()[0])
.Replace('5', nativeDigits[5].ToCharArray()[0])
.Replace('6', nativeDigits[6].ToCharArray()[0])
.Replace('7', nativeDigits[7].ToCharArray()[0])
.Replace('8', nativeDigits[8].ToCharArray()[0])
.Replace('9', nativeDigits[9].ToCharArray()[0]);
}
else return str;
}

Usage:

for (int i = 0; i <= 9; i++)
{
Response.Write(strLineBreak + i.ToString().ToArabicEx());
Response.Write(strLineBreak + DateTime.Now.ToString().ToArabicEx());

}

Happy coding!

While sitting in just another meeting with another lead developer, I was told that they are using UpdatePanels with jQuery just because they read it somewhere over the internet.

I threw them with PageMethods alternate solution; (although it can be script’ize using ScriptManager.RegisterClientScriptBlock), especially when used with jQuery. To my bewilderment she did not know about the PageMethods; and I was gladly eager to tell her more! (0:

It is not “just another” way of interacting with server; its reliable, and communicates in the shortest forms possible – lowest client/server data exchange; plus, the response by the WebMethod gives the freedom to manipulate and interact with the HTML the way we want.

Its a static method that is exposed using WebMethod attribute; and is called using Javascript. Follow the following steps:

1. Set the `.EnablePageMethods` property of ScriptManager to True.

2. Mark the static method with WebMethod attribute
3. Call method using javascript. Like:

PageMethods.MyMethod(
Arg1,
Arg2,
ArgN,
Incase_Success/*Optional*/,
Incase_Failure/*Optional*/);

function Incase_Success(results/*Returned by the method call*/ , userContext, methodName) {
alert(results);
}

function Incase_Failure(errors, userContext, methodName) {
alert(errors.get_Message());
}

The PageMethod calls the web method MyMethod with the defined number of arguments, and upon successful completion of the function call, it redirects the response to SuccessFunction or FailureFunction according the status that it has.

When calling the method, the first N parameters in the PageMethods call matches the parameters of the class method. In this example we have only only one parameter.

There are two optional parameters that takes the names of the methods to be called in case of failure or success. The callback for success, followed by the callback for failure.

Following is a quick comparison between UpdatePanel, and PageMethod from Encosia.

PageMethod data exchange,

An important point to note, is that most of us relate the the term web service with SOAP and XML. But in this case ASP.NET AJAX doesn’t use SOAP and XML.

Btw, this article is a MUST READ!

Happy coding!

Waiting at Dubai airport, for the connecting flight back home to Karachi… reaping the fruits of last-minute-flight-schedule sown(read: reserved) by my admin department! I have a tweltve hour wait for the next “connecting” flight! Yep, those who have been-there-done-that know very well about such an exhausting experience.

With all the “unlimited” time that I have, I opened my ‘Blogs’ folder… searched through my incomplete blog related to aspect oriented programming.

I have been working over it off an on, adding multiple angles of understanding so that it would be easiest to digest.

Though this has been a pretty old subject now; but some once again was dragged into the technical argument among peers. Quite a couple of hours ranting about what is it, what it does, and when to use. On heading home I thought its a “must blog” (0: so here it is.

To understand the aspect oriented programming, it is important to understand the term aspect. Aspect generally means an area of particular interest/concern; a much widely used term that is the jist of AOP is cross cutting concerns.

So what actually is a “cross cutting concern”?

To understand that, lets discuss a small example. Consider following set of classes:

1. Products – This class add/update the products
2. Customers – This class maintains customers
3. AuditTrails – This class maintains the audit trail
4. UI – This class renders the UI
5. Logger – Logs the activity in a text file

A business “concern” could come up to implement a policy that would validate the length product name, and it should not be more than 20 characters. Or…

  • A system level concern may be to provide logging in all of the modules.
  • Another concern could be to ensure a database transaction should not result in loss of data – across all the data layer related modules.
  • Or that authorization is required to perform certain operations; for instance authenticate/authorize for Funds Transfer in case of a banking application.

The above are called “concerns” – specific area of interest; and since these concerns “can” span across the application(in case of logging, for instance), so this is how it gets the name “cross cutting concern”.

A couple of practical scenarios where AOP could be utilized:

  • Logging invocation and public property access, as discussed earlier.
  • Handling exceptions in a structured manner
  • Validating parameter values; function parameters.
  • Caching method results and property values
  • Authorizing method and property requests
  • Measuring target method performance

Typically, if you want to enforce a behaviour across many different classes in a transparent way, AOP comes a best practice.

If you are a Java guy AspectJ might interest you; and for .NET/C# a good open library is Aspect.NET. Though Microsoft does provide Policy Injection Application block which can be utilized with Unity (Dependency Injection Framework – DI) application block that I reviewed sometime earlier in my posts.

Terms that are used in AOP:

From Wikipedia:

Cross-cutting concerns: Even though most classes in an OO model will perform a single, specific function, they often share common, secondary requirements with other classes. For example, we may want to add logging to classes within the data-access layer and also to classes in the UI layer whenever a thread enters or exits a method. Even though each class has a very different primary functionality, the code needed to perform the secondary functionality is often identical.
Advice: This is the additional code that you want to apply to your existing model. In our example, this is the logging code that we want to apply whenever the thread enters or exits a method.
Pointcut: This is the term given to the point of execution in the application at which cross-cutting concern needs to be applied. In our example, a pointcut is reached when the thread enters a method, and another pointcut is reached when the thread exits the method.
Aspect: The combination of the pointcut and the advice is termed an aspect. In the example above, we add a logging aspect to our application by defining a pointcut and giving the correct advice.

Bear in mind, you will pay a performance penalty if you’re injecting behaviour into many fine-grained objects in your application, so you may want to consider if having this feature is worth the performance trade-off. Fortunately, one of the benefits of AOP is that you can enable/disable pointcuts fairly easily, which would allow you to measure the performance difference. If interested in knowing the code level implementations, here is a good article to start with.

Happy coding!

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!

Briefly, the solution works as follows: the crawler finds a pretty AJAX URL (that is, a URL containing a #! hash fragment). It then requests the content for this URL from your server in a slightly modified form. Your web server returns the content in the form of an HTML snapshot, which is then processed by the crawler. The search results will show the original URL.

Source: http://code.google.com/web/ajaxcrawling/docs/getting-started.html

http://toughestdeveloperpuzzleever.com/ – Second puzzle with 100 levels, no one has completed it yet! It started two days ago, May 31st.

I’m stuck at level 7 – looping around!

Following are the answers till 9 😦

Note that, I am sharing the first few puzzles in case some one is “stuck” on a level and try a different one. Please do not scroll down otherwise you will not be able to enjoy the pleasure of such puzzles.

Level 0. Step1.aspx

Level 1.
Clue: Try step2.aspx
Answer: step2.aspx
————-
Level 2.

Clue: See step3.png
Answer: stepthree.aspx
————-
Level 3.
Clue: Parse the morse code
Answer: four.aspx
————-
Level 4.

Clue: type the grayed characters
Answer: fiveisit.aspx
————-
Level 5.

Open source:

<img alt="Come on and get in the boat, fish! Come on and 

get in the boat, fish fish!" src="Assets/Images/strongbad.png" />



Passphrase =   










i
5

Clue: google Strong bad email, open hrwiki article, goto number 44
Answer: lures & jigs

————-
Level 6.

[HttpException]: The file ‘/lasteasyone.aspx’ does not exist.
Clue: Open source code
Answer: http://toughestdeveloperpuzzleever.com/tdpe2/Level1.aspx –>

————-
Level 7. Dont ask! I’m stuck 😦 see the picture above.
Clue: Tried, subtracting red ones from the black ones, addition, ‘bookkeeping’ etc etc.
Answer: Know, and let me know!

–EDIT–

Got the answer already :); rotate the image upside down, subtract red ones from the black ones; you get 5537. Rotate back the number akin to the original numbers of the image, it’d give you LESS (5537) – Turn the “less” upside down to see 5537!

Level 8.
(ruby – ru) + (foxpro – po – fox) + (python – p – t – (hay – a)) + s + (delphi – phi – el) + (java – va – j) + (ugg + h – g) + te + r + ?

Combining this gives: by r on s d a uh te r
Clue: Google for Byrons daughter
Answer: Ada Lovelace

Level 9.

Content:

Clue:The image “view- source:http://toughestdeveloperpuzzleever.com/tdpe2/Assets/Images/puzzle.png” cannot be displayed, because it contains errors. Save the .png on your desktop as .txt, open the file.  

Answer:http://toughestdeveloperpuzzleever.com/tdpe2/ThatsNotAKnife.aspx Important to note, is that don’t forget the keep track of the “Clue” tag in all of the pages, I believe it will lead some where.

Lets move on! 🙂

Why JSON? One word: Simplicity.

More than one word: JSON is simple, simpler than Xml. I am big fan of Xml, and that makes me a love XPath as well. But this does not mean that I am against JSON or otherwise. While on my way back home the other evening, this guy who works in the IT department of one of my customer, where I was for the project implementation. While he was talking to “his” friend(colleague, probably) about JSON and Xml, and if Xml is there then why would you ever use JSON? I was sort of magnet’ically attracted to the discussion and eventually became the part of it. So, here I thought I should add my two cents of understanding of how and where I would use either and what would be the use case.

Xml is more “documented” oriented, has its own defined format; you may use Xml in cases where structured documents are required – and that with a large amount of data. While JSON is more like “data oriented”, which makes JSON handy for lightweight data exchange.

The purpose of JSON and Xml may be the same – data exchange; but the usage scenario for each is different. For instance you cant use a mallet, where a ball-pein is required.

“Ajax is a technique used for building interactive web applications that provide a snappier user experience through the use of out-of-band, lightweight calls to the web server in lieu of full-page postbacks. These asynchronous calls are initiated on the client using JavaScript and involve formatting data, sending it to a web server, and parsing and working with the returned data. While most browsers can construct, send, and parse XML, JavaScript Object Notation (or JSON) provides a standardized data exchange format that is better-suited for Ajax-style web applications.” – Writes Atif Aziz

JSON is more handy as compared to Xml when there a browser-server communication is desired. Plus its,

  • Similar to Xml human/machine readable format
  • Both has support for Unicode
  • “Self-documenting format” – that is, describes the structure, fields, and values
  • Mostly used in cases where you have to maintain a list, or arrays, or trees, or records.

This could mean that JSON may become handy and lightweight way of data exchange if you think about how to use it within jQuery based AJAJ calls.

Some of the things that people take as benefit is that, to avoid name conflicts Xml has namespaces; while in JSON there is no namespace; but the URI that you fetch the JSON document from implicitly becomes the namespace.

With Xml you have to think ‘DOM’ically; but in JSON the data is plain, simple and easy to read.

JSON does not support data validation; is not extensible.

So, conclusion – whatever you use, choose it based upon what is required.

“JSON is a data format, but one which is more naturally fit for browser data consumption. JSON is a subset to JavaScript, and by structuring a data payload as a JSON response, you are effectively bypassing the need to parse an XML document in a browser to get to the actual data. JSON uses a stripped-down syntax compliant with the native JavaScript interpreter provided on all browsers. Access and navigation to JSON data is done through the same standard JavaScript notation used to access string, array or hashtable values in a typical JavaScript application” – Regina Lynch

So if you do like JSON, chances are that you would like the YAML.

References and must reads:

Should you come across a scenario where you want spawn threads from within a loop, you can have a quick two options:

Option 1: Use ThreadPool.QueueUserWorkItem

Depending on the size of the job to be processed, I always admire the ThreadPool.QueueUserWorkItem; this creates a handy pool of threads, and execute the process upon request whenever a thread is idle’ly availble in the pool.

using System;
using System.Threading;
public class Example {
public static void Main() {
// Queue the task.
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));

Console.WriteLine("Main thread does some work, then sleeps.");
// If you comment out the Sleep, the main thread exits before
// the thread pool task runs. The thread pool uses background
// threads, which do not keep the application running. (This
// is a simple example of a race condition.)
Thread.Sleep(1000);

Console.WriteLine("Main thread exits.");
}

// This thread procedure performs the task.
static void ThreadProc(Object stateInfo) {
// No state object was passed to QueueUserWorkItem, so
// stateInfo is null.
Console.WriteLine("Hello from the thread pool.");
}
}

Option 2: Implement a custom ThreadPool using BackgroundWorker, incase you are hating ThreadPool for whatever reason.

The main worker object.

/// 
/// The core entity that handles
///

public class CWorkers
{
public int _nIndex { get; private set; }
public BackgroundWorker bgWorker { get; private set; } //the main "culprit"

public CWorkers(int nIndex)
{
_nIndex = nIndex;
bgWorker = new BackgroundWorker();
}
}

The manager class that manages the worker thread.

/// 
/// Manages the worker thread.
///

public class CWorkerManager
{
private List _lstWorkers;//list of worker threads
private const int MAXWORKERS = 5;//Max workers you want; change/update or pull it from app.config.

public CWorkerManager()
{
Initialize();
}

///
/// Initializes the thread pool - sorta customized threadpool
///

private void Initialize()
{
_lstWorkers = new List();//initialize the list

for (int i = 0; i < MAXWORKERS; i++)
{
_lstWorkers.Add(CreateAWorker(i)); //inits a worker objects and adds to list
}
}

///
/// Looks for a free thread
///

/// Returns the thread if found, else nothing.
public CWorkers RequestForWorker()
{
foreach (var theWorker in _lstWorkers)
{
if (!theWorker.bgWorker.IsBusy)
return theWorker;
}

return null;
}

///
/// Emulate the BCL's .WaitOne()
///

public void WaitAndSignalWhenFree()
{
while (true)
{
//Loop through the list to find an idle thread
foreach (var theWorker in _lstWorkers)
{
if (!theWorker.bgWorker.IsBusy)
return;
}
Thread.Sleep(1);//This may be a hack; not really recommended as a production code.
}
}

///
/// Inits a CWorker object; adds the
///

///
///
private static CWorkers CreateAWorker(int nIndex)
{
var theWorker = new CWorkers(nIndex);

theWorker.bgWorker.DoWork += (sender, e) => ((Action)e.Argument).Invoke();
theWorker.bgWorker.RunWorkerCompleted += (sender, e) => Console.WriteLine("Finished worker number:[" + theWorker._nIndex + "]");

return theWorker;
}
}

The test program:

class Program
{
private static List _lstWorkers;
private const int MAXWORKERS = 5;
static CWorkerManager theManager;

static void Main(string[] args)
{
theManager = new CWorkerManager();

ProcessJobs(20000);
Console.ReadKey();
}

///
/// Simulator that request the Manager for worker threads
///

///
private static void ProcessJobs(int nMaxTime)
{
Random rndRandom = new Random();
DateTime dteStart = DateTime.Now;

//Run till the max time.
while (DateTime.Now - dteStart < TimeSpan.FromMilliseconds(nMaxTime))
{
var theWorker = theManager.RequestForWorker();//Request for a worker

if (theWorker != null)
{
theWorker.bgWorker.RunWorkerAsync(new Action(() =>
ProcessThis(theWorker._nIndex,
rndRandom.Next(1500, 2500)//Generate somethign random
)));
}
else
{
Console.WriteLine("All busy, lets wait...");
theManager.WaitAndSignalWhenFree();
}
}
}

///
/// Actual method that processes the job.
///

///
///
static void ProcessThis(int nIndex, int nTimeout)
{
Console.WriteLine("Worker {1} starts to work for {0} ms", nTimeout, nIndex);
Thread.Sleep(nTimeout);
}
}

Output:

Happy threading.

%d bloggers like this: