Welcome to MSDN Blogs Sign in | Join | Help

Microsoft Maren, Write Arabic in English letter anywhere you like

By Mostafa Ashour, PM of Maren Team

Dear All,

 

We’re pleased to announce that today the Cairo Microsoft Innovation Center (CMIC) is releasing Microsoft Maren, a Windows extension that allows you to type Arabic in Roman characters and have it converted on the fly to Arabic script.  Maren integrates seamlessly with Windows and works in most Windows applications and websites.

 

We are inviting you to download and install Maren from: www.GetMaren.com

 

Email or IM a friend. Comment on a photo. Search the web. Write a document. Blog. Keep a to do list. Maren makes it easier to complete many day to day tasks in Arabic and using the applications you use today for accomplishing these tasks.

 

So please help us out and spread the word:

·         Tell people about GetMaren.com

·         Forward this email to your friends and family

·         Join the Facebook group

Posted by mohammed hossam | 0 Comments
Filed under: ,

Windows 7 RC downloads will end August 15th

From Windows Team Blog post at http://windowsteamblog.com/blogs/springboard/default.aspx

 

“Still on the Windows 7 Beta,? You need to move to the RC and fast. Starting July 1st, the Beta will start to reboot every 2 hrs and expire Aug 1st.

Want to download the RC? . The RC download program closes August 15th. After that, you won’t be able to get the download, but you can still install the RC and get a key if you need one. (To get a key, just go to the Downloads page and follow the instructions.)

If you’re using the Windows 7 Release Candidate, we hope you like what you see. Let us know -- go to http://input.microsoft.com and tell us what you think. You’ll be able to give feedback on various aspects of the operating system.”  

Posted by mohammed hossam | 0 Comments
Filed under:

WhyLinuxIsBetter.net Seriously!

I enjoy going in debates with Linux fans, and I always enjoy reading about Linux and how it evolves, and how every single calendar year Linux fans consider it Linux Desktop year, however this time I need to write this reply on what is listed on http://www.whylinuxisbetter.net/ because some of the reasons just don’t make sense, and it is always the same Linux 2009 vs Windows 9x kind of reasons

I will go through them one by one, and remember this is my own opinion from my experience, it is not by any means Microsoft’s opinion

1- Forget About Viruses

Sure, I am with you, when I Linux has with the most optimistic statistics 1% of market share, with a majority of Geeks (no offense I am a geek myself) that know what they are doing, you sure have to forget about viruses, who is going to waste his time targeting this!

and now seriously, if you accept attachments from people you don’t know, or auto running flash drives that has been used on tons of other non trusted machines, running your machine with Admin rights 100% of the time, not using a decent anti-virus, it is like unsafe sex, if you don’t take care and avoid all warnings you should be responsible.

2- Is Your System Unstable

Sure, my system is stable, I didn’t reinstall my Windows XP back home in Cairo for more than 2 years, let me rephrase it, since I purchased that pc, I have 2 laptops at home with Vista Home * Windows 7 RC, and 2 machines at work with Windows Vista Enterprise, Server 2008, I didn’t reinstall windows on any of these boxes since I got them, I just installed Windows 7 RC on my laptop and I have been enjoying using it since then.

Do you wanna know my secret

  • Keep your machine updated with latest updates, Service Packs … etc
  • Use trusted drivers for your hardware

Don’t tell me you don’t need the previous two reasons to keep your Linux box stable.

3- Don’t Pay $300 for your Operating System

mmm, this is also not true, especially when you buy an OEM machine, you get the OS almost for free, for example compare Netbooks prices Ubuntu & Windows ones, how much difference? about $20 and what you get is peace of mind for $20 in terms of support and being part of the world (use same programs playing same games) is another thing :)

In the other non OEM case, I can still argue that it depends, especially when customers start returning their Linux netbooks, which means that the $300 is not for nothing, somebody made effort and studies making this use friendly and easy to do real business on, also rates are different $300 is a rough number, it depends on the classifications (students, business, home users) everyone has his way of getting legal software in a way that is suitable for his case, also Developers have to eat :)

4- Freedom

Ok, I agree with this point to an extent, the right to copy distribute and modify is certainly a plus in the Linux world, however I strongly disagree with this statement mentioned there

"So what do you care about freedom? Imagine that Microsoft disappears tomorrow (okay, that's not very likely, but what about in 5 years, 10 years?). Or imagine it suddenly triples the price for a Windows or Office license. If you're tied to Windows, there's nothing you can do. You (or your business) relies on this one company, on its software, and you can't possibly make things work without it (what good is a computer without an operating system?). Isn't that a serious problem? You're depending on one single company and trusting it wholeheartedly to let something so important nowadays as your computers work the way they should. If Microsoft decides to charge $1000 for the next version of Windows, there's nothing you can do about it (except switch to Linux, of course). If Windows has a bug that bothers you very much and Microsoft won't fix it, there's nothing you can do (and submitting bugs to Microsoft isn't that easy, see the "Report bugs" section).”

We are still in a free market, the prices are controlled by supply & demand, if Microsoft tripled the price of Windows or Office, there are other Software vendors can compete and already are competing, and also there are Laws that governs the market and everybody knows that it is very tempting for some people to charge Microsoft for anything.

5- When the System has installed, why would you still need to install stuff?

Windows already comes with most of daily use software, and offers free download for more advanced stuff

  • Windows Photo Gallery
  • Windows Media Player
  • Wordpad, Notepad
  • Internet Explorer
  • Windows Live Messenger
  • Built in Zip compressor/decompressor
  • Windows Movie Maker
  • CD/DVD burner
  • Windows Games
  • Parental Control
  • Windows Media Center (Windows XP Media Center, Vista Home Premium, Vista Ultimate)
  • Windows Live Mail
  • Windows Live Writer (the one I used to write this post)
  • Paint (basic editor)
  • Paint.net Advanced Editor
  • Windows Defender
  • ….

Most OEM providers preinstall the machine with software like

  • Adobe Reader
  • Microsoft Works
  • Alternate CD/DVD burner
  • Antivirus (Mcafee, Norton, Windows Live One Care … etc)

You can still download your favorite software for other uses, it is your computer customize it the way you want, every single application mentioned on Linux can be used on Windows too, what’s the problem ?

6- Forget About Drivers

Ha, yes I can forget about drivers if I am using Linux, no comment

7- Update all your software with Single Click

This is a very nice feature I like in Ubuntu, and I wish it happens in Windows, Windows Update as far I know only updates Microsoft software + partner drivers but every software needs its own way of managing updates, I really appreciate the effort made in Linux making this happen.

8- Why copy software illegally if you can get it free

Yes, I really encourage if you are not willing to use legal software to use free software.

9- Need new Software, Don’t bother search the web, Linux gets it for you

This is a good way of finding software, Windows Market place is one place to go, however the Windows ecosystem is huge, and it is almost impossible to put everything in one place, however places like download.com does a good job for being a one stop shop for most applications

10 - Jump into the next generation of desktops.

Be my guest exploring the next generation of USABLE desktop http://www.microsoft.com/windows/windows-7/videos.aspx with the multi-touch capabilities and tons of time savers and search without the need to turn my desktop into a cube wasting my time rotating the desktop to find my icons, xgl is a nice eye candy, but it is far from usable

11- Does your digital life seem fragmented ?

This is a myth that Linux doesn’t need defragmentation, it is proven so many times, for example here & here, as a matter of fact I didn’t defrag a drive since 2002 :D it just doesn’t do much, and in general Windows boot up time and application startup times are way faster that they are on Linux, even for the same application, try Open Office on Windows Vista & Ubuntu and see the difference.

12- Choose what your desktop looks like.

Having a default consistent UI that evolves with the customer feedbacks is what making Windows great, and what makes customers use windows, and as long you are providing the right API’s for third parties to go crazy you’ve done your job as an operating system, but having inconsistent UI is something that will frustrate users, developers and almost everybody, because different concepts means more points where application can break, an example of third party crazy and cool alternatives are BumpTop or Talisman

13- Why does your Windows get slower day after day

I agree, if you keep installing every piece of junk you find on the internet that adds more services and startup stuff in your machine, and this is simple, more application running, the slower it gets, it doesn’t matter what OS you’re running, of course there are more applications on windows and also more crapware as a side effect, but it is the same as if you know what you’re doing you will have a healthy machine for years, and Windows comes with tools such as msconfig to show you what starts up with your system, and you can use more power tools like sysinternal tools to see exactly what happen to optimize every bit of performance possible, again it is a user behavior problem, not a system fault.

14- Environment

Are you kidding, use Linux to be green?? you can purchase and download Windows online from Microsoft Store as well as any other piece of software, this is not a reason this is waste of time.

15- No backdoors in your software.

Oh my god, have you ever seen a privacy statement, don’t you know if Microsoft is sending private information about its customer without their approval is considered a crime, and it is very easy to prove, this is becoming really silly.

16- Enjoy free and unlimited support

Community support exists as long as there are users, if windows has more users you will find better support, you can ask a friend or a neighbor or ask a question on a forum or mailing list or chat or twitter or …

and the best thing that if you don’t know how to deal with it, for example my mom is not gonna use an IRC to ask for a problem, she can call Support centers, and Microsoft is providing support for its product for up to 10 years (5 basic, 5 extended paid), so imagine people are asking questions for Windows 2000 and Office 2000 till now.

17- Too many windows? Use workspaces.

Different people different keystrokes, in Windows too many windows? use Aero flip3d or Aero peek in Windows 7, or anything else, I have never been a fan of multiple desktops or workspaces, it just wastes time trying to know where stuff are, on which desktop and moving windows around between them, too much work for me

18 - Reporting bugs

Seriously, some bugs in Linux have been there for ages too, the bottom line that there are no software that is bug free and as long as high priority bugs are fixed as fast as possible, this is what makes customer safe and not bothered every single day with an update that affect 0.001% of the user base.

and the funny sentence

“Nearly all open source software (including Linux distributions) have a bug tracking system” I don’t know what to laugh about more, the word Nearly or mentioning the bug tracking system as a modern rocket science silver bullet solution, Microsoft builds bug tracking systems for god’s sake

19- Are your tired of restarting your computer all the time?

Again to Windows 9x culture that all Linux users are using to compare with Linux, My work machine has been up for weeks, I don’t restart my laptop unless I want to switch between Windows Vista & 7 mostly for fun, and I don’t bother restart if a windows update is provided, it is a good reason to restart especially it doesn’t take more than few seconds, compared to most Linux distros boot times

20- Let your old computer have a second life

This is also another meaningless point, at any point of time you will always have two different supported Windows Systems, if your computer is an above average you would like to use this hardware capabilities and run the newer version of Windows, otherwise you can still use the older version of windows, the same happens all the time, Windows 98, ME & Windows XP, Windows XP & Windows Vista, Windows Vista & Windows 7

and if you can install the latest Windows 7 Ultimate on a 1 GB ram, 1.6 Ghz Atom processor on a netbook, I think we don’t need to comment more.

21- Play hundreds of games for free

LOL, Are you serious games on Linux?

22- Help other countries, and your own

Hehehehe, so stop using Intel, AMD, MSI, Nokia, HTC, … etc every manufacturer has a country of origin, welcome to Planet Earth.

23- Use MSN, AIM, ICQ, Jabber, with a single program

What prevents you from doing this on Windows, the same programs that provides these capabilities on Linux, do that on Windows too

24- Get a great music player

Oh my god, I will change my entire OS to get a music player while I have (Windows Media Player, Winamp, GomPlayer, Windows Media Player Classic, Zune Player, iTunes, Quicktime, Real Player …. etc)

25- Keep and eye on the weather.

A weather application, I would give up my games and applications for a weather application, it is done with a gadget on Windows Vista and tons of other applications since forever, I still don’t see a point of mentioning this as reason.

The base line is so far Linux is not even close in terms of functionality, support of business to what windows is offering especially if you combined Windows + office or even with any well known and widely used software such as Adobe photoshop or Auto-CAD or 3D studio max … etc.

Thanks

Mohamed.

Technorati Tags: ,

kick it on DotNetKicks.com

Posted by mohammed hossam | 17 Comments
Filed under: ,

Microsoft to ship & support jQuery

A fresh announcement from ScottGu today, that Microsoft will be shipping jQuery (the light weight javascript library) in the long term with Visual Studio as well as shipping it in the short term with the next versions of Microsoft ASP.net MVC.

Microsoft also is going to develop new controls on top of jQuery, not only this but also full support for jQuery, which mean enterprises can open cases on Microsoft PSS for jQuery.

Great news, and very nice move

Here are some more details from ScottGu, Scott Henselman and jQuery

I'm a PC in MCDC

Posted by mohammed hossam | 0 Comments
Filed under:

I’m a PC, Do you have a problem with that?

I am a PC guy, I always was, for me PC gives more freedom, you can do whatever you like, build the craziest machine you think it is good for you, and you will never be over priced, with PC you are always in control, if you want to add more capacity, just go and buy a new hard drive, if you need more gaming capabilities upgrade your display adapter, more memory, get a new memory stick, as simple as this, you can make your machine evolves easily with your needs, if you want your pc to become a business machine you can, a gaming platform you can, a parent machine you can, you can find a pc from $100 to thousands of dollars depending on your needs, and for sure you can have fun building your own, I built a lot for me and my friends and it is always fun.

I'm PC, are you?

If you don’t like to build a pc, and prefer to buy it from a vendor, you still have a lot of choices, Dell, Toshiba, IBM, HP, Sony, Lenovo, … you name it, and every vendor has a great number of choices for you to choose from, and here are some of my favorite desktop & notebooks

First check out these fancy All-in-one PC’s from Dell,Hp and Sony

Dell - XPS One E4500 All-in-One

HP - TouchSmart All-In-One Desktop

Sony – All-in-one Desktop

VAIO JS Series Desktop PC

And check these amazing notebooks

Sony Vaio FW Series

Dell XPS M1530

HP HDX Series

Toshiba Satellite A300

And this is not the whole thing, these are just samples of the choices you have with a PC.

I’m a PC, are you?

Posted by mohammed hossam | 1 Comments
Filed under: ,

Live Mesh, Synchronizing Life

Windows Live has some great products, and you are already using bunch of them, Windows Live Messenger, Windows Live Hotmail, Windows Live Writer, Windows Live Photo Gallery, Windows Live Mail … etc, but the newest and the most interesting one is Windows Live Mesh.

Windows Live Mesh is simply one of those products that after you use it for couple of days, you find yourself saying “how I used to live before??” it solves so many problems that you used to live with them even though they are annoying.

With so many devices you deal with today for example (Your home PC, your work PC, your notebook, your Zune, your mom’s MAC, your mobile phone, your kids XBOX, … etc) keeping these devices in sync is very annoying, and simply you can get out of sync, and lose track with which device has the latest version of my documents, spreadsheets, images, files, contacts … etc

What Live Mesh is proposing, is a very simple elegant and natural solution, you simply need nothing more than what you do now, and you get a completely new experience, Imagine that you have this magic folder on your computer, that when you put anything in it, woooosh it appears in a matter of seconds on all your other devices, not just this, but if you want, your friends devices as well ;)

This is it, this is exactly what you do, any folder on your PC, MAC, Phone can be turned into this magic folder, with Windows Live Mesh.

So imagine this concept applies to your most important folders (Your documents, projects, music library, pictures, … whatever), how cool is that!!

Is this the whole thing, simply NO, you can also access your files even if you are not using any of your devices, from any internet device (as long as it has a browser) you can access your online windows live mesh desktop, and access your magic folders, even add some new folders/files to them and everything gets synced in seconds, what about a device that is not connected at the moment, no problem, once it gets connected, it will receive the updates.

Is this the whole thing, Still NO, it also gives you another amazing feature, you can access any of your devices in the Mesh remotely from the web, so even if you are not around your device, you can connect to it inside the browser, and do whatever you like on it, it is awesome.

If you like what you read so far, you like this the most, it is completely Free.

Here is a very nice video summarizes what I said earlier

Windows Live Mesh, Synchronizes Life

Now you can start simply by logging in www.mesh.com cool URI isn’t it ;) with your windows live ID, and add your devices, and be part of the Mesh, The current CTP supports only Windows XP/Vista, soon it will support Mac & Mobile Phones ;)

LiveJournal Tags: ,,
Posted by mohammed hossam | 2 Comments
Filed under: , ,

C# 4.0 Meet the team

Almost an hour of conversation about C# 4.0 from the (Almost new) C# team, you will be surprised who joined the new C# team which can give you a hint about the future of C#.

C# 4.0 is one of the greatest achievements of MS and it is still proving that with every new release, I can't wait to get my hands on some new bits :)


C# 4.0: Meet the Design Team
Posted by mohammed hossam | 2 Comments
Filed under:

Bill Gates, Looking Back, Moving Ahead

Billg moving ahead

 I know you are not waiting for me to know that last Full Time day for Bell Gates was yesterday, however I couldn't help it to write about this great journey that inspired everybody.

Bill Gates was always the perfect geek, and will always be, he is an inspiration for everybody, inside Microsoft, or outside, even his competitors can't deny his influence on them and how he could give the right vision and direction for the company in the last 3 decades.

 I will try to give you some goodies about Bill Gates, that I personally like

Bill Gates Harvard Speech (Believe me this one is funny :) )

Bill Gates Looking Back, Moving Ahead

Bill Gates in MacWorld in 1997 (The funniest part when Microsoft was planning to help Apple in Java)

Posted by mohammed hossam | 3 Comments
Filed under:

Hello World

Hey, this is my first blog post for my new blogs :)

I will copy some of my old blog posts that I personally like to this new blog, so you will find it being updated every now and then, keep in touch ;)

Posted by mohammed hossam | 1 Comments
Filed under:

My longest two weeks ever

Hey, It's been a while since my last blog post, I was somehow busy getting married, moving to another country, dealing with tons of paper work, however finally I had a weekend, and I am back to blogging, I have a lot to say, and I think it will be interesting enough for you to keep reading till the end

So basically this is what I am going to blog about today

  1. Last days in Cairo
  2. Moving to Canada & Vancouver City
  3. Microsoft Canada Development Center (MCDC)
    1. First Days
    2. MCDC Cares Day

Last days in Cairo

The past two weeks started with my wedding arrangement and God, this is very exhausting, lots of stuff to deal with, writing a guest list, however Thanks to Facebook I didn't have to call everybody, and the result I came out of the wedding experience is, my kids whatever their IQ will be, they will have one of two options in their career life, either being a wedding planner or a hair dresser and/or make up artist.

The wedding was nice, it was a very nice opportunity for me to see everybody before being relocated to Canada, I really thank everyone for showing up that night, I was really proud of my friends.

Moving to Canada & Vancouver City

Couple of days after my wedding I was in the plane with my wife heading to Vancouver, we had a 20 hours journey from Cairo, we had a connection in London, the flight went smooth and very nice, however my back hurts when I recall sitting for 10 hours from London to Vancouver.

Once we arrived to Vancouver, we took a cab to our temp house, the first thing I noticed the high-tech cabs, the cab has a GPS with maps for the city, and also a very interesting fare counter, the counter was moving like a stop watch, even when the cab wasn't moving, the counter continues to move, the ride from the Airport to the temp house, which took around 15 mins cost about 27 CAD.

The city is wonderful, the streets are clean, nice and easy to learn, people are extra friendly, both cars and people are moving according to traffic rules, this is quite interesting for anyone coming from a country like Egypt :)

The temp house is in a very nice area, Map, I am in the 29th floor, so I have an amazing view of the sea and the mountains.

My first couple of days were very hard, because of the electricity here in Vancouver, the problem that the voltage range here is 100~110, while Egypt is 200~220 so many devices I had didn't work, also I found the strange outlet in the wall, which is different from the Egyptian outlets, so all devices like Laptops, Mobiles ... etc went out of charge during the first couple of days, I had to find a store where I can buy some adapters, in these days I felt like stone age, no mobile phones, no computers, no Internet, how could we live 15 years before today, Once I got the adapters I could communicate with my friends who arrived in Vancouver city couple of days before me (Haytham, Mustafa and Abdullah)

Also a nice tip, when I was changing money from Egypt, CAD was cheaper than USD, in Vancouver, CAD is higher than USD, so I lost some money when I exchanged some USD to CAD here in Vancouver.

Live/Google maps works great in Vancouver, and all Canada area, providing great help for directions and finding addresses, Google Maps though has a nice feature to give direction in public transit, so you can see which busses you'll need to take and at what time.

Microsoft Canada Development Center


In the picture from left, Abdullah, Mostafa and Me


In the picture from left, Abdullah, Mustafa and Haytham 

Here comes the first day @ Microsoft, the first day started in a park nearby Microsoft, the day started with some introductory sessions about Microsoft Canada, and Microsoft future of Computing, and the future vision of MS.

After couple of hours we went to MCDC, we had a nice tour around the facility, the place is very amazing, simple and fun, some parts still under construction.

People there are from everywhere, it is like a small united nations, Egyptians are all over the place and we are increasing, in our batch there was 7 Egyptians out 31 new hires, this is quite nice number.

Then after the tour we had another session about the needed paperwork, lots of forms to fill, I had to write my name about 50 times later this night when filling in the forms, then we head to our offices.

My office is in Building 3, Office 1077B, I am sharing the same office room with Mostafa, every dev is using two machines, one for web surfing, email, IM, ... etc and the other for development, the machines are GREAT, I even found people working in triple machine setup according to their work needs.

 

In the first day my manager called me from Redmond, I IMed the other team mates, I found out that I am the only dev outside Redmond in my team.

During the first days, we were all busy finishing the paperwork, we didn't start working yet, however in the forth day we had a great experience.

MCDC Cares

Since our first day, we were asked to join this event, the event called MCDC Cares, is a community work program that Microsoft will help the Richmond city in building a 700ft long boardwalk in Richmond Park, the idea is that this part of the park is very muddy that no visitors can get inside, so Microsoft decided to help in building this boardwalk by providing manpower (150 computer geeks) for a whole day.

So early on May 15th, all Microsoft Canada Development Center gathered in the cafeteria where Parminder (Par) Singh, the Managing Director of MCDC gave a short speech to everybody


In the picture Parminder Singh

After this we all moved to the park, the park is quite big, it was my first time to actually feel being in the woods, were the trees are very high and land is either very green or very muddy.

In this picture the completed part of the boardwalk we were about to complete, the  boardwalk goes very deep into the woods.

So first things first, we had to move 1500 pieces of wood from the parking area outside the park to the working place deep into the woods, about 800m distance, this part of the job took around 4~5 hours.

After this phase we had a lunch break and during this break

Then phase 2 started, the phase 2 was to nail the 1500 pieces of wood we moved in phase 1 with 6 nails per piece, so in a period of 3 hours we had to hummer about 9000 nails manually.

Then we head back to MCDC, very exhausted but very happy with the work we've done, this boardwalk will be there for ages, and this was a very nice opportunity to do something useful.

In MCDC we had a BBQ party for everyone so the day ended pretty much after the BBQ, then I believe that everybody slept like a baby for more than 9 hours :)

Here you can find the TV coverage of MCDC Cares day

If you read this line so you survived the whole blog post, thank you for reading this, I will be blogging again & again, so keep in touch :)

Posted by mohammed hossam | 1 Comments
Filed under: , ,

Using WebHttpBinding & JSON Support in WCF

I had some cool time working with WCF new features shipped with .net 3.5, one of the most ineteresting and useful features is the JSON support and how easy you can enable the JSON support for your current WCF services by changing the configurations.

Why do we need JSON support?

Well, JSON (JavaScript Object Notation) is very suitable for building ajax based applications for some reasons.

  1. The other popular alternative (XML) requires parsing code in the client side to extract the data from the document, which is not the best thing to do using Javascript.
  2. XML documents size are relatively bigger than JSON documents containing the same data

To get more info about JSON check here and here

What WCF offers to support JSON

All what you need is doing two things

  1. Create an end point that uses the new binding (WebHttpBinding)
  2. Configure the end point behavior and enabling the WebScript (which will generate a javascript proxy for your service contract and data contracts)

This is a sample configuration

<system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="ChatAspNetAjaxBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="ChatService">
        <endpoint address="" behaviorConfiguration="ChatAspNetAjaxBehavior" 
                binding="webHttpBinding" name="ajaxEndpoint" contract="IChat"/>
      </service>
    </services>
  </system.serviceModel>

As you can see the endpiont configuration is using the Binding "webHttpBinding" and it is also configured in the behavior tag to enable web script.

Now the WCF runtime will generate a javascript proxy containing all services and data contracts as javascript classes, we will see an example shortly.

Example: Building a Chat Application using WCF & JSON support

It is time for more detailed example, in this example we will develop a small web based chat application using javascript as a client language and WCF as a server side.

The chat application will be able to do these functionalities

  1. Register users
  2. User logins
  3. Retrieve users list
  4. Check new messages
  5. Send message
  6. Log out

So let's write down the contract for this service (we will ignore good design practices for the sake of simplicity and will make one service that does both the user management and chatting)

[ServiceContract(Namespace = "")]
public interface IChat
{
    [OperationContract]
    User Register(string username, string password);
 
    [OperationContract]
    User Login(string username, string password);
 
    [OperationContract]
    bool Call(Guid fromUserId, string toUsername, string message);
 
    [OperationContract]
    Message[] GetMyMessages(Guid userId);
 
    [OperationContract]
    bool SignOut(Guid userId);
 
    [OperationContract]
    User[] GetUsers();
}

 

This is basically how the service contract looks like, we are still missing two data contracts User & Message and here they are.

[DataContract]
public class Message
{
    [DataMember]
    public Guid ID { get; set; }
    [DataMember]
    public string Body { get; set; }
    [DataMember]
    public DateTimeOffset Date { get; set; }
    [DataMember]
    public string FromUsername { get; set; }
 
    public Message()
    {
        ID = Guid.NewGuid();
        Date = DateTimeOffset.Now;
    }
}
 
[DataContract]
public class User
{
    [DataMember]
    public Guid ID { get; set; }
 
    [DataMember]
    public string Username { get; set; }
 
    public string Password { get; set; }
 
    public User()
    {
        ID = Guid.NewGuid();
    }
}

The implementation of the service is not very important and the code is attached with the blog entry, basically it saves all the messages and users in static collections, in real life cases the implementation will be different most probably a database is going to be used.

Now let's start building the client side of the chat application.

We will be hosting the chat service on IIS so we will create a .svc file chat.svc which will contain one line

<%@ ServiceHost Language="C#" Debug="true" Service="ChatService" CodeBehind="~/App_Code/Chat.cs" %>

And this will be the address of our service.

and then we will place the configuration of the service in web.config

1: <system.serviceModel>
2:   <behaviors>
3:     <endpointBehaviors>
4:       <behavior name="ChatAspNetAjaxBehavior">
5:         <enableWebScript/>
6:       </behavior>
7:     </endpointBehaviors>
8:   </behaviors>
9:   <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
10:   <services>
11:     <service name="ChatService">
12:       <endpoint address="" behaviorConfiguration="ChatAspNetAjaxBehavior" 
13:         binding="webHttpBinding" name="ajaxEndpoint" contract="IChat"/>
14:     </service>
15:   </services>
16: </system.serviceModel>

The configuration is similar to the above one, except for the line #9 which is the serviceHostEnvironment, all what you need to know about this attribute that enabling it will make asp.net treats the WCF service as regular asmx service, for more details about different modes of running WCF services with ASP.net check this article

We will now create two views

  1. Login View
  2. Chat View

The login view is basically like this

Two text boxes (txtUsername, txtPassword) and two input type buttons for register and login actions

The Chat View will look like this

Which contains two more textboxes (txtToUsername, txtMessage) and a select control containing the current users (slGuests) and a panel that will show the message history (pnlMessageHistory)

May be it is not the best user interface but it will do the basic things.

now we will need to add the ScriptManager to the page and add a reference to the wcf service

1: <asp:scriptmanager id="scrptMgr" runat="server">
2:     <services>
3:         <asp:servicereference path="~/Chat.svc" />
4:     </services>
5: </asp:scriptmanager>

This will add a script element with a source pointing to this url http://[domain]/Chat.svc/js which will download the javascript proxy code.

We will now do some initialization codes let's see how it looks like...

1: var user;
2: var chatService = new IChat();
3: var guests = new Array();
4: window.onload = function(){
5:     var btnRegister = $get("btnRegister");
6:     $addHandler(btnRegister, "click", doRegister);
7: }

 

Let's check line #2, this is the neat part of using WebScript, the IChat class is the generated proxy object for the IChat service contract, and for this application we need only one object so the object is created and initialized globaly.

Now let's write the register function

1: function doRegister()
2: {
3:     var username = $get("<%=txtUsername.ClientID %>").value;
4:     var password = $get("<%=txtPassword.ClientID %>").value;
5:     chatService.Register(username, password, onRegisterSuccess);
6: }
7:  
8: function onRegisterSuccess(result)
9: {
10:     if(result != null)
11:     {
12:         user = result;
13:         var btnRegister = $get("btnRegister");
14:         btnRegister.value = "Sign Out";
15:         $clearHandlers(btnRegister);
16:         $addHandler(btnRegister, "click", doSignOut);
17:         var btnLogin = $get("btnLogin");
18:         btnLogin.style.display = "none";
19:         $get("<%=txtUsername.ClientID
            %>").disabled = true;
20:         $get("<%=txtPassword.ClientID
            %>").disabled = true;
21:         $get("divChat").style.display = "inline";
22:         setTimeout(doCheckMessages, 1500);
23:     }
24:     else{
25:         alert('Error!');
26:     }
27: }

 

the doRegister function is calling the Register method defined in the IChat service contract, you will notice a nice feature that VS intellisence is working nice in this part

All the proxy function will have the same parameters defined in the contract, but because of the nature of the asynchronous call, all the functions will add three extra parameters (onSuccessCallback, onFailureCallback, userContext)

The onSuccess callback is very important, as this where you will get to know the return value (if any), and also where you can say that the server finished working on the request, so in the Register example, in the onRegisterSuccess if the user is created, the Login view is disabled and the Chat view is displayed, also an important part is a timer configured for polling the server for new messages, and the timer is called once every 1.5 seconds, and the result parameter to the onRegisterSuccess function is the return value of the Register method on the IChat service, which in our case it is either a User object or null, if the user object is returned it is saved to the global variable user.

Now let's see when we send a new message to a certain user

1: function doSend()
2: {
3:     var pnlHistory = $get("<%=pnlMessageHistory.ClientID %>");
4:     var txtMessage = $get("<%=txtMessage.ClientID %>");
5:     var txtTo = $get("<%=txtToUsername.ClientID %>");
6:     pnlHistory.innerHTML += "<b>" + user.Username + " says:</b><br>" + txtMessage.value + "<br>";
7:     chatService.Call(user.ID, txtTo.value, txtMessage.value, onSendSuccess);
8: }
9:  
10: function onSendSuccess(result)
11: {
12:     var txtMessage = $get("<%=txtMessage.ClientID %>");
13:     txtMessage.value = "";
14: }

The send message function will call the Call function on the service, and also writes down the message details on the message history panel.

The callback of this function is simply clears the message textbox.

Now when you send a message to someone else, the message is temporarily saved on server till the recipient user queries the server for his messages, this logic is done through a client side timer.

1: function doCheckMessages()
2: {
3:     chatService.GetMyMessages(user.ID, onCheckMessagesSuccess, onCheckMessagesFail);
4:     chatService.GetUsers(onGetUsersSuccess);
5: }
6:  
7: function onCheckMessagesSuccess(result)
8: {
9:     if(result == null)
10:         return;
11:     var pnlHistory = $get("<%=pnlMessageHistory.ClientID %>");
12:     for(var i=0; i<result.length; i++)
13:     {
14:        pnlHistory.innerHTML += "<b>" + result[ i].FromUsername + " says:</b><br>" + result[ i].Body + "<br>"; 
15:     }
16:     setTimeout(doCheckMessages, 1500);
17: }
18:  
19: function onCheckMessagesFail(err)
20: {
21:     alert(err.message);
22:     setTimeout(doCheckMessages, 1500);
23: }

 

The doCheckMessages function does two things, first it checks for the new messages from server, and the other thing is checking for new users in the chat.

the onCheckMessagesSuccess is reading all the messages in the result array of messages, and print them out on the message history with proper format, and then it initialzes the timer again.

This is typically how the chat will look like

Summary

In today's entry I was giving a small overview of one of the new features introduced in WCF 2.0 (.net 3.5) which is WebScript and JSON support, this feature allowed us to create a rich web based application using only Javascript as a client code, we also developed a simple Chatting application to prove the concept and the code is attached with this post for further information and details.

Have a nice day.

 

Technorati Tags: ,,,,
Posted by mohammed hossam | 0 Comments
Filed under: , , , , ,

Attachment(s): Chat.zip

PLINQ is coming up soon (PFX)

I've been hearing about PLINQ (Parallel Linq) since the first days of announcing LINQ, the idea of making use of the new functional style programming provided in DotNet 3.5 in order to give better performance on Multi Core machines, the idea sounds cool since first day, and it now comes true in a new name Parallel FX or PFX

The programming model provided is quite simple and utilizes the same LINQ model, the new assembly is called System.Concurrency.dll which is the library that contains the new interface called IParallelEnumerable<T>, also it adds an extension methods for all collections and arrays that implement old IEnumerable, the extension method is called AsParrallel<T> which converts any collection to a Parallel enabled collection of type IParallelEnumerable<T>

Take a look of the following code

IEnumerable<int> data = new int[] {1, 2, 3, 4, 5, 6}; // or whatever complex data collection
var q = data.Where(x => x > 4).OrderBy(x=>x).Select(x => x);
foreach (var i in q) ....

This code is what you already write in C# 3.0, now if you want to add PLINQ support all what you have to do is adding the AsParallel function call before using any query operation so the previous code will look like this

IEnumerable<int> data = new int[] {1, 2, 3, 4, 5, 6}; // or whatever complex data collection
var q = data.AsParallel().Where(x => x > 4).OrderBy(x=>x).Select(x => x);
foreach (var i in q) ....

or you can write it in the LINQ query style

IEnumerable<int> data = new int[] {1, 2, 3, 4, 5, 6}; // or whatever complex data collection
var q = from i in data.AsParallel()
        where i > 4
        orderby i
        select i;
foreach(var i in q) .... 

Once you've added the AsParallel function call, PLINQ will be ready to execute transparently all the OrderBy, Where, Select, GroupBy ... etc on all the available processors.

You don't need to explicitly create threads, locks and manage concurrent execution (Unless you are making something big).

This doesn't mean that you can make use of the PLINQ power on anything other than Queries, the ParallelEnumerable class also adds some extra extension methods like the ForAll method

The ForAll method is useful if you are applying some kind of operation on all the members of a certain collection, so the ForAll function will do this operation in parallel for all the members of the collection

IEnumerable<int> data = new int[] {1, 2, 3, 4, 5, 6}; // or whatever complex data collection
data.ForAll(i=>Console.WriteLine(i));

The previous code sample will print out all the members of the array, if you imagined calling more complex function that does some heavy work on each array member, the ForAll will give you extra power to do the job faster by making use of the parallel data processing techniques.

This is not all the new stuff introduced in the System.Concurrency library, the new Parallel class is also a nice addition, it provides some extra general purpose parallel execution, so it is not related to LINQ, the most important part is the Parallel.For function, which as you expected from the name executes a parallel loop.

Check the following code

void ParMatrixMult(int size, double[,] m1, double[,] m2, double[,] result)
{
  Parallel.For( 0, size, delegate(int i) {
    for (int j = 0; j < size; j++) {
      result[i, j] = 0;
      for (int k = 0; k < size; k++) {
        result[i, j] += m1[i, k] * m2[k, j];
      }
    }
  });
}

This is an example I got from here, it illustrates a Matrix Multiplication using Parallel.For, as you can see the Parallel.For method accepts the start index and the length, then a delegate to execute.

There is also Parallel.Aggregate function which can be used to aggregate a certain data item over a parallel loop safely.

This all what I could write in one post, however the System.Concurrency contains more cool API's.

Here comes the resources for further readings.

  1. Optimize Managed Code for Multi-Core Machines
  2. Running Queries on Multi-Core processors
  3. Channel9 Video Programming in the Age of Concurrency (Andres Hejlsberg and Joe Duffy)

kick it on DotNetKicks.com

SOA via WCF - Part 2 -

This is the second part of my presentation in SilverKey Demo Day 2 (SKDD 2) last July, for the first part, Check Here, you will also find the presentation slides & samples attached in Part 1 or you can download from here
So let's start
Let's check our Agedna


In Part 1 we discussed what is SOA and the concepts behind it, also we had a walk through different approaches to apply SOA in our applications in terms of standards and patterns.
In Part 2 we are going to discuss WCF or (Windows Communication Foundation) which is Microsoft new framework to unify communication mechanisms and provide an infrastructure for our SOA applications.


As we've just mentioned WCF stands for Windows Communication Foundation and also it used to be called Indigo.
WCF was shipped with Windows Vista in November 2006 as part of .net framework 3.0, however it is also available for Windows 2000, XP and 2003.



WCF is all about providing an unified infrastructure that handles all communication scenarios and protocols, which includes different transport, messaging patterns, encoding .... etc.
WCF also playing a great role in making the life easier for .net developer, so the messages exchanged between different services are exposed as CLR types (classes), and also the services are represented as interfaces and classes, so it provides a good and very high level of abstraction.
So as one sentence you can say that WCF is the infrastructure for building Services.



As we said WCF unifies the communication techniques, but how ?
Before the WCF days, we used to have different technologies for different communication problem, so if you are doing TCP communication you will be using Sockets for example, and if you are providing online services over HTTP, you will be using Web Services, and if you are doing message queues you will be using MSMQ ... etc
So this was good, however it has some drawbacks.
  1. You have to learn different models for every communication technique.
  2. You can't change the communication technique you are using in a certain application to another without massive changes in your code.



So what WCF provides is a One Right Solution for all problems, which saves your time and effort, also it comes with a full fledged set of goodies such as Tracing, Logging which can be used regardless of the communication technique you are using.



One of WCF great benefits that it provides a very handy extensible model, that you can add support for new protocols easily, or even slight changes to current protocols like adding a new encoding or encryption algorithm.or a new tracing mechanism.
Another thing that WCF is supporting almost all the WS-* standards like WS-Addressing, WS-AtomicTransaction which makes the messages generated from WCF runtime interoperable with any current or future application built with same standard messaging.
and The most elegant feature of WCF, that all the configuration of the services and protocol specific properties can be configured using XML config files outside the application, which is a great feature that allows administrators to be part of the game, so they can change stuff like the impersonation options, and security settings, enabling and disabling trace listeners and logging, without the need to ask developers to do it, which is somehow similar to ASP.net configuration.
Also this config file can be edited using a UI tool..
For architects it is really easy to stay in the high level design and forget about implementation details and technology limitations.



So let's have a sample service
In this demo we will be discussing the basic elements in any WCF application.
The most basic three elements are
  1. Address
  2. Binding
  3. Contract
They are also called the ABC's of WCF, because every service has to define these three elements.
We will be discussing everyone of these elements in details,
let's now see how a Service is defined in WCF. in steps we will discuss how to build a simple News service.
1. Define the Contracts
In this step we will define the different contracts of the service the first type is

Service Contracts
[ServiceContract(Namespace="com.silverkeytech.news")]
public interface INewsService
{
[OperationContract(IsOneWay=false)]
Article[] GetArticles();
}

As you see the Service Definition is just an interface (Contract) which is decorated with an attribute called ServiceContract.
This interface defines the different functions provided by the service in terms of inputs/outputs and exchange patterns.
Every service function is represented in a form of interface method, and the inputs of the service function are represented as inputs to the method and also the output is represented as return type of the method.
The exchange pattern is by default Request/Response which is represented using the Attribute OperationContract with the IsOneWay property set to false, if it was set to true this means that this service function is a fire & forget type of service, which the service clients will not expect any response for the messages sent to this functions.

Data Contracts
Also if you noticed in our method return type is a complex type Article this is not a primitive type in .net, it is a user defined type which has to be defined like this.
[DataContract]
public class Article
{
string title;
string details;

[DataMember]
public string Title
{
get { return title; }
set { title = value; }
}
[DataMember]
public string Details
{
get { return details; }
set { details = value; }
}
}

As you can see it is a simple data class that is decorated with a DataContract attribute, so it tells the WCF runtime that this class will be converted to a message that will be sent or received by one or more service functions, also every field or property of interest has to be decorated with another attribute called DataMember.

2. Implement the Service
Now we need to provide the implementation of the Service Contract interface, which will do the actual job of the service, all what we need is to implement the interface in a class like this.
public class NewsService : INewsService
{
public Article[] GetArticles()
{
List<Article> articles = new List<Article>();
for (int i = 0; i < 10; i++)
{
Article article = new Article();
article.Title = "Title " + i.ToString();
article.Details = "Details " + i.ToString();
articles.Add(article);
}
return articles.ToArray();
}
}

So the class NewsService implements the interface INewsService and provides an implementation of the service that does the actual job of how the service will handle the incoming requests.

3. Hosting the Service
Now after we implemented the service, we have to host it on an application, there are different choices depending on your need, you can host the service on Windows Applications (Console, Windows Forms, Windows Services) or Web Applications (IIS), for simplicity I will host my service on a console application.
namespace Host
{
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(NewsService)))
{
host.Open();
Console.ReadKey();
}
}
}
}
As you see, the host is very simple, all the hard work is done in the ServiceHost class which its constructor requires the type of the class that implements my service, in our case NewsService class.
Then we call the Open method to allow the service to accept any incoming requests and process them, the last Console.ReadKey is just for not allowing the application to exit unless somebody presses any key.

4. Configuring the Service
After we hosted the service we need to configure this service, we need to write how the service is going to interact with its clients, this will be done using the App.Config file of the host
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <services>
            <service name="BeebcNews.NewsService">
                <endpoint address="EndPoint1" binding="basicHttpBinding"
                    bindingConfiguration="" name="HttpEndpoint" contract="BeebcNews.INewsService" />
                <host>
                    <baseAddresses>
                        <add baseAddress="http://localhost:9000/beeBC" />
                    </baseAddresses>
                </host>
            </service>
        </services>
    </system.serviceModel>
</configuration>
This is sample configuration file that is used to configure the NewsService we've just implemented

5. Consuming The Service
After we host and deploy our service, we need to consume it, which mean we need to write client applications that sends and receives requests and responses from the service.

Generating Proxy Class
So for the client application to be able to use the service we need to use a proxy class, the proxy class is generated using a tool called svcutil.exe this tool can be applied either on the Service dll or on the WSDL file url of the service.
so let's assume our NewsService dll is called MyLibrary.dll
We will write this command in the command prompt.

svcutil.exe MyLibrary.dll

This command will generate the XSD files & WSDL file for the types and services inside the library, there are more switches can be used for more specific options.
Then after we generate the XSD, WSDL of the wcf service we apply this command on the generated files.

svcutil.exe *.xsd *.wsdl /language:C#

This command will use the XSD, WSDL file we generated with the first command to generate a proxy class in C# and an XML config file.

Then we can use the new files to write our client applications.
Another way of generating the Proxy classes is to switch on the MetaData publishing for the service, so the service will have a http url that contains the WSDL file, then we can use this command

svcutil.exe http://[the service url]

and this will generate the C# proxy and the config file

Implementing the Client Application
namespace Client
{
class Program
{
static void Main(string[] args)
{
NewsServiceClient client = new NewsServiceClient("HttpEndpoint");
Article[] myArticles = client.GetArticles();
foreach(Article a in myArticles)
Console.WriteLine(a.Title);
Console.ReadKey();
}
}
}
The previous code is a simple example of a client application that uses the generated proxy class we've just generated that generated the NewsServiceClient class, which has the same functions provided by the INewsService interface so we can call them and the WCF will handle the communication between the client and server.



Now let's have an overview of the architecture of WCF, or let's call it the journey of the incoming message to the service and how it is going to be handled.
The architecture of WCF is basically a pipeline, the message arrives on the transport layer which is going to pass it to the next layer to be decoded and then it passes through different protocol specific layers till it reaches the dispatcher, which is going to decide this message belongs to which method in the running instance of the service, and then deliver it to the method to be processed then the return value (if any) takes a similar path down the pipeline back to the original sender.
This pipeline is configured using the Configuration and the Contract, the configuration defines the layers in the WCF pipeline and the Contract helps the Dispatcher to find the destination of the message.



If you take a look on the XML Configuration in the previous example, you will find that under the Service element there is something called EndPoint
The EndPoint is the container that has the three basic elements of the service we mentioned before (Address, Binding & Contract).
So in our previous example the Address was EndPoint1, which is going to be concatenated with the baseAddress of the Service in our case "http://localhost:9000/beeBC"so the result address will behttp://localhost:9000/beeBC/EndPoint1, then the Binding which was "basicHttpBinding" which is the simply SOAP messages over HTTP using text encoding.
and the Contract which has the full name of the INewsService interface which defines our service contract.
Now let's see each Endpoint element in details


The Address
Defines Where the endpoint resides



The Binding
Defines How the service is communicating with the outside world.



The Contract
Defines What the service will offer to its clients.



Before we end this presentation, I would like to highlight that WCF 2 is on the way, it will be shipped with next version of Visual Studio 2008 and .net framework 3.5
The new version of WCF will have better support for Webby style services such as REST style services and also supports different encodings like RSS, ATOM and JSON.
Also the huge change will be that WCF and WF are merged together in what is called Silver project, which will enable developers to develop WCF service with Workflow as an implementation.


These are some resources for more information about WCF and SOA also some books for further information.

I hope you read this line, which means that you kept reading the whole presentation, I hope it was useful for you, if you have any questions write them as a comment to this blog post and I will be answering them immediately.

kick it on DotNetKicks.com
More Posts Next page »
 
Page view tracker