Dennis’s Weblog

Archive for March 2009

Here are something that i learned from sample projects.(Blogengine.Net)

1.You should make full use of   Object Oriented Concept.

a.Provider Model.

When you design a core engine for blog, you should first design the core module. 

It will contain abstract class and interfaces which will help you to extend  and manage the functions later.

                           ProviderBase(it is a buildin class, that offer the function to commnicate with settings with web.config. that’s the benefit of extend

                                    ||          /*because of the extend, you can fully utilize ProviderBase class.  Use XML file the dynamic set the database provider without change your code.  After you add new functions

                                    ||           to BlogProvider, it will offer a model for later extend.  for example:  XMLProvider and DbBlogProvider, they are all ProviderBase object ! They have the same functions from 

                                   \/           ProviderBase.   */


                                    ||             /* And when later use of these class(XMLProvider and DbBlogProvider) will be consider as BlogProvider; BlogProvider dbBlogProvider= new DbBlogProvider();

                                    ||                  This is a abstract process, It seems like there are a layer between DbBlogProvider and Database, when you change your database provider you didn’t need to change

                                    \/                 The code.*/

             (XMLProvider or DbBlogProvider)




                           BlogService  (use the data and functions provided by BlogProvider at the upper layer to offer the capability of retrieve and update data from database. As well as the basic logical.)

       private static void LoadProviders()


// Avoid claiming lock if providers are already loaded

if (_provider == null)


lock (_lock)


// Do this again to make sure _provider is still null

if (_provider == null)


// Get a reference to the <blogProvider> section

BlogProviderSection section = (BlogProviderSection)WebConfigurationManager.GetSection(“BlogEngine/blogProvider”);

// Load registered providers and point _provider

// to the default provider

_providers = new BlogProviderCollection();

ProvidersHelper.InstantiateProviders(section.Providers, _providers, typeof(BlogProvider));

_provider = _providers[section.DefaultProvider];

if (_provider == null)

throw new ProviderException(“Unable to load default BlogProvider”);





…………………………………Use these code to set different Provider for this BlogService(Offer basic function for operate on database)…………………………………

So from this , when you start a new project, you should think about how to utilize system buildin class and make use of them. Like language Localization and IHttpModule and so on.


public abstract class BusinessBase<TYPE, KEY> : IDataErrorInfo, INotifyPropertyChanged, IChangeTracking, IDisposable where TYPE : BusinessBase<TYPE, KEY>, new()

When you extend a interface you can not extend anything from it, you just want to make use of Object Oritented Concept ‘s  Polymorphism.  Implement the interface and then it can be pass into other function.    for example     

<add verb=”*” path=”file.axd” type=”BlogEngine.Core.Web.HttpHandlers.FileHandler, BlogEngine.Core” validate=”false”/>
How can this XML clause take effect ?
Becase :
 public class FileHandler : IHttpHandler
It extend the IHttpHandler, so it can be added to web.config file and take effect. Without the polymorphism concept, you can not implement this!
another example:
private static Uri GetPermaLink(IPublishable publishable)
And because of this, all the class that implement the IPublishable interface can put into this function and retrieve a Uri.
c. 还是继承!!!

public abstract class BusinessBase<TYPE, KEY> : IDataErrorInfo, INotifyPropertyChanged, IChangeTracking, IDisposable where TYPE : BusinessBase<TYPE, KEY>, new()
It will be extended by all the object used by this BlogEngine. And because of the extend, all the objects extend this class can make use of the function offered by it.

public DateTime DateCreated
if (_DateCreated == DateTime.MinValue)
return _DateCreated;
return _DateCreated.AddHours(BlogSettings.Instance.Timezone);
if (_DateCreated != value) MarkChanged(“DateCreated”);
_DateCreated = value; 



protected virtual void MarkChanged(string propertyName)


_IsChanged = true;

if (!_ChangedProperties.Contains(propertyName))









public event PropertyChangedEventHandler PropertyChanged;

/// <summary>

/// Raises the PropertyChanged event safely.

/// </summary>

protected virtual void OnPropertyChanged(string propertyName)


if (PropertyChanged != null)


PropertyChanged(this, new PropertyChangedEventArgs(propertyName));



They are all in the BusinessBase class, Do you see anything ?

BusinessBase class extend the INotifyPropertyChanged interface:


    // Summary:

    //     Notifies clients that a property value has changed.

    public interface INotifyPropertyChanged


        // Summary:

        //     Occurs when a property value changes.

        event PropertyChangedEventHandler PropertyChanged;


It just contain a field of EventHandler,  and the client can set the EventHandler function to call When property are modified outside. MarkChanged function will call OnPropertyChanged to indirect call the eventHandler set by client.    And BusinessBase class implement this function for the descendants. When some field in BusinessBase changed it will call MarkChanged to indirect implement the eventHandler. That sounds very good, right ?

So this method is used to offer common method for descendants, very good!

<2> Leave the space for later reinforce


protected abstract void ValidationRules();//the descendant can implement this function and can be used by class outside.


/// <summary>

/// Gets whether the object is valid or not.

/// </summary>

public bool IsValid





return this._BrokenRules.Count == 0;




<3> use enum


virtual public SaveAction Save()


if (IsDeleted && !IsAuthenticated)

throw new System.Security.SecurityException(“You are not authorized to delete the object”);


if (!IsValid && !IsDeleted)

throw new InvalidOperationException(ValidationMessage);


if (IsDisposed && !IsDeleted)

throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, “You cannot save a disposed {0}”, this.GetType().Name));


if (IsChanged)


return Update();



return SaveAction.None;


<4> use bitwise operation to implement privileges!!

<5>for extend

#region Data access


/// <summary>

/// Retrieves the object from the data store and populates it.

/// </summary>

/// <param name=”id”>The unique identifier of the object.</param>

/// <returns>True if the object exists and is being populated successfully</returns>

protected abstract TYPE DataSelect(KEY id);


/// <summary>

/// Updates the object in its data store.

/// </summary>

protected abstract void DataUpdate();


/// <summary>

/// Inserts a new object to the data store.

/// </summary>

protected abstract void DataInsert();


/// <summary>

/// Deletes the object from the data store.

/// </summary>

protected abstract void DataDelete();



1.use NUNIT

a.install NUNIT

b.Write a test class in our project, remember to import the NUNIT.core and NUNIT.framework

c.Then open the project in NUNIT UI. the project in visual studio 2005, and then set the breakpoint at the position that you want to debug. NUNIT execute the function that you want to debug.

//Attatch to process used the attached the library that will be generated by current project to the process that will call this library,

Because of the invocation, the debug code will be triggered.


When want to debug a webapplication with build unit test, you should follow this:

debug the program,

and leave the aspnet_webserver alive(don’t close it).

//(don’t need) and then stop the debug,after that navigate to the unit test function,

//(don’t need) Web then attach all the code the webserver.exe process,

and click debug the unit test.


为什么用attach to process呢?其实我们生成的都是一些DLL文件,里面只是一些供调用的函数,所以只有attach to process,在那个process中会以各种方式调用我们DLL中的函数,从而触发DLL中的函数,并定位到breakpoint.

以下的Webserver debug,调用的方法是通过因特网访问。


In this tutorial we shall talk of debugging managed code using the Visual Studio .Net debugger .

To debug managed code, you need to have the Machine Debug Manager(mdm.exe) service running on your remote server. To check if MDM is installed, Click Start -> Programs -> Administrative Tools -> Services . Scroll down to see if Machine Debug Manager is running. If it is not, you need to install it. To install MDM, run Visual Studio .Net setup. Click on the Remote Components Setup.

The below screen opens up ->

Scroll down ->

For managed code debugging, you need to install full remote debug components .Click the ‘Install Full’ button ->

Once the installation is complete, verify that the MDM service is running.

Next you need to find out with what id the ASP.Net worker process is running. If this is running with the same id with which you are logged on to your client machine, then it is enough if your id is part of the debugger group on the server. If not, to debug the worker process, you need to have administrative access on the remote server. The worker process runs with the ASPNET account by default. To change the account with which the worker process runs, you need to modify the machine.config file – and that would be different topic in itself. Let us assume that you have administrative access on the remote server, that is, the id with which you are logged onto the client, is part of the administrator group on the remote server.

Open a Visual Studio Instance. Click Tools -> Debug Processes . The processes window opens up à

In the Name text box , type in the name of the remote server and press Enter.

The list of available processes is shown as below –

Select the aspnet_wp.exe, which is the ASP.Net worker process. Click Attach. The below screen pops-up. Make sure Common Language Runtime checkbox is checked. In the list below, where it shows ‘The below programs will be debugged’ you should see a list of sites on the server that are debuggable. The application that you are trying to debug

should also be listed in it. If it is not, then probably the web.config file has the debug option disabled. Open up the web.config file and check the compilation attribute à

Change the debug attribute to true. On attaching the debugger to the worker process, your application should be listed now.

Click OK on the Attach to process window. Click Close on the Process window.

On the visual studio instance, click File -> Open . Open the file(s) that you wish to debug. For example, I want to debug the webservice1 application, which runs a vb file called service1.asmx.vb. I want to debug the webmethod . I put a breakpoint in webmethod1()

Next, I need to execute the webservice so that my breakpoint gets hit and I can debug.

Open up an Internet Explorer window and type http://RemoteServer/WebService1/service1.asmx

I click the async method

Click Invoke. And Yo ! Visual Studio pops-up with the breakpoint highlighted à

Congratulations ! You are now ready to debug !!


Dated 25th Nov 2004

Mask (computing)

From Wikipedia, the free encyclopedia

In computer science, a mask is data that is used for bitwise operations.

Using a mask, multiple bits in a byte, nibble, word (etc.) can be set either on, off or inverted from on to off (or vice versa) in a single bitwise operation.



[edit]Common bitmask functions

[edit]Masking bits to 1

To turn certain bits on, the bitwise OR operation can be used. Recall that Y OR 1 = 1 and Y OR 0 = Y. Therefore, to make sure a bit is on, OR can be used with a 1. To leave a bit unchanged, OR is used with a 0.

Example – turning on the 5th bit

    10011101   10010101
 OR 00001000   00001000
  = 10011101   10011101

[edit]Masking bits to 0

There is no way to change a bit from on to off using the OR operation. Instead, bitwise AND is used. When a value is ANDed with a 1, the result is simply the original value, as in: Y AND 1 = Y. However, ANDing a value with 0 is guaranteed to return a0, so it is possible to turn a bit off by ANDing it with 0: Y AND 0 = 0. To leave the other bits alone, ANDing them with a 1 can be done.

Example – Turning off the 5th bit

    10011101   10010101
AND 11110111   11110111
  = 10010101   10010101

[edit]Querying the status of a bit

It is possible to use bitmasks to easily check the state of individual bits regardless of the other bits. To do this, turning off all the other bits using the bitwise AND is done as discussed above and the value is compared with 0. If it is equal to 0, then the bit was off, but if the value is any other value, then the bit was on. What makes this convenient is that it is not necessary to figure out what the value actually is, just that it is not 0.

Example – Querying the status of the 5th bit

    10011101   10010101
AND 00001000   00001000
  = 00001000   00000000

[edit]Toggling bit values

So far the article has covered how to turn bits on and turn bits off, but not both at once. Sometimes it does not really matter what the value is, but it must be made the opposite of what it currently is. This can be achieved using the XOR (exclusive or) operation. XOR returns 1 if and only if an odd number of bits are 1. Therefore, if two corresponding bits are 1, the result will be a 0, but if only one of them is 1, the result will be 1. Therefore inversion of the values of bits is done by XORing them with a 1. If the original bit was 1, it returns 1 XOR 1 = 0. If the original bit was 0 it returns 0 XOR 1 = 1. Also note that XOR masking is bit-safe, meaning that it will not affect unmasked bits because Y XOR 0 = Y, just like an OR.

[edit]Uses of bitmasks

[edit]Arguments to functions

In programming languages such as C, bit masks are a useful way to pass a set of named boolean arguments to a function. For example, in the graphics API OpenGL, there is a command, glClear() which clears the screen or other buffers. It can clear up to four buffers (the color, depth, accumulation, and stencil buffers), so the API authors could have had it take four arguments. But then a call to it would look like

glClear(1,1,0,0); // This is not how glClear actually works and would make for unreadable code.

which is not very descriptive. Instead there are four defined field bits, GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_ACCUM_BUFFER_BIT, and GL_STENCIL_BUFFER_BIT and glClear() is declared as

void glClear(GLbitfield mask);

Then a call to the function looks like this


Internally, a function taking a bitfield like this can use binary and to extract the individual bits. For example, an implementation of glClear() might look like:

void glClear(GLbitfield mask) {
  if (mask & GL_COLOR_BUFFER_BIT) {
    // Clear color buffer.
  if (mask & GL_DEPTH_BUFFER_BIT) {
    // Clear depth buffer.
  if (mask & GL_ACCUM_BUFFER_BIT) {
    // Clear accumulation buffer.
  if (mask & GL_STENCIL_BUFFER_BIT) {
    // Clear stencil buffer.

The advantage to this approach is that function argument overhead is decreased. Since the minimum datum size is one byte, separating the options into separate arguments would be wasting seven bits per argument and would occupy more stack space. Instead, functions typically accept one or more 32-bit integers, with up to 32 option bits in each. While elegant, in the simplest implementation this solution is not type-safe. A GLbitfield is simply defined to be an unsigned int, so the compiler would allow a meaningless call to glClear(42) or even glClear(GL_POINTS). In C++ an alternative would be to create a class to encapsulate the set of arguments that glClear could accept and could be cleanly encapsulated in a library (see the external links for an example).

[edit]Inverse Masks

Masks are used with IP addresses in IP ACLs (Access Control Lists) to specify what should be permitted and denied. Masks in order to configure IP addresses on interfaces start with 255 and have the large values on the left side: for example, IP address with a mask. Masks for IP ACLs are the reverse: for example, mask This is sometimes called an inverse mask or a wildcard mask. When the value of the mask is broken down into binary (0s and 1s), the results determine which address bits are to be considered in processing the traffic. A 0 indicates that the address bits must be considered (exact match); a 1 in the mask is a "don’t care". This table further explains the concept.

Mask Example:

network address (traffic that is to be processed)


network address (binary) 00001010.00000001.00000001.00000000

mask (binary) 00000000.00000000.00000000.11111111

Based on the binary mask, it can be seen that the first three sets (octets) must match the given binary network address exactly (00001010.00000001.00000001). The last set of numbers are "don’t cares" (.11111111). Therefore, all traffic that begins with 10.1.1. matches since the last octet is "don’t care". Therefore, with this mask, network addresses through (10.1.1.x) are processed.

Subtract the normal mask from in order to determine the ACL inverse mask. In this example, the inverse mask is determined for network address with a normal mask of – (normal mask) = (inverse mask)

ACL equivalents

The source/source-wildcard of means "any".

The source/wildcard of is the same as "host"

[edit]Image masks

Raster graphicsprites (left) and masks (right)

In computer graphics, when a given image is intended to be placed over a background, the transparent areas can be specified through a binary mask. This way, for each intended image there are actually two bitmaps: the actual image, in which the unused areas are given a pixel value with all bits set to 0’s, and an additional mask, in which the correspondent image areas are given a pixel value of all bits set to 0’s and the surrounding areas a value of all bits set to 1’s. In the sample at right, black pixels have the all-zero bits and white pixels have the all-one bits.

At run time, to put the image on the screen over the background, the program first masks the screen pixel’s bits with the image mask at the desired coordinates using the bitwise AND operation. This preserves the background pixels of the transparent areas while resets with zeros the bits of the pixels which will be obscured by the overlapped image.

Then, the program renders the image pixel’s bits by blending them with the background pixel’s bits using the bitwise OR operation. This way, the image pixels are appropiately placed while keeping the background surrounding pixels preserved. The result is a perfect compound of the image over the background.

This technique is used for painting pointing device cursors, in typical 2-D videogames for characters, bullets and so on (the sprites), for GUI icons, and for video titling and other image mixing applications.

Although related (due to being used for the same purposes), transparent colors and alpha channels are techniques which do not involve the image pixel mixage by binary masking.

[edit]Hash tables

To create a hashing function for a hash table often a function is used that has a large domain. To create an index from the output of the function, a modulo can be taken to reduce the size of the domain to match the size of the array; however, it is often faster on many processors to restrict the size of the hash table to powers of two sizes and use a bit mask instead.

  • In: Web Design
  • Enter your password to view comments.

This content is password protected. To view it please enter your password below:

  • In: C#
  • Enter your password to view comments.

This content is password protected. To view it please enter your password below: