Dec 8, 2013

Web design - responsive web-design yes-no, cross-browser compatibility

I'm not web designer, I'm web developer. Period.
But ... some people from management echelon of many companies either don't care or choose to forget that.
Sadly small companies can't afford web-developer and professional web-designer.
Bottom line is that they ask from web-developer to know his way around web-design.
"Hey ! It's not that complicated, little bit of layout, little bit of  color, fonts etc.
Are you telling me you don't know this !? "

How many times I have heard this...

Ok, so our bosses tend to take for granted that we can deal with web-design.

Hence as beginner in web-design and strictly from perspective of building business web sites here is some high level tips & tricks and observations.

Responsive web design

Is this just buzz word or some thing to consider ?

http://msdn.microsoft.com/en-us/hh535902.aspx

Here is the closing word from above article that, for me, sums up:

Jumping on the responsive Web design wagon isn’t something to take lightly. Take into account what you need to achieve, and consider whether catering to a specific version of a desktop or mobile device makes the most sense.
Responsive Web design is in its early stages. Web designers will continue to offer different opinions and recommend directions related to whether to build for mobile first, how to fit these decisions into the design process, whether to slice up the comps into all the different screen sizes, and so forth. And as more and more screen sizes and form factors arrive, the conversation will continue. 

From VS 2013 Microsoft decide to give official support to one of html frameworks that supports this concept - Tweeter Bootstrap.
Does this mean that Bootstrap is must-have ? Should I invest in Bootstrap? Lady from above does not think so.
Let's go step back. Can we have today modern web site that does not care about device sizes ? No.
So what's then in the middle? Is there middle ?

Bit old but efficient and I think cheaper approach is to enforce classic and mature HTML frameworks like BoilerTemplate etc.
Yes you can use and Bootstrap only as HTML framework. Still Bootstrap is build on LESS. Don't know what's LESS? Well that's my point. I don't want to learn Less so I can efficiently use Bootstrap.

Here is some quick result from Google:

http://komelin.com/en/5tips/5-most-popular-html5-responsive-frameworks
http://www.sitepoint.com/boilerplate-bootstrap/

This is interesting quote from above column:
Boilerplate is more server-side oriented – a good starting template if you work with server-side technologies such as PHP.
Bootstrap is a client-side solution – a complete toolkit for building client-side web sites.

A bit more about responsive itself:

http://mobile.smashingmagazine.com/2011/07/22/responsive-web-design-techniques-tools-and-design-strategies/

A still bit more about predecessor of Responsive Web design:
http://en.wikipedia.org/wiki/Progressive_enhancement

Here is a quick starter with Bootstrap in ASP.NET:

http://geekswithblogs.net/JeremyMorgan/archive/2012/09/18/how-to-use-twitter-bootstrap-on-an-asp.net-website.aspx

Here is a bit more pro & cons for Responsive web design approach:
http://www.asp.net/whitepapers/add-mobile-pages-to-your-aspnet-web-forms-mvc-application

Cross-browser compatibility

This is endless subject. As rookie in web-design make sure to not make big promises for cross-browser compatibility for your web-design solutions. This is common pitfall of many web-design starters.
"Oh yeah, I did it... Sure it works and looks same on all browsers types and versions... Wait a minute, isn't it suppose to ?"

Major compatibility culprit is IE. Maybe this can help:

Internet Explorer 11 guide for developers -> http://msdn.microsoft.com/library/ie/bg182636(v=vs.85).aspx
I think you can also search for older version development guides.


  • Advantage: Optimizes rendering for the specific device in use, even for unknown future devices according to whatever screen and input characteristics they have
  • Advantage: Easily lets you share server-side logic across all device types – minimal duplication of code or effort
  • Disadvantage: Mobile devices are so different from desktop devices that you may really want your mobile pages to be completely different from your desktop pages, showing different information. Such variations can be inefficient or impossible to achieve robustly through CSS alone, especially considering how inconsistently older devices interpret CSS rules. This is particularly true of CSS 3 attributes.
  • Disadvantage: Provides no support for varying server-side logic and workflows for different devices. You can’t, for example, implement a simplified shopping cart checkout workflow for mobile users by means of CSS alone.
  • Disadvantage: Inefficient bandwidth use. You server may have to transmit the markup and styles that apply to all possible devices, even though the target device will only use a subset of that information.



Media queries

Corner stone of modern web-design...
http://www.w3.org/TR/2010/CR-css3-mediaqueries-20100727/#media0

Dec 2, 2013

What not to do in ASP.NET, and what to do instead

Remember to read:

http://www.asp.net/aspnet/overview/web-development-best-practices/what-not-to-do-in-aspnet,-and-what-to-do-instead#browsercap

ASP.NET in 2012, 2013 - what's new ? - Quick guide for very lazy developers

I'm lazy developer.
Instead of regularly following news in my ASP.NET field I watch SF Star Gate. :)
Then you get stuck on your daily basis on boring SQL driven apps or even .NET desktop app's and you'r through.
So every year or two I wake one day and understand that I don't know nothing of most cool and sexy stuff people use for building web in ASP.NET.

Today is end of 2013. Now I'm an common ASP.NET developer not some MVP geek so my goal is to found out what's out there ready, tested and mature that helps me, as very lazy person :), to build more slicker, cooler and faster business web-sites.

Scott Hanselman  made very good intro for one off his post:

http://www.hanselman.com/blog/ReleasedASPNETAndWebTools20122InContext.aspx

Last year the ASP.NET team started talking about something we're calling "One ASP.NET." I showed some mockups of our ideas last summer at the aspConf Keynote that you can watch online.
We also announced then that we would add new features to ASP.NET as out of band releases (OOB) without breaking existing functionality. This means that developers don't have to wait for the next version of Visual Studio for great web development features today. We're aiming to add to ASP.NET and Web Tools every 6 months.
For those that don't want to wait, Mads and the team also started a feature playground called Web Essentials. This is an extension to Visual Studio that updates all the time with ideas and brainstorms about how VS can be an even better editor for the web. As features "graduate" from Web Essentials, they move into ASP.NET and Web Tools proper. A bunch of features graduate with today's release.

So boys and girls:

One ASP.NET


First buzz word - repeat and remember - new flagship of ASP.NET !


Web Tolls


http://www.asp.net/aspnet/overview/visual-studio-web-development-features/what-is-web-tools

To spare you 10 mins for watching above video. Yes, you need web tools. They won't mess with your choices of technology or way you work. They are optional helpers whom you have to choose explicitly to make your life easer.

Web Essentials

So Web Essentials is so to say community development package  for Web Tools products.

If you ever write CSS, HTML, JavaScript, TypeScript, CoffeeScript or LESS, then you will find many useful features that make your life as a developer easier. 
Unobtrusive helpers for CSS, Html, Javascript ...
They are not in the way but can help...

Modernizr


http://modernizr.com/
Taking advantage of cool new web technologies is great fun, until you have to support browsers that lag behind. Modernizr makes it easy for you to write conditional JavaScript and CSS to handle each situation, whether a browser supports a feature or not. It’s perfect for doing progressive enhancement easily.
For a while I stumble of this little guy in VS web project templates and I have no clue what a heck is purpose of it. So here it is.
If you are experienced web designer (which I'm not :) ) you need to take special (and expensive ! ) care about browser compatibility.





Nov 7, 2013

Microsoft.VisualStudio.TestTools.UnitTesting hints

My experience with Microsoft.VisualStudio.TestTools.UnitTesting.

Attributes [TestInitialize] & [TestCleanup] are executed after each test marked with [TestMethod].
So if you have test class like this:

[TestClass]
public class Test
{

[TestInitialize]
public void Initialize

[TestMethod]
public void GetIsAdAvailable_InvalidCampaignId_ShouldFail()

[TestMethod]
public void GetIsAdAvailable_ValidCampaignId_InvalidCampRange_ShouldFail()

[TestCleanup]
public void Cleanup()

}

If you run all tests here is execution flow:

Initialize

GetIsAdAvailable_InvalidCampaignId_ShouldFail

Cleanup

Initialize

GetIsAdAvailable_ValidCampaignId_InvalidCampRange_ShouldFail

Cleanup

Nov 4, 2013

NPoco tricks

NPoco is continuation of PetaPoco Micro ORM .NET solution.

As open source project is not very well documented so I'll write down few tricks picked up along the way.


1. For SQL code cosmetics :

Sql sql = Sql.Builder
sql.Append(";declare @@countResViews int ");
sql.Append("set @@countResViews = (select count(*) from MYTABLE where Expiry<=GETDATE() and                      UserId<>@0 and CampaignId =@1) ", userId, campaignId);

sql.Append("select @@countResViews ");

2.  Using SQL params inside T-SQL that should not be mapped to provided arguments:

  • Place ;  on very beginning of T-SQL statement.
  • Use double @ for your vars.
Example:

                Sql sql = Sql.Builder.Append(string.Concat(
                                             ";declare @@countResViews int ",
                                             "set @@countResViews = (select count(*) from MYTABLEwhere Expiry<=GETDATE() and UserId<>@0 and CampaignId =@1) ",
                                             "select @@countResViews ")
                                             , userId, campaignId);
                                         
                int count = db.FirstOrDefault<int>(sql);

3. Semicolon is needed when not starting SQL with SELECT.

4. Executing stored proc and getting result dataset is straightforward:

sql.Append(";exec dbo._TempPostboxReqAdConsumation");
List<Product> list = db.Fetch<Product>(sql); 
5. Fetch lambdas always return List, NEVER null. Hence check for Count==0 not NULL:

 List<Campaign> dbCampaigns = db.FetchWhere<Campaign>(c => c.Name == campaign.Name);
                Campaign dbCampaign = dbCampaigns.Count==0 ? new Campaign() : dbCampaigns.FirstOrDefault();

6. Composite Primary key syntax
 If you have Primary key consisting of two columns use this syntax:

[TableName("UserCampaigns")]
    [PrimaryKey("UserId,CampaignId", AutoIncrement = false)]
    public partial class UserCampaign
    {
        public int UserId { get; set; }
        public int CampaignId { get; set; }
        public int StatusId { get; set; }
    }
Obtaining record by PK when composite PK:
      UserCampaign userCampaignDB = db.SingleOrDefaultById<UserCampaign>(
                                                                       new { UserId = 4,CampaignId = 3 }
                                                                );
7. Executing stored proc and returning output var & result rowset:

    var totalRecords = new SqlParameter("4", System.Data.SqlDbType.Int);
   totalRecords.Direction = System.Data.ParameterDirection.Output;
sql.Append(";EXEC GetActiveCampaigns @0, @1, @2, @3, @4 OUTPUT", user.Id,     UserCampaignStatus.New, page, itemsPerPage, totalRecords);

Not related strictly to NPoco but I keep forgetting it :
connection string ...   providerName="System.Data.SQLClient"

8. One to many join:

var sql = Sql.Builder.Append("select a.*,r.* from ApiIdentifier a")
.Append("left join ApiIdentifierRole ar on ar.ApiIdentifierId = a.Id")
.Append("left join ApiRole r on r.Id = ar.RoleId"); 
var adIdents = db.FetchOneToMany<ApiIdentifier, ApiRole>(apid => apid.Id, sql);




Oct 22, 2013

C# basics revised - "Essentials C# 4.0" - Mark Michaelis

Once in a while you need to refresh you memory. People forget.
I'm going through terrific "Essentials C# 4.0" - Mark Michaelis.


DATA TYPE

Float vs Double vs Decimal ?

Float has only 7 digit precision...
...
            float floatSource = 1234.5678F;
            double doubleSource = 1234.5678D;
            decimal decimalSource = 1234.5678M;
            decimal float2decimal = (decimal)floatSource;
            decimal double2decimal = (decimal)doubleSource;
            Console.WriteLine(float2decimal==decimalSource);
            Console.WriteLine(double2decimal == decimalSource);
            Console.ReadLine();
...
This results in:

false
true
Double has 15 digit precision but in business apps you can sometimes reach that limit too.


  • Further good reading on subject :

Unexpected Inequality with Floating-Point Types 
multiplying, dividing and casting between float and double results in Not equal results.
page 90


  • Dividing with 0 and overflowing max is allowed with double / float and results with special NaN and Infinity


Rule of a thumb: For business apps use only DECIMAL type for storing money data.

Overflowing an integer value

Unless used with special checked block numerical type will overflow:

// int.MaxValue equals 2147483647
intn = int.MaxValue;
n = n + 1 ;
System.Console.WriteLine(n)

;results in : -2147483.

Prein(de)cremental and postin(de)cremental operands are NOT thread safe


int result = myAge++;  // Not thread safe

//Correct thread safe way
long b=0;
long i = System.Threading.Interlocked.Increment(ref b);

FLOW CONTROL

I didn't know for this :
 case "Candies":
                   Console.WriteLine("I love all candies");
                    goto default;
case "Icecream":
                    Console.WriteLine("Jummy ... icecream.");
                    goto case "Candies";
default : ...

To comment or not ?

158 page
As  part  of  the  coding  process,  it  is  a  best  practice  to  continually
review  your  code  and  look  for  opportunities  to  refactor.  This  involves
looking for blocks of code that are difficult to understand at a glance and
moving them into a method with a name that clearly defines the code’s
behavior.  This  practice  is  often  preferred  over  commenting  a  block  of
code, because the method name serves to describe what the implementation does.

Don't use exceptions as validation rules!


198 page

Exceptions are designed specifically for tracking exceptional, unexpected, and potentially fatal situations.
Using them for an unattended purpose such as expected situations will
cause your code to be hard to read, understand, and maintain.
Additionally, (as with most languages) C# incurs a slight performance
hit when throwing an exception—taking microseconds compared to the
nanoseconds
most operations take. This delay is generally not noticeable
in human time—except when the exception goes unhandled. For example,
when executing Listing 4.19 and entering an invalid age the exception is
unhandled and there is a noticeable delay while the runtime searches the
environment to see whether there is a debugger to load. Fortunately, slow
performance when a program is shutting down isn’t generally a factor to
be concerned with.

Naming convention - field vs property -> field should have _ to make distinction


Because the property name is FirstName, the field name changed from
earlier  listings  to _FirstName.  Other  common  naming  conventions  for
the private field that backs a property are _firstNameand m_FirstName

Regardless of which naming pattern you use for private fields, the coding standard for public fields and properties is Pascal case. Therefore, public  properties  should  use  the  LastName and FirstName type  patterns.
Similarly,  if  no  encapsulating  property  is  created  around  a  public  field,
Pascal case should be used for the field.


// FirstName property
public string FirstName
{
get
{
return _FirstName;
}
set
{
_FirstName = value;
}
}
private string _FirstName;

Single property can have different access modifiers for setter and getter

// Id property declaration
public stringId
{
            get
            {
                 return_Id;
            }
            // Providing an access modifier is in C# 2.0
            // and higher only
            private set
           {
              _Id = value;
           }
}
private string_Id;

Use Automated property in combination with access modifiers for short and consistent use of properties

Unless there is some specific logic needed use consistently automated properties. 
public static int First { get; set; }
If it is required to allow only private setting of property use this:

public static int First { get; private set; }


Don't mix field initialization in declaration and in constructor


Developers should take care when using both assignment at declaration  time  and  assignment  within  constructors.  Assignments  within  the
constructor  will  occur  after  any  assignments  are  made  when  a  field  is
declared (such as string  Salary  =  "Not  enough"in Listing 5.5). Therefore, assignment within a constructor will override any value assigned at
declaration time. This subtlety can lead to a misinterpretation of the code
by  a  casual  reader  whereby  he  assumes  the  value  after  instantiation  is
assigned at declaration time. Therefore, it is worth considering a coding
style  that  does  not  mix  both  declaration  assignment  and  constructor
assignment within the same class.

 Constructor chaining

public Employee(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
public Employee(int id, string firstName, string lastName ) : this(firstName, lastName)
{
Id = id;
}

Static Constructors

In bellow code first will get executed declaration 42 then random generator.

classEmployee
{
static Employee()
{
Random randomGenerator = new Random();
NextId = randomGenerator.Next(101, 999);
}
// ...
public static int NextId = 42;
// ...
 Favor Static Initialization during Declaration instead of static constructors because compiler injects special extra check to ensure that constructor initialization always wins over field initialization which can be expensive.

Favor static properties instead of static fields

It is almost always better to use a static property rather than a public static
field  because  public  static  fields  are  callable  from  anywhere  whereas  a
static property offers at least some level of encapsulation.

Use extension methods wisely

Note  that  specializing  a  type  via  inheritance  is preferable to using an extension method. Extension methods do  not  provide  a  clean  versioning  mechanism  since  the  addition  of  a 
matching  signature  to  the  extended  type  will  take  precedence  over  the 
extension method without warning of the change. The subtlety of this is 
more pronounced for extended classes whose source code you don’t control.  Another  minor  point  is  that,  although  development  IDEs  support IntelliSense for extension methods, it is not obvious that a method is an extension method by simply reading through the calling code. In general, 
use extension methods sparingly.

public class Dummy
    {
        public int Id { get; set; }
        public int BuildUrl()
        {
            return this.Id * 2;
        }
    }
    static class Extensions
    {
        public static int BuildUrl(this Dummy value)
        {
            return value.Id;
        }
    }
In above example there will be no warning and compiler will execute method instance (this.Id * 2).
Extension method will be ignored!


One of the features included with extension methods is the fact that they 
too are inherited. If we extend a base class such as PdaItem, all the extension  methods  will  also  be  available  in  the  derived  classes.  However,  as 
with all extension methods, priority is given to instance methods. If a compatible signature appears anywhere within the inheritance chain, this will take precedence over an extension method.

Partial methods




// File: Person.Designer.cs public partial class Person
{
     partial void OnLastNameChanging(stringvalue);
     partial void OnFirstNameChanging(stringvalue);
...
// File: Person.cs partial class Person
{
    partial void OnLastNameChanging(stringvalue)
   {
       if(value == null)
       {
        ...
It is important to note that a partial method must return void.Similarly, outparameters are not allowed on partial methods.

Custom explicit operator

public class Dvd:Storage
    {
        public string Name { get; set; }
        public static explicit operator CdRom(Dvd dvd)
        {
            CdRom result = new CdRom();
            ...
            return result;
        }
    }
...
 CdRom cdromFromDvd = (CdRom)dvd;

Class inheritance with "as" and "is"

By using the as operator, you are able to avoid additional try/catch
handling code if the conversion is invalid, because the as operator provides
a way to attempt a cast without throwing an exception if the cast
fails.
One advantage of the is operator over the as operator is that the latter
cannot successfully determine the underlying type. The latter potentially
casts up or down an inheritance chain, as well as across to types supporting
the cast operator. Therefore, unlike the as operator, the is operator can
determine the underlying type.

The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception.
Base baseType = derivedType as Base;
if (derivedType is Base) ...
Note that the as operator only performs reference conversions and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

Mimicing multiple inheritance with single inheritance & private members

public classPdaItem
{}
public classPerson
{}
public classContact : PdaItem 
{
private Person InternalPerson {get; set; }
public string FirstName
{
get{ return InternalPerson.FirstName; }
set{ InternalPerson.FirstName = value; }
}

Method marked override always has precedence over base virtual method

public class Storage
    {      
        public virtual string SerialNum()
        {
            return "Storage";
        }
public class CdRom : Storage
    {      
        public override string SerialNum()
        {
            return "CdRom";
        }
            CdRom cdrom = new CdRom();
            Storage storage = cdrom;          
            Console.WriteLine(storage.SerialNum());            
output -> CdRom

In order to instruct compiler to call Storage.SerialNum() change this:

        public override string SerialNum()  -->         public new string SerialNum()

The rule is that whenever the runtime encounters a virtual method, it calls the most 
derived  and  overriding  implementation  of  the  virtual  member. In  creating  a  class,  programmers  should  be  careful  when  choosing  to allow overriding a method, since they cannot control the derived implementation. 

Accessing members of parent type using base keyword

public class Storage
    {
        public string BaseVersion { get; set; }
...
public class CdRom : Storage
    {
        public void Eject()
        {
            string StorageBaseVersion = base.BaseVersion;
        }

Abstract classes 


public abstract class Storage ...
{
      public abstract string GetUID();
...
public class Dvd : Storage ...
{
      public override string GetUID();


Abstract vs interfaces


The key point, therefore, is that base classes let you share implementation along with the member
signatures, whereas interfaces allow you to share the member signatures without the implementation.

Explicit vs Implicit interfaces


Example of two interfaces. Idea is to version changes in CalculateSerialNum() functionality.
Bellow example demonstrates how can we introduce changes in functionality for method with signature CalculateSerialNum() without changing method signature.
Using explicit interface members we are allowed to freely add unlimited versions of same method signature CalculateSerialNum() just by introducing new interfaces.

interface IStorageV2
    {
        string CalculateSerialNum();
    }

interface IStorage
    {
        void Save();
        void Load();

        string CalculateSerialNum();
    }

public class Dvd : IStorage, IStorageV2
    {
        public void Save()
        {
            throw new NotImplementedException();
        }

        public void Load()
        {
            throw new NotImplementedException();
        }
        // Implicit interface implementation
        public string CalculateSerialNum()
        {
            return "Version 1";
        }      
        // Explicit interface implementation
        string IStorageV2.CalculateSerialNum()
        {
            return "Version 2";
        }
    }

             Dvd dvd = new Dvd();          
            //original initial code
            Console.WriteLine( dvd.CalculateSerialNum());
            //new functionality without touching method signature
            Console.WriteLine(((IStorageV2)dvd).CalculateSerialNum());

Explicit interface implementation is a technique for enabling the separation of mechanism concerns from model concerns.
In general, it is preferable to limit the public surface area of a class to be “all model” with as little extraneous mechanism as possible.

Since changing an implementation from implicit to explicit results in a
version-breaking change, it is better to err on the side of defining interfaces
explicitly, allowing them to be changed to implicit later on. Furthermore,
since the decision between implicit and explicit does not have to be consistent
across all interface members, defining some methods as explicit and
others as implicit is fully supported.

Interfaces can inherit single or multiple interfaces

Although inheritance is the correct term, conceptually it is more accurate to realize that an interface represents a contract; and one contract is allowed to specify that the provisions of another contract must also be followed.

Interfaces can be extended with extension method

public static class Extensions
    {
        //Extending interface with extension method
        public static bool IsBig(this IStorage value)

Observe that "value" is not standard param. It is missing when using method. Purpose is to optionally use value of provided instance in method logic.
         Dvd dvd = new Dvd().IsBig();

Extension method can extend collection of target class or interface

Extending collection of class:
public static class Extensions
    {
        public static bool MyExists(this IEnumerable<Dvd> dvds, Dvd dvd)
        {
            return dvds.Any<Dvd>(d => d.Equals(dvd));
...
            Dvd dvd = new Dvd();
            List<Dvd> dvds = new List<Dvd>();
            bool isOk = dvds.MyExists(dvd);
Extending collection of interface:

public static class Extensions
    {
        public static bool MyExists(this IEnumerable<IStorage> storages, IStorage storage)
        {
            foreach (var item in storages)
            {
                if (item.Equals(storage)) return true;
            }
            return false;
        }
            ...
            Dvd dvd = new Dvd();
            List<Dvd> dvds = new List<Dvd>();
            dvds.MyExists(dvd);
            List<CdRom> cdroms = new List<CdRom>();
            CdRom cdRom = new CdRom();
            cdroms.MyExists(cdRom);

Versioning with interfaces

Changing interfaces during the development phase is obviously acceptable, although perhaps laborious if implemented extensively. However, once an interface is released, it should not be changed. Instead, a
second interface should be created, possibly deriving from the original interface.

Abstract classes vs interfaces

Interfaces


Cannot be instantiated.

Although no default implementation
can appear, classes implementing
interfaces can continue to derive from
one another.

All members are automatically
virtual and cannot include any
implementation.

Cannot store any data. Fields can be
specified only on the deriving
classes. The workaround for this is
to define properties, but without
implementation.

Extending interfaces with additional
members breaks the version
compatibility.

Implementation of all members of the
interface occurs in the base class. It is
not possible to implement only some
members within the implementing
class.

Abstract classes

Cannot be instantiated independently
from their derived classes.
Abstract class constructors are called
only by their derived classes.

Define abstract member signatures
that base classes must implement.

Are more extensible than interfaces,
without breaking any version compatibility.
With abstract classes, it is
possible to add additional nonabstract
members that all derived
classes can inherit.

Can include data stored in fields.

Allow for (virtual) members that
have implementation and, therefore,
provide a default implementation of
a member to the deriving class.

Deriving from an abstract class uses
up a subclass’s one and only base
class option.


Value vs Reference types

The amount of memory that is required for the value type is fixed at
compile time and will not change at runtime. This fixed size allows value
types to be stored in the area of memory known as the stack.

The memory area of the data a reference type points to is the heap.

Besides string and object, all the C# primitive types are value types.

Value types


All value types are sealed. In addition, all value types derive from System.ValueType. This means that the inheritance chain for structs is always from object to ValueType to the struct.
As with classes, you can override the virtual members of System.Object. The rules for overriding are virtually the same as with reference types. However, one difference is that with value types, the default implementation for GetHashCode() is to forward the call to the first non-null field within the struct.
Also, Equals() makes significant use of reflection. This leads to the conclusion that if a value type is frequently used inside collections, especially dictionary-type collections that use hash codes, the value type should include overrides for both Equals() and GetHashCode().

Boxing

int dummy = 1;
object dummyBoxed =  (object)dummy;
Process:
1.First, memory is allocated on the heap that will contain the value
type’s data and a little overhead (a SyncBlockIndex and method
table pointer).
2. Next, a memory copy occurs from the value type’s data on the stack,
into the allocated location on the heap.
3. Finally, the object or interface reference is updated to point at the
location on the heap.

Don't use boxing and unboxing value types without variables

Don't change value type value during boxing/unboxing in single statement. Use temp variables to first store boxed or unboxed value on stack or heap. Then apply change to value.
Bellow is example of  statements that failed expected behavior since change of value type is done "on fly" without first assigning it to appropriate variables.
struct Angle : IAngle
{
// ...
// NOTE: This makes Angle mutable, against the general
// guideline
public void MoveTo(int hours, int minutes, int seconds)
{
_Hours = hours;
_Minutes = minutes;
_Seconds = seconds;
}
}
interface IAngle
{
void MoveTo(int hours, int minutes, int seconds);
}
// ...
Angle angle = new Angle(25, 58, 23);
object objectAngle = angle; // Box
Console.Write( ((Angle)objectAngle).Hours);
// Unbox and discard
((Angle)objectAngle).MoveTo(26, 58, 23);
Console.Write( ((Angle)objectAngle).Hours);
// Box, modify, and discard
((IAngle)angle).MoveTo(26, 58, 23);
Console.Write(", " + ((Angle)angle).Hours);
// Modify heap directly
((IAngle)objectAngle).MoveTo(26, 58, 23);
Console.WriteLine(", " + ((Angle)objectAngle).Hours);
// ...
Output: 25, 25, 25, 26

Sep 19, 2013

Quickly generating POCO classes from DB table

You add new table to database.
You want to quickly create appropriate POCO class uses solely for ORM (NPOCO) or any of your own.
How?

http://stackoverflow.com/questions/10136520/how-to-automatically-create-model-from-database-using-petapoco-library

Create console app.
Add app.config
Add connection string

Install NuGet package "Peta Poco" (Topten Software, ver 5.0.1 but any will do).

I'm not sure do you need to rebuild.

Peta poco should generate Models / Generated / Database.tt
Right click Database.tt and "Run custom toll":
Voila !
Under Database.tt you will find Database.cs. There you'll find all your Poco classes.

Watch it  !

Carefully check what is generated. This template from Peta Poco is not perfected but it should do job for most common scenarios.

Sep 17, 2013

Visual Studio - tracking multiple web projects in single instance

I have 2 webapi's  in one solution.
They communicate with eachother.
Question is how to debug both of them in same time.
Select solution, not project!
Go to properties of solution and select Startup project.
Choose multiple projects as startup.
Now VS will start multiple projects in standalone W3WP processes and all debug breakpoints will be loaded for all projects.

Jul 23, 2013

Javascript OO concepts

Good reading for getting deeper picture on what is JSON and why are function's first class citizens in Javascript.
Must read for any use of JQuery  past the basics.

MANNING - Bear Bibeault, Yehuda Katz "JQuery in Action" - appendix: JavaScript that you need to know but might not!

Jul 18, 2013

Repository pattern

During my experience as .NET developer I've embraced "Repository" pattern from senior developers.
This is rarely used and raises question mark on people faces.
Hence here is not to forget guy who speaks more theoretically on matter.

http://www.codeproject.com/Articles/586364/UsingplusASP-NetplusWebAPIpluswithplusWebplusForms

Jul 17, 2013

IE7 and IE8 Control Focus issue on Page Load

This is here so I don't forget it ...

http://carstent.com/2009/12/31/ie-7-and-8-control-focus-issue-on-page-load/

Dynamic Data Localization

If you use Dynamic Data sooner or later you'll need localization.
Just to note I'm using Entity Framework.
First part shows how to localize model table names.

So here is my inspiration:

http://carstent.com/2009/12/23/aspnet-dynamic-data-4-ui-table-localization/


I've simple translated it to C#. Tested, it works, like charm.

Oh yes, I'm using Log4Net.

Table names

 /// <summary>
    /// Supports localization
    /// </summary>
    public class BackOfficeMetaTable : MetaTable
    {
        private readonly ILog Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public BackOfficeMetaTable(MetaModel metaModel, TableProvider tableProvider) : base(metaModel,tableProvider)
        {
        }
        public BackOfficeMetaTable(MetaModel metaModel, TableProvider tableProvider, string globalResourceClassNameParam):base(metaModel,tableProvider)
        {      
            globalResourceClassName = globalResourceClassNameParam;
        }
        private readonly string globalResourceClassName;
        protected override void Initialize()
        {
            base.Initialize();
        }
        public override string DisplayName
        {
            get
            {
                Log.Info("Try obtaining display name.");
                var baseDisplayName = base.DisplayName;
                if (string.IsNullOrWhiteSpace(globalResourceClassName)) return baseDisplayName;
                string resourceKey = string.Concat("DDtable_", baseDisplayName);
                try
                {                  
                    return HttpContext.GetGlobalResourceObject(globalResourceClassName, resourceKey).ToString();
                }
                catch (System.Exception e)
                {
                    Log.Error(string.Format("Can't find resource key->{0}", resourceKey),e );
                }
                return baseDisplayName;
            }
        }
    }
 /// <summary>
    /// Support for DD localization
    /// </summary>
    public class BackOfficeMetaModel : MetaModel
    {
        public BackOfficeMetaModel() : base()
        {          
        }
        public BackOfficeMetaModel(string globalResourceClassNameParam)
        {
            globalResourcesClassName = globalResourceClassNameParam;
        }
        private readonly string globalResourcesClassName;
        protected override MetaTable CreateTable(System.Web.DynamicData.ModelProviders.TableProvider provider)
        {
            if (string.IsNullOrWhiteSpace(globalResourcesClassName)) return base.CreateTable(provider);
                else return new BackOfficeMetaTable(this, provider, globalResourcesClassName);
        }
    }

Fields


Second part shows how to localize Fields.
I've tried using System.ComponentModel.DataAnnotations.Display attribute.
This required making global resources files public :

http://holyhoehle.wordpress.com/2010/02/20/making-global-resources-public/

It looked all fine on local IIS but on production Release version I keep getting error that res.key can't be found. Don't use this unless you can figure out how to make it work.
Here it is code that uses Display and may give you trouble:

 [ScaffoldTable(true)]
    public class Customer_Metadata
    {
        [Display(ResourceType = typeof(GlobalLocalization), Name = "MenuCustomers", ShortName = "MenuCustomers")]
        public object Name { get; set; }
    }

  [MetadataType(typeof(Customer_Metadata))]
    public partial class Customer
    {      
    } 
GlobalLocalization is Global Resource class name.

I was lucky since my coworker wrote attribute for localization:

Here it is:

public class ResourceDisplayNameAttribute : DisplayNameAttribute
    {
        #region Static Fields
        /// <summary>
        /// The resourceManagers Field
        /// </summary>
        private static readonly SortedList<string, ResourceManager> ResourceManagers = new SortedList<string, ResourceManager>();
        /// <summary>
        /// The syncLock Field
        /// </summary>
        private static readonly object SyncLock = new object();
        #endregion
        #region Fields
        /// <summary>
        ///     replaced field
        /// </summary>
        private bool replaced;
        /// <summary>
        /// The resourceType Field
        /// </summary>
        private readonly string resourceType = "Resources.Shared";
        #endregion
        #region Constructors and Destructors
        /// <summary>
        ///     Initializes a new instance of the <see cref="ResourceDisplayNameAttribute" /> class.
        /// </summary>
        /// <param name="resourceKey">The resource key used for display name.</param>
        public ResourceDisplayNameAttribute(string resourceKey)
            : base(resourceKey)
        {
        }
        public ResourceDisplayNameAttribute(string resourceKey, string resourceType)
            : base(resourceKey)
        {
            this.resourceType = resourceType;
        }
        #endregion
        #region Public Properties
        /// <summary>
        ///     Gets the display name for a property, event, or public void method that takes no arguments stored in this
        ///     attribute.
        /// </summary>
        /// <value></value>
        /// <returns>The display name.</returns>
        public override string DisplayName
        {
            get
            {
                if (!this.replaced)
                {
                    this.replaced = true;
                    this.DisplayNameValue = this.GetString();
                }
                return base.DisplayName;
            }
        }
        /// <summary>
        /// Gets the string.
        /// </summary>
        /// <returns></returns>
        private string GetString()
        {
            ResourceManager resourceManager = GetResourceManager(this.resourceType);
            return resourceManager.GetString(base.DisplayName);
        }
        /// <summary>
        /// Gets the resource manager.
        /// </summary>
        /// <param name="resourceType">Type of the resource.</param>
        /// <returns></returns>
        private static ResourceManager GetResourceManager(string resourceType)
        {
            lock (SyncLock)
            {
                if (ResourceManagers.ContainsKey(resourceType))
                {
                    return ResourceManagers[resourceType];
                }
                ResourceManager resourceManager = new ResourceManager(resourceType, System.Reflection.Assembly.Load("App_GlobalResources"));
                if (!ResourceManagers.ContainsKey(resourceType))
                {
                    ResourceManagers.Add(resourceType, resourceManager);
                }
                return ResourceManagers[resourceType];
            }
        }
        /// <summary>
        ///     When implemented in a derived class, gets a unique identifier for this <see cref="T:System.Attribute" />.
        /// </summary>
        /// <value></value>
        /// <returns>An <see cref="T:System.Object" /> that is a unique identifier for the attribute.</returns>
        public override object TypeId
        {
            get
            {
                return typeof(DisplayNameAttribute);
            }
        }
        #endregion
    }
You can use it like this:

  [ScaffoldTable(true)]
    public class Customer_Metadata
    {      
        [ResourceDisplayName("CustomerName", "Resources.DBColumns")]
        public string Name { get; set; }    

Foreign key

By default each list has on top list of foreign key filters. You localize them same way as fields above just reference correct property from model like bellow or you could use above custom attribute.

  [MetadataType(typeof(User_Metadata))]
    public partial class User
    {
    }
[ScaffoldTable(true)]
    public class User_Metadata
    {
        [Display(ResourceType=typeof(App_GlobalResources.GlobalLocalization),Name="MenuCustomers",ShortName="MenuCustomers")]
        public virtual Customer Customer { get; set; }
    }

Jul 8, 2013

Phonegap build - how to build app that uses Cordova API?

Key power of Phonegap project is its cloud base build service.
You create website, build it using Phonegap Build and you get native app.
Great!
But another part of Phonegap project is Phonegap API.
You use it to access mobile device's resources (GPS, storage etc.).
So you extend your website/app with support for Phonegap API.
But how to build it ?
Official docs guides, depending on OS development platform, install Eclipse, SDK's etc.
In this approach we are responsible to build app.

So you say no! I want to build my website/api that uses Cordova (phonegap) API using Phonegap Build cloud service.

Now here comes the catch 22 !
When you develop website with Cordova API and build it on your own you are expected to use something like this:

<script type="text/javascript" src="js/cordova-2.5.0.js"></script>

But when you want the very same code to build on Phonegap Build service you must drop above line and use this :

<script type="text/javascript" src="phonegap.js"></script>

Already twice I've lost some time to figure this out.
I don't know am I dumb or what but this info is not on any get started pages or I did not find them.

Here is officially Github repo of phonegap examples that uses above approach:

https://github.com/phonegap/phonegap-app-hello-world

Jul 5, 2013

Delaying javascript execution

Delaying execution of javascript until certain condition is fulfilled :

    function WaitForAnsycPostback(cb) {
        var requestManager = Sys.WebForms.PageRequestManager.getInstance();
        if (requestManager.get_isInAsyncPostBack()) {
            setTimeout(function () {
                WaitForAnsycPostback(cb);
            }, 250);
        }
        else {
            if (typeof(cb) == 'function') cb();
        }
    }

Jun 20, 2013

.NET Culture, Localization - bits & pieces

Two settings rule culture settings:

The UICulture property is used to specify which resource files are loaded for the page. The
resource files can contain all the text content of your pages translated into a particular
language. You can set this property to any standard culture name. This property is
discussed in detail during the discussion of using local and global resources later in this
chapter.
The Culture property, on the other hand, determines how strings such as dates, numerals,
and currency amounts are formatted
. It also determines how values are compared and
sorted. For example, by modifying the Culture property, you can display dates with
language-specific month names such as January (English), Januar (German), or Enero
(Spanish).
Make distinction between neutral & specific culture:

Notice that each culture name consists of two parts. The first part represents the language
code and the second part represents the country/region code. If you specify a culture
name and do not provide a country/region code—for example, en—then you have specified
something called a neutral culture. If you provide both a language code and a
country/region code—for example, en-US—then you have specified something called a
specific culture.

Set explicitly culture on current thread (no matter Desktop or Website app).
Watch out if you run multithreaded app upon instancing of thread do this:

System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("de-DE");

Although above will work in most cases proper way in WebForms website is to override InitializeCulture() like this:

 protected override void InitializeCulture()
        {
            Culture = "en-US";
        }

Set culture for complete website in web.config:

<system.web>
     <globalization culture="de" uiCulture="DE"/> 
Alternatively use granular approach and assign explicitly to each value its own culture:

var deCulture = new CultureInfo("de-DE");
labCurrency.Text = (2323.23m).ToString("c",deCulture);
If you work on multi-language app you should take special care on comparing string values of different language. Use string.Compare :

if (String.Compare(“Hello”, “Hello”, true, new CultureInfo(“de-DE”)) == 0)
lblResult.Text = “The strings are the same!”; 

Resources file in website

Create App_LocalResources under root of ASPX web pages you want localized.
Place in it resource file named :
MyWebPage.aspx.resx
This is neutral culture default resource file.
To support different languages add Culture id in name like this:

MyWebPage.aspx.de-DE.resx

You can write it neutral culture also:

MyWebPage.aspx.de.resx

Then  in html markup explicitly address resource file member like this:

<asp:Literal ID="literal" runat="server"  Text="<%$ Resources:CURRENCY %>"></asp:Literal>
Above is explicit retrieving of resource value.

There is more intuitive implicit localization using meta tag in server controls:

<asp:Label meta:resourceKey="labCurrency2" id="labCurrency2" runat="server" ToolTip="Funny" ></asp:Label>

labCurrency2.Text de_currency2Text labCurrency2.Tooltip de_currency2Tooltip
If needed you can access content of resource file even outside context of web page.
But still you need to have access to HttpContext:

return (string)HttpContext.GetLocalResourceObject(“~/LocalizablePage.aspx”,
“ClickHere”);

Global resource

When localization is addressing frequent same text it is best to put it in global resource file.
Just create App_GlobalResources folder and place in resource file named what ever you like.
For example:
/_App_GlobalResources
                    site.resx
You obtain value on same ways as explained for localized resources. Here is meta tag example:

<%$ Resources:Site,Copyright %>

Alternative from code is:
(string)GetGlobalResourceObject(“Site”, “Title”);
Since global  resource files get compiled immediately upon change they can  be accessed directly through their namespace:
labName = Resources.Site.Copyright;

How to convert language code page (e.g. 1033) to .NET country ISO code (e.g. DE):


var twoLetterLangugageISO = (new CultureInfo(languageId)).TwoLetterISOLanguageName;

Jun 19, 2013

Simple reusable javascript object - basics

You need to create javascript to handle multiple instances of same type of functionality with ability to input standardized arguments.
We need to model Javascript object. Javascript does not support objects in OOP sense and this creates a lot of confusion. On top of it its dynamic language. Comparing it to .NET classes where mostly you deal with static members of class is not possible.
So here is example of simple Javascript object to implement creating and configuring simplest div container.
I'm using JQuery.

Declaring:
counterPanel = function (pnlId, argsParam) {
    var args = $.extend({
        title: "title",
        color: "rgb(255,250,250)",
        execute: null
        },argsParam
        );
    this.Show = function Show() {
         
        if (!DoesContainerExists(pnlId)) {      
            $('#countersContainer').append('<div id="'+pnlId+'"><h1 style="color:'+args.color+'">'+args.title+'</h1></div>');
        }
       
    }
    this.Hide = function Hide() {
        if (DoesContainerExists(pnlId)) {
            $('div#' + pnlId).Hide();
        }
    }
    if (typeof(args.execute) == 'function') args.execute();
    function DoesContainerExists(pnlId) {
        return ($('#countersContainer div#' + pnlId + ':First').attr('id') != undefined);
    }
}
Instancing with various input params including function injection.

var dlgFirst = new counterPanel("dlgFirst", {title:"something special", color:"rgb(0,0,100)"});
        dlgFirst.Show();
        var dlgSecond = new counterPanel("dlgSecond", { title: "special", color: "rgb(110,0,100)", execute: function () { alert('2');} });
        dlgSecond.Show();

Jun 17, 2013

ASP.NET Running recurring background threads inside IIS

You have time consuming tasks that happen on time regular basis.
For example contacting web service or long db process.
They should run in background to free front website of locking into long task.

There is proper way of easily doing this inside legacy ASP.NET website.

There are even open source framework for this.

The challenge resides in fact that IIS & ASP.NET own app domain and destroy it when they determine that website lifespan is finished or app pool gets recycled.

Read more:

http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx
https://github.com/NuGet/WebBackgrounder
http://fluentscheduler.codeplex.com/workitem/list/basic

Jun 13, 2013

IIS bits & pieces

Type of Pipeline on application pool?
Always use default Integrated.
Classic pipeline is backward compatibility for IIS6.0

Read more:
http://stackoverflow.com/questions/716049/what-is-the-difference-between-classic-and-integrated-pipeline-mode-in-iis7
http://www.iis.net/learn/application-frameworks/building-and-running-aspnet-applications/aspnet-integration-with-iis

I've always asked myself why can't you mix different .NET versions on one application pool.
So here is explanation:

Unfortunately, due to the limitation of the ability to load only one CLR version into a single worker process, you must make sure that two applications that use different versions of ASP.NET are never configured to exist within the same application pool. When this common mistake is made, the first request loads the CLR of the corresponding aspnet_isapi.dll, and subsequent requests to the other version within the same application pool will fail.

When you open global.asax.cs you can see various empty event handlers. These are simply mappers to above explained integrated pipeline events:


In Integrated mode, the ASP.NET request-processing stages that are exposed to modules are directly connected to the corresponding stages of the IIS pipeline. The complete pipeline contains the following stages, which are exposed as HttpApplication events in ASP.NET:
So the HttpApplication class corespondes to pipeline.

Nice step by step of practical use of integrated pipeline and plugging into IIS request pipeline.
On any medium or large scale website you will encounter such extensions so its good to know what a heck it is.

http://www.iis.net/learn/develop/runtime-extensibility/developing-iis-modules-and-handlers-with-the-net-framework

For above, in a nutshell : you develop module when need to address all request from pipeline and use handler for targeting exact url, extension etc.

This guy was former PM of IIS 7.0 and ASP.NET

http://mvolo.com/

Jun 4, 2013

ASP.NET security - authentication- revisited

UPDATE 14.09.15

Must read: http://www.codeproject.com/Articles/689801/Understanding-and-Using-Simple-Membership-Provider
http://www.codeproject.com/Articles/408306/Understanding-and-Implementing-ASP-NET-Custom-Form
http://www.codeproject.com/Articles/578374/AplusBeginner-27splusTutorialplusonplusCustomplusF

--------------------------
I'm exploring simplest way to employ web security with legacy ASP.NET components.
Basic and most often type of web site authentication is forms authentication.

Forms


It is very straightforward and simple:

1. Add in web.config:

<authentication mode="Forms">
      <forms defaultUrl="default.aspx" loginUrl="login.aspx" name=".ASPXAUTH">
      </forms>
    </authentication>
    <authorization>
      <deny users="?"/>
    </authorization>   

2. Create your own Login.aspx and use:

System.Web.Security.FormsAuthentication

;for redirecting from and to login.
Whole idea is that after you issue redirect command cookie is created and persisted.
Don't use param strCookiePath in RedirectFromLoginPage. It seems that it prevents SignOut() to destroy cookie!
There is also SignOut which destroys cookie and you'r back to square one.
Authenticated user are obtained from:

Context.User.Identity.Name

Simple and works like a charm if you wish to create completely manually handling of user creation, managment and etc.

Not sure is this required:

FormsAuthentication.SetAuthCookie(userName, persistent);

Membership

There is tone of stuff about ASP.NET membership component.
But what is the simplest scenario to use it?
I want to integrate Forms & Membership in most simplest scenario.
So here it is.

1. Open "Developer Command Prompt for Visual Studio"  and execute "aspnet_regsql.exe"
    Select your database and you'll end up with bunch of aspnet_xxx tables & stored procs used by membership.
2. Configure custom Membership provider in your web.config and make sure it points to correct connection string. Example:

<configuration>
  <connectionStrings>
    <add name="AdventureSQLConnection" connectionString="Data Source=DB_SERVER;Initial Catalog=AdventureWorksLT2008;Persist Security Info=True;User ID=XXXX;Password=XXXXXXX;"/>
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
 
    <authentication mode="Forms">
      <forms defaultUrl="default.aspx" loginUrl="login.aspx" name=".ASPXAUTH">
      </forms>
    </authentication>
    <authorization>
      <deny users="?"/>
    </authorization>      
    <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
      <providers>
        <clear />
        <add
          name="SqlProvider"
          type="System.Web.Security.SqlMembershipProvider"
          connectionStringName="AdventureSQLConnection"
          applicationName="MyApplication"
          enablePasswordRetrieval="false"
          enablePasswordReset="true"
          requiresQuestionAndAnswer="true"
          requiresUniqueEmail="true"
          passwordFormat="Hashed" />
      </providers>
    </membership>
  </system.web>
</configuration>
 Two remarks, first be sure to use <clear/> so default aspnetSQLprovider gets destroyed. This one is registered in MACHINE.CONFIG. And second be sure to use correct connection string.

3. Use infamous ASP.NET website configuration to test whether you did above work correctly and optionally set initial set of users, roles whatever.

4. In your login.aspx use combination of Membership methods and above mentioned FormsAuthentication  to query and manage your users, roles, whatever. For example, here is the simplest one-liner of validating user:

if (Membership.ValidateUser("sinisa", "demo1234x!"))
     FormsAuthentication.RedirectFromLoginPage("sinisa", true);

http://msdn.microsoft.com/en-us/library/xdt4thhy(v=vs.100).aspx

May 22, 2013

Detecting checked radio button on UI dialog

Here is container for jquery UI dialog filled with radio buttons:


<div id="gfdialog" title="Meldung vom Website">
            <div>xxxxxxxxxxxxxxxxxx?</div>
            <input type="radio" name="radLstCopyType" value="1" checked="checked" /><span>Option 1</span>
            <div style="margin-left: 21px!important; margin-bottom: 15px;">Option 2.</div>
            <input type="radio" name="radLstCopyType" value="3" />
            <span>Szenario-CFG</span>
            <div style="margin-left: 21px!important; margin-bottom: 15px;">Option 3</div>
            <input type="radio" name="radLstCopyType" value="2" />
            <span>Muster-CFG</span>
            <div style="margin-left: 21px!important; margin-bottom: 15px;">xxxxxxxxxxxxxxxxxx.</div>
        </div>

; and here is code that gets checked radio button:


function RegisterGFCopyBGDialog() {          
            $("#gfdialog").dialog({
               
                autoOpen: false,
                width: 400,
                buttons: [
                    {
                        text: "Ok",
                        click: function () {
                            var selectedCFG_artId = $('input[name="radLstCopyType"]:checked').val();                          
                           
                            if (selectedCFG_artId == null) return;
                            __doPostBack('radLstCopyType', selectedCFG_artId);
                            $(this).dialog("close");
                        }
                    },
                    {
                        text: "Abbrechen",
                        click: function () {
                            $(this).dialog("close");
                        }
                    }
                ]
            });
        }


Most important part is  :

$('input[name="radLstCopyType"]:checked').val();                           

and NOT:

$('input[name="radLstCopyType"][checked="checked"']).val();                          

or

$('input[name="radLstCopyType"][checked="true"']).val();                          

or

$('input[name="radLstCopyType"][checked]).val();                          


May 3, 2013

Linq lambda group by aggregate by multiple columns



Example of grouping input DataTable by string column and getting aggregate MAX for second bool column:
     var sTables = (bindSrcColumns.DataSource as DataTable).Rows.Cast<DataRow>())
                        .GroupBy(r =>   ColumnsHelper.GetTablePart(r[EDITORCOLUMN_FIELDNAME].ToString()))
                        .Select(g => new Tuple<string, bool>(g.Key, g.Max(m => m[EDITORCOLUMN_ISSELECTED] as bool? ?? false)))
                        .OrderBy(s=>s.Item1)
                        .ToList();

Apr 11, 2013

Windows forms data binding tutorial

http://www.codeproject.com/Articles/24656/A-Detailed-Data-Binding-Tutorial

Windows Forms / DataGridView / End row edit upon value change

I've created DataGridView in windows forms app with check box and text box.
When I click on checkbox I want some action executed - another button clicked.
I require that editing of row in which click occurred finishes its editing session  so that underlying BindingSource is updated to latest change.
So if my click unchecked or checked given field I wish to have it in my underlying DataTable so some other logic can immediately use it.
This proved to bit a bit tricky.
Note that in this scenario Checkboxcolumn in question is expected exactly at columnindex 0.


public EditorGUI()
        {
            InitializeComponent();

gridTables.CellContentClick += ( o, e ) =>
{
if ( e.ColumnIndex > 0 ) return;
gridTables.CommitEdit( DataGridViewDataErrorContexts.Commit );
};
gridTables.CellValueChanged += ( o, e ) => btnQuicksrch_Click( this, null );
        }

Here is second scenario. There are two grids - gridColumns & gridSelFields.
They both reflect same data but filter it in different way.
When user clicks and checks/unchecks checkbox in gridColumns second grid should immediately get  updated since they reflect same data.

private delegate void AfterDirtyStateChangedDelegate();
private void  MyForm()
...


       gridColumns.CurrentCellDirtyStateChanged += gridColumns_CurrentCellDirtyStateChanged;
       gridColumns.CellValueChanged += gridColumns_CellValueChanged;


First event to detect click and SPACE on checkbox is CurrentCellDirtyStateChanged:


void gridColumns_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if ((sender as DataGridView).IsCurrentCellDirty)
            {
                BeginInvoke(new AfterDirtyStateChangedDelegate(DirtyStateChanged));
            }
        }


If cell "dirty" (change occured) async invoke committing of changes to underlying data list.


private void DirtyStateChanged()
        {
            Debug.Print("DirtyStateChanged()");
            gridColumns.CommitEdit(DataGridViewDataErrorContexts.Commit);
            gridColumns.EndEdit();
            bindSrcColumns.EndEdit();
        }


In DirtyStateChanged all three commits must execute to make sure our change is commited.
Above committing will finally raise CellValueChanged event.


void gridColumns_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {        
            UpdateIsSelectedToSelFields(e);
            GridColumnsFieldSelection(e.RowIndex);
        }

Only at this point we are sure that binding source of Columns is updated so we can use it.

...

var selField_SelRow_IsSelected = (bindSrcSelFields.DataSource as DataTable).Rows.Find(col_SelRow[EDITORCOLUMN_FIELDNAME])[EDITORCOLUMN_ISSELECTED];          
            (bindSrcSelFields.DataSource as DataTable).Rows.Find(col_SelRow[EDITORCOLUMN_FIELDNAME])[EDITORCOLUMN_ISSELECTED] = !Convert.ToBoolean(selField_SelRow_IsSelected);

...

Watch it ! In above this DOES NOT work :

selField_SelRow_IsSelected = !Convert.ToBoolean(selField_SelRow_IsSelected);

There is at the moment still active bug with DataGridView. When you press SPACE on checkbox field and handle CellContentClick you get exception.
Here it is explained:

http://connect.microsoft.com/VisualStudio/feedback/details/780347/nullreferenceexception-in-notifymassclient-after-checking-unchecking-a-checkbox-in-datagridview-with-spacebar#details

That's where I got above delegate thing.

There is only one misbehavior with above scenario. When you use SPACE key you cannot check and immediately uncheck same record. After first SPACE leave current row and come back.

This is due to fact that after first SPACE we ended EditMode and only by leaving and getting focus again will enter Edit mode again.

Furthermore consider  DataGridView.EditMode

http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&l=EN-US&k=k(System.Windows.Forms.DataGridView.CellContentClick);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&rd=true