Archive for September, 2010

how to make GridView auto partial update like Gmail inbox



The way presented in this article is a way of how to add new rows from database to gridview without refresh of the page . This is useful when a client want to see new rows (eg. new letters) without having to refresh the page. If you wanna see a live demo, please logIn to your Gmail account(load standard Gmail), then send a letter from a different browser to your Gmail address and see that your Gmail Inbox will auto add the new letter’s row to your letters’ gridView

There are a quick way to show new rows : put GridView inside an updatePanel and refresh the updatePanel every 3(or any) seconds, but this way increase page source’s size and page’s load time…….


but , in this article we will learn a way to automatically get new rows automatically every 3(or any) seconds [by javascript timeout] from server[by jQuery get method] and then those new rows to gridView [by jQuery html manipulation]  


You should know :


jQuery html manipulation – you can learn from w3schools.com


jQuery and ajax – you can learn from w3schools.com


Suppose we wanna(want to) have a gridView with ability of auto adding new rows from database to it
we follow the following steps to have a gridView like Gmail Inbox perl gridView !


step 1 :
Add the following Javascript code to the page that contains your gridView




Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - September 30, 2010 at 8:24 pm

Categories: C#   Tags: , , , ,

Developing web application with time zones support

When you develop web application you should know that client PCs can be located anywhere on earth. Even if you develop app just for your country users you should remember it (in Russia now we have 9 time zones, before 28 of March we had 11 time zones). On big sites with many members do it very easy – you can place field “time zone” in member profile, in Sharepoint I saw this solution, and many enterprise app do it like this. But if we have simple website with blog publications or website with news and we don’t have member profiles on server, how we can support user’s time zones?

I thought about this question because I wanted to develop time zone support on my own site. My case is ASP.NET MVC app and MS SQL Server DB. First, I started from learning which params we have at HTTP headers, but it doesn’t have information about it. So we can’t use regional settings and methods DateTime.ToLocalTime and DateTime.ToUniversalTime until we get user time zone on server. If we used our app before without time zones support we need to change dates from local time zone to UTC time zone (something like Greenwich Mean Time). You can do it easily with this sql update statements:

update dbo.MyTable set [Date] = dateadd(hour, -4, [Date])

I have -4 in this statement because time zone of server is GMT+4 (summer time). Next in code where you get current time you need to change functions: in tsql scripts getdate() to getutcdate(), and on server change DateTime.Now (or Today) on DateTime.Now.ToUniversalTime(). So on server (app and DB) we will always have dates in UTC time zone.

Next step – how to show datetime on client in browser. We need to show correct time for user (in his time zone). Get user time zone you can with Javascript function getTimezoneOffset(), it return difference in minutes from UTC to user time zone. On server I render all dates in format “dd.MM.yyyy HH:mm”. All dates I placed in html element with CSS class utcdate, if date located in text I just surround it with span element. So all dates I have like this:


<%= Model.BlogPost.Date.ToString("dd.MM.yyyy HH:mm")%>

And definition of CSS class utcdate:

.utcdate {display: none; }

When user get page all dates are invisible. I did it because on some pages in Internet Explorer we can see how old dates change with other dates (in other browsers JavaScript change it very quickly).

I wrote this JavaScript code for this:

function utcToLocal(u) { var l = new Date(u.substring(6, 10), u.substring(3, 5)-1, u.substring(0, 2), u.substring(11, 13), u.substring(14, 16)); var d = new Date(l.getTime() + (-l.getTimezoneOffset() * 60 * 1000)); return wZ(d.getDate()) + ‘.’ + wZ(d.getMonth()+1) + ‘.’ + d.getFullYear() + ‘ ‘ + wZ(d.getHours()) + ‘:’ + wZ(d.getMinutes());}function wZ(x) { if (x <;= 9) return '0' + x; return x; }function doCurrentDate() { $(".utcdate").each(function () { if ($(this).css("display") != "inline") { this.innerHTML = utcToLocal(this.innerHTML); $(this).css("display", "inline"); } });}$(document).ready(function () { doCurrentDate();});

I confess that I’m not a professional in JavaScript, so maybe you will say me how to do it better. I use jQuery, write this functions without jQuery will be more difficult, because jQuery help with selectors. Last 3 lines of this script on document ready state invoke doCurrentDate() function, which find all elements with css class utcdate and do for each: if display property of style doesn’t have ‘inline’ value than with function utcToLocal we change date from utc to user time zone and set ‘inline’ value for property display.

Function utcToLocal it is very simple. It parses input string on each date time parts, creates new date object, and then creates new date object from previous with adding required amount of time (getTime() return milliseconds, so we multiply value of getTimezoneOffset on 60 seconds in minute and 1000 milliseconds in second), and then It return formated value of date. I added function wZ, which add 0 before value if needed, because I want to show 01.01.2010 instead of 1.1.2010 on my site.

Because in method doCurrentDate we have check that date is changed on user’s time zone (check that display hasn’t ‘inline’ value), we can invoke this function so many times as we need. So when on my site user added comment (I use AJAX for add comments and include html of it with JavaScript at page) I can invoke doCurrentDate again.

Of course it is no good, that I don’t use user’s date format for showing date, because in US date format is MM/dd/yyyy and in Russia is dd.MM.yyyy. You can use JavaScript function toLocalString() which return formatted string with date. But it placed seconds and days of week, and I don’t want to see it on my site, I think that it is trash Developing web application with time zones support

I think will be great if HTML 5 format will have html date supports. Example, you can write this on page:

03.04.2010T00:38:00+04:00

And browser will change it in user’s local time. And date element can use some attribute for specify which date format you want to see on your site.

View the original article here

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - September 28, 2010 at 9:00 pm

Categories: C#   Tags: , , ,

Natural Search Engine Optimization the Easy Way

When it comes to search engine optimization, it takes a lot of time, manpower and effort. However, if you have the courage and confidence, you can perform search engine optimization organically for your website without any assistance from other consultants.

Take a look at this natural search engine optimization for example. It provides the tips and steps required to perform search engine optimization organically without any external help. If you follow the points mentioned then you will surely get great results.

But you definitely have to dedicate yourself to implement the tips mentioned, otherwise it just won’t work. If you sit idle after building a site then you will not get the expected results and your site will not rank properly in search engines. Moreover, natural search engine optimization also introduces a secret tool with which you can perform search engine optimization without outsourcing the work to other companies.

Don’t mess up this time, you can make your site search engine friendly by following the steps mentioned in the natural search engine optimization if you really want it!

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - September 22, 2010 at 7:52 am

Categories: SEO   Tags:

XNA Menus

This code allows you to display a menu with unlimited options and results very easily.

There are two classes and an xml file that are key to each new menu you want. The two classes are Menu.cs and MenuItem.cs. To use the classes you must first create a menu xml file. To create a menu you must create a folder in the Content part of your game project called Menus. Within that create an xml file with the following structure:

Main MenuOption 1ShowMessageBoxOption 110100

This structure requires MenuName as the name you want your menu to be identified by, PositionX and PositionY are the top left x and y coordinates of your menu when it is displayed. You can have as many MenuItem sets as you like. Within a MenuItem must be MenuItemText, the text that is displayed to the user, MenuItemEvent, the name of the method to call when the user selects that item and optionally you can have EventParams, used as extra parameters if you have a method that needs them.

To use the menu you need to do the above and 5 more things to your code:
1. Load a menu
2. Add an EventHandler
3. Optionally set what your current menu is
4. Get input from the menu
5. Draw the menu

To load a menu you have to get a list of xml files that are in your Menus folder then create a new menu and load it using the selected file name. My code works on the basis you can have multiple menus so loads all available in LoadContent() and has a method for selecting one of them. The code for loading looks like the following:

//Get a list of the xml filesstring[] Files = Directory.GetFiles(Content.RootDirectory + “\\Menus\\”);//Loop through each oneforeach (string FileName in Files){//Create a new menuMenu AMenu = new Menu();//Tell it load the fileAMenu.Load(FileName);//Add it to the listMenus.Add(AMenu);//If it is the Main Menu set it as the current menuif (AMenu.MenuTitle == “Main Menu”){CurrentMenu = AMenu;}foreach (MenuItem AnItem in AMenu.MenuItems){AnItem.OnConfirmedEvent += new EventHandler(AnItem_OnConfirmedEvent);}}

My code gets a list of files, loops through them creating a new menu and loading it. It also checks if the menu its just loaded is the Main Menu and then sets it as the CurrentMenu being displayed. To use a menu you must also add an event handler to all the menu items’ OnConfirmedEvents. Whilst adding them you can distinguish between what methods you set the events to call but I chose to set them all to the same method. This method is as follows:

private void AnItem_OnConfirmedEvent(object sender, EventArgs e){MenuItem TheItem = (MenuItem)sender; switch (TheItem.EventName) { case “ShowMessageBox”: System.Windows.Forms.MessageBox.Show(TheItem.EventParams[0]); break; case “Quit”: this.Exit(); break; default: break; }}

It gets what MenuItem called it then looks at the method name and if its equal to ShowMessageBox then it shows a message box with the first event parameter in it. My menu also has GetInput() and Draw() methods. GetInput() is used in update when you wish to allow the user to select a menu option.

That’s it! Not much too it realy but it can be surprisingly difficult to do for yourself. It took me a while to get this working.

I had fun working out a sensible xml file standard that would encompass everything I wanted to do and thus be flexible, it’s surprisingly difficult!

View the original article here

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - September 16, 2010 at 7:28 pm

Categories: C#   Tags:

New Code Comparison Tool CodeCompare Provides Advanced Programming Language Oriented Approaches

Visual Studio integrated file and folder comparison tools. These brand-new products take into account specificity of programming languages, that makes significant advantage in source code comparing.

CodeCompare, the brand-new code comparison tool from Devart, demonstrates an absolutely new way of source code comparison. Advanced comparison approaches, that consider the peculiarities of different programming languages, perfectly fit the needs of developers.

Unique Visual Studio integration helps to make all of the development and merging operations within one environment at the same time.

CodeCompare can be easily integrated with any version control system that support external comparators. Solution can be set up as an comparison and merge tool with the help of the command line.

CodeCompare still stays absolutely free and solves most of the tasks referred to the source comparing.

CodeCompare Pro offers advanced features for sources comparison.

Version 2.00 contains the following features

- Structure comparison
- Moved block detection and visualizing
- Difference Explorer
- Folder comparison
- Lexical parsing
- Comparison pane swapping
- Word by word comparison
- Optional auto case ignoring that considers language specificity
- Comparison in modal window in Visual Studio 2010 (useful when VisualSVN or TFS is used)

Pricing and Availability

CodeCompare is an absolutely free utility, but nevertheless you can receive full support. CodeCompare is available for immediate download at http://www.devart.com/codecompare/download.html

Code Compare is a free software, that provides basic functionality and solves most of the tasks referred to the source comparing. It includes a 30-day free trial of CodeCompare Pro. Price of Code Compare Pro now as little as $34.95.

Users are welcome to write any comments and suggestions about CodeCompare on its support page – http://www.devart.com/codecompare/support.html .

About Devart

Devart is a software development company with 11 years of experience on the software market and over 20 thousands of devoted users.

We specialize in providing comprehensive development and management tools as well as native connectivity solutions for the most popular databases, including Oracle, SQL Server, MySQL, PostgreSQL, InterBase, Firebird, and SQLite.

For additional information about Devart, visit www.devart.com/company/

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - September 16, 2010 at 7:19 am

Categories: Press Releases   Tags: ,

Addition, Multiplication of Very Long Integers

Well, I am posting an article after a long gap. When i was reading a C++ Programming, i came across a programme that was showing using of very long integers. It was quiet good and that impressed me and made me write the same in C#.

The purpose of the article is to be able to build a class that allows any C# programmer to use very long integer related functionalities like addition and multiplication. I have implement it using operator overloading. While reading in C++ and while analyzing the programme to write in C#, i came to a conclusion, that using operator overloading makes the performance ease and it is very easy to understand the code and functionality in certain cases.

In computer programming, operator overloading (less commonly known as operator ad-hoc polymorphism) is a specific case of polymorphism in which some or all of operators like +, =, or == have different implementations depending on the types of their arguments. Sometimes the overloadings are defined by the language; sometimes the programmer can implement support for new types. Operator overloading is claimed to be useful because it allows the developer to program using notation “closer to the target domain” and allows user-defined types a similar level of syntactic support as types built into the language. It can easily be emulated using function calls; for an example, consider the integers a, b, c:

a + b * c

In a language that supports operator overloading, and assuming the ‘*’ operator has higher precedence than ‘+’, this is effectively a more concise way of writing:

add (a, multiply (b,c))

All unary and binary operators have pre-defined implementations, that are automatically available in any expressions. In addition to this pre-defined implementations, user defined implementations can also be introduced in C#. The mechanism of giving a special meaning to a standard C# operator with respect to a user defined data type such as classes or structures is known as operator overloading. Remember that it is not possible to overload all operators in C#. The following table shows the operators and their overloadability in C#.

Operators Overloadability

+, -, *, /, %, &, |, <<, >> All C# binary operators can be overloaded.

+, -, !, ~, ++, –, true, false All C# unary operators can be overloaded.

==, !=, <, >, <= , >= All relational operators can be overloaded,
but only as pairs.

&&, || They can’t be overloaded

() (Conversion operator) They can’t be overloaded

+=, -=, *=, /=, %= These compound assignment operators can be
overloaded. But in C#, these operators are
automatically overloaded when the respective
binary operator is overloaded.

=, . , ?:, ->, new, is, as, size of These operators can’t be overloaded

In C#, a special function called operator function is used for overloading purpose. These special function or method must be public and static. They can take only value arguments.The ref and out parameters are not allowed as arguments to operator functions. The general form of an operator function is as follows.

public static return_type operator op (argument list)
Where the op is the operator to be overloaded and operator is the required keyword. For overloading the unary operators, there is only one argument and for overloading a binary operator there are two arguments. Remember that at least one of the arguments must be a user-defined type such as class or struct type.

Overloading Unary Operators – the general form of operator function for unary operators is as follows.public static return_type operator op (Type t){// Statements}Where Type must be a class or struct.The return type can be any type except void for unary operators like +,~, ! and dot (.). but the return type must be the type of ‘Type’ for ++and o remember that the true and false operators can be overloaded only as pairs. The compilation error occurs if a class declares one of these operators without declaring the other.

Operating overloading allows us to pass different variable types to the same function and produce different results. In this article i have given the low-down on operator overloading in C#.Operator overloading is common-place among many efficient C# programmers. It allows you to use the same function name, but as different functions.

In this article I have shown exactly what operator overloading is, and how you can get it to work for you in C#.

Inside Logic

First the very long numbers are inputted as string. Then each characters in the string are converted as integers. The same is done for the another input string. Now the digits are added and is stored in a separate character array. Adn finally this character array is converted as string, which the exact output that we need.

public static VeryLongInteger operator +(VeryLongInteger veryLongInteger1, VeryLongInteger veryLongInteger2) // Adds two very long numbers. { char[] outputChars = new char[MAXLENGTH]; string veryLongString1 = Reverse(veryLongInteger1.ToString()); string veryLongString2 = Reverse(veryLongInteger2.ToString()); int length1 = veryLongString1.Length; int length2 = veryLongString2.Length; int maxLength = length1 > length2 ? length1 : length2; int carry = 0; int j = 0; for (j = 0; j < maxLength; j++) { int digit1 = (j > length1 – 1) ? 0 : Convert.ToInt32(veryLongString1[j].ToString()); int digit2 = (j > length2 – 1) ? 0 : Convert.ToInt32(veryLongString2[j].ToString()); int digitsum = digit1 + digit2 + carry; if (digitsum >= 10) { digitsum -= 10; carry = 1; } else carry = 0; outputChars[j] = Convert.ToChar(Convert.ToString(digitsum)); } if (carry == 1) outputChars[j++] = ’1′; return new VeryLongInteger(Reverse(new string(outputChars))); }

Here also the same logic. But here we add some extra functionalities like multiplying a single digit, multiplying with 10.

public static VeryLongInteger operator *(VeryLongInteger veryLongInteger1, VeryLongInteger veryLongInteger2) // Multiplies two very long numbers. { char[] outputChars = new char[MAXLENGTH]; string veryLongString = Reverse(veryLongInteger2.ToString()); VeryLongInteger powerproduct = null; VeryLongInteger outputVeryLongInteger = new VeryLongInteger(“0″); int j = 0; for (j = 0; j < veryLongString.Length; j++) { int digit = Convert.ToInt32(veryLongString[j].ToString()); powerproduct = MultiplyDigit(veryLongInteger1, digit); // Browse the source code for this method for (int k = 0; k < j; k++) { powerproduct = Mulitply10(powerproduct); // Browse the source code for this method } outputVeryLongInteger = outputVeryLongInteger + powerproduct; } return outputVeryLongInteger; }

Here we acheive factorial as a recursive calling of multiplication. We can find factorial of number upto 250 (!Wow).

VeryLongInteger v1 = new VeryLongInteger(“1″);int num = 100;for (int i = num; i > 0; i–){ VeryLongInteger v2 = new VeryLongInteger(i.ToString()); v1 = v1 * v2;}

screenshot2.jpg

Thanks for viewing this article. I expect feedback from you. You expect more from me.

View the original article here

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - September 15, 2010 at 12:20 am

Categories: C#   Tags: , ,

HTML 5: Up and Running

If you don’t know about the new features available in HTML 5, now’s the time to find out. The latest version of this markup language is going to significantly change the way you develop web applications, and HTML 5: Up & Running (O’Reilly Media, $29.99 USD) provides your first real look at HTML 5′s new elements and attributes.

Even though work on HTML5 is ongoing, browsers such as Safari, Mozilla, Opera, and Chrome already support many of its features-and browsers for smart phones are even farther ahead, especially iPhone’s MobileSafari browser.

Mark Pilgrim, author and accessibility architect, has been following the development of HTML 5 long before it was called HTML 5. “In the mid-90′s, browser vendors were competing with each other to see who could lock people into their platform,” says Pilgrim. “Now, browser vendors implementing the HTML 5 standard are competing on things like speed and user-friendliness. This book will help programmers develop next-generation web applications.”

Mark Pilgrim adds, “I have a strong interest in open standards, and this is my contribution towards ensuring that the web remain open and available to all I have a strong interest in open standards, and this is my contribution towards ensuring that the web remain open and available to all.”

With HTML 5: Up & Running, you’ll learn how HTML 5 can help you develop applications that:

. Display video directly in the browser, without having to rely on plugins
. Work even when a user is offline, by taking advantage of HTML 5′s persistent storage
. Offer a drawing canvas for dynamically generated 2-D graphics

HTML 5: Up and Running is the most complete and authoritative book you’ll find on the subject. Stay ahead of the curve.

HTML 5: Up and Running
Mark Pilgrim
ISBN: 978-0-596-80602-6
224 pages
Book Price: $29.99 USD
Ebook Price: $23.99 USD

1 comment - What do you think?
Posted by Anand Narayanaswamy - September 5, 2010 at 11:46 pm

Categories: Press Releases   Tags: , , ,

First Guide to MEF and Silverlight (Part–II)

In my previous article “First Guide to MEF & Silverlight (Part–I)” I discussed about MEF with a small simple console application. Hope that was useful to you to understand the basic knowledge of MEF. In this article, I will guide you to create a simple Silverlight application using the MEF. If you are new to MEF, I strongly recommend you to read my previous article to gain knowledge on the basic things of MEF like Importing, Exporting, Catalog, Container etc. Read the complete article and at the end if you have any queries, please let me know. I will try to answer them as soon as possible. Always Appreciate your valuable feedbacks. To start working with the Silverlight & MEF application, you need to setup your development environment. In your development PC, you need the following things already installed: Visual Studio 2010 with .Net Framework 4.0 Silverlight 4.0 Tools for Visual Studio 2010 Once your environment is ready with the above tools, we can start with our next step. First of all, we need to create a Silverlight application project and then we have to add some assembly reference in order to work with the MEF. Hence, follow the following steps to setup your project: Open your Visual Studio 2010 IDE Now go to File –> New –> Project or just press Ctrl + Shift + N to open the “New Project” dialog window. From the left panel expand “Visual C#” and then select “Silverlight”. This will populate the right pane with the Silverlight templates.

Image [http://www.kunal-chowdhury.com] 

In the right pane, select “.Net Framework 4” from the DropDown present at the top of the screen. This is require because, we want to do application programming for the target version i.e. Framework 4. Chose “Silverlight Application” from the right pane and click “OK”. I assumed that, you selected proper location and named your application project properly (in our case, I named it as “MEFWithSilverlightDemo”). Once you click “OK”, it will ask you to create a new Web site. This step is require to host the Silverlight application.

Image [http://www.kunal-chowdhury.com]

Be sure that, in the above dialog “Silverlight 4” has been selected as the Silverlight version. Once you click “OK” the Visual Studio IDE will start creating your Silverlight project. It will create two project (one is your Silverlight application project and the other is your Silverlight application hosting website).

Image [http://www.kunal-chowdhury.com]

Once the project created by the IDE, you need to add a reference of the Assembly named “System.ComponentModel.Composition” and a reference of the Assembly named “System.ComponentModel.Composition.Initialization” to your project. To do this, right click on your Silverlight Application project and click “Add Reference”. From the “Add Reference” dialog find the assembly named “System.ComponentModel.Composition” and “System.ComponentModel.Composition.Initialization” to add them to your project.

Image [http://www.kunal-chowdhury.com] 

Once done with all the above steps, your project is ready for the MEF development. Let us first decide what we want to do in our example. We will create a Silverlight application where we will include some UserControls as a Widget. This is for learning purpose and hence don’t go with the UI. So, in our sample application we will create a UserControl and mark it as Exportable. Then we will import the UserControl in our application to add it in the UI. Next we will create another UserControl and mark it as Exportable, so that without any other change in the code, it should add in the main UI. This is just an example to showcase the MEF functionality in Silverlight applications. Let’s jump into the code. First of all, we will create an Interface called IWidget and we will use this interface to build our UserControl. We will just inherit this to the UserControl and while exporting or importing we will use the same interface type. Reason behind this is to make sure only the specified type of control will be marked for MEF. If we have two different types for two different kind of controls, it will be easier for us to manage in the main screen. So, just create a blank interface named IWidget which will look like below: Now, in the MainPage.xaml add an ItemsControl & name it as “widgets”. Wrap the ItemsControl with a StackPanel to hold the items. The XAML file will look as below:

Now it’s time to create a UserControl. Right click on the Silverlight project and add one UserControl & name it as “EmployeeWidget”. We will not design more inside it as it is not require to understand the MEF. To make it properly visible just add one TextBlock with some strings. In our example, I am setting “Employee Widget” as the text string for the TextBlock and also setting a color “Red” to the Grid background. Resize the UserControl to 150 x 150, so that, it will set properly in the screen. Let’s see the below code for detailed layout:


As mentioned above, I resized the control to 150 x 150 and then changed the background color to Red. Added a TextBlock having “Employee Widget” as the value to the TextProperty of the TextBlock with a foreground color of White, so that, it will be visible on top of the Red color. No need to describe more on it. Just check the above xaml and you will get the idea behind it.

Press F7 in the EmployeeWidget.xaml page to open up the code behind file. Inherit the EmployeeWidget class from IWidget. Once done, add the attribute “Export” having the type of IWidget to the class. This will ensure that the class will export for the MEF to Satisfy. Look into the code here:


As our UserControl has been exported for the MEF to satisfy, it’s the time to import it in our MainPage. To do this, open the MainPage.xaml.cs and create a property “Widgets” of IWidget type array. We are using array type to ensure that, we can import many widgets there. So, mark the property with the atrribute “ImportMany” of type IWidget. Once that is done, our code is ready to import the exported class. Now inside your MainPage constructor, iterate through the array and add all the Widgets as the item to the “widgets” items control which we already added in the XAML. Now if you run your application, you will notice that the Widgets array is null. Why? Just think. Oh yea!!! We forgot to satisfy the MEF Initializer to satisfy the property. What to do for that? To satisfy the imports, you need to call “CompositionInitializer.SatisfyImports(this);” just before iterating through the array list. Have a look into the code:


Now, run your application once again and this time you will see the EmployeeWidget added to the UI screen with a text “Employee Widget” having a Red background. Here is the screenshot of the same:

image


Woho!!! Nice. We didn’t create the object of the UserControl and add it to the ItemsControl. The MEF framework did it for us. Once satisfied, it created the object and imported it to the MainPage.


That’s it. Now we will do one more thing. We will create another UserControl named “CustomerWidget” and follow the same steps mentioned above for exporting the control. This time we will set the text to “Customer Widget” and will set the background color to Green. This will make it easy for us to distinguish between the items. Here is the XAML code of the CustomerWidget usercontrol:


Now open the code behind file of CustomerWidget by pressing F7 in the xaml page and follow the same step as we did for the EmployeeWidget i.e. implement the CustomerWidget from the interface named IWidget and mark the class exportable by setting the Export attribute of the IWidget. Here is the code for your reference:


That’s it. This time we didn’t add/modify anymore code in our MainPage. Just run the application and you will see the CustomerWidget added in the panel along with the control named EmployeeWidget. See the screenshot of the same here:

image

So, what did we learn here? We learnt that without changing the original code, we can easily import any control with the help of MEF. It is very easy to plug something into our original application without doing any change in the main application. In such case, instead of updating the original application we can easily attach our feature like a plug-in. Hope, this article helped you to understand the basic functionality of MEF with the help of Silverlight. In my next article, I will show you more on MEF with the help of a Console Application. Till then keep learning about MEF & do your small small POCs to learn in depth. Please don’t forget to post your feedbacks and/or suggestions to improve this article. Appreciate your time for reading through this article

View the original article here

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - September 3, 2010 at 7:54 pm

Categories: C#   Tags: , , , , ,

Getting elevated privileges on demand using C#

With going on stage Windows Vista and Windows 7 later on and new user security paradigm introduction (UAC), it becomes necessary to support such behavior when elevated privileges are required to perform some portion of code base, i.e. writing to registry, modifying files under system protected folders, etc.

So, in general, there are two ways to implement such behavior:

Embed a manifest info executable to indicate that the application requires elevated privileges from the beginning and can’t be run without gaining administrative rights at all. Here’s an example of such manifest:
Separate the code base into two parts: the first doesn’t require elevated privileges and the second – does, so call one from another. The article covers a case when the calling application is a console with a number of command line arguments: some of them can be run in normal mode and some – only with administrative rights.

Usually the part of the program requires elevated privileges is a settings form which writes to Windows registry when the core functionality – don’t.

Another case – a console application where core functionality requires elevated privileges and some helpers – such as help message displaying – don’t.

Let’s declare the skeleton of such console application.

Entry point method parses input command line arguments and branches the flow control relying on the parse results wrapped into a object:

static void Main(string[] args){ // wrap command line arguments to an object Core.Settings = ApplicationSettingsParser.Parse(args); if (Core.Settings.UsageFlag || (args.Length == 0)) { // run without elevated privileges PrintUsage(); } else if (!Core.Settings.EngageFlag) { // runs with the same arguments plus flag mentioning the main action performing var info = new ProcessStartInfo( Assembly.GetEntryAssembly().Location, String.Join(” “, Enumerable.Concat(args, new[] { “–engage” }))) { Verb = “runas”, // indicates to eleavate privileges }; var process = new Process { EnableRaisingEvents = true, // enable WaitForExit() StartInfo = info }; process.Start(); process.WaitForExit(); // sleep calling process thread until evoked process exit } else if (Core.Settings.EngageFlag) { // do stuff under elevated privilegesConsole.WriteLine(“Elevated privileges gained={0}”, Core.IsElevated); }}

Here’s a method just displaying a sample help message:

private static void PrintUsage(){ Console.WriteLine(“Usage: ElevatedPrivilegesOnDemand.exe –do [--engage] | -?”);}

Parsing method is placed into a dedicated helper:

public static ApplicationSettings Parse(string[] args){ var settings = new ApplicationSettings(); for (int i = 0; i < args.Length; i++) { var param = args[i]; switch (param) { case "-?": { // stop further parsing and return only meaning flag return new ApplicationSettings() { UsageFlag = true }; } case "--do": { settings.DoFlag = true; break; } case "--engage": { settings.EngageFlag = true; break; } } } return settings;}

Which returns a POCO object keeping settings:

class ApplicationSettings{ public ApplicationSettings() { // default settings setup } public bool DoFlag { get; set; } public bool EngageFlag { get; set; } public bool UsageFlag { get; set; }}

Internal singleton setting instance is attached to a pivot class. It also contains an addition helper method to check elevated privileges obtaining:

static class Core{public static bool IsElevated{get{return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);}}public static ApplicationSettings Settings { get; set; }}

The executing flow is being separated to the two parts: in the first it’s being determined whenever elevated privileges are required relying on command line arguments specified or not. And if yes – an additional parameter is being added and passed to the same application but started with administrative rights and redirected  console output.
And in the second, the core functionality is being executed with full privileges gained.

Now there is no needs to run the whole application under elevated privileges mode when it is not necessary.

Unfortunately it seems that it’s not possible to hide child process window and elevate its privileges in the same time:

ProcessStartInfo.Verb will only have an effect if the process is started by ShellExecuteEx() which requires UseShellExecute = true Redirecting I/O and hiding the window can only work if the process is started by CreateProcess() which requires UseShellExecute

I’m investigating this behavior and will update my article as far will find a solution to hide a window of started elevated process. 

Reader can find next links to be interesting: 

Questions tagged UAC and manifest on Stack Overflow, especially this and related. 

28/08/2010 – version 1.0.1 – Initial release.  

29/08/2010 – version 1.0.2 – Fix of example source code.

30/08/2010 – version 1.1.3 – Code change and remark addition considering hiding window of process started with elevated previliges.

View the original article here

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - September 3, 2010 at 12:59 am

Categories: C#   Tags: , , , , , ,

Programming WCF Services Released

Programming WCF Services, Third Edition is the authoritative, bestselling guide to Microsoft’s unified platform for developing modern service-oriented applications on Windows.

“I’ve included my ServiceModelEx library, a framework of useful utilities, tools, and helper classes that let you simplify and automate many tasks, and extend WCF,” says author, speaker, and Master Architect Juval Löwy.

Löwy revised this edition to include the newest productivity-enhancing features of .NET Framework 4 and the Azure AppFabric Service Bus, as well as the latest WCF ideas and techniques. By teaching you the why and the how of WCF programming, Programming WCF Services will help you master WCF and make you a better software engineer.

This book will help you:

• Learn about WCF architecture and essential building blocks, including key concepts such as reliability and transport sessions

• Use built-in features such as service hosting, instance and concurrency management, transactions, disconnected queued calls, security, and discovery

• Master the Windows Azure AppFabric Service Bus, the most revolutionary piece of the new cloud computing initiative

• Increase your productivity and the quality of your WCF services by taking advantage of relevant design options, tips, and best practices in Löwy’s ServiceModelEx framework

• Discover the rationale behind particular design decisions, and delve into rarely understood aspects of WCF development

Hailed as the definitive treatment of WCF, Programming WCF Services provides unique insight, rather than documentation, to help you learn the topics and skills you need for building WCF-based applications that are maintainable, extensible, and reusable.

Juval Löwy is the principal of IDesign, a company specializing in .NET architecture consulting and advanced training. Juval is Microsoft’s Regional Director for the Silicon Valley, and he participates in the Microsoft internal design reviews for future versions of .NET and related technologies. Juval is one of the world’s top .NET experts and industry leaders—and a Microsoft Software Legend.

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - September 2, 2010 at 1:28 am

Categories: Press Releases   Tags: , , , , ,

Next Page »