Friday, April 30, 2010

Good books? GoodReads.com

While browsing for online books, along with the moment of luck I "stumbled upon" this GoodReads.com!

Though, I was not expecting the website would list those classic collection. I was amazed to see a collection of books they have - you name it, they have it. Plus reviews as well; and reviews are of the type, worth reading.

Among several, one the things that I liked is that you can find old books as well; for instance I was able to find a collection of Mumtaz Mufti, Allama Iqbal, Bano Qudsia, 'Udas Naslein' by Mohammad Hussein, Paulo Coelho, Stefan Covey, Benazir Bhutto, Nelson Mendela... Man!


I was glad to find Alakh Nagri, Talash, Muftiyane and others. I think myself and Mumtaz Mufti has an inward relationship, probably because I've read him alot, almost all of his writings.

I've learnt that we meet many people in our lives and love many, be eternal or fleeting. Regardless of the time that love is shared, or held on to, the depth, the "intensity", the interwoven-sense-of-purpose varies with the passage of time. We may not always love the person that we love now; we may not even always remain with the person that we love and yet we may love them forever!

I have learnt alot from his thoughts. So +1 for that! (Plus'One-ish? Stackoverflow-flu! :0)

When I used to work in Islamabad, I became friends with the this boy who had access to a library. He used to lend me a book on every Friday(weekend) on the promise that I would return that on Monday; and every Monday I would tell him the name of book to bring the next weekend. And I remember the first time I got a grip of 'Alipur ka Ayli', how I couldn't get away from that book, and finished the ~1400 paged book in two days. I think thats the record earliest read that I have. I am a slow reader.

The thoughts, the intellect - the empathic decisions, the life style, the courage, and the ways to achieve a varied level of human'ic-frequency to understand people - well, they call it Emotional Intelligence.

A paraphrasis popping in my mind, regard the courage, its worth listening(read: reading):

"Courage is a hard thing to figure. You can have courage based on a dumb idea or a mistake, but you’re not supposed to question adults, or your coach, or your teacher because they make the rules. Maybe they know best but maybe they don’t. It all depends on who you are, where you come from. Didn’t at least one of the six hundred guys think about giving up and joining with the other side? I mean, Valley of Death, that’s pretty salty stuff. That’s why courage is tricky. Should you always do what others tell you to do? Sometimes you might not even know why you’re doing something. I mean, any fool can have courage.

But honor, that’s the real reason you either do something or you don’t. It’s who you want to be. If you die trying for something important then you have both honor and courage and that’s pretty good. " - The Blind Side

Heres how it works; also if you like it(the GoodReads.com), and if you do blog, then here is a small tutorial that would tell you how to add the goodread books gadget on your blogger. If you are still curious here is a small review about the website by CrunchBase.

Happy reading, and have nice weekend!

Wednesday, April 28, 2010

WebBrowser Control: Callbacks not working!

Problem statement:
Callbacks not working in WebBrowser control.

Possible resolution:
Check to see if your code is COM Callable? Because for WebBroswer.ObjectForScripting to work COMVisible attribute must be added and set to true.


Something like following on the top of the class declaration:

[System.Runtime.InteropServices.ComVisibleAttribute(true)]

From MSDN:

Use this property to enable communication between a Web page hosted by the WebBrowser control and the application that contains the WebBrowser control. This property lets you integrate dynamic HTML (DHTML) code with your client application code. The object specified for this property is available to Web page script as the window.external object, which is a built-in DOM object provided for host access.

From MSDN:

using System;
using System.Windows.Forms;
using System.Security.Permissions;

[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public class Form1 : Form
{
    private WebBrowser webBrowser1 = new WebBrowser();
    private Button button1 = new Button();

    [STAThread]
    public static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new Form1());
    }

    public Form1()
    {
        button1.Text = "call script code from client code";
        button1.Dock = DockStyle.Top;
        button1.Click += new EventHandler(button1_Click);
        webBrowser1.Dock = DockStyle.Fill;
        Controls.Add(webBrowser1);
        Controls.Add(button1);
        Load += new EventHandler(Form1_Load);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        webBrowser1.AllowWebBrowserDrop = false;
        webBrowser1.IsWebBrowserContextMenuEnabled = false;
        webBrowser1.WebBrowserShortcutsEnabled = false;
        webBrowser1.ObjectForScripting = this;
        // Uncomment the following line when you are finished debugging.
        //webBrowser1.ScriptErrorsSuppressed = true;

        webBrowser1.DocumentText =
            "" +
            "";
    }

    public void Test(String message)
    {
        MessageBox.Show(message, "client code");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        webBrowser1.Document.InvokeScript("test",
            new String[] { "called from client code" });
    }
}

Happy 'callback'ing! (0:

Tuesday, April 27, 2010

WebBrowser control in a Console app

A few notes for those trying to question, how to run WebBrowser in a Console application?
  • WebBrowser control is primarily intended for Forms based app. 
  • Console app is not on STA(Single Threaded Apartment - which offers a message-based communication between OS and application for dealing with multiple objects running concurrently) by default; which means no message pumping, which means no events are going to be fired - so don't be shockingly surprised, must if you go that way!

If must, you choose Console, then following may be the options:

  • You can use a WebClient, or HttpWebRequest to request a page and parse response manually.
  • You can write your own message pump by adding a GetMessage/DispatchMessage in a while loop; and then you add the switch cases for the Message that you are looking for. Its goes something like:

while (GetMessage(&msg, NULL, 0, 0)) {
  TranslateMessage(&msg);
  DispatchMessage(&msg);
}
  • Add a Form(with WebBrowser control) to your console app and do Application.Run(YourForm), for it to dispatch the events.
  • Show the Form in another thread with its own message pump; probably a hidden form.

[STAThread]
static void Main(string[] args)
{
    System.Threading.Thread thdBrowser = new System.Threading.Thread(RunFormInParallel);
    thdBrowser.SetApartmentState(System.Threading.ApartmentState.STA);
    thdBrowser.Start();

    Console.ReadLine();
}

private static void RunFormInParallel()
{
    Form form1 = new Form();//new form

    WebBrowser webBrowser = new WebBrowser();//create a browser
    webBrowser.Dock = DockStyle.Fill;
    webBrowser.Url = new Uri("http://www.bing.com");

    form1.Controls.Add(webBrowser);//add to form
    
    Application.Run(form1);//run
} 

Enjoy coding!

Thursday, April 22, 2010

C# 4.0: dynamic 'contextual keyword'

There is a new type, a contextual keyword, called dynamic in C# v4.0; getting to much of a popularity among advanced programming.It is used to call operations of dynamic languages (DLR).


To put it simply, binding is the association of a symbol within a program with an address in memory. The term “binding”, in this case refers to the process of resolving types, members, and operations.
  • Static binding happens at compile time, where a compiler identifies, resolves, and throws exception if necessary, at compile time.
  • Dynamic binding refers to identification, resolution, and throwing of exception if any, during runtime.
Dynamic binding in useful in cases where you know that a certain member, function, or operation would be available at run time. But compiler doesn’t know about that; the compiler would not throw any exceptions as well because it would just “trust you”, because you used dynamic keyword.
“A dynamic type tells the compiler to relax. We expect the runtime type of d to have
a Quack method. We just can’t prove it statically.” – (C# in a Nutshell Chap-4 Pg161)
dynamic dynTest = new Test();
dynTest.AnotherTest(1);

dynamic means that all expressions using dynTest is bound at execution time, rather than at compile-time, and thus makes it behave dynamically.

dynamic versus var keyword

A lot of times dynamic is confused with the var keyword; and to prove that statement, following is such an example that creates quite a confusion.

//CODE 1
var varTest = new Test();
varTest.AnotherTest(1);


//CODE 2
dynamic dynTest = new Test();
dynTest.AnotherTest(1);

Here, in CODE 1, var means the static type is inferred - in this case it's same as
Test varTest = new Test();

var is static typed - the compiler actually knows the type All the binding is still done entirely statically.

dynamic, in CODE 2, means that all expressions using dynTest is bound at execution time, rather than at compile-time, and thus makes it behave dynamically. Compiler won't check whether the AnotherTest() method exists - the behavior is determined at execution/run time.

Note that, somewhat on a tangent, if the object implements IDynamicMetaObjectProvider it could decide what to do with the call at execution time, responding to any method call - in other words, there doesn't have to be a "real" method called AnotherTest() at all.


This type of binding is also called “Custom Binding”; Custom binding occurs when a dynamic object implements IDynamicMetaObjectProvider (IDMOP). I’ll write more about custom binding sometime.


If you'd like to read more, here is a worth viewing, if you are short of reading time, article C# 4.0 – Dynamic Language Runtime by Microsoft's Bruno Terkaly with excellent visuals.

Happy dynamic’s! (0:

Tuesday, April 20, 2010

Do no trust: Browse Safe and Secure


"There's only two men I trust. One of them is me. The other's not you" - Nicolas Cage, Con Air
Thats pretty much an old movie but I cant forget the dialogue! Talking about the trust, many a times you become an e-victim of cross site scripts, cookie thefts, and well online redirects from secure to non secure sites to steal the credentials - either by clicking upon a tinyurl or googl like service or by some other obvious reasons. So its  important to keep yourself secure/safe; especially when travelling I find it important as well as hard to keep myself and my transactions, especially financial transactions, anonymous and secure.

To avoid certain surprising, full of spined-shocks, situations you can use certain methods to keep yourself secure.

TrueCrypt is a free open-source disk encryption software for Windows 7/Vista/XP, Mac OS X, and Linux; you can use TrueCrypt, which actually creates a virtual encrypted disk(your choice of encryption) within a file and mounts it as a real disk, where you can keep the stuff that you want safe and out of reach.


The 'real' stuff can be whatever you do on a daily basis, for isntance shopping, etc. The encrypted hard drive is useful in case your computer gets compromised, especially when using free hotspots, for instance on some airport terminal waiting for the "connecting-flight" to tug you in.

While browsing for a similar ware I came across this nice look-n-feel website that was discussing Tor project, an anonymity network software that enables internet anonymity by thwarting network traffic analysis. Though you can download and start running the software, but this method is "not recommended", not atleast on the website.

You can use Tor for browsing purpose but still I'd avoid banking credentials as much as I can; and use an ATM or phone to do that. Some countries/companies have strict policies against Tor, for instance the middle eastern region, where right now, I am on a project for a small duration.

Better, if your work offers SSH or a VPN mechanism for accessing your company's email, that'd be the best way to do it. Mine does that.

Well... whereever you are travelling, a clean computer is always a good idea; there are certain countries that take a full copy of drives; and even have strict policies regarding encryption software, for instance in China. Better would be to bring a computer with an empty or no hard drive and a Ubuntu CD. You can use Ubuntu to tunnel your remote desktop to your home computer.

Also, you can use openVPN. That way you can run all your traffic over the secure path.

Or you may set up an SSH server at home; so that you can create a secure session when in remote parts of the world. Note that some countries do not allow SSH and probably will block secure ports, so its possible to go through a different well-known port, 80 for instance; if its not too much for you.

Above all its a good practice to revise your "critical" passwords frequently, specially before and after a travel.

Have a safe browsing!

Monday, April 12, 2010

ORM Market Analysis

http://www.ormbattle.net/ best to get ORM benchmarks; decide for an ORM based upon your business; that means, now an OR really depends on how complex your application will be. For instance, the data structure, Linq2Sql is recommended. If it's getting more complex then try NHibernate, if you want a quick solution for a smaller business go for SubSonic;

Thursday, April 8, 2010

Best DI Framework: Microsoft Unity Application Block

Best DI Framework: Microsoft Unity Application Block

Change is the lifeblood of a software. So how does DI helps in that? For that you may would want to learn about the history of DI.

Dependency Injection is a design pattern use frequently utilized plug in/component based software architecture. Or in cases where intention is to reusing existing components and wiring together "disparate" components to form a cohesive software architecture. DI is a type of inversion of control; in which the flow of control is "inverted" to the users' or more specifically, to the frameworks' end. And framework decides what to call and what not to call.

You may have been writing manual DI unknowingly; the hand crafted factory pattern (adapter factory, method factory). Its simple, not much is the learning curve, no dependencies, no reflection, everyone knows what calls what in the code. The two types of injections are:

1. Setter injection
2. Constructor injection

With a dependency injection framework there is consistency, which means, on a large team you can actually "push" the team to do things in consistent manner; mostly because of the consistent nature of frameworks. Can define functional scope, rules of instantiation, etc, easily understandable and changeable.

Well, I would, instead writing just another essay repeating `No Silver Bullet` "for the 18,000th time", suggest you read more about the DI framework basic concept and provided by Martin Fowler at his Bliki.



Microsoft Unity Application Block, that now comes with the Enterprise Library as well.
Pico Container
Google's GUICE
Spring.NET

Happy injecting dependencies! (0:

Friday, April 2, 2010

Active Directory Application Mode (ADAM)

Active Directory Application Mode (ADAM):

Couple of projects ago, I had this SSO scenario to be implemented in a web app using LDAP to access Active Directory; having no access to any Active Directory - let alone a test environment - I was compelled to go through the ADAM and had myself it running to test the scenario.

ADAM enables you to create a practice environment for developing Active Directory Service Interfaces(ADSI) scripts, without having to install Active Directory. Learn how to set up and configure ADAM on any Windows XP Professional or Windows 2003 computer, and see how you can use ADAM as a workbench for writing scripts that manage such things as users, groups, contacts, inetOrg persons, and organizational units.

Well, if you want a detailed technical explanation, you came to the wrong place; instead, check out the whitepapers found here for more information.

A good idea for overview of ADAM, by Greg Stemp, is Madam, I'm ADAM. The article discusses about browing through a directory, using ADAM, binding to an instance, creating an Organizational Unit(OU), creating a user account, showing all users in OU; though the code used is VB.NET but you can always convert the snippet from online language translators.


Use ADAM for Roles in ASP.NET 2.0 is if you are doing a web app.

This article shows how to develop an ASP.NET Web site that uses Active Directory Application Mode (ADAM); which was the case that I had with my project. It shows how to configure ADAM and the Authorization Manager (AzMan) policy store - though I did not get into much of AzMan as I did for ADAM; created a few roles, and users, and started testing the web app against the SSO scenario that I had in hand.

Using ADAM as a roles-store is a good solution for applications accessed over an intranet or extranet where the user accounts store is Microsoft Active Directory® directory service or ADAM and where the application requires application-specific roles that are different from Active Directory group.

Erlend has discussed in detail and thorough ADAM related functionality.


ADAM installation:
1. Download and install ADAM from here.
2. Run the installer
3. Select "unique instance"
4. Provide the instance name
5. Select a free ports
6. Select "Yes, create an application directory"; and provide an organization name
7. Select a place for file
8. Select default for `Service Account Selection`
9. Select "Currently logged on account" for ADAM Adminstrators
10. Import "MS-User" and "MS-Userproxy"
11. Click next to finish.

ADAM configuration:
1. Open "ADAM ADSI Edit" from the ADAM program group in your start menu


2. Select "Action-->;Connect to..."
3. For name use [instance name] + "directory" ("MyInstance directory")
4. Alter the correct portnumber in the Port textbox (40000)
5. Choose "Distinguished name" and enter the distinguished name of your instance ("O=MyDirectory")

6. Click "Ok"
7. Right-click the "O=MyDirectory"-folder and select "New" and "Object..". Rename "OrganizationalUnit" to "Users".

8. Right-click the new "OU=Users"-folder and select "New" and "Object...". Select "user" and give the user an admin-like name ("ADAMAdmin"). We have now created our ADAM-adminuser
9. Right-click the "CN=ADAMAdmin"-account and choose "Reset password". Choose a sensible admin password.
10. Double-click the "CN=ADAMAdmin"-user and set the "msDS-UserAccountDisabled" to False
11. Go to the "CN=Roles"-folder and double-click the "Administrators"-account. Locate the "member" attrbitute and double-click it. Choose "Add ADAM-account" and enter the distinguished name of your newly created user (CN=ADAMAdmin,OU=Users,O=MyDirectory). Click the Ok-buttons to close the editor.
12. Close the "ADAM ADSI Edit" app.

WEB.config configuration?
In web.config, add following connection string:

 


Add membership provider:




 

All the way towards development, this guy, Will Asrari, helped like anything! Quite a collection of C# code snippets to browse through the active directory.

If you are interestd in getting to know "How to get the list of UserIDs from active directory", then read this post. And an issue that I came across that active directory was not showing all of the users.

If you are interested in building Custom Providers for ASP.NET 2.0 Membership; then this would helpful - though I just skimmed through the article but the amount of code and detail is worth some time!

Happy dating with ADAM! (0:

Related Posts

Popular Posts