Tuesday, June 30, 2009

How AJAX Works: 10 Practical Uses For AJAX

AJAX has gotten more and more popular over the years, and has allowed web applications to act more and more like desktop applications. AJAX can provide a lot of additional functionality that could not be accomplished any other way.

What Is AJAX? How Does It Work?
AJAX stands for Asynchronous JavaScript and XML. It is used for allowing the client side of an application to communitcate with the server side of the application. Before AJAX, there was no way for the client side of a web application to communicate directly with the server. Instead, you would have to use page loads. With AJAX, the client and server can communicate freely with one another.

Here is how the usual AJAX script goes:
  • Some action triggers the event, like the user clicking a button.
  • The AJAX call fires, and sends a request to a server-side script, using XML
  • The server-side script (PHP, ASP, or whatever) takes the input from JavaScript, can access the database if it needs to, and processes the data.
  • Using XML again, the script sends the data back to the original client-side page that made the request
  • A second JavaScript function, called a callback function,catches the data, and updates the web page

Throughout this tutorial, we will discuss how various scripts use this routine to accomplish a wide variety of effects.


1. Login Forms
Instead of going to a login page, and then navigating back to the page you originally wanted, with AJAX, a user can type in their user name and password directly into the original page. From there AJAX will send a request to the server to log them in. The server let’s the page know they’ve been logged in, and the page you are on can update as needed. Digg has a login-system that works like this.

Example: Digg.com (top of page)

Plugin: jQuery Form Plugin

2. Auto-Complete
Google was one of the first major companies to start using AJAX, and Google’s search suggestion tool was one of the first ways they used it, and one of the first auto-complete tools made. When typing into the Google search bar, it starts to use AJAX to get common results from the database on each keystroke. Auto-Complete is great for forms where you have a lot of possible inputs, and making a select drop down would be too long and cumbersome.

Example: Google Search

Plugin: jq autocomplete

3. Voting and Rating

Social bookmarking sites like Digg and Reddit let the users decide the main content of the site by voting on content that the users like. They use AJAX to handle all of the voting, so that the users are able to voice their opinions on a number of stories quickly and easily.

Example: Reddit


4. Updating With User Content

One of the things that made Twitter so popular was their simple and easy-to-use interface. When someone makes a ‘tweet’, it is instantly added to their feed, and everything is updated. Recently, Twitter has started using AJAX with their ‘trending topics’ pages. Every few seconds, the page lets the user know that more tweets have been made about the subject, giving them up-to-the-second updates.

Example: Twitter


5. Form Submission & Validation
Forms have always tricky to work with, but AJAX can make them a lot better for the users. AJAX can be used in a variety of ways, from the auto complete mentioned above, to validation and submission as well. Some sites use AJAX to check if a form meets certain requirements, such as password strength, or if something is a valid email or URL.

Example: 10 Cool jQuery Form Plugins


6. Chat Rooms And Instant Messaging
Chatting online has come a long way from the days of IRC. Chat rooms and instant messaging can now be handled in the browser completely. There are two main AJAX processes in a chat room or IM application. Think of one of them as your ears, and one of them as your mouth. Your ‘mouth’ updates the server and lets it know that you have sent a message. The ‘ears’ check with the server constantly, and updates your page with messages that have been sent by whoever you are chatting with.

Example: Meebo Chat (Uses Ajax)

Plugin: GMail/Facebook Style Chat Script


7. Slicker UIs


Creating a clean, slick user interface is a very popular use of AJAX. It allows users to accomplish more on a single page. The benefits of this are twofold: First, it makes using the web application quicker and easier for the user; Secondly, it cuts down on the number of requests you have to make to the server, which cuts down on bandwidth and load times. A free file upload service called Drop.io uses this well. Google has also really pushed the envelope of what is possible with AJAX by making desktop-like applications like Google Docs and Google Maps.

jQuery UI Library


8. External Widgets
When using AJAX, the page that is using the JavaScript isn’t just limited to the server it is located on. The AJAX can make a call to any server online. This is how a number of plug-ins for Content Management Systems like Wordpress work, and other various scripts like Google Adsense.

Example: Google Adsense

Plugin: Script for loading external content into div


9. Lightboxes instead of pop-ups
Pop-up blockers are very common place these days, and for a good reason: pop-ups are annoying. Using light boxes, which are pop-ups inside the browser window, the pop-up blocker can’t stop it, and they aren’t quite as irritating to the user. Some people use them for advertising, like on Darren Rowe’s ProBlogger.com. They can also be used for something like a login or register box, like Reddit does when you try to vote and you are not logged in.

Example: Logo Sauce

Plugin: Lightbox Plugin


10. Using AJAX With Flash


Using AJAX along with Flash is a rarely used technique, but it can be used to generate some impressive results. The flash game website Kongregate uses this to great effect. Using their API, they have their own achievement system that involves winning ‘badges’ for completing various accomplishments in games. When a badge is earned, the API in Flash sends a response back to JavaScript, which then uses AJAX to update the user’s profile with the newly earned award.

Example: Kongregate

Plugin: jQuery Flash Plugin


Reference
1) How AJAX Works: 10 Practical Uses For AJAX

Monday, June 29, 2009

Bing.com - Why Microsoft Won’t Succeed Right Now

The talk of the internet over the last few days has been over a strangely named new website called Bing.com. In case you hadn’t heard, its actually Microsoft’s brand new attempt at stealing back some of Google’s ever growing search dominance. It looks pretty, with a beautiful back drop on the homepage. And it has some great new search features. But I know Bing won’t really take off in its current form (and not just because of the odd name associations - badda bing… chandler bing etc). But why?
Here are the main reasons why I think Bing.com won’t succeed in wrestling away much of a search share back from Google, and what they need to change…

1: Bing.com is not friendly to first time users - it doesn’t give a real value proposition on the homepage. And when I mean no value proposition, I mean that it doesn’t inform users about why they should use Bing rather than another search like Google or Yahoo. Microsoft are obviously just expecting people to try using Bing just because its the new cool thing by Microsoft, and use it because its supposed to be the new competitor to Google. But it doesn’t let the user know why they should run their search on Bing.com instead of at Google. If people don’t understand the real value behind Bing after the first few searches, they are simply going to go straight back to Google or Yahoo, probably rarely to come back. Remember that web users are more fickle and picky than ever before! Fair enough if Bing.com was the first web search on the scene, but its not. And it really needs to help persuade people better with the goliath that is Google just a few clicks away.

2: The homepage doesn’t explain the unique features of Bing and why its better than other search engines. Imagine thinking about buying a supposedly great camera without seeing a list of its great features. Bing is like that. They don’t offer a complete list of the benefits of using Bing anywhere that I found on their site. And its not like they don’t have great features - they have better filtered searching, better image search, autoplay video in results, cashback offers, and more - here is a more complete list of good Bing features. For a better first time user experience, on the Bing homepage, there needs to be a prominent area with words saying something along the lines of ‘First time user? Find out why you should use Bing.com’, with clear benefits listed after clicking. Maybe even show a comparison Matrix highlighting why Bing search is better than Google search. Come on Microsoft - play tough - just look at the abuse you are taking from Apple on those PC vs. Mac commercials… go big or go home.

3: Lack of ‘real time’ news search options showing in regular results- No breaking news results come up at the top or bottom of Bing searches like appear on Google search results - these news results are often much more real time than the regular search results, and are of high value to many searchers wanting the newest information possible. There is also no ‘blog’ results search either, which are often another great news source. Probably pretty easy to integrate these better.

4: Bing needs some serious grass-roots viral marketing campaigns to make a real impact. Even if Microsoft do fix the above issues, Bing really needs some kind of wondrous viral marketing campaign, at the grass roots level, aimed at trying to convert the hardcore and loyal Google search users into loyal Bing users. If you convert the mavens like these people, they will spread the word naturally. And the masses will begin to follow. Traditional advertising online is not likely going to work very well here, sorry Microsoft.

Overall, nice try though Microsoft - Bing has some good features, and at least you are showing up for the fight. Now really make the people want to use it - in the very least, don’t make the user work to try and understand the benefits of Bing. It will be very interesting to see how things pan out for Bing - I personally hope they do well, and at least wrestle some of the search share back away from Google’s monopoly, which is bad for a search user experience. Anyone else have any good thoughts on Bing and their search future?

Reference
1) Bing.com - Why Microsoft Won’t Succeed Right Now


Sunday, June 28, 2009

Microsoft Expression Blend™ 2 Features

Modern Interface
Enjoy Expression Blend's uniquely scalable, design oriented interface built using the Windows Presentation Foundation (WPF) and concentrate on the process of design instead of digging through nested menus and rearranging floating palettes that are always in the way. Expression Blend's interface maximizes the space for your work and includes features such as a dynamically filterable Properties panel to help you find what you're looking for instantly.




Design for Desktop and Web
Leverage the full power of WPF on the desktop and Silverlight on the internet to provide your audience with big-impact, high-performance user experiences that drive brand recognition and repeat use.




WYSIWYG Design Surface
Composite your vector and bitmap artwork, video, audio, rich text, controls, and containers, and create custom vector elements using sophisticated layout and snapping tools with real-time feedback. Make immediate creative decisions based on live previews of interface elements including those dynamically bound to each other or to external data sources.




Over 30 Controls and Containers
Add standard controls such as buttons, scroll bars, list boxes, menus, radio buttons, and checkboxes-or composite multiple control elements together to form compound controls. Expand your interface by including advanced controls and layout functions, such as ready-made gridsplitters, ink canvases, treeviews, expanders, sliders, rich text boxes, tab controls, and toolbars. Design adaptive layouts using containers that automatically handle scaling and re-positioning of content and controls. (Desktop only)




Professional Timeline
Expression Blend has a world-class timeline that is based on time instead of abstract frames. Animate individual properties of objects along one or more timelines by setting property keyframes, using onscreen motion path editing for precise trajectory control.




Styling and Customization
Expression Blend includes versions of the standard Windows controls that are easy to visually style and customize enabling applications that are a perfect fit for their purpose. Add animation, graphics, 3D, and video as design elements to any control, including interactive, state-based effects. Define your own reusable custom styles or apply standard Windows themes then drag and drop to reuse your styles and templates across screens and projects.



True 3D
Import geometry from leading 3D authoring tools, or create models directly in Expression Blend. Then easily manipulate and animate in true 3D, using camera position, surface materials, z-space animation, and surface texture mapping. (Desktop only)



Databinding
Bind your interface elements to each other, to user input, or to data from Web services and .NET objects, so that your interface updates dynamically and your application comes to life even before writing code. (Desktop only)



XAML
Directly edit XAML code in either code or split view complete with colored syntax highlighting. All changes on the design surface are directly reflected in the code view and vice versa so you maintain total control of the details of your design.



Visual Studio Integration
Productivity is enhanced by seamlessly sharing projects, Silverlight, WPF, as well as in-progress XAML designs with Visual Studio. This enables designers and developers to quickly build and test iterative revisions of the application's functionality and design, as well as allowing enhanced development capabilities - debugging, Web services design, and enterprise application lifecycle management, without impacting your design freedom.




Reference
1) Microsoft Expression Blend™ 2 Features


Expression Blend Property Window Animation

While working in the Expression blend environment, I really notice one good thing about the expression blend is the , the way it display the properties. Especially the properties which are grouped togather, Main properties are shown while other properties, which are the advance propperties are hidden, and you can see the advance properties by clicking on the down arrow. In this post I will create the animation which is used when you click to see the advance properties of the control. I have created the common properties of the property window and here is the normal view of the that area.


And after you click the down arrow here is the view of the advance properties as well. Now you can see the down arrow is converted to up arrow.


Let us start with the code as you have seen the normal and the advance view of the window. Here is the code which is used to show and hide the advance properties using the animation, when you click on the down/up arrow. When you see the code, you can see that I have two Double animation object one is the Main display Area and second one is the Extra Area animation object. The extra area which is the advance properties are inside the main display area where the other common properties are displayed.
private void brdExpanderBorder_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DoubleAnimation dblaMainDisplayAreaAnimation = new DoubleAnimation();
DoubleAnimation dblaExtraAreaAnimation = new DoubleAnimation();

if (blnIsHeightIncreasing)
{
dblaMainDisplayAreaAnimation.To = 287;
dblaExtraAreaAnimation.To = 140;
blnIsHeightIncreasing = false;
imgDirection.Source = new BitmapImage(new Uri("/Images/uparrow.png", DUriKind.RelativeOrAbsolute));
}
else
{
dblaMainDisplayAreaAnimation.To = 150;
imgDirection.Source = new BitmapImage(new Uri("/Images/downarrow.png", DUriKind.RelativeOrAbsolute));
dblaExtraAreaAnimation.To = 0;
blnIsHeightIncreasing = true;
}
dblaMainDisplayAreaAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(250));
Storyboard.SetTargetName(dblaMainDisplayAreaAnimation, grdMainGrid.Name);
Storyboard.SetTargetProperty(dblaMainDisplayAreaAnimation, new PropertyPath(Grid.HeightProperty));

dblaExtraAreaAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(200));
Storyboard.SetTargetName(dblaExtraAreaAnimation, grdExtraArea.Name);
Storyboard.SetTargetProperty(dblaExtraAreaAnimation, new PropertyPath(Grid.HeightProperty));

Storyboard strbStoryBoard = new Storyboard();
strbStoryBoard.Children.Add(dblaMainDisplayAreaAnimation);
strbStoryBoard.Children.Add(dblaExtraAreaAnimation);
strbStoryBoard.Begin(this);
}

Here I have placed a Boolean flag blnIsHeightIncreasing which is used to decide either the height of the main display area and the extra area are increasing or decreasing. As I am using same function to increase and decrease the height of the control and other properties of double animation objects are same except for the To property of the main display and extra area. When the height of the controls is increasing then I have set the blnIsHeightIncreasing flag to false and set the new image for the down arrow which is the up arrow in case of height increase, and when height of the control decrease I have set the flag to true to next time when user click on the arrow then animation will be down side mean increase the height of the control, and also change the image from uparrow to down arrow. As you can see from the code I have only set the To property of the double animation object and not set the From property, if you didn't set the From Property then the current value of the height is taken as the value of the From property.
The theme or the resource dictionary used for this post is the Expression dark, you can find more detail about and link to download the expression dark from here. You can download the source code from here.

All and any comments / bugs / suggestions are welcomed!

Saturday, June 27, 2009

Using responseText in Ajax Call (Part 2)

In my previous post about "Using responseText in Ajax Call" on of the reader post a question of how to execute the sub query from the first query. Here is the question "I'm looking for the best way for the user to be able to click on any of the returned results in order to invoke a query. For example, the results being returned right now are a list of Product Categories. The user should be able to click on any of those categories to get a list of products in that category." In this post what I have made some modification to my last post to achieve the desire result. Here is the look of the form , I have divided the result area into two half area so when user click on the parent record then the detail of the parent record is shown in that detail area.


The changes which I have made to get desired result is that I have now pick the countries from the Employees tables and depending on the value of the country in the dropdownlist employees are populated and then from there I have added a button with each employee record to see the order list attached with the employees. The population of the dropdownlist control is same except the sql query to populate the dropdownlist control is changed. Same is the case of the onChange event of the dropdownlist it is same but the sql query to retrieve the list of employee is changed. If you look at the main screen image which I have attached at the top, you can see that I have added a button control with each record of the employee. Here is the addition line of code which is added with each of the employee records to add the button for employees orders. You can see from the code below that here I am attaching the orderList javascript functin with the button which is used to make ajax call again to retrieve the list of order attached with the employees. I have pass the employee id to the orderList function, as employeeid is used as foreign key in the order table.
Response.Write("< type="'button'" class="'Button'" onclick="'OrderList(">+ strEmployeeID+ " );' >Employees Orders< / button> ");
And here is the OrderList function on the main form. where I have to display the result or you can say the page where the employee detail is displayed. This function is similar to the ShowCustomer function except for the few minor things. First I have change the country query string parameter to employeeid parameter. and second difference is the call of the on change event handler which in this case is the OrderCallstateChanged, where I am assigning the return responseText to the sub detail div which is the divEmployeeOrders div.
/**************************************************************************
Retreive the list of the order based on the employee id.
**************************************************************************/
function OrderList(strEmployeeID)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="OrderDetail.aspx";
url=url+"?EmployeeID="+strEmployeeID;
url=url+"&sid="+Math.random();
url=url+"&type=1";
xmlHttp.onreadystatechange=OrderCallstateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
return false;
}
/**************************************************************************
+++++++++++++++++++++++++++++++++++++++++
**************************************************************************/

/**************************************************************************
State changed event to retreive the orderl ist
**************************************************************************/
function OrderCallstateChanged()
{
if (xmlHttp.readyState==4)
{
var divDetail = document.getElementById("<%= divEmployeeOrders.ClientID%>");
divDetail.innerHTML = xmlHttp.responseText;
}
}
/**************************************************************************
+++++++++++++++++++++++++++++++++++++++++
**************************************************************************/
Hope this will solve your problem. You can download the source code from here.

All and any comments / bugs / suggestions are welcomed!


Thursday, June 25, 2009

What is Cloud Computing?

Life before cloud computing
Traditional business applications—like those from SAP, Microsoft, and Oracle—have always been too complicated and expensive. They need a data center with office space, power, cooling, bandwidth, networks, servers, and storage. A complicated software stack. And a team of experts to install, configure, and run them. They need development, testing, staging, production, and failover environments.When you multiply these headaches across dozens or hundreds of apps, it’s easy to see why the biggest companies with the best IT departments aren’t getting the apps they need. Small businesses don’t stand a chance.

Cloud-computing: a better way
Cloud computing is a better way to run your business. Instead of running your apps yourself, they run on a shared data center. When you use any app that runs in the cloud, you just log in, customize it, and start using it. That’s the power of cloud computing.Businesses are running all kinds of apps in the cloud these days, like CRM, HR, accounting, and custom-built apps. Cloud-based apps can be up and running in a few days, which is unheard of with traditional business software. They cost less, because you don’t need to need to pay for all the people, products, and facilities to run them. And, it turns out they’re more scalable, more secure, and more reliable than most apps. Plus, upgrades are taken care of for you, so your apps get security and performance enhancements and new features—automatically.
The way you pay for cloud-based apps is also different. Forget about buying servers and software. When your apps run in the cloud, you don’t buy anything. It’s all rolled up into a predictable monthly subscription, so you only pay for what you actually use.Finally, cloud apps don’t eat up your valuable IT resources, so your CFO will love it. This lets you focus on deploying more apps, new projects, and innovation.The bottom line: Cloud computing is a simple idea, but it can have a huge impact on your business.

What is Cloud Computing?
Cloud Computing is a relatively new term that conveys the use of information technology services and resources that are provided on a service basis. According to a 2008 IEEE paper, “Cloud Computing is a paradigm in which information is permanently stored in servers on the internet and cached temporarily on clients that include desktops, entertainment centers, table computers, notebooks, wall computers, hand-helds, sensors, monitors, etc.”


History of Cloud Computing
In network diagrams, resources that are provided by an outside entity are depicted in a “cloud” formation. In the current (but still evolving!) model of cloud computing, the cloud computing infrastructure consists of services that are offered up and delivered through data centers that can be accessed from anywhere in the world. The cloud, then, in this model, is the single point of access for the computing needs of the customers being serviced.

In the cloud computing definitions that are evolving, the services in the cloud are being provided by enterprises and accessed by others via the internet. The resources are accessed in this manner as a service – often on a subscription basis. The users of the services being offered often have very little knowledge of the technology being used. The users also have no control over the infrastructure that supports the technology they are using.

Pros and Cons of Cloud Computing
In cloud computing models, customers do not own the infrastructure they are using, they basically rent it, or pay as they use it. The loss of control is seen as a negative, but it is generally out-weighed by several positives. One of the major selling points of cloud computing is lower costs. Companies will have lower technology-based capital expenditures, which should enable companies to focus their money on delivering the goods and services that they specialize in. There will be more device and location independence, enabling users to access systems no matter where they are located or what kind of device they are using. The sharing of costs and resources amongst so many users will also allow for efficiencies and cost savings around things like performance, load balancing, and even locations (locating data centers and infrastructure in areas with lower real estate costs, for example). Cloud computing is also thought to affect reliability and scalability in positive ways. One of the major topics in information technology today is data security. In a cloud infrastructure, security typically improves overall, although there are concerns about the loss of control over some sensitive data. Finally, cloud computing results in improved resource utilization, which is good for the sustainability movement (i.e. green technology or clean technology.)


Reference
1) What is Cloud Computing?
2) What is cloud computing?



Tuesday, June 23, 2009

This Week in jQuery, vol. 2

while reading the second post related to the "This week in jquery, Vol. 2", I have found new and nice plug-ins. One of which is the time picker. Here is the link for the time picker where you can find the documentation and the on line example of the time picker. The next plug-in is the "fun little text effect" which is very cool and nice the most favorite or you can say the functionality I like most about it is the "typewriter", when you apply this functionality it seem that someone is writing directly in the text box or some area. Here is the complete post of the series.

jQuery Core Development
Brandon Aaron has been on a roll the past few days, fixing bugs and enhancing features for the next version of jQuery. Among the updates committed to the Subversion repository were better support for nested fixed position elements and added support for contexts other than document with the .live() and .die() event delegation methods. See the past week’s timeline here.


Plugins
  • A new release of Haineault’s Timepickr plugin is available.
  • Diego A. has updated his Star Rating plugin.
  • Jason Frame put together a set of “fun little text effects.”
  • The new Flexbox acts as a “replacement for html textboxes and dropdowns, using ajax to retrieve and bind JSON data.”
  • Not really a plugin, Sunday Morning is a fun jQuery-based translation bookmarklet using the Google Translate API.
Tutorials and Blog Entries

Reference
1) Jquery Blog

Monday, June 22, 2009

This Week in jQuery, vol. 1

While reading about the latest of the jquery from the jquery blog, I have read the series of blog post on the jquery side. From the first post of the "This week in Jquery " series, what I like most about this series is that it give latest new related to the jquery, plug-in and there bug fix etc. While reading the first post of this series, what I about this post is that masked input plug-in and
OS X Dashboard Widgets with jQuery and many more Here is the complete article for you hope you will also like it.
This is the first in what we’re hoping to be a weekly series of blog posts about what is going on in the world of jQuery. We’ll take a look at new or updated plugins, recent tutorials, and other jQuery-related news.

Book
Jonathan Chaffer and I (Karl Swedberg) just had our book Learning jQuery 1.3 published by Packt Publishing. It’s an update of the popular Learning jQuery book, which was released nearly two years ago. The new one features additions to the library (event namespacing, JSONP, new effects methods, etc.) introduced since the release of the first book, improved and extended examples, expanded plugins chapters, and a quick reference to all methods and selectors. It’s available on the Packt website and on amazon.com.


Magazine

JSMag, a promising new magazine for JavaScript developers, just published their first issue. The magazine’s goal is to provide “quality JavaScript content to educate, motivate and inspire you in your work with JavaScript.” PDF-only issues are US$4.99 each, with bulk licensing discounts starting at 30% off the individual price. Contents of the first issue include:

  • Debugging JavaScript without alert()
  • Introduction to ExtJS
  • Community News
  • Unit testing with YUI
  • What’s new in jQuery 1.3
  • Functional Programming in JavaScript

Check out a sample (PDF) from the first issue.

Plugins

Among the ever-growing selection of jQuery plugins, a few perennial favorites were updated this week. Ariel Flesler released version 1.2.7 of his LocalScroll plugin, which animates anchor navigation within a web page. Mika Tuupola updated his Jeditable plugin, for seamless in-place editing, with a number of “callback hooks” and a few bug fixes. Josh Bush’s new version of Masked Input includes bug fixes and a few feature enhancements as well.

After looking for a simple, fast and flexible grid/spreadsheet component, Michael Liebman decided to roll his own. This week he put out a call for contributors, seeking “experienced developers who can pick this up and turn it into something that everybody can use,” perhaps by converting it into a plugin. The code can be found at http://code.google.com/p/slickgrid/.

Tutorials
Steve Reynolds has posted a tutorial on how to create OS X Dashboard Widgets with jQuery. For those who want to know “What in the heck is JSONP and why would you use it?” Raymond Camden gives you the answers on the O’Reilly Inside RIA blog (hint: cross-domain ajax).

Reference
1) Jquery Blog


Sunday, June 21, 2009

Jquery Accordion Using WPF Animation

While seeing many of the jquery animations I have tried every animation of the jquery in WPF, as I am currently working in WPF, this help me a lot learning the WPF by implementing the jquery animation in WPF.In this post I have implemented the Accordion animation of the jquery in WPF. Here is the main screen of the example code which is similar to the original link you can check it as well. I have made is very simple as you can see I didn't place any detail of the sections.


Let me explain the example code. From the main screen if you look at the xaml of the main form you can see that I have added a stack panel and then I have added a grid control which has three rows. each row consist of the border and a stack panel.When the border is clicked the corresponding stack panel in the same row is set the maximum height. And the Grid is kept in the stack panel control. This what I have on the xaml side of the application. Now come to the code behind file which is cs file in this case as I am using the C# language for this application. First I have Stack panel object which is used to save the previous stack panel, as when the animation begin the previous stack panel which have maximum height is decrease to the minimum height which is 0(zero). Then I have local variable which is used to save the maximum height of the stack panel. Here is the code which is used to animate the current stack panel, if you click the any of the section label or blue strip then then the animation start ,increasing the height of the current stack panel and decreasing the height of the previous stack panel.
private void AnimateCurrentStackPanel(StackPanel pspnlCurrentPanel)
{
DoubleAnimation dblaCurrentStack = new DoubleAnimation();
dblaCurrentStack.From = 0;
dblaCurrentStack.To = dblStackPanelHeight;
dblaCurrentStack.Duration = new Duration(TimeSpan.FromMilliseconds(200));

Storyboard strbCurrentStoryBoard = new Storyboard();
strbCurrentStoryBoard.Children.Add(dblaCurrentStack);
Storyboard.SetTarget(dblaCurrentStack, pspnlCurrentPanel);
Storyboard.SetTargetProperty(dblaCurrentStack, new PropertyPath(StackPanel.HeightProperty));

if (spnlPreviousStackPanel != null)
AnimatePreviouseStackPanel();

strbCurrentStoryBoard.Begin();
spnlPreviousStackPanel = pspnlCurrentPanel;
}
You can see in the AnimateCurrentStackPanel function that this function will increase the height of the current panel which is passed to this function and before the story board begin I have place the if condition to check the previous stack panel object if it is not null, then call the AnimationPresiousStackPanel function which is used to decrease the height of the previosue stack panel. When the application run for the first time , as I have set the maximum height of the first section so in the constructor of the form I have assign the spnlFirstSection to the previous stack panel object. And here is the definition of the AnimatePreviouiseStackPanel. Which is used to decrease the height of the previouse stack panel.
private void AnimatePreviouseStackPanel()
{
DoubleAnimation dblaPreviouseStack = new DoubleAnimation();
dblaPreviouseStack.From = dblStackPanelHeight;
dblaPreviouseStack.To = 0;
dblaPreviouseStack.Duration = new Duration(TimeSpan.FromMilliseconds(200));

Storyboard strbPreviousStoryBoard = new Storyboard();
strbPreviousStoryBoard.Children.Add(dblaPreviouseStack);

Storyboard.SetTarget(dblaPreviouseStack, spnlPreviousStackPanel);
Storyboard.SetTargetProperty(dblaPreviouseStack, new PropertyPath(StackPanel.HeightProperty));

strbPreviousStoryBoard.Begin();
}
I hope that you got some understanding of the accordion animation of the jquery will be used in the WPF application.You can download the source code from here.

All and any comments / bugs / suggestions are welcomed!


Saturday, June 20, 2009

What’s New in Expression Blend 3 Preview

While using the latest version of the expression blend 3 I have found some cool new feature of the expression blend especially the support for editing the source file like C# (which I have used for my project) in the expression blend which was not provided in the expression blend 2, If you need to edit the code behind file then you have to open the visual studio or other editor. Here are the list of new features of the expression blend 3.
With Microsoft Expression Blend 3 Preview, you can create Windows Presentation Foundation (WPF) applications for the desktop and Microsoft Silverlight 3 applications for the web. Expression Blend 3 Preview is a major new release, taking the product in a number of new, important directions, such as on-the-fly sample data generation. We also added support for several Silverlight 3 features. Expression Blend 3 Preview is a step on a long journey towards tools that are meant to empower designers to participate in the process of software creation in deep, meaningful, and creative ways. Using Expression Blend 3 Preview, you, the designers, can make computers easier and more fun to use, and can delight customers with great applications and great content.

Design

1) Importing Photoshop and Adobe Illustrator files
You can now use Expression Blend 3 Preview to import both Adobe Photoshop (.psd) files and Adobe Illustrator (.ai) files directly into your projects, while retaining layers, shapes, text elements, and more for easy editing inside Expression Blend itself. Note: Adobe live effects, blend modes, and the symbol sprayer are not supported. When you import an Adobe file, Expression Blend 3 Preview will display a message to let you know if any features of the imported file are not supported, and what actions you can take.

2) Effects
Expression Blend 3 Preview introduces support for WPF and Silverlight graphic effects. Open the Asset Library, click the Effects tab, and drag an effect onto an object. You can modify properties of the effect in the Properties panel.

3) Gradient tool improvements
Expression Blend 3 Preview makes using the gradient tool even easier and more powerful than in earlier versions. You can now change the offset values of a gradient directly on an object that has a gradient applied to it. To change a stop position, you just drag the stop. To add a new stop, hold down the ALT key and then click the gradient adorner. You can also quickly redefine the gradient by dragging a new gradient adorner onto the artboard. When you double-click anywhere on the artboard, a color picker appears. You can use the color picker to change the color of the stop.

4) Layout operation improvements
Expression Blend 3 Preview introduces several improvements to layout operations. Moving objects with direct manipulation on the artboard is more consistent and predictable, alignment adorners are shown for more containers, layout properties and bindings are preserved when reparenting or grouping objects, and layout properties are no longer written to the XAML code-behind file unnecessarily.


5) Design-time annotations
Designers can now add visual bubble annotations (very similar to Microsoft Visio comments) to the artboard. These annotations are stored in the XAML file in the form of attached properties. They can be used to improve communication between team members. The annotations do not appear at runtime.

Skinning

1) Creating templates from artwork
You can use the modified Make Into Control menu command to select artwork on the artboard and to convert it into a skin (control template) for a control. From there, you can right-click objects and click Make Into Part to assign objects in your control to specific roles. For example, if you convert artwork to a Slider control template, you can then select one of the objects in your template and assign it to the role of the slider's HorizontalThumb. The Parts panel makes it easy to manage and create the parts required by a control template.

2) Improved support for VSM
Support for the Silverlight Visual State Manager (VSM) in Expression Blend 3 Preview has been improved with a revised user interface for the States panel. You can see more states for controls, regardless of whether those states were defined in your XAML originally, and the States panel displays a warning indicator when a property has been changed in more than one state group.

3) State pinning
You can now pin a preview of one state in a state group while modifying another state in a different state group.

4) Editing state transitions
You can select the storyboard for a state transition and modify it in the Objects and Timeline panel.

5) Drawing into state
When you select a state and draw a new element, the new element will be visible only in the selected state at runtime. This is called drawing into state.

Interactivity

1) XAML, C#, and Visual Basic Code Editing
Expression Blend 3 Preview improves on its XAML support by introducing time-saving features. With Expression Blend 3 Preview, you can modify C# and Visual Basic code files right inside the product. The code editor supports several features that you can use to increase your productivity when you modify code. These features include IntelliSense (syntax completion), auto-formatting, brace matching, function summary writing, event handler creation, and more.

Data

1) Using sample data
Expression Blend 3 Preview makes it easy to create and test data-connected applications without having access to live data. You can use the Data panel to generate sample data or import sample data from an XML file. Sample data is available to controls on the artboard at design time. You can extensively customize your sample data details, and you can easily switch between using sample data and using live data at run time. For more information, see Use the DataGrid control.

2) Data binding
Expression Blend 3 Preview also includes the following new data binding features:
  • The ability to drag and drop items of data from the Data panel into the Objects and Timeline panel to create data bindings.
  • The ability to bind the property of one object to a property of another object in Silverlight 3.
  • Support for the DataGrid control in Silverlight 3 applications.
  • Support for Master/Detail scenarios by using the list view and details view of the Data panel.
  • Improved support for binding to a data context.
  • The ability to define hierarchical data schemas that enable you to create data connected applications.
Silverlight

1) Silverlight 3 support
You can create and modify Silverlight 3 applications in Expression Blend 3 Preview. If you open a Silverlight 2 project, Expression Blend 3 Preview will display a dialog box to ask if you want to update your project files from Silverlight 2 to Silverlight 3.

Web site support

1)Using sample data
When you create a new Silverlight project in Expression Blend 3 Preview, you now have an additional project type called Silverlight Application + Web Site. When you create a Silverlight application using this kind of project, you get both a Silverlight application and an associated website with a default HTML page that will load your Silverlight application.

Source file version control

1)TFS support
Expression Blend 3 Preview introduces support for Microsoft Visual Studio 2008 Team Foundation Server. You now have the ability to perform common source control–related tasks on solutions and projects such as checking in, checking out, merging, and more.

Animation

1) More properties available to animate
In a Silverlight project, you can now record keyframes for many more properties than before. To help with this, there is a new menu command, Record Current Value, on the Advanced property options menu that appears when you click the marker next to individual properties in the Properties panel.

2) Better support for easing in Silverlight
You can now apply predefined, named easing functions to individual keyframes by selecting a keyframe and then selecting an EasingFunction in the Properties panel.

3) Animating to resource values
You can now animate to/from some resources. For example, you can animate a color property from a static value to a color resource. To select the color resource, use the Advanced property options pop-up menu on the Editor tab in the Brushes category of the Properties panel.

Text

1) Improved embedding of fonts and subsets of fonts
With Expression Blend 3 Preview, you can easily embed and create subsets of fonts in Silverlight and WPF projects. The new Font Manager lets you select fonts installed on your computer and customize which subset of the characters to embed.

Extensibility

1) Extensible Asset Library
You can populate the contents of the Asset Library in Expression Blend 3 Preview by registering a directory that contains one or more assemblies. You can write your code to display custom icons and more. You can also instantiate controls stored in those known assemblies, and Expression Blend will then add the necessary assembly references to your project.

2) Artboard extensibility
Expression Blend 3 Preview introduces more refinements to the extensibility APIs for WPF and Silverlight. The extensibility points are compatible with the Microsoft Visual Studio designer, and you also have more flexibility to extend the artboard.

3) Extensible project templates
Expression Blend 3 Preview now supports extensible project templates, which provide customizable project and item stubs to improve project creation. These project templates, which are a subset of what Visual Studio supports, can be used to create complex solutions with inter-project dependencies and assembly references.

Workspace

1) Docking and workspace configuration
Expression Blend 3 Preview extends the workspace configuration features found in earlier releases by providing full docking support for all panels. You can customize the Expression Blend 3 Preview user interface to your liking and save this configuration as a preset.

2)Direct selection improvements
Expression Blend 3 Preview contains some significant changes to the selection model that will make it easier to change your selection and draw new objects on the artboard. The changes include extending the functionality of the Selection tool to behave similarly to the Direct Selection tool, and improving the creation and parenting behavior on the artboard with the help of visual indicators and gestures.

3) Marquee selection of points
When you use the Direct Selection tool, you can now select individual points on a path by using marquee selection. Just drag to define the area that contains the points you want to select.

4) Auto-scroll and zoom improvements
Now, when you move or resize an object, the Expression Blend 3 Preview artboard scrolls automatically. If you move the cursor past the artboard, the scrolling will stop. Another change is that rotating the mouse wheel now zooms the artboard by default.

5) Keyboard shortcuts and modifier keys
Expression Blend 3 Preview makes common tasks easier by introducing new keyboard shortcuts and modifier keys for actions such as direct selection, marquee selection, duplication of content, panning/zooming, and more.

Source for the above list of features.


All and any comments / bugs / suggestions are welcomed!


Using Sql In Operator In Select Function of DataTable

During work related to storing the sql server tables in local cache like in DataSet, Data table, I often need to use the Select function of the data table. To which I have to pass some expression to filter the records of the table, I have used simple equality expressions to filter the records. But few days back I have to filter the record based on the Ids, Where I have to pass the multiple values of the key columns, and I have to use the in operator of the sql server in C#. Here is the simple example to share my knowledge with you.
For this example I have sued the region and the territory table of the northwind database and I have store the database in simple xml format so if anyone of you don't have sql server or northwind database the example still run fine. For the Gui I have added check box list control which is used to bind the region table and then I have the grid view control which is used to display the filtered record when user select the region from the check box list and then press search button. Here is the main screen of the example.

Here is the code for the search button which is used to built the comma separated list of the region id in a string format. In this example I have set strRegionIDs to globally static type, as I have set the allow paging of the grid to true, so if user set the filter criteria and move to the next page then same filter criteria will be used.
protected void cmdSearch_Click(object sender, EventArgs e)
{
strRegionIDs = string.Empty;
foreach (ListItem listItem in chkRegion.Items)
if (listItem.Selected)
{
if (strRegionIDs.Trim() == string.Empty)
strRegionIDs = listItem.Value.ToString();
else
strRegionIDs += "," + listItem.Value.ToString();
}
grdvResultGrid .DataSource = GetGridDataTable();
grdvResultGrid.DataBind();
}
And here is the definition of the GetGridDataTable function. This function will be used when paging on the grid is clicked and when user press the search button on the main screen. At the start of the function I have declared the tblReturnTable variable which is returned from this function. I have used the Clone function of the second table so that the structure of the tblReturnTable have same structure of the second table in the dataset have which is the territory table. Next I have the strexpression variable which is used to have the filter criteria in this case it will contain the in operator of the sql. Note that I have used same structur of the in operator just like sql used it.
private DataTable GetGridDataTable()
{
DataTable tblReturnTable = dsRegions.Tables[1].Clone();
string strExpression = string.Empty;

if (strRegionIDs.Trim() != string.Empty)
strExpression = "RegionID in (" + strRegionIDs + ")";

DataRow[] dtrMatchResult = dsRegions.Tables[1].Select(strExpression);
foreach (DataRow dtrCurrentRow in dtrMatchResult)
tblReturnTable.ImportRow(dtrCurrentRow);

return tblReturnTable;
}
After filter the records from the second table of the dataset (territory table) I have loop through the resultant rows and place them in the new table and then return that table. In this example I have also set the dsRegion dataset set as stattic so I have to populate it once the page is loaded. You can download the source code from here.

All and any comments / bugs / suggestions are welcomed!


Sunday, June 14, 2009

How To get Total Memory of Computer

In this post I will show you how you can get the Total Ram of your computer. This example is in VB.net, after explaining the code I will tell you how you can use this code in your C# language and get the total memory of the computer. To get the total memory of the computer what you have to do is to import the Microsoft.VisualBasic.Devices namespace in your file and then use the ComputerInfo class of that namespace. The ComputerInfo class Provides properties for getting information about the computer's memory, loaded assemblies, name, and operating system. Here are some of the useful properties which are used to get the total physical and virtual memory.
Property Name
Description
AvailablePhysicalMemoryGets the total amount of free physical memory for the computer
AvailableVirtualMemoryGets the total amount of the computer's free virtual address space.
TotalPhysicalMemoryA double-precision floating point number data type
TotalVirtualMemoryGets the total amount of virtual address space available for the computer.
Here is the code which is used to get the Available Physical Memory, Available Virtual Memory, Total Physical Memory and the Total Virtual Memory.
Sub Main()
Dim computerInfo As New ComputerInfo

Console.WriteLine("Available Physical Memory: {0}", computerInfo.AvailablePhysicalMemory)
Console.WriteLine("Available Virtual Memory: {0}", computerInfo.AvailableVirtualMemory)
Console.WriteLine("Total Physical Memory: {0}", computerInfo.TotalPhysicalMemory)
Console.WriteLine("Total Virtual Memory: {0}", computerInfo.TotalVirtualMemory)

End Sub
And here is the output of the above code. Which display the Available Physical Memory, Available Virtual Memory, Total Physical Memory and the Total Virtual Memory.


If you want to use this code in your C# language what you have to do is to import the Microsoft.VisualBasic.Devices name space by using the using Statement in you file and then you will have the ComputerInfo class accessible in you code and you can use that class to get the information.

All and any comments / bugs / suggestions are welcomed!


Saturday, June 13, 2009

Using PadLeft Function for Integer Values

Sometimes you may need to show series number along the record to show total number of records, or you may show the size of particular object and compare it with the size of the other object.In case of your serial number for the record, lets says you have total 100 records starting from 1. Then your serial number will be 1,2,3,4 ..... 100. You see that from 1 to 9 serial number consist of one digit and from 10 to 99 it consist of 2 digit and then last is the 100 which consist of 3 digit. In order to have all the serial number of same number of digit you can use String.PadLeft method and give the character to pad. Here is the Pad function of the string which consist of the PadLeft and the PadRight.
  1. PadLeft:This method right-aligns the characters in a string, padding on the left with spaces or a specified character for a specified total length.
  2. PadRight:This method left-aligns the characters in a string, padding on the right with spaces or a specified character, for a specified total length.

Here is the code which is used to show you how you can use the PadLeft string function to add 0 (zero) on the left side of the integer value. You can see from the code that I have three integer variables intMaximumValue , intAverageValue and the intMinimumValues which hold the Maximum Values, Average Value and the Minimum Values. Here I have 100, 50 and 1 as Maximum , Average and Minimum values.
static void Main(string[] args)
{
int intMaximumValue= 100;
int intAverageValue = 50;
int intMinimumValue = 1;

Console.WriteLine("Original Values:\n{0}\n{1}\n{2}",intMaximumValue,intAverageValue ,intMinimumValue );
Console.WriteLine("Padleft: {0}", intMinimumValue.ToString().PadLeft(intMaximumValue.ToString().Length,'0'));
Console.WriteLine("Padleft: {0}", intAverageValue.ToString().PadLeft(intMaximumValue.ToString().Length, '0'));
Console.WriteLine("Padleft: {0}", intMaximumValue.ToString().PadLeft(intMaximumValue.ToString().Length, '0'));
}
In the code above I have used the PadLeft function of the string. Which take the total width and the padding character, Here I have used the intMaximumValue.ToString().Length to calculate the total width for the PadLeft function and I have passed '0' (zero) to be pad on the left side of the value. Here is the output of the above code and you can see after PadLeft all the three value are consist of 3 digits.

When using the PadLeft function it will return new String that is equivalent to this instance, but right-aligned and padded on the left with as many paddingChar characters as needed to create a length of totalWidth. Or, if totalWidth is less than the length of this instance, a new String that is identical to this instance. Here are the detail of the two overloaded function of the PadLeft string function

Data Type
Description
PadLeft(Int32)Right-aligns the characters in this instance, padding with spaces on the left for a specified total length
PadLeft(Int32, Char)Right-aligns the characters in this instance, padding on the left with a specified Unicode character for a specified total length.


All and any comments / bugs / suggestions are welcomed!