ITypedList Interface and PropertyDescriptor Simplified

Most of the time during databinding, you need some columns which are not present in your datasource object or collection object. At that time with the help of PropertyDescriptor and ITypedList interface, any number of virtual properties can be created and same can be added as columns.

e.g.

class A
{
public int x { get; set; }
public string name { get; set; }
}

class B
{
public List<A> aObj { get; set; }
public string empName { get; set; }
}

So if we should have some collection of type class B but with columns as empName, name, x and other based on combination of any of these, ITypedList can be very useful.

Here is the ITypedList and PropertyDescriptor modified for the above structure defined.

public class CollectionB : List<B>, ITypedList
{
      private PropertyDescriptorCollection propertyDescriptors;

public void CalculatePropertyDescriptors()
{
// start out with the properties that are really in the MasterRecord
PropertyDescriptorCollection origProperties = TypeDescriptor.GetProperties(typeof(B));

ArrayList properties = new ArrayList();

//this will Add all proprties of B apart from of type A
foreach (PropertyDescriptor desc in origProperties)
       if (!typeof(A).IsAssignableFrom(desc.PropertyType))
properties.Add(desc);

foreach (var item in this[0].aObj)
{
properties.Add(new PropertySummaryDescriptor(item.name.ToString()));
}

// Last, convert the ArrayList back into a PropertyDescriptorCollection.
propertyDescriptors = new PropertyDescriptorCollection((PropertyDescriptor[])properties.ToArray(typeof(PropertyDescriptor)));
}

#region ITypedList Members

public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
{
return propertyDescriptors;
}

public string GetListName(PropertyDescriptor[] listAccessors)
{
      return “”;//Can be left blank
}

#endregion

}

Here is the Property Descriptor :

public class PropertySummaryDescriptor : PropertyDescriptor
{

public PropertySummaryDescriptor(string name)
: base(name, null)
{
}

public override bool CanResetValue(object component)
{
return false;
}

public override Type ComponentType
{
get { return typeof(B); }
}

public override object GetValue(object component)
{

B pr = (B)component;
    int x = 0;

    foreach (A a in pr.aObj)
if (a.name == this.Name)
x = a.x;
return x;

}

public override bool IsReadOnly
{
get { return true; }
}

public override Type PropertyType
{
get { return typeof(int); }
}

public override void ResetValue(object component)
{

}

public override void SetValue(object component, object value)
{

}

public override bool ShouldSerializeValue(object component)
{
return true;
}
}

About these ads

Dependency Property

Tags

, , , ,

Dependency properties are properties backed by WPF engine. They use more sufficient storage and support for additional feature such as change notifications & property value inheritance.

These are also the basis for a number of key WPF features like animation, data binding and styles.

Dependency properties in the WPF library are always wrapped by ordinary .Net property procedures.

e.g. Margin for any container control like StackPanel etc.

Steps in Creation of Own Dependency Property : 

  • Define an object that represents your property. (Add Property keyword at the end of property name)
    e.g.
    public static readonly DependencyProperty MarginProperty;
  • Register a dependency property
    e.g.
    static FrameworkElement()
    {
         FrameworkPropertyMetadata metadata = new FrameworkPropertyMetadata(new Thickness(),
                                                                                           FrameworkPropertyMetadataOptions.AffectsMeasure);

    MarginProperty = DependencyProperty.Register(“Margin“,typeof(Thickness),
                                 typeof(FrameworkElement),metadata,new ValidateValueCallback(FrameworkElement.IsMarginValid));
    }

  • Adding a Property Wrapper
    public Thickness Margin
    {
          set { SetValue(MarginProperty,value);}
         get { return (Thickness)GetValue(MarginProperty);}
    }

Out Vs Ref

Tags

, , ,

There are some basic differences in Out and Ref.

Out :  Passed by reference and it must be set by the called method, otherwise there will be compiler error.

e.g.

int x; // no need to assign any value as the method in which it will be passed as OUT , its method responsibility to set its value.

void OutEx(out int x)
{
//x should be set some value before exiting from this method other compiler error
}

Ref : Already assigned passed and no need to reset in the called method.

e.g.

int x = 0;//here x must be set before passing as ref, because its not guarantee that the method in which it is passed as Ref, will set.

void RefEx(ref int x)
{
// x is already set, so no need to set. but you change
}

Another benefit of out modifier :  It allows the caller to obtain multiple return values from a single method invocation.

Interviewer can ask in a different way like : If you have to return multiple values from a single method, what will you do. Simple answer is use Out modifier.

What’s the Difference between String and StringBuilder?

Tags

,

Strings are Immutable means whenever you change any value of string variable, a new object is created in memory. That’s why where a significant number of strings modifications need to be done, StringBuilder should be used. Its present in System.TextBuilder namespace.

Now questions comes, why strings are Immutable or what are the benefits of immutability :

  • First, All Immutable instances are thread safe. Because on modifying their values, a new instance is created , So no Thread can actually modify it.
  • There will be no side-effect on passing an immutable types as parameter in a function, as if there is x = “abc” in the starting of function,  that doesn’t change in the body of the method, then x == "abc" at the end of the method.
  • Copying is fast and simple, to create a clone just return this. Since the copy can’t be changed anyway, pretending something is its own copy is safe.
  • You can use strings in Hash-table, key-value pairs collection for their key part.

ABC’s and Endpoint of WCF

Tags

, , , , ,

ABC’s of WCF : 

A – Address
Basically URL, specifies where this WCF service is hosted .

B – Binding

Binding will describes how client will communicate with service.
Transport – HTTP, Named Pipes, TCP, and MSMQ .
Encoding (Optional) – Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM).
Protocol(Optional) – Defines information to be used in the binding such as Security, transaction or reliable messaging capability
C – Contract
Collection of operation that specifies what the endpoint will communicate with outside world.

End Point :

WCF service cab be communicated by any client using End Points. An End Point contains three information : Address, Binding and Contract. As you see from the screenshot : One WCF service can have more than one end point and using the same type of End Point, Any client can communicate with the service.

Same Type means Like if one Endpoint of a service is using Http protocol and another End point is using on TCP. Then Client has to decide with which protocol, It wants to connect the service. So Basically, All the ABC’s of one service end point should exactly match with the client’s Endpoint’s ABC’s for successful communication.

Value Type Vs Reference Type

Tags

, , ,

There is always a confusion between value types vs refernce types or a struct vs a class. Specially during interview times .. :), when Interviewer starts question by asking whats the difference between Value Types vs Refernce Types and ends by delocating of memory.
There is a simple difference of these two is about how these are allocated in memory.
e.g.
Value Types like struct, int, double etc. all premitive data types are stored in Stack and Reference types like classes are stored in Heap.
In classes, there are two things : one is instance and second is object.
Class Employee
{
    int ID;
    int Salary;
}
Employee Emp; // this is instance 
Emp = new Employee;//this is object
So, Instance is stored in Stack, whereas actual object is stored in Heap.

Memory Allocation / Deallocation:

In case of Value types variables, as the value is stored in Stack, after function execution, all values from Stacks are popped and memory deallocated.
In case of Reference types, as references are stored in Stack, these are also popped up from Stack but the main object which is created in Heap, that still remains in memory until Garbage Collector cycle doesn’t run because it’s GC(Garbage Collector) responsibility to clear all unallocated objects.

Passing as Parameter:

Suppose there is a struct say Point P and Class Employee as defined above:
Struct Point
{
    int X;
    int Y;
}
Class Employee
{
    int ID;
    int Salary;
}

By default, every paramter is passed by value. Suppose there is a function ChangeValues.

public void ChangeValues(Point P, Employee emp)
{
P.X = 200;      //There will be no change on original P.X passed
emp.ID = 5;    //This will change original ID
emp = null;     //No change on original Emp object
}

Reason : Point is a value type which is passed as copy of original value, so any change done inside the function will not reflect original value. Employee emp has been passed as a reference(instance), So emp represent here as a pointer to main object, so emp = null will not change the oringinal object, but this emp reference points to original object, so emp.ID will change original object properties. Let’s clear the picture by passing these two as passing by reference.

public void ChangeValuebyRefernce(ref Point P, ref Employee emp)
{
P.X = 200;      //There will be change because refernce to original value is passed

emp.ID = 5;    //This will change original ID

emp = null;     //This will change original reference
}

This was the brief summary of how value types and refernce types ate stored in memory, how these are deallocated from memory, how these behave in passing as parameter. In further blogs, I’ll try to clear more doubts.
Follow

Get every new post delivered to your Inbox.