This blog is a knowledge base...where I clip cool tricks and urls

Script#

Writing javascript in C#
clipped from www.nikhilk.net
public class HelloWorldScriptlet : IScriptlet {
private Button _okButton;
private TextBox _nameTextBox;
private Label _helloLabel;
private XMLHttpRequest _request;
public void Start() {
_okButton = new Button(Document.GetElementById("okButton"));
_nameTextBox = new TextBox(Document.GetElementById("nameTextBox"));
_helloLabel = new Label(Document.GetElementById("helloLabel"));
_okButton.Click += new EventHandler(OnOKButtonClick);
}
private void OnOKButtonClick(object sender, EventArgs e) {
Callback completedCallback = new Callback(this.OnRequestComplete);
_request = new XMLHttpRequest();
_request.Onreadystatechange = Delegate.Unwrap(completedCallback);
_request.Open("GET", "Hello.axd?name=" + _nameTextBox.Text, /* async */ true);
_request.Send(null);
}
private void OnRequestComplete() {
if (_request.ReadyState == 4) {
_request.Onreadystatechange = null;
string greeting = _request.ResponseText;
_helloLabel.Text = greeting;
}
}
 blog it

Export .NET to COM

clipped from www.codeproject.com
using System;
using System.Runtime.InteropServices;
namespace Tester
{
[Guid("D6F88E95-8A27-4ae6-B6DE-0542A0FC7039")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface _Numbers
{
[DispId(1)]
int GetDay();
[DispId(2)]
int GetMonth();
[DispId(3)]
int GetYear();
[DispId(4)]
int DayOfYear();
}
[Guid("13FE32AD-4BF8-495f-AB4D-6C61BD463EA4")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("Tester.Numbers")]
public class Numbers : _Numbers
{
public Numbers(){}
public int GetDay()
{
return(DateTime.Today.Day);
}
public int GetMonth()
{
return(DateTime.Today.Month);
}
public int GetYear()
{
return(DateTime.Today.Year);
}
public int DayOfYear()
{
return(DateTime.Now.DayOfYear);
}
}
}
 blog it

NHibernate SessionScope in ASP.NET

Getting started with NHibernate and Log4Net

Going on with session


As in ADO.NET we use database connection class to create queries or data adapter,
in NHibernate we use session object which is responsible for maintaining connection to database,
loading data into domain objects, detecting changes to domain object and syncing domain state with database.
NHibernate requires at least one session to work. As NHibernate caches domain object instances to
ensure that single row is loaded only once from database multi-user work with one session object is questionable.
This issue differ usage of NHibernate in WinForms and ASP.NET application.
The general idea is to have only one session per request and this can be achieved
either by using singleton pattern on using HttpModule. We will use the last one.
To do this we need to create a custom class, make it inherit IHttpModule interface

<httpModules>
    <add

type
="Dummy.DAL.NHibernateHttpModule"
name="NHibernateHttpModule"/>

  </httpModules>
 blog it

high-performance, distributed memory object caching system

clipped from www.danga.com

What is memcached?


memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

Danga Interactive developed memcached to enhance the speed of LiveJournal.com, a site which was already doing 20 million+ dynamic page views per day for 1 million users with a bunch of webservers and a bunch of database servers. memcached dropped the database load to almost nothing, yielding faster page load times for users, better resource utilization, and faster access to the databases on a memcache miss.

 blog it

Anonymous Class - C# 3.0

public class var { … }

 

public class Program

{

         public void MyMethod (var thing1, // does this mean var keyword or var class??

                   string thing2,

                   int thing3)

         {

                   var myString = “Hello, world”;

                            // var here means string (System.String)

                   var myInt = 1;

                            // var here means int (System.Int32)

                   var myVar = new var();

                            // var here means the class var

                   var myVar2 = null;

// does this mean var keyword or var class??

                   var myVar3;

// does this mean var keyword or var class??

}

}

 

private void Form1_Load(object sender, EventArgs e)

        {

            var methods = typeof(string).GetMethods();

            var methodDetails =

                from m in methods

                where ! m.IsStatic

                orderby m.Name

                select new {

                    Name = m.Name,

                    CallingConvention = m.CallingConvention,

                    Abstract = m.IsAbstract,

                    Virtual = m.IsVirtual,

                    Public = m.IsPublic

                } ;

 

            BindingSource bindingSource = new BindingSource();

            bindingSource.DataSource = methodDetails;

            dataGridView1.DataSource = bindingSource;

        }

 blog it

How to expose .NET library to COM

clipped from www.codeproject.com

The problem is, suppose that I have written a nice library, set of utility functions, etc.. running under the .NET Framework, however I want to use this under pre .NET development environments. For SimonS he would like to use VB6 specifically. Enter the COM Callable Wrapper (CCW) to create a proxy that will provide access to our functions through interface pointers. This can be accomplished through the use of those fun little attribute tags (I keep finding them more and more useful everyday) and with an interface of course.

 blog it

CCW - COM Callable Wrapper

clipped from msdn2.microsoft.com
COM Callable Wrapper 

When a COM client calls a .NET object, the common language runtime creates the managed object and a COM callable wrapper (CCW) for the object. Unable to reference a .NET object directly, COM clients use the CCW as a proxy for the managed object.

The runtime creates exactly one CCW for a managed object, regardless of the number of COM clients requesting its services. As the following illustration shows, multiple COM clients can hold a reference to the CCW that exposes the INew interface. The CCW, in turn, holds a single reference to the managed object that implements the interface and is garbage collected. Both COM and .NET clients can make requests on the same managed object simultaneously.

Accessing .NET objects through COM callable wrapper
COM callable wrapper
 blog it

.NET-COM RCW Marshalling

clipped from www.codeproject.com

.NET Marshalling

Thus .NET runtime automatically generates code to translate calls between managed code and unmanaged code. While transferring calls between these two codes, .NET handles the data type conversion also. This technique of automatically binding with the server data type to the client data type is known as marshalling. Marshaling occurs between managed heap and unmanaged heap. For example, Fig.4 shows a call from the .NET client to a COM component. This sample call passes a .NET string from the client. The RCW converts this .NET data type into the COM compatible data type. In this case COM compatible data type is BSTR. Thus the RCW converts the .NET string into COM compatible BSTR. This BSTR will be passed to the object and the required calls will be made. The results will be returned to back to the RCW. The RCW converts this COM compatible result to .NET native data type.


  1. Interop marshalling
  2. COM marshalling
 blog it

.NET-COM Model

clipped from www.codeproject.com

CCW will be created by the .NET utility RegAsm.exe. This reads metadata of the .NET component and generates the CCW. This tool will make a registry entry for the .NET components.

Fig.3 calling a .NET component from COM client

Generally COM client instantiates objects through its native method coCreateInstance. While interacting with .NET objects, the COM client creates .NET objects by coCreateInstance through CCW.

 blog it

tags need to use serviced component

clipped from www.codeproject.com
#import "mscorlib.tlb"
// Import the .NET component's typelibrary
#import "HelloDotNet.tlb" no_namespace
 blog it

consuming .NET assembly as COM

clipped from www.codeproject.com
In the latter half of this article, we took a dip into exploring how COM aware clients from the pre-.NET era could consume .NET components as if they were classic COM components. We saw how the CCW and the CLR facilitate this to happen seamlessly from a programming perspective. We briefly explored the possibilities of using attributes to emit metadata into .NET types so that the typelibrary generated could be tailored and fine-tuned to your requirements. We looked at how the exception handling mechanisms in the two worlds are correlative. We also discussed about how to go about receiving asynchronous event notifications from .NET components in unmanaged event sinks. Then, we turned our attention to the deployment options available and how to deploy .NET components as Shared assemblies. Lastly, we discussed the thread-neutral behavior of .NET components and saw how Context-agile .NET components are analogous to Classic COM 'Both' threaded components
 blog it

Creating a template item with Wizard

clipped from msdn2.microsoft.com

To create a custom template wizard

  1. Create an assembly that implements the IWizard interface.

  2. Install the assembly into the global assembly cache.

  3. Create a project and use the Export Template wizard to create a template from the project.

  4. Modify the template by adding a WizardExtension element in the .vstemplate file to link the template to the assembly that implements IWizard.

  5. Create a new project using the custom wizard.

 blog it

Overriding SessionId

clipped from msdn.microsoft.com
To optimize this behavior, you can take advantage of the ASP.NET 2.0 custom session ID generation features to hide the session ID for a request, thereby preventing any session state work for that request. You can do this by implementing a custom type that derives from System.Web.SessionState.SessionIDManager, and then implementing the GetSessionID method to return a null session ID for requests that do not require session state (see Figure 2). For all other requests, you can delegate to the default GetSessionID implementation of the SessionIDManager class, which provides the default cookie and cookieless session ID support in ASP.NET.
 blog it

SessionID Manager

clipped from msdn.microsoft.com

Session state runtime operation is implemented by the SessionStateModule class which plugs into the request processing pipeline in the application as an IHttpModule. SessionStateModule executes once before handler execution in the AcquireRequestState pipeline stage, and once after handler execution in the ReleaseRequestState pipeline stage (see Figure 1). In the AcquireRequestState stage, SessionStateModule attempts to extract the session ID from the request and retrieve the session data for that session ID from the session state store provider. If the session ID is present and the state is retrieved successfully, the module builds the session state dictionary that can be used by the handler to inspect and change the session state.

Figure 1 Maintaining Session State
Figure 1 Maintaining Session State
 blog it

Hacking Session mechanism

clipped from www.codeproject.com

InitModules(), all the modules listed under <system.web>/<httpModules> section are initialized, i.e., Init method of each of these HttpModules is called, i.e.. Init method of SessionStateModule is called. In the Init method of SessionStateModule, session state settings are read from <system.web>/<sessionState> section of web.config file of your ASP.NET application, and then it calls another method InitModuleFromConfig. The signature of this method is listed below:

private void InitModuleFromConfig(HttpApplication app, 
Config config, bool configInit);

The parameter app represents the instance of HttpApplication class that is being used to serve the HTTP request.

InitModuleFromConfig adds various event handlers for session management related events that are raised from InitInternal() method of HttpApplication.

 blog it