Enginerds

06/01/2009

The C5 Generic Collection Library

Filed under: Bookmarking — Mart Leet @ 22:46

C5 is a library of generic collection classes for C# and other CLI languages and works with Microsoft .Net version 2.0 and later, and Mono version 1.2 and later.

C5 provides functionality and data structures not provided by the standard .Net System.Collections.Generic namespace, such as persistent tree data structures, heap based priority queues, hash indexed array lists and linked lists, and events on collection changes. Also, it is more comprehensive than collection class libraries on other similar platforms, such as Java. Unlike many other collection class libraries, C5 is designed with a strict policy of supporting "code to interface not implementation".

Downloads and resources

05/01/2009

Collection of 404 Posts

Filed under: Uncategorized — kris @ 19:01

image

 

 

 

 

 

 

 

 

 

 

 

http://patterntap.com/tap/collection/15

Assert.That("NUnit", Has.Some.Matches("Fluent Interface Pattern")

Filed under: .NET arendus,Bookmarking — Mart Leet @ 16:40

Equal Constraint

To implement an equality assertion:

Assert.That(1 + 1, Is.EqualTo(2));

To implement an inequality assertion:

Assert.That(1 + 1, Is.Not.EqualTo(3));

To implement an equality assertion for floating point numbers and allow for a range of tolerance:

Assert.That(2.5000 + 2.5001, Is.EqualTo(5).Within(.0001));

To implement an equality assertion for strings in a case-insensitive manner:

Assert.That( "Hello", Is.EqualTo( "hello" ).IgnoreCase );

NOTE: In this section, I introduced the Is.Not "syntax helper". It, in effect, returns the opposite of its partner Is and it’s usable in almost all the places that Is…well… is.
Also, some of you may have noticed that the "syntax helpers" in the last three examples (e.g.: Is.EqualTo(5).Within(.0001) and Is.EqualTo( "hello" ).IgnoreCase) displayed a syntax of "chained" methods/properties. This syntax is popularly known under the name of Fluent Interfaces.


SameAs Constraint

To implement a "same referenced object" assertion:

Object o1 = new Object();

Object o2 = o1;

Assert.That(o1, Is.SameAs(o2));

Condition Constraints

To implement boolean assertions:

Assert.That(true, Is.True);

Assert.That(false, Is.False);

To implement "Not A Number" assertions:

Assert.That(Double.NaN, Is.NaN);

Assert.That(1, Is.Not.Nan);

To implement assertion for empty Strings or Collections:

Assert.That("", Is.Empty);

Assert.That(new ArrayList(), Is.Empty);

To implement assertion for Collections containing only unique items:

ArrayList al = new ArrayList();

al.Add(1);

al.Add(2);

Assert.That(al, Is.Unique);

Comparison Constraints

To implement comparison assertions:

Assert.That(7, Is.GreaterThan(3));

Assert.That(7, Is.GreaterThanOrEqualTo(3));

Assert.That(7, Is.AtLeast(3));

Assert.That(7, Is.GreaterThanOrEqualTo(7));

Assert.That(7, Is.AtLeast(7));

Assert.That(3, Is.LessThan(7));

Assert.That(3, Is.LessThanOrEqualTo(7));

Assert.That(3, Is.AtMost(7));

Assert.That(3, Is.LessThanOrEqualTo(3));

Assert.That(3, Is.AtMost(3));

Note: Is.AtLeast() is a synonym for Is.GreaterThanOrEqualTo() and Is.AtMost() is a synonym for Is.LessThanOrEqualTo().


Type Constraints

To implement an "exact type" assertion:

Hashtable ht = new Hashtable();

Assert.That(ht, Is.TypeOf(typeof(Hashtable)));

Assert.That(ht, Is.Not.TypeOf(typeof(IDictionary))); //not exact type

To implement an "instance of a type" assertion:

Hashtable ht = new Hashtable();

Assert.That(ht, Is.InstanceOfType(typeof(IDictionary)));

Assert.That(ht, Is.Not.InstanceOfType(typeof(String)));

To implement an "assignable from a type" assertion:

Hashtable ht = new Hashtable();

Assert.That(ht, Is.AssignableFrom(typeof(System.Configuration.SettingsContext))); //subclass

Assert.That(ht, Is.Not.AssignableFrom(typeof(IDictionary)));

String Constraints

To implement string assertions:

string phrase = "Make your tests fail before passing!";

Assert.That( phrase, Text.Contains( "tests fail" ) );

Assert.That( phrase, Text.Contains( "make" ).IgnoreCase );

Assert.That( phrase, Text.StartsWith( "Make" ) );

Assert.That( phrase, Text.DoesNotStartWith( "Break" ) );

Assert.That( phrase, Text.EndsWith( "!" ) );

Assert.That( phrase, Text.EndsWith( "PASSING!" ).IgnoreCase );

Assert.That( phrase, Text.Matches( "Make.*tests.*pass" ) );

Assert.That( phrase, Text.DoesNotMatch( "your.*passing.*tests" ) );

Collection Constraints

To implement a collection assertion where each item must pass the specified constraint:

int[] iarray = new int[] { 1, 2, 3 };

string[] sarray = new string[] { "a", "b", "c" };

Assert.That(iarray, Is.All.Not.Null);

Assert.That(sarray, Is.All.InstanceOfType(typeof(string)));

Assert.That(iarray, Is.All.GreaterThan(0));

To implement a collection assertion where at least 1 item must pass the specified constraint:

int[] iarray = new int[] { 1, 2, 3 };

string[] sarray = new string[] { "a", "b", "c" };

Assert.That(sarray, Has.Some.Not.Null);

Assert.That(sarray, Has.Some.InstanceOfType(typeof(string)));

Assert.That(iarray, Has.Some.GreaterThan(2));

To implement a collection assertion where each item must fail the specified constraint:

int[] iarray = new int[] { 1, 2, 3 };

string[] sarray = new string[] { "a", "b", "c" };

Assert.That(sarray, Has.None.Null);

Assert.That(sarray, Has.None.InstanceOfType(typeof(double)));

Assert.That(iarray, Has.None.GreaterThan(5));

NOTE: List.Contains() has been replaced by Has.Member() in version 2.4.2.
To implement a "unique items only" collection assertion:

int[] iarray = new int[] { 1, 2, 3 };

string[] sarray = new string[] { "a", "b", "c" };

Assert.That(sarray, Is.Unique);

To implement a "must contain this item" collection assertion:

int[] iarray = new int[] { 1, 2, 3 };

string[] sarray = new string[] { "a", "b", "c" };

Assert.That(iarray, Has.Member(3));

Assert.That(sarray, Has.Member("b"));

Assert.That(sarray, Has.No.Member("x"));

NOTE: Has.Member() uses object equality to find an object in a collection. To check for an object equal to an item the collection, use Has.Some.EqualTo().
To implement an "equivalent" collection assertion:

int[] iarray = new int[] { 1, 2, 3 };

string[] sarray = new string[] { "a", "b", "c" };

Assert.That(new string[] { "c", "a", "b" }, Is.EquivalentTo(sarray));

Assert.That(new int[] { 1, 2, 2 }, Is.Not.EquivalentTo(iarray));

NOTE: 2 collections are equivalent if they contain the same items, in any order. To compare collections for equality, use Is.EqualTo()
To implement an "is a subset of" collection assertion:

int[] iarray = new int[] { 1, 2, 3 };

string[] sarray = new string[] { "a", "b", "c" };

Assert.That(new int[] { 1, 3 }, Is.SubsetOf(iarray));

BoundField DataField="ContactDetails.TelephoneNumber"

Filed under: Uncategorized — Mart Leet @ 14:55

Päris nii ei saa ja seda tean ma päris hästi. Omal ajal sai selleks tehtud igasugu DTO-sid jms (jama).

Esiteks on võimalus teha nii:

<asp:TemplateField>
    <ItemTemplate>
        <%# Eval("ContactDetails.TelephoneNumber") %>
    </ItemTemplate>
</asp:TemplateField>

Teiseks aga nii:

<jag:ObjectField BoundField="ContactDetails.TelephoneNumber" />

ning see jag on hetkel komponent:

ObjectField.cs

Rohkem infot:

[Allikas]

02/01/2009

OpenRasta (REST based web)

Filed under: Bookmarking — Mart Leet @ 16:31

Selline näeb välja uri, handleri ja lehe kokkuviimine.

public class Configurator : IConfigurationSource
    {
        public void Configure()
        {
            using (OpenRastaConfiguration.Manual)
            {
                ResourceSpace.Has.ResourcesOfType<Home>()
                        .AtUri("/home")
                        .HandledBy<HomeHandler>()
                        .AndRendededByAspx("~/Views/HomeView.aspx");
            }
        }
    }

Näide ja rohkem juttu allikast

[Allikas]

CreateTemporaryPassword

Filed under: Uncategorized — Mart Leet @ 01:32

  public string CreateTemporaryPassword(int length)
  {
      Func<Random, char> randomNumber = rnd => (char) rnd.Next(48, 58);
      Func<Random, char> randomCharacter = rnd => (char) rnd.Next(97, 123);
   
      var funcArray = new[] {randomNumber, randomCharacter};
      var chars = new char[length];
      for (int i = 0; i < length; i++)
      {
         var index = random.Next(0, funcArray.Length);
         chars[i] = funcArray[index](random);
     }  
     return new string(chars);
}

[Allikas]

Castle Windsor on ka Fluent-ina olemas

Filed under: Uncategorized — Mart Leet @ 00:08

Alles nüüd avastasin, et saab ka igasuguse Caste spetsiifilise xml-i ära kaotada. Kuna ma nagunii stringipõhiselt ehk key põhjal neid kunagi ei küsi, siis päris hea stringivaba lähenemine taas. Pluss igasugune refaktoorimine lihtsustub.

Asi ise niivõrd lihtne ongi:

var container = new WindsorContainer();
container.Register(Component.For<ICatalogService>().ImplementedBy<MyCatalogService>().Lifestyle.Singleton);
[Allikas]

01/01/2009

ASP.NET Charting Control

Filed under: Uncategorized — Mart Leet @ 23:18

Microsoft recently released a cool new ASP.NET server control – <asp:chart /> – that can be used for free with ASP.NET 3.5 to enable rich browser-based charting scenarios:

FluentNHibernate

Filed under: nHibernate — Mart Leet @ 20:38

Nimelt mõni aeg tagasi proovisin ja nüüd kasutan mappimiseks FluentNHibernatet. Alguses tundus see vaid hea mõttena ning kuna hetkel teen projektis suures osas ainult mina domeeni, mappimist jne siis refaktoorimist justkui ei tuleks ette. Siiski esimesed kasud juba leitud.

Nimelt Fluent aitab compiletime vigu leida, toetab refaktoorimist ning nHibernate puhul kaotab ära vajaduse xml (hbm) failide järele. Tegelikult küll mitte, sest fluenti idee on, et luuakse nHibernate jaoks siiski samasugused xml failid, kuid seda inmemory-na ehk mina kui arendaja neid ei näe (kui ma just nimelt ei taha näha).

Aga sisu ise:

On olemas generic ClassMap<T> ning lambda expressionite abil saab koodis entity-d ära mappida.

Näide:

public class HorseMap : ClassMap<Horse>
    {
        public HorseMap()
        {
            DefaultAccess.AsReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore);

            Id(x => x.Id).GeneratedBy.Native()
                .WithUnsavedValue(0);

            HasMany<HorseRecord>(x => x.HorseRecords)
                .WithKeyColumn("HorseId")
                .Cascade
                .AllDeleteOrphan();
            HasMany<HorseStatistics>(x => x.HorseStatistics)
                .WithKeyColumn("HorseId")
                .Cascade
                .AllDeleteOrphan();
            HasMany<HorsePerformance>(x => x.PastPerformances)
                .WithKeyColumn("HorseId")
                .Cascade
                .AllDeleteOrphan();

            References(x => x.Sex, "Sex");

            Map(x => x.Age);
            Map(x => x.AtgId);
            Map(x => x.HorseNameAndNationality);
            Map(x => x.IsRegisteredInSweden, "IsSwedenReg");
            Map(x => x.IsThoroughbred);
            Map(x => x.Name);
            Map(x => x.NationalityInBorned, "NationalityBorn");
            Map(x => x.NationalityInOwnered, "NationalityOwner");
            Map(x => x.NationalityInRaised, "NationalityRaised");
        }
    }

Nagu näha saab enamus mappinguid valmis teha stringe kasutamata (mis mulle eriti meeldib). Kuna ma ise ei loonud andmebaasi ning mappimine käib andmebaas –> domeen –> mappingud viisil, siis mõnes kohas siiski baasi columnname ei ole sama, mida ma property-na tahan kasutada.

Eelmises posituses viitasin ITimeStamped interfacele ning ka siinkohas on Fluent lähenemine igati kasulik. Nimelt on mul default property-d mapitud ära baas class-i ning nii on vähem koodikordavust.

public class TimeStampClassMap<T> : ClassMap<T> where T : ITimeStamped
{
    public TimeStampClassMap()
    {
        DefaultAccess.AsReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore);

        Id(x => x.Id).GeneratedBy.Native()
            .WithUnsavedValue(0);

        Map(x => x.DateLastModified)
            .TheColumnNameIs("LastUpdated");

    }
}

ning sellest class-ist tulenev entity:

public partial class LicenseOwnerMap : TimeStampClassMap<LicenseOwner>
{
    public LicenseOwnerMap()
    {
    WithTable("Start_LicenseOwner");
        References(x => x.Owner)
            .TheColumnNameIs("LicenseOwnerId")
            .Cascade
            .SaveUpdate();
        References(x => x.Status)
            .TheColumnNameIs("Status");
        References(x => x.Type)
            .TheColumnNameIs("Type");
    }
}

Mappinguid on lisaks veel eriti hea testida:

[Test]
[Category("Integration")]
public void VerifyMapping_IsSuccessful()
{
    new PersistenceSpecification<T>(Dao.Session)
        .VerifyTheMappings();
}

Eelnevas on T Fluentiga mappitud entity. Siinkohal tegelikult tehakse seda, et luuakse uus T ning setitakse kõik default valued property-teks ning salvestatakse baasi. Teises sessioonis tehakse päring ning võrreldakse tulemusi algupärase objektiga. Lõpuks lastakse loodud objekt baasist maha.

Tegelikult saab testimist veidi põhjalikumaks teha ning anda ette väärtused, mida testida. See just kaslik siis References ning HasMany puhul. Näide siiski lihtne string-DateTime

[Test]
[Category("Integration")]
public void VerifyMapping_IsSuccessful()
{
    new PersistenceSpecification<Log>(Dao.Session)
    .CheckProperty(x=>x.Date, DateTime.Now)
    .CheckProperty(x=>x.Logger, NewString("Logger"))
        .VerifyTheMappings();
}

Millest seni puudust tundnud? Default Cascade entity tasandil (võibolla ei ole veel leidnud) ning private fieldide mappimine. Kuid viimase kohta käib vastavas arendajate google group-sis elav arutelu ehk ainult ajaküsimus, millal olemas.

nHib 2.0 and EventListener

Filed under: nHibernate — Mart Leet @ 20:17

Nagu alljärgnevalt näha kasutan projektis Castle NHibernateIntegration facility-t ning ka FluentNHibernatet. Castle komponent laseb mugavalt konfida seaded, haldab õige Configuration objekti kokkupanemist (tegelikult paneb selle ja SessionManageri jm IoC-ga alati kättesaadavasse kohta ka – detailidesse laskumine pole hetkel antud postituse point). Fluenti kohta võib aga vabalt omaette seeria postitusi teha.

Käesolevalt aga on teatud hulk entity-sid, mis implementeerivad interfase ITimeStamped. Tegelikult antud juhul on selle juures veel puudusi, kuid selle lahendamiseni veel jõuab.

public partial class TimeStampedSaveEventListener : DefaultSaveOrUpdateEventListener
{
    protected override object PerformSaveOrUpdate(SaveOrUpdateEvent evt)
    {
        if(evt.Entity is ITimeStamped)
        {
            ITimeStamped entity = evt.Entity as ITimeStamped;
            if(entity != null)
            {
                entity.DateLastModified = DateTime.Now;
            }
        }

        return base.PerformSaveOrUpdate(evt);
    }
}

Ja et asja ka nhibernate kasutusse võtaks on konfis see kirjas:

<facility type="Castle.Facilities.NHibernateIntegration.NHibernateFacility, Castle.Facilities.NHibernateIntegration"
          id="nhibernate"
          configurationBuilder="Seda.Pole.Vaja.Teada.FluentConfigurationBuilder, Seda.Pole.Vaja.Teada"
          isWeb="false"
          useReflectionOptimizer="false">
    <factory id="nhibernate.factory">
        <settings>
            <item key="connection.provider">NHibernate.Connection.DriverConnectionProvider</item>
            <item key="connection.driver_class">#{nhibernateDriver}</item>
            <item key="dialect">#{nhibernateDialect}</item>
            <item key="connection.connection_string">#{connectionString}</item>
            <item key="cache.provider_class">NHibernate.Caches.SysCache.SysCacheProvider, NHibernate.Caches.SysCache</item>
            <item key="cache.use_query_cache">true</item>
            <item key="show_sql">true</item>
            <item key="relativeExpiration">30</item>

        </settings>
        <assemblies>
            <assembly>Seda.Pole.Vaja.Teada</assembly>
        </assemblies>
        <listeners>
            <listener type="Seda.Pole.Vaja.Teada.TimeStampedSaveEventListener, Seda.Pole.Vaja.Teada"
                      event="Save" />
            <listener type="Seda.Pole.Vaja.Teada.TimeStampedSaveEventListener, Seda.Pole.Vaja.Teada"
                      event="SaveUpdate" />
        </listeners>
    </factory>
</facility>

I Am NHibernating…

« Previous PageNext Page »

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.