Google Sitemap .NET links

Some links with information about creating a Google Sitemap either directly in XML or via some .NET code.

http://gerardmcgarry.com/blog/creating-a-google-sitemap-aspnet-website

http://www.codeproject.com/KB/aspnet/GoogleSiteMapProvider.aspx

.NET Resource localization

ResourceBlender is open source and works for .NET:

http://www.resourceblender.com/

Using Multiple Configuration files for NHibernate (HybridSessionBuilder)

 

I have been using Castle Windsor and NHibernate for some months now, so I am a bit new and still learning. But then again, it is learning developers like me, that asks all the questions.

This post is also written because of a simple question: Does the HybridSessionBuilder support multiple configurations?

Why this question? Well, I have a project where some repositories uses one database and some other uses another database.

Original implementation

My little journey started out with my looking original implementation of the HybridSessionBuilder (HSB). You can read about the original implementation here:

http://jeffreypalermo.com/blog/use-this-nhibernate-wrapper-to-keep-your-repository-classes-simple/

But as you can see:image

The original implementation used a static session factory and session, so this is does not support multiple configurations.

CodeCampServer/Tarantino

I then found out that the CodeCampServer also was using the HSB. Hoping to find an implementation that supported my request, I then started to read the source code.

But by viewing the source code for CodeCampServer I soon found out that the code, for the HSB, had been updated to support multiple factories and sessions. Yeeeaaaaa :)

Furthermore I found out that the HSB now is a part of a collection of libraries called Tarantino.

I was happy, the HybridSessionBuilder now supported my requests, and it was ready to be used in my projects. I thought.

Test web application

image Then I build a small test web application project. It used Castle Windsor (for dependency injection) and NHibernate. I quickly configured Castle Windsor and made two NHibernate configuration files.

nhibernate.cfg.xml used this connection string:

Data Source=localhost\sqlexpress;Initial Catalog=DB1;Integrated Security=true

nhibernate2.cfg.xml used this connection string:

Data Source=localhost\sqlexpress;Initial Catalog=DB2;Integrated Security=true

My windsor.config.xml looks like this:

<component id="firstRepository" type="HybridSessionBuilderTest.FirstRepository, HybridSessionBuilderTest">
  <parameters>
    <ConfigurationFile>hibernate.cfg.xml</ConfigurationFile>
  </parameters>
</component>
 
<component id="secondRepository" type="HybridSessionBuilderTest.SecondRepository, HybridSessionBuilderTest">
  <parameters>
    <ConfigurationFile>hibernate2.cfg.xml</ConfigurationFile>
  </parameters>
</component>

It basically just configures the two repositories with each own configuration.

But to my surprise, it did not work. I made a small page that prints the connection string of each of the repositories:

image

Only the default NHibernate configuration file was used.

Bug or feature?

That was not the output I was looking for, so to find the problem, I did some more test and dug into the code.

I was expecting an object structure like this:

image

But I got something like this:

image  I identified the following method to be the central, when the session was instantiated:

   1: private ISession getExistingOrNewSession(ISessionFactory factory, string configurationFile)
   2:         {
   3:             if (HttpContext.Current != null)
   4:             {
   5:                 var session = GetExistingWebSession();
   6:  
   7:                 if (session == null || !session.IsOpen)
   8:                 {
   9:                     session = openSessionAndAddToContext(factory, configurationFile);
  10:                 }
  11:  
  12:                 return session;
  13:             }
  14:  
  15:             var currentSession = _currentSessions.ContainsKey(configurationFile)
  16:                                     ? _currentSessions[configurationFile]
  17:                                     : null;
  18:             if (currentSession == null || !currentSession.IsOpen)
  19:             {
  20:                 _currentSessions[configurationFile] = OpenSession(factory);
  21:             }
  22:  
  23:             return _currentSessions[configurationFile];
  24:         }

Patch/solution

The problem I identified is line #5. It returns the existing session based on the default configuration, no matter what you specify in the configurationFile parameter.

I changed it to:

   1: var session = GetExistingWebSession(configurationFile);

 

And tadaaa:

image

The second repository now uses the second configuration file :)

Conclusion

You might ask, why I spend time writing a blog post describing this little change to the HybridSessionBuilder.

First of all, having a HSB that can use multiple configurations is rather important to me and the projects I am working on.

Second of all, as NHibernate and Castle Windsor is still a bit new to me, one of the best ways to learn its capabilities and how to use it, is to dig in deep. And that is exactly what I have done.

And BTW – I have not just learned about HSB, but also CodeCampServer, Tarantino, S#arp and how it handles multiple configurations, and how it all works together.

NHibernateSessionModule

Please note. Before my change is used, you need to also update the NHibernateSessionModule. It does currently not dispose all the sessions that are opened.

Posted in Development. Tags: , , . No Comments »

Multiple Configurations for NHibernate (HybridSessionBuilder)

 

I have been using Castle Windsor and NHibernate for some months now, so I am a bit new and still learning. But then again, it is learning developers like me, that asks all the questions.

This post is also written because of a simple question: Does the HybridSessionBuilder support multiple configurations?

Why this question? Well, I have a project where some repositories uses one database and some other uses another database.

Original implementation

My little journey started out with my looking original implementation of the HybridSessionBuilder (HSB). You can read about the original implementation here:

http://jeffreypalermo.com/blog/use-this-nhibernate-wrapper-to-keep-your-repository-classes-simple/

But as you can see:image

The original implementation used a static session factory and session, so this is does not support multiple configurations.

CodeCampServer/Tarantino

I then found out that the CodeCampServer also was using the HSB. Hoping to find an implementation that supported my request, I then started to read the source code.

But by viewing the source code for CodeCampServer I soon found out that the code, for the HSB, had been updated to support multiple factories and sessions. Yeeeaaaaa :)

Furthermore I found out that the HSB now is a part of a collection of libraries called Tarantino.

I was happy, the HybridSessionBuilder now supported my requests, and it was ready to be used in my projects. I thought.

Test web application

image Then I build a small test web application project. It used Castle Windsor (for dependency injection) and NHibernate. I quickly configured Castle Windsor and made two NHibernate configuration files.

nhibernate.cfg.xml used this connection string:

Data Source=localhost\sqlexpress;Initial Catalog=DB1;Integrated Security=true

nhibernate2.cfg.xml used this connection string:

Data Source=localhost\sqlexpress;Initial Catalog=DB2;Integrated Security=true

My windsor.config.xml looks like this:

<component id="firstRepository" type="HybridSessionBuilderTest.FirstRepository, HybridSessionBuilderTest">
  <parameters>
    <ConfigurationFile>hibernate.cfg.xml</ConfigurationFile>
  </parameters>
</component>
 
<component id="secondRepository" type="HybridSessionBuilderTest.SecondRepository, HybridSessionBuilderTest">
  <parameters>
    <ConfigurationFile>hibernate2.cfg.xml</ConfigurationFile>
  </parameters>
</component>

It basically just configures the two repositories with each own configuration.

But to my surprise, it did not work. I made a small page that prints the connection string of each of the repositories:

image

Only the default NHibernate configuration file was used.

Bug or feature?

That was not the output I was looking for, so to find the problem, I did some more test and dug into the code.

I was expecting an object structure like this:

image

But I got something like this:

image  I identified the following method to be the central, when the session was instantiated:

   1: private ISession getExistingOrNewSession(ISessionFactory factory, string configurationFile)
   2:         {
   3:             if (HttpContext.Current != null)
   4:             {
   5:                 var session = GetExistingWebSession();
   6:  
   7:                 if (session == null || !session.IsOpen)
   8:                 {
   9:                     session = openSessionAndAddToContext(factory, configurationFile);
  10:                 }
  11:  
  12:                 return session;
  13:             }
  14:  
  15:             var currentSession = _currentSessions.ContainsKey(configurationFile)
  16:                                     ? _currentSessions[configurationFile]
  17:                                     : null;
  18:             if (currentSession == null || !currentSession.IsOpen)
  19:             {
  20:                 _currentSessions[configurationFile] = OpenSession(factory);
  21:             }
  22:  
  23:             return _currentSessions[configurationFile];
  24:         }

Patch/solution

The problem I identified is line #5. It returns the existing session based on the default configuration, no matter what you specify in the configurationFile parameter.

I changed it to:

   1: var session = GetExistingWebSession(configurationFile);

 

And tadaaa:

image

The second repository now uses the second configuration file :)

Conclusion

You might ask, why I spend time writing a blog post describing this little change to the HybridSessionBuilder.

First of all, having a HSB that can use multiple configurations is rather important to me and the projects I am working on.

Second of all, as NHibernate and Castle Windsor is still a bit new to me, one of the best ways to learn its capabilities and how to use it, is to dig in deep. And that is exactly what I have done.

And BTW – I have not just learned about HSB, but also CodeCampServer, Tarantino, S#arp and how it handles multiple configurations, and how it all works together.

Posted in Development. Tags: , , , . No Comments »

How will you parallelize your existing codebase? Try R.A.S.P

Original post:

http://www.atalasoft.com/cs/blogs/rickm/archive/2008/12/23/how-will-you-parallelize-your-existing-codebase-try-r-a-s-p.aspx

———————————————————————————————————————-

How will you parallelize your existing codebase? Try R.A.S.P.

There
has been much talk of how we will be writing all of our new code with
parallelization in mind.  However, what of our existing code?  It’s
unlikely that everyone will just suddenly dump decades of existing code
and write everything from scratch.  In this article I’m going to
provide a simple methodology for how we might deal with the ever
building problem of parallelizing our existing mountains of code. 
Comments and contributions are welcome.

 

Methodologies of the Past

From
the STL to .NET, the frameworks we have constructed our applications
around have been heavily dependent on the idea of an application having
a single thread.  Given that the foundation of what we have all been
using for a very long time was constructed around this preconception,
it’s unreasonable to expect that much of our existing code will ever be
fully parallel.  Even those that wrote code on top of a thread safe
framework may find that years of patches and and poor design decisions
make ground up parallelization impossible.

If we set our
expectations reasonably, we see that we should instead focus on
leveraging parallelism to improve the performance of the slowest parts
of our software.  From this viewpoint, parallelization is an
optimization problem.  Like all optimization, the difficulty of
parallelizing code will have much to do with the methodologies which
were used to write it.  

Of course, object-oriented code being written with modern S.O.L.I.D. principles
and will be easier to parallelize than older procedural code.  At the
same time, a poorly organized codebase or poorly written code will
always make change difficult and so also hard to parallelize.  This is
why well written code is worth the investment.  We will see the
investment paying off in spades for the companies who have bothered to
care about code quality.  Others who find they have spaghetti code
under the hood will find they will need to deeply segregate and
modularize before parallelization is possible.

 

A Methodology for Revisiting the Past

In
most cases it would be a poor choice to implement your own threading
API.  Efficient and easy to use parallelization APIs are coming to (or
already part of) every commonly used language and framework.  Most of
these APIs are not only built on top of years of research,
they also have been written and debugged by a large number of people
with specific expertise.  These APIs are a godsend because they will
allow most developers to parallelize existing software with a minimum
amount of pain.  The parallelization of existing code bases will be
much the same as any other kind of performance tuning. 

The
key will be using a profiler to identify places in the code that would
be sped up by parallelization and leveraging these new APIs to take
advantage of the available hardware.  The exciting part is that this
can be done with any existing profiler and many existing APIs.  The
unfortunate part is that because memory sharing is such a big issue,
parallelization requires a degree of separation beyond other types of
optimization and so is likely to require some amount of refactoring.

Not
all types of performance problems are conducive to being solved by
parallelization, careful evaluation of the problem at hand is
required.  Also, as with anything that requires significant code
change, building a solid test fixture is key to introducing as few bugs
as possible.  By leveraging the ideas of avoiding premature optimization, pragmatic unit testing, using existing APIs, and mindful refactoring it will be possible to introduce parallelization into many already existing projects with a manageable amount of risk.

 

What is RASP?

While not included in the acronym, the first step in any kind of optimization is profiling
Before you can begin to parallelize your code, you must determine where
the bottlenecks might be.  A broadly defined list of parallelizable
things to look for would be, to quote Rich Hickey,
“independent data/work, moderate-to-course-grained work units and/or
complex coordination logic that would be simplified with threads”.  A
couple quick examples of low hanging fruit to be on the lookout for
would be slow iterative loops and blocking I/O.  It is important to
note that as a general guideline it would be wrong to parallelize
anything if it would not significantly increase the speed of your
software.

For each of the bottlenecks found while profiling, parallelization is best separated into four steps:

Review: Review code to determine if it is a good candidate for parallelization.
Anchor: Create a unit test fixture to ensure that the behavior of the to be parallelized code does not change.
Separate: Ensure that the to be parallelized code has no shared memory constraints, and if it does, factor them out if possible.
Parallelize: Minimally refactor for parallelization while leveraging an existing API to do the heavy lifting.

As
the specifics of what each of these would entail depends greatly on
exactly which platform and language is in use, I will not go into them
deeply now.  Overall, it’s a simple methodology but I think both
sufficient for the task at hand and broadly applicable. 

 

Conclusion

Review,
Anchor, Separate, Parallelize.  It’s not intended to be a difficult
concept but instead to provide a simple path to parallelization.  I
would be very interested in hearing about any opinions on what RASP
might be missing or how it may be better clarified.  While I didn’t
have time to discuss them deeply in this post, parallelization patterns
are also a key concept in using RASP as if you can’t easily identify
what can be parallelized than it would be impossible to use any
parallelization methodology.  In the future I hope flush out RASP
further as well as discuss parallelization patterns in depth.

Create Word Documents using .NET without Interop

Original blog post:

http://www.invoke.co.nz/products/docx.aspx

————————————————————————————–

We have decided to release another component we've been using (FREE of charge, click here to download).
This library creates Word Documents (.docx) using .NET. It is written
purely in C#, you don't need any Word viewing applications or Interop
(COM) dlls installed/registered.

It works very similar to a
Repeater control, instead of HTML markup you create a docx template
using Word 2007 (Open XML format), specify parameters/placeholders to
hold values then pass the document to the library, it will then merge
those fields.

Here's an example:
To create a Word (.docx document)
- Open up Word 2007, create a new file and type in the following (without the " "):
"Hello %NAME%"
- Save & Exit (save as hello.docx)

- Create a new VS 2008 Console Application project, add a reference to the docx library, copy paste the code into Program.cs

static void Main(string[] args)
{
    File.Copy("hello.docx", "hello_ready.docx", true); // create a copy of template file for later use
    // DocumentDataSource holds name/value pair data
    DocumentDataSource source = new DocumentDataSource();
 
    source["NAME"] = "Joe Bloggs"; // assign a value to parameter %NAME%
    DocumentRenderer.ProcessDocument("hello_ready.docx", source); // process the document
 
    Process.Start("hello_ready.docx"); // run MS Word to see merged document
}

Result
Create a Word Document using C# without Interop (COM)

That's an over simplified example, the library is able to do a lot more, if you'd like to download it or find out more please click here,

Posted in Development. Tags: , , , , . No Comments »

Ayende explains cascading with NHibernate

To continue my little "post with good links"… here is a good article by Ayende, explaining cascadin with NHibernate:

http://ayende.com/Blog/archive/2006/12/02/NHibernateCascadesTheDifferentBetweenAllAlldeleteorphansAndSaveupdate.aspx

Here is the basics:

Here is what each cascade option means:

  • none – do not do any cascades, let the users handles them by themselves.
  • save-update – when the object is saved/updated, check the assoications and save/update any object that require it (including save/update the assoications in many-to-many scenario).
  • delete – when the object is deleted, delete all the objects in the assoication.
  • delete-orphans – when the object is deleted, delete all the objects in the assoication. In addition to that, when an object is removed from the assoication and not assoicated with another object (orphaned), also delete it.
  • all – when an object is save/update/delete, check the assoications and save/update/delete all the objects found.
  • all-delete-orhpans – when an object is save/update/delete, check the assoications and save/update/delete all the objects found. In additional to that, when an object is removed from the assoication and not assoicated with another object (orphaned), also delete it.

 

Posted in Software. Tags: , , , , . No Comments »

Using .ToString(string Format) in C#

Read more Formatting on the "Formatting Overview" on MSDN (http://msdn2.microsoft.com/en-us/library/26etazsy(VS.71).aspx), or take a look in the Customer Numeric Format Strings section below (Original text here: http://msdn2.microsoft.com/en-us/library/0c899ak8(VS.71).aspx)

Custom Numeric Format Strings

If the standard numeric format specifiers do not provide the type of formatting you require, you can use custom format strings to further enhance string output. A standard format string consists of a single alphabetic character optionally followed by a sequence of digits that form a value between 0 and 99; all other format strings are custom format strings.

The following table shows the characters you can use to create custom numeric format strings and their definitions. Note that the result strings produced by some of these characters are influenced by the settings in the Regional Options control panel of the NumberFormatInfo object associated with the current thread. Computers using different cultures will generate different result strings.

Format character Name Description

0

Zero placeholder If the value being formatted has a digit in the position where the ‘0′ appears in the format string, then that digit is copied to the result string. The position of the leftmost ‘0′ before the decimal point and the rightmost ‘0′ after the decimal point determines the range of digits that are always present in the result string. The "00" specifier causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "00" would result in the value 35.

#

Digit placeholder If the value being formatted has a digit in the position where the ‘#’ appears in the format string, then that digit is copied to the result string. Otherwise, nothing is stored in that position in the result string. Note that this specifier never displays the ‘0′ character if it is not a significant digit, even if ‘0′ is the only digit in the string. It will display the ‘0′ character if it is a significant digit in the number being displayed. The "##" format string causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "##" would result in the value 35.

.

Decimal point The first ‘.’ character in the format string determines the location of the decimal separator in the formatted value; any additional ‘.’ characters are ignored. The actual character used as the decimal separator is determined by the NumberDecimalSeparator property of the NumberFormatInfo that controls formatting.

,

Thousand separator and number scaling The ‘,’ character serves two purposes. First, if the format string contains a ‘,’ character between two digit placeholders (0 or #) and to the left of the decimal point if one is present, then the output will have thousand separators inserted between each group of three digits to the left of the decimal separator. The actual character used as the decimal separator in the result string is determined by the NumberGroupSeparator property of the current NumberFormatInfo that controls formatting.

Second, if the format string contains one or more ‘,’ characters immediately to the left of the decimal point, then the number will be divided by the number of ‘,’ characters multiplied by 1000 before it is formatted. For example, the format string "0,," will represent 100 million as simply 100. Use of the ‘,’ character to indicate scaling does not include thousand separators in the formatted number. Thus, to scale a number by 1 million and insert thousand separators you would use the format string "#,##0,,".

%

Percentage placeholder The presence of a ‘%’ character in a format string causes a number to be multiplied by 100 before it is formatted. The appropriate symbol is inserted in the number itself at the location where the ‘%’ appears in the format string. The percent character used is dependent on the current NumberFormatInfo class.

E0

E+0

E-0

e0

e+0

e-0

Scientific notation If any of the strings "E", "E+", "E-", "e", "e+", or "e-" are present in the format string and are followed immediately by at least one ‘0′ character, then the number is formatted using scientific notation with an ‘E’ or ‘e’ inserted between the number and the exponent. The number of ‘0′ characters following the scientific notation indicator determines the minimum number of digits to output for the exponent. The "E+" and "e+" formats indicate that a sign character (plus or minus) should always precede the exponent. The "E", "E-", "e", or "e-" formats indicate that a sign character should only precede negative exponents.

\

Escape character In C# and the Managed Extensions for C++, the backslash character causes the next character in the format string to be interpreted as an escape sequence. It is used with traditional formatting sequences like ‘\n’ (new line).

In some languages, the escape character itself must be preceded by an escape character when used as a literal. Otherwise, the compiler interprets the character as an escape sequence. Use the string "\\" to display ‘\’.

Note that this escape character is not supported in Visual Basic; however, ControlChars provides the same functionality.

‘ABC’

"ABC"

Literal string Characters enclosed in single or double quotes are copied to the result string literally, and do not affect formatting.

;

Section separator The ‘;’ character is used to separate sections for positive, negative, and zero numbers in the format string.

Other

All other characters All other characters are copied to the result string as literals in the position they appear.

Note that for fixed-point format strings (strings not containing an "E0", "E+0", "E-0", "e0", "e+0", or "e-0"), numbers are rounded to as many decimal places as there are digit placeholders to the right of the decimal point. If the format string does not contain a decimal point, the number is rounded to the nearest integer. If the number has more digits than there are digit placeholders to the left of the decimal point, the extra digits are copied to the result string immediately before the first digit placeholder.

Different formatting can be applied to a string based on whether the value is positive, negative, or zero. To produce this behavior, a custom format string can contain up to three sections separated by semicolons:

  • One section: The format string applies to all values.
  • Two sections: The first section applies to positive values and zeros, and the second section applies to negative values. If the number to be formatted is negative, but becomes zero after rounding according to the format in the second section, then the resulting zero is formatted according to the first section.
  • Three sections: The first section applies to positive values, the second section applies to negative values, and the third section applies to zeros. The second section might be left empty (by having nothing between the semicolons), in which case the first section applies to all nonzero values. If the number to be formatted is nonzero, but becomes zero after rounding according to the format in the first or second section, then the resulting zero is formatted according to the third section.

This type of formatting ignores any preexisting formatting associated with a number when the final value is formatted. For example, negative values are always displayed without a minus sign when section separators are used. If you want the final formatted value to have a minus sign, you should explicitly include the minus sign as part of the custom format specifier. The following example illustrates how section separators can be used to produce formatted strings.

[C#]
double MyPos = 19.95, MyNeg = -19.95, MyZero = 0.0;

string MyString = MyPos.ToString("$#,##0.00;($#,##0.00);Zero");

// In the U.S. English culture, MyString has the value: $19.95.

MyString = MyNeg.ToString("$#,##0.00;($#,##0.00);Zero");

// In the U.S. English culture, MyString has the value: ($19.95).
// The minus sign is omitted by default.

MyString = MyZero.ToString("$#,##0.00;($#,##0.00);Zero");

// In the U.S. English culture, MyString has the value: Zero.

[C#]
Double myDouble = 1234567890;
String myString = myDouble.ToString( "(###) ### - ####" );
// The value of myString is "(123) 456 – 7890".

int  MyInt = 42;
MyString = MyInt.ToString( "My Number \n= #" );
// In the U.S. English culture, MyString has the value:
// "My Number
// = 42".

Posted in Development. Tags: , . No Comments »