March 2010 - Posts
Invoking Javascript From a WebBrowser Control
Today I got a
request to use
A WebForms application
inside a WinForms
application. One problem
that we needed to solve
was how to make an
interaction between the WinForm and the WebForm it uses.
The post will show the solution.
Invoking Javascript From a WebBrowser Control
When you want to use a WebForm within a WinForms
application you should use the WebBrowser control. Taken from
MSDN the WebBrowser control “Enables the user to navigate Web
pages inside your form.”.
One of the nice features of the WebBrowser control is its ability to
invoke Javascript. On the other hand, WebForm Javascript can also
invoke methods in the WinForms which host them using a the
WebBrowser control.
Lets see how to do so.
The first thing to do is to enable scripting on the WebBrowser control.
This can be achieved by the following code:
webBrowser1.ObjectForScripting = this;
As you can see we use the ObjectForScripting property of the
WebBrowser control and give it the form which it is located in.
This property must be set in the form's constructor or the form’s Load
event. In order to invoke a Javascript which is located inside a WebForm
we need use the Document property of the WebBrowser control and
from the document the InvokeScript method. The InvokeScript
method gets as parameters the method name to invoke and a set
of parameters. For Example:
webBrowser1.Document.InvokeScript("doLogin");
will invoke the doLogin method which is located in the WebForm.
In order to do the opposite, which is to invoke a method that is
located in the WinForm from the WebForm, we use the
window.external method and call from it the method in the WinForm.
For example the following example will call a method called
Say which get a string as its parameter:
window.external.Say('Hello')
The method on the WinForm must be public or else the operation
will fail.
Summary
Since I had a need for two ways communication between a
WinForms application and a WebForms application I used the
WebBrowser control which enables this behavior. I hope this
will help you if you’ll need such a solution in your application.
CodeProject
Self Validation in Validation Application Block
There are times
when you don’t
find a solution for
a validation you
need inside
Validation Application
Block validators.
When this is happening Self Validation
can help you to keep using VAB and gaining
all its abilities. This post will explain how to use
Self Validation in VAB.
What is Self Validation?
Self validation gives you the ability to implement validation logic
inside the class you want to validate. When you have a
complicated validation or your validation logic can’t be performed
using the VAB validators you can apply this method.
How to use Self Validation?
The first thing to do when you want to indicate that a class has
self validation is to decorate the class with a HasSelfValidation
attribute. Then you decorate every self validation method with
the SelfValidation attribute. The method signature need to be
void and take only one instance of ValidationResults as parameter.
This collection will be updated inside the method if the validation
failed.
For example the following class uses self validation:
using System;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
using Microsoft.Practices.EnterpriseLibrary.Validation;
namespace Search
{ [HasSelfValidation]
public class Search
{ #region Properties
public int Sum { get; set; }
#endregion
#region Methods
[SelfValidation]
public void CheckSum(ValidationResults results)
{ if (Sum < 0)
{ results.AddResult(new ValidationResult("Must have positive sum", this, "Positive", null, null));
}
}
#endregion
}
}
As you can see this is only an example and I could have used the
regular VAB validators to achieve the same impact.
The SelfValidation attribute can also be used within a specific
rule set by providing to it the rule set name as parameter.
When we want to use the self validation logic we use it as we
used all the other validators in VAB.
For example:
var search = new Search();
var validator = ValidationFactory.CreateValidator<Search>();
var results = validator.Validate(search);
Summary
I use a lot the the Validation Application Block as a validation
framework. When I get stuck with complicated validations or
the supplied validators can’t help me then I use the self
validation feature. It is very simple and easy to apply.
In the post I showed how to use it in code. I hope you will
find it helpful.
CodeProject
DevAcademy4 Has Left the Building
Today I attended
the DevAcademy4
conference. The
day started for me
at 0700 when all the
lecturers for the
conference got together for a morning briefing.
After that I went to a nice breakfast which was served in
the Avenue hall for all the attendees.
After the keynotes session which was great and included a
laptop giveaway for one of the attendees, I went to prepare for my
session about Entity Framework Evolution in .Net Framework 4.
In that point I want to thank all of the attendees in my session.
I had a great session and I hope you had fun too. As promised, you can
download the session slide deck and demos from here.
The next session I went for was Parallel Programming in .Net 4 and VS2010
with Sasha Goldshtein. As always Sasha was great.
I always admire his typing skills. In the lecture Sasha talked about PLINQ and
its new abilities in VS2010 including the ability to get a visual stack trace for
tasks and more.
After Sasha I went to Maor David’s session – Introduction to Cloud Computing &
Windows Azure Platform. The session was about Windows Azure and included
the reason to use the platform and of course a demo of how to deploy an
application to the cloud and many more details.
The last breakout session I took was Shai Raiten’s session Introduction to
CodedUI Testing and Microsoft Test Manager. The main reason was because
Pavel’s session was full and I didn’t want to stand for one hour. Even so the
subject isn’t my favorite, Shai delivered the session so funny and cool so I
found myself interested.
In the last time slot I went to the demo session of Vlad Azarkhin –
The Five Coolest IIS 7 Features for Developers. I knew all the features
Vlad talked about so I didn’t get any added value from the session.
Even so, the session was good.
This is it for DevAcademy4, see you next time in other conferences or in
DevAcademy5.
MIX10 – Summary
Home sweet home!
I arrived today back
to Israel after a trip
of six days to the
MIX10 conference
(three days conference and almost three days “on the roads”).
To tell the truth, I was a little disappointed from the conference.
I’ve expected more relevant information and less recycling of things
that I already know. As you know (if you followed the MIX10),
there were announcements about Windows Phone 7, Silverlight 4, OData
protocol, IE9 and more. After being at the conference and meeting attendees
from all over the world, I think that Microsoft missed an opportunity to do
more buzz then I think they did. Every person that I talked to said the same
things so apparently it isn’t only my opinion. As I see it the world of the
web is going to shift to platforms like Silverlight which I’m going to learn
in the future in order not to stay behind.
Moreover, I’ve be asked why did I went to the conference. The answer is really
simple – from the beginning of my professional life I’ve been more web oriented.
So I hope this is making more sense to the people who asked me that question.
The next thing in mind now is my session in the DevAcademy4 conference which
is going to take place next Monday in Israel. If you want to hear my EF4 session
you are most welcome.
See you there!
EF Evolution in .Net Framework 4
On next Monday
I’m going to give
a session about EF4
in the DevAcademy4
conference.
The session will provide
you details about why you will want EF in your application,
which development approaches EF provides and how to apply
them and the major tooling and functionality enhancements.
If you are interested in the subject go to the DevAcademy4
web site for more details.
Meet you there!
MIX10 – Last Day Wrap up
The last day of MIX
has arrived and
in this day we haven’t
had a keynote session.
The first session I went for was Building Great Standards-Based
Websites for the Big Wide World with Microsoft ASP.NET 4.
A very big title for a session about XHTML, usability and accessibility
which are things that you are require to do when you develop
major sites. The lecturers showed an Australian site which was
developed with standards. Also they showed an nice open source
framework that they wrote which is called WebFormsMVP.
The second session that I participated was Building Innovative Windows
Client Software. It was an experts panel about all kind of stuff that is
connected to innovation and design. It really resembled the SDP MVP panel
we had last year but without the technical stuff. In the end there
was a lottery and five people won Zune devices.
The third session of today was IronRuby for .NET Developer
with Cory Foy. I wanted to learn a bit about DLR so this talk was
my first look at the IronRuby language.
That is all for me today in regard of sessions. In the forth slot I couldn’t
find a session that really interests me so I decided to go back to the
hotel and enjoy Vegas.
Expect a summary of my visit in a next post.
MIX10 – Second Day Wrap up
This is the wrapping up
of the second day I had in
the MIX10 conference.
In the keynotes Dean Hachamovitch talked about
IE9 and how it will support HTML5 standard. There will be a lot
of improvements in IE9 which include: performance, standards
support, GPU powered HTML5, an IE9 platform and the punch line
hardware accelerated HTML5 video. After Dean Scott Guthrie
talked about the Microsoft web platform which include a lot
of enhancements and there were demos of VS2010 by Scott
Hanselman. Then the main part for me started. Douglas Purdy
talked about the OData protocol which will give a uniform
protocol for services powering experience. The protocol is being
used by SharePoint 2010 which exposes OData services. Also, there
is Excel support plug-in for OData and more. Much to expect in this
area. For more details I encourage you to go to http://odata.org.
Then Bill Buxton talked about our real role has developers and application
creators which isn’t the technology which is our tool but the experience
that we deliver to our users.
The first session I went for was Pablo Castro’s OData: There is a Feed
For that. Pablo explained what is OData which is
- Uniform way of representing structure data.
- Uniform URL conventions.
- Uniform operations.
- Based on the AtomPub (or Json)
Then he showed how SharePoint 2010 exposes lists as OData.
Also he showed that we can use OData in reporting services and many
more examples.
The next session which I attended was Nikhil Kothari’s Developing
with WCF RIA Services Quickly and Effectively. Nikhil showed an end
to end application that uses WCF RIA Services under the hood.
I enjoyed that session since it was a long demo that showed how to
do stuff with WCF RIA Services which is an area that I want to explore
further.
I then went to Mike Flasko’s session – Implementing OData: How to
Create a Feed for That. Mike is a great presenter and since I like
WCF Data Services I enjoyed this session a lot. There were a few things
that I learned such as $select operation which perform data projections.
This was the second OData session I saw this day and it completed the
first session by Pablo so if you are interested in OData go and see both
of the sessions.
The last session was How jQuery Makes Hard Things Simple by jQuery’s
creator John Resig. It was a Tips and Tricks like session.
Wrapping the day, the second day had lots of interesting sessions
and I need to see some of the sessions that I missed in the future.
Stay tuned for more updates.
MIX 10 – First Day Wrap up
As I wrote earlier
this week I’m
attending the MIX
conference at Las
Vegas.
This is a summary of the
first day I had in the conference.
The day started with a keynote session by Scott Guthrie. The keynotes
included information about Silverlight 4, Windows Phone 7 and more.
Lots of cool demos and exciting news for web developers.
After the keynote I went to the Building Offline/Cache mode web Apps
using Sync Framework session with Mike Clark. The news here are the
OData-Sync protocol and Windows Azure support. Combining the OData
protocol which is AtomPub+EDM protocol with a sync protocol will enable
the Sync Framework to reach application on other platforms. Also
Sync Framework team are working on a Silverlight integration for
offline using Sync Framework which will use in memory collections
which will be put into isolated storage on the disk. Making Silverlight
integration also means that this will work on Windows Phone 7 in the
future.
The next session I attended was Understanding the MVVM Pattern
with Laurent Bugnion. In the session I learned about the
Model-View-ViewModel pattern which is being used with Silverlight.
Laurent also explained how to use command, messages and more.
The last session was Designing and Delivering Scalable and Resilient
Web Services with Ron Jacobs. Ron talked about AppFabric cache
which was once known as Velocity. I learned a new thing – the bulk
get method. All the other stuff I already know but Ron is
a great lecturer so it was interesting. At the end of the session I
talked to Ron about some stuff such as integrating AppFabric
caching to WCF Data Services which was a question that was asked.
Here are some pictures I took in the first day:

I’ll continue tomorrow so stay tuned.
MIX10 – Here I Come
I’m flying today to attend
MIX10 conference in Las Vegas.
This will be my first MIX and my
first visit to Las Vegas so I’m very
excited. I’m attending this conference
with four other colleagues from Sela Group.
I’ll try to keep you updated with things that happen in the conference
so expect for more posts this week.
If you are also attending the conference and want to meet me there
you can contact me through the blog.
Have a nice week!
Performing Queries Against Active Directory Domain Services
One of the missions
that needed my
attention lately was
to check whether a
user exists in an
enterprise Active Directory.
The post will show exactly how to perform such a query.
The DirectoryEntry Class
The DirectoryEntry class represent an entry in Active Directory.
That entry live in memory when created and changes that you
perform on it won’t be submitted to Active Directory unless you
call the CommitChnages method. That class can be found in
System.DirectoryServices namespace.
The following code shows how to create a DirectoryEntry object
using a the path to the LDAP, username and password:
var entry = new DirectoryEntry(path, username, password);
The DirectorySearcher Class
The DirectorySearcher class enable us to perform queries
against Active Directory. Once you have a DirectoryEntry in
hand you can pass it to the DirectorySearcher and then commit
queries to your Active Directory. When you create the DirectorySearcher
you also supply the optional list of properties that you want to
retrieve. As the DirectoryEntry, it is also available in the
System.DirectoryServices namespace.
The following code shows how to create a DirectorySearcher
with a given DirectoryEntry:
var searcher = new DirectorySearcher(entry);
How to Perform a Query Against Active Directory Domain Service
The following code snippet shows a simple method that
perform a query against Active Directory:
private SearchResult SearchLDAPById(string userId, string path, string username, string password)
{ var entry = new DirectoryEntry(path, username, password);
var search = new DirectorySearcher(entry);
search.Filter = string.Format("({0}={1})", "SAMAccountName", userId); search.PropertiesToLoad.Add("displayName");
return search.FindOne();
}
The query returns the display name for a logon name of a user which
is saved in Active Directory as SAMAccountName. As you can see
we get back a SearchResult object which we can investigate for
our retrieved display name.
Summary
In the post I showed how you can perform a query against
Active Directory domain service. I also introduced the
DirectoryEntry and DirectorySearcher classes.
I hope you will find this information useful.
CodeProject
Discover which Control Raised a PostBack
Yesterday I
needed a
solution for
an annoying
problem. I have
some buttons
on a ASP.NET
web form
and I need to know which button raised the postback not in the
event itself but in the page load event. This post will show a
way to solve this conundrum.
Discover which Control Raised a PostBack
When we use ASP.NET and we have ASP buttons on the page
if we want to do something before their postback event happen
we need to discover whether they raised a postback. Since
an ASP button uses the form.submit() method on the client side
then on the server side the
Page.Request.Params[“__EVENTTARGET”] will return null.
The following method will discover which control raised a postback:
private Control GetControlThatRaisedPostBack()
{ string id = Page.Request.Params["__EVENTTARGET"];
if (!string.IsNullOrEmpty(id))
{ return Page.FindControl(id) as Control;
}
foreach (var ctlID in Page.Request.Form.AllKeys)
{ Control c = Page.FindControl(ctlID) as Control;
if (c is Button)
{ return c;
}
}
return null;
}
As you can see if the control isn’t a button then it will
have __EVENTTARGET which will be handled first. If we
deal with ASP buttons then we need to iterate on the form
keys and through them we will find the button. This is because
when a button is clicked it uses the form.submit() method.
That method add the button to the list of elements that are
submitted in the form (and only the button that called the submit
and no other buttons).
Summary
Finding which control raised a postback in the form outside
the postback event can be very annoying. I hope that the method
I provided will be helpful to you.
CodeProject
CompiledQuery in Entity Framework
There are times
when we want
to make optimizations
on some piece of
code. If we want to
reduce the cost of
executing a query in Entity Framework we can use a CompiledQuery
to the rescue. Yesterday I used added a compiled query to a code
base which was executing multiple times. This reduced the execution
time of the repeating queries. In the post I’ll explain what are
CompiledQueries and how to use them.
CompiledQuery
CompiledQueries are a delegate which store a compiled LINQ query that we
have built in advance. When we use them we can reduce the cost of
executing a LINQ query. This can be very helpful when we have a query that
we execute multiple times. Pay attention that the compilation of a query
also cost so don’t use CompliedQueries for every query you build only for
the queries that you want to run a lot.
Creating a CompliedQuery
When we want to use a CompiledQuery we will first create a static member
which will hold the delegate that will be created from the CompiledQuery.
The reason for the static member is because CompliedQuery is always
used with a context and we don’t want to lose it when we dispose the
context. The following code is showing how to declare a CompiledQuery:
private static Func<SchoolEntities, decimal, IQueryable<Department>> _compiledQuery =
CompiledQuery.Compile((SchoolEntities ctx, decimal budget) =>
(from d in ctx.Departments
where d.Budget > budget
select d));
We declare a Func delegate which will hold the compiled query as a static
member and we use the CompiledQuery object to with the Compile
method to compile the LINQ query.
When we want to use the compiled query we do it by invoking it:
using (var context = new SchoolEntities())
{ var query = _compiledQuery.Invoke(context, 150000);
foreach (var item in query)
{ Console.WriteLine(item.Name);
}
}
CompiledQuery Restrictions
Currently there are few restrictions that you must know when you
are using a CompiledQueries:
- No compilation is being done up until the first execution of the
query. This means that in the first execution of a CompiledQuery
we will get a downgrade of performance (because of the
compilation). The other executions will much faster.
There is a side affect of this restriction. When combined with Merge
options the first Merge option that you pass with the first context
will be saved and will be used in the other executions.
For example running the following code for the first compiled query
execution will cause the next running to use the
MergeOption.NoTracking:
context.Departments.MergeOption = MergeOption.NoTracking;
var query = _compiledQuery.Invoke(context, 150000);
- Changes to the query such as compositions or calling for methods like
First(), FirstOrDefault() and more will produce a not complied query.
You must use the query as is.
If you want to avoid this problem call the AsEnumerable() method
and transform the query to LINQ to Objects query.
Summary
Lets sum up, CompiledQuery is a very powerful tool for performance
when you use Entity Framework. You should follow the restrictions
I wrote when you use them in your code.
CodeProject