Getting Started with Adobe After Effects - Part 6: Motion Blur
First Time? You can support us by signing up. It takes only 5 seconds. Click here to sign up. If you already have an account, click here to login.

1st Prize - Apple iPad

Answers by Dmitry Kharlap (aka Docker)

Previous 1 | 2 | 3 | 4 Next
  • Score
    Dmitry Kharlap (aka Docker) replied on 01-22-2011 00:08

    What is the difference between Co & Contra Variance

    In .NET 4.0 Microsoft introduced covariance and contravariance for generic type parameters in interfaces and delegates. Covariance means you can use an interface instance (or generic delegate) that has methods with more derived return types than originally specified. Here is an example from MSDN:

    IEnumerable<Derived> d = new List<Derived>();
    IEnumerable<Base> b = d;

    Contaravariance means you can use an interface instance (or generic delegate) that has methods with less derived parameter types. Here is an example from MSDN:

    Action<Base> b = (target) => { Console.WriteLine(target.GetType().Name); };
    Action<Derived> d = b;
    d(new Derived());

    Covariance and contravariance allows implicit conversion where a type argument of a template is a reference. Values are still invariant. This limitation is in place (at least right now) to avoid actual data changes (reference).

    Generally speaking covariance and contravariance were introduced before .NET 4.0 however it wasn't explicitly mentioned. For example in C#, variance were supported in the following scenarios:

    1. Covariance in arrays (since C# 1.0, it's considered "not safe" though)
    2. Covariance and contravariance in delegates, also known as “method group variance” (since C# 2.0)

    You can find detailed description of these cases as well as few examples in Covariance and Contravariance FAQ article by Alexandra Rusina

    When do you use each of these in practical scenario. Explain Why?

    In general, a covariant type parameter can be used as a return type of interface's methods or a delegate, and contravariant type parameters can be used as parameter types for interface's methods or a delegate.

    I believe explanation comes from object-oriented language "rules" particularly Liskov substitution principle. According to this if class B inherits class A then the problem for instances of B is how to be perfectly substitutable for instances of A. For this all inherited member functions of B must return the same or narrower set of types as A; i.e. return type is covariant. From the other side inherited member functions of B can take the same or broader set of arguments compared with the member functions of A; the argument type is said to be contravariant. So, the only way to guarantee type safety and substitutability is to be equally or more liberal than A on inputs, and to be equally or more strict than A on outputs.

    Another benefit of using variances in generics is type safety. In some scenarios it allows to catch errors in compile time that otherwise would be causing exceptions during code execution. You can find a simple example at video presentation done by Eric Lippert. Besides variances for template interfaces and delegates definitely add more flixibility for writing the code.

    There is also a nice general explanation of variances in Wikipedia.

  • Score
    Dmitry Kharlap (aka Docker) replied on 01-30-2011 23:45

    To parse the document I'll use XMLDocument. XmlDocument is an in-memory (cached) tree representation of an XML document. As our document is small, then lets assume they all will be relatively small, so we can use XMLDocument. However if a document is large enough XmlDocument will become really resource demanding. So, in this case we'll have to have a look at using XmlReader.

    Two make comparison case-insensitive I am using translate function. Please note that this code will work only for English. If we expect language other than English we should add this to translate arguments. Futhermore as per XPath 1.0 specification :

    The translate function is not a sufficient solution for case conversion in all languages. A future version of XPath may provide additional functions for case conversion.

    Unfortunately .NET still supports XPath 1.0 only. Since XPath 2.0 there is fn:upper-case, fn:lower-case functions that are intended to do the conversion. There is also ms:string-compare function that can do the job, however it also still not supported by .NET. In my code translate function is selected to minimize number of statements (as this is one of the requirements). However if we expect some undefined languages the solution will be different.

    Exception processing and input parameter validation are not required. However it's required to minimize number of statements. So, exception processing as well as input parameter validation are not included. They can be easily included later. So here is the code:

    public static XmlNode GetBook(string strXMLFilePath, string strPublisherName, string strTitle) 
    XmlDocument xmlDocument = new XmlDocument(); 
    return xmlDocument.SelectSingleNode( "/AllBooks/Publishers/Publisher[translate(@PublisherName,'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')='" +  strPublisherName.ToUpper() + "']" + "/Books/Book[translate(@Title,'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')='" + strTitle.ToUpper() + "']"); 
  • Score
    Dmitry Kharlap (aka Docker) replied on 03-02-2011 22:53

    Thank you for the interesting question Brian. In the statement

    st.Triggered += (s, a) => Console.WriteLine("{0} reporting ...", c);

    c is an outer variable for the lambda expression. Unlike local variables, the lifetime of an outer variable extends until a lambda expression is eligible for garbage collection (or maybe even longer if there are other references to it). In our case the reference to c is captured at the time the delegate is created. So, if we execute your code all the functions assigned to Trigerred will reference one variable that will have "West" value at the time of their execution. To avoid it we can modify the code to create 4 different variables that will keep corner names at the time functions in Triggered are executed. Probably the easiest way to do so is to modify foreach statement to be like this:

    foreach (var c in corners) 
    var corner = c; 
    st.Triggered += (s, a) => Console.WriteLine("{0} reporting ...", corner); 

    In this case corner variable will be created 4 times and every variable will keep one corner from corners array.

  • Score
    Dmitry Kharlap (aka Docker) replied on 03-04-2011 00:17

    To answer this question let's first look at MSDN.

    WCF RIA Services

    Microsoft WCF RIA Services simplifies the traditional n-tier application pattern by bringing together the ASP.NET and Silverlight platforms. RIA Services provides a pattern to write application logic that runs on the mid-tier and controls access to data for queries, changes and custom operations. It also provides end-to-end support for common tasks such as data validation, authentication and roles by integrating with Silverlight components on the client and ASP.NET on the mid-tier.

    What Is Windows Communication Foundation

    Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint.

    As an example Microsoft BizTalk Server R2, Windows Workflow Foundation and definitely Microsoft Silverlight utilize WCF as a communication technology.

    So, in fact RIA services is a new technology that is built on top of WCF services and in Silverlight applications it helps you to make client-server integration "transparent" for a developer. At compile time RIA services generate client side classes based on the actual server side classes. Then the client can use generated client side functionality in almost the same way as if it was executing actual server side class. For example RIA servises support serializing LINQ queries between the client and the server, so the client can create the LINQ query and have it run server side without writing any code to handle client server communication. So, this allows RIA Services to provide a much richer client side object model by including any business rules and relationships between objects.

    I have to mention that there are few limitations for RIA services right now. For example RIA services serializer doesn't support some data types that WCF does (reference) or RIA Services do not recognize many-to-many relationships in an Entity Framework model (reference). However I believe they will soon be addressed in the future releases.

    So, to answer the question WCF is generic and provides you great flexibility and abilities to handle asynchronous messages from one service endpoint to another. From the other side RIA service is a "new layer" on top of WCF that simplifies the development. The role of RIA service is to simplify even more an integration between client side and server code in Silverlight applications, so functionality like business rules, data validation, access to data for queries and any other custom operations could be executed in the client code in almost the same manner as if they were executed on server side.

  • Score
    Dmitry Kharlap (aka Docker) replied on 03-05-2011 01:38

    I believe the solution for this question is to add a common event handler to elements (e.g. MouseLeftButtonDown in the code below). Then using FindElementsInHostCoordinates method iterate through all elements that exist at the mouse event point. FindElementsInHostCoordinates provides UIElements in the order from top to bottom so it makes it perfect tool to implement tunneling. Implementing common event handler to the object that raises the event will allow us to implement tunneling even in rare cases when we need it for events like MouseEnter or MouseLeave (as these events are not passed to any other object except where they were raised). It will also provide better control on what elements should be used in tunneling. So, the code for the solution will be:


    <Rectangle x:Name="rect1" Fill="Pink" MouseLeftButtonDown="Common_OnMouseLeftButtonDown" /> 
    <Rectangle x:Name="rect2" Fill="Green" MouseLeftButtonDown="Common_OnMouseLeftButtonDown" /> 
    <Rectangle x:Name="rect3" Fill="Blue" MouseLeftButtonDown="Common_OnMouseLeftButtonDown" /> 
    <Rectangle x:Name="rect4" Fill="Red" MouseLeftButtonDown="Common_OnMouseLeftButtonDown" />


    private void Common_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) 
    var elements = VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(LayoutRoot), LayoutRoot); 
    foreach (var element in elements) 
    // Process MouseLeftButtonDown events here 
  • Score
    Dmitry Kharlap (aka Docker) replied on 03-06-2011 02:48

    Serializing by data contracts is a new type of serializer introduced in .NET 3.0. WCF uses the data contract serialization engine called DataContractSerializer by default to serialize and deserialize data. To explicitly create DataContract we should apply DataContract attribute. DataContractSerializer also supports "old" Serializable attribute. Here is short comparison of Serializable and DataContract attributes:

    • Serializable uses opt-out approach while DataContract has an opt-in approach. This ensure that only necessary DataContract members are included in serialization.
    • Serializable attribute operates directly on class members bypassing any logic in properties used to access this members.
    • Serializable attribute provides no direct support for versioning.
    • Serializable attribute offres no support for aliasing type names or members, or for mapping a new type to a predefined data contract
    • Serializable attribute does not offer clean separation between the ability to use this type as a WCF operation parameter and the ability to serialize it.
    • Serializable attribute is supported by all serializers. DataContract is supported only by DataContractSerializer.

    As DataContract is supported only by DataContractSerializer we also need to consider differences between DataContractSerializer and other serializers. For example you can find a short comparison of DataContractSerializer and XmlSerializer here. Also DataContractSerializer has some limitations on supporting XML schema elements as described in MSDN .

    DataContractSerializer allows both Serializable and DataMember attributes to be part of serializable object. For example:

    namespace SerializableInDataContract
    public class SerializableMember 
    public string Member1; 
    public int Member2; 
    class SampleDataContract 
    [DataMember] public string DataMember1; 
    [DataMember] public int DataMember2; 
    [DataMember] public SerializableMember SerializableMember; 
    class Program 
    static void Main(string[] args) 
    SerializableMember sm = new SerializableMember 
    Member1 = "Serializable member 1", 
    Member2 = 2 
    SampleDataContract sdc = new SampleDataContract 
    DataMember1 = "Data Member 1", 
    DataMember2 = 2, 
    SerializableMember = sm }; 
    static Message ObjectToMessage(T obj) 
    DataContractSerializer ser = new DataContractSerializer(typeof(T)); 
    return Message.CreateMessage(MessageVersion.Soap12, "", obj, ser); 

    So, as a result you will get

    <s:Envelope xmlns:s="">
    <Action s:mustUnderstand="1" xmlns=" addressing/none" />
    <SampleDataContract xmlns:i="" xmlns="">
    <DataMember1>Data Member 1</DataMember1>
    <Member1>Serializable member 1</Member1>

  • Score
    Dmitry Kharlap (aka Docker) replied on 03-07-2011 01:14

    The reason for this behavior is ASP.NET does not save information about dynamically added server controls (actually it saves information about control attributes, but not control itself!), so this task should be done by us. I believe the most generic ways to do it is to use view state or control state. In both cases every time page renders we add dynamic controls back to the page in the same order as they were added before. Here are some more details about both ways.

    View State

    This is the simplest way that can be used in relatively simple cases. All information about properties of dynamically added controls will be saved in view state automatically between page calls. Parsing view state and setting control parameters to values stored in the view state is done in LoadViewState event that is raised after Init but before Load event. So we need to put code to recreate controls into Init event handler. It's also extremely important to add properties AFTER adding newly created control to Controls otherwise ViewState will not keep property information (you can modify sample below and see that edit field height will not be saved).

    Please note that if we need to keep control values ONLY then we don't need to have view state. Values are saved and are put back to server controls in LoadPostbackData event that does not require ViewState at all. LoadPostbackData is fired after LoadViewState and before Load event. You can see it in the sample provided below. If you disable view state edit boxes will keep their values, however height attribute value will be lost.

    So here is a code:

    ASPX page

    <%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="DynCtrlTestPage.aspx.cs" Inherits="TestApp.DynCtrlTestPage" ViewStateMode="Enabled" %>
    <form id="form1" runat="server">
    <asp:HiddenField ID="TextBoxCount" runat="server" Value="0" />
    <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
    <br /><br />
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

    And code behind:

    namespace TestApp 
    public partial class DynCtrlTestPage : System.Web.UI.Page 
    protected void Page_Init(object sender, System.EventArgs e) 
    if (IsPostBack) 
    protected void AddExistingTextBoxes() 
    int textBoxCountInt = int.Parse(Request.Form["TextBoxCount"]); 
    for (int i = 1; i <= textBoxCountInt; i++) 
    AddTextBox(i, false); 
    protected void AddTextBox(int contolId, bool isNew) 
    TextBox txt = new TextBox(); 
    txt.Text = txt.ID = "mytxtbox" + contolId.ToString(); 
    if (isNew) 
    txt.Height = contolId * 50; 
    protected void Button1_Click(object sender, EventArgs e) 
    int textBoxCountInt = int.Parse(TextBoxCount.Value); 
    TextBoxCount.Value = (++textBoxCountInt).ToString(); 
    AddTextBox(textBoxCountInt, true); 

    You may be able to get away if you recreate dynamic controls in PageLoad instead of PageInit, as it looks like Controls.Add() method recursively loads the parent's view state into its children, even though the load view state stage has passed.

    There is an amazing article describing ASP.NET view state in MSDN where you can find most of the information mentioned above.


    If you can't use ViewState for whatever reason or you have lots of complex custom controls you can use ControlState functionality. In this case you'll have to create class for your custom control redefining methods OnInit, SaveControlState and LoadControlSate. As I mentioned above ViewState maybe disabled but ControlState will still work. So to do the same as in the example listed in ViewState solution we should define custom control class (my sample is oversimplified just for demonstration purposes):

    public class MyTextBox : TextBox 
    protected override void OnInit(EventArgs e) 
    protected override object SaveControlState() 
    return (Height); 
    protected override void LoadControlState(object state) 
    if (state != null) 
    Height = (Unit)state; 

    And modify the sample above to change TextBox txt = new TextBox(); to be MyTextBox txt = new MyTextBox(); Voila! Everything works. Please note that I am not saving actual value of text box as it's carried through standard Load/SavePostbackData events. However in real life I would probably add value to ControlState as well.

  • Score
    Dmitry Kharlap (aka Docker) replied on 03-07-2011 22:50

    Sorry, Niall I haven't got it from your your question. However I don't see adding events as a big problem. There are actually few ways to do it.

    1 . You can add event handler and mark your control with autopostback = true when you are creating/recreating control. For example if you add lines:

    txt.AutoPostBack = true; 
    txt.TextChanged += new EventHandler(ProcessDynControlEvent);


    txt.Text = txt.ID = "mytxtbox" + contolId.ToString();

    in AddTextBox method that I listed in my previous answer you will get an automated posted back event handler attached to you control. You can easily see it in the source of page rendered, besides it will be done in absolutely the same way as if control was added manually. Definitely you also should define void ProcessDynControlEvent(object sender, EventArgs e) and sender argument will define what control raised the event.

    2 . If you need to have a Javascript on the page that you want to catch your event you can add something like this

    txt.Attributes.Add("onclick", "javascript:ProcessDynControlEventCtrl(this)");


    txt.Text = txt.ID = "mytxtbox" + contolId.ToString();

    So, every time user clicks your control it will call you Javascript function that can do whatever ou want

    3 . You can play around with a standard mechanism of automated post back events, i.e. __doPostBack Javascript function. But it can bring some small roadblocks (e.g. you need at least one Visible control that is marked as AutoPostBack etc.), besides you never know how automated postback events will evolve in future versions of .NET. So, while it's possible to do I would prefer solutions in item 1 or 2 instead.

    I hope I answered your question this time ;) Let me know if I can do more clarifications.

  • Score
    Dmitry Kharlap (aka Docker) replied on 03-08-2011 00:40

    This is a very interesting question. Thank you Anoop.

    As per MSDN execution of LINQ query that returns sequence of values is deferred until the query variable is iterated over in a foreach loop or or by calling one of the LINQ conversion operators (ToList, ToArray, ToLookup, and ToDictionary) that will cause immediate execution.

    Execution of queries that return a singleton value is different. In contrast to the deferred execution of queries that produce a sequence of values, queries that return a singleton value are executed immediately. Some examples of singleton queries are Average, Count, First and Max.

    So, execution of the query defined in the sample is deferred. Because execution is delayed the lambda function inside of Where statement is executed only where we run Console.Write("{0} ",r.Count()); statement. Let's have look at lambda expression definition:

    item => item > num

    Here num is an outer variable for the lambda expression. Unlike local variables, the lifetime of an outer variable extends until a lambda expression is eligible for garbage collection (or maybe even longer if there are other references to it). In our case the reference to num is captured at the time the delegate is created. So, if we execute our code all the functions assigned to Where will reference only one num variable that will have value 10 at the time of their execution. That's why we have all 0 in the results.

    So, there are few approaches to help Mr. Tintumon:

    1 . Probably the least intrusive way (however not the optimal one) is to create 10 different variables that will keep values from numbers list at the time of query execution. We can do it just slightly modifying the first foreach loop:

    foreach (var num in numbers) 
    var lnum = num; 
    results.Add(numbers.Where(item => item > lnum)); 

    2 . As we need count of values only and count function returns a singleton we can force query to run immediately just by adding Count() to the LINQ query. For example like this:

    static void Main(string[] args) 
    int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 
    List < int > results = new List < int > (); 
    foreach (var num in numbers) 
    results.Add(numbers.Where(item => item > num).Count()); 
    foreach (var r in results) 
    Console.Write("{0} ", r); 

    or even like this

    static void Main(string[] args) 
    int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 
    foreach (var num in numbers) 
    Console.Write("{0} ", numbers.Where(item => item > num).Count()); 

    3 . The third option is to force query execution by applying LINQ conversion operation ToList. To do this we just need to modify the first foreach loop to be:

    foreach (var num in numbers) 
    results.Add(numbers.Where(item => item > num).ToList());
  • Score
    Dmitry Kharlap (aka Docker) replied on 03-09-2011 02:37

    Thank you for the interesting question RamiReddy. The key point to answer your question is to deeply understand how postback works. I'll do it as a part of my answer to your first question.

    1 . Is Disabling viewstate will effect the triggering of events???What is the internal mechanism used by to trigger events? Where it will store the control's state information?

    If you have at least one control set as Visible and marked with AutoPostBack ="true" then while rendering a page ASP.NET will generate the following Javascript function (along with couple hidden fields required)(I replaces two underscores with -- sign as I can't make wmd editor work) :

    &lt;script type="text/javascript"&gt; 
    var theForm = document.forms['ctl01']; 
    if (!theForm) { 
    theForm = document.ctl01; 
    function --doPostBack(eventTarget, eventArgument) { 
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) { 
    theForm.--EVENTTARGET.value = eventTarget; 
    theForm.--EVENTARGUMENT.value = eventArgument; 

    It will also add calling to javascript:--doPostBack(...) function to every control that requres automated postback. So, whenever a postback event happens on the page, the page will be submitted to the server via --doPostBack function. eventTarget and eventArgument parameters (i.e. --EVENTTARGET, --EVENTARGUMENT hidden fields) will identify control that fired the event and event arguments.

    On the server side ASP.NET will call appropriate event handler defined in the page class. The interesting part is that for events like OnSelectedIndexChanged, OnTextChanged etc. ASP.NET will also verify if control value actually changed. It will be done according to the following scenario:

    a . If old conrol state is available in ViewState, ASP.NET will compare the old value to the new value that came from control and will call event handler only if value is changed

    b . If old conrol state is not available in ViewState (e.g. ViewState is disabled), ASP.NET will compare default control value to the new value that came from control and will call event handler only if value is changed

    This causes some interesting behaviour. For example you have a TextBox control with OnTextChanged postback event defined and ViewState is enabled. Then if you get to the TextBox and press Enter with no text change it will postback the page, however OnTextChanged event handler will not be called on server side. This is due to the fact that actual value stayed unchanged.

    Another "unexpected" behaviour can be seen if ViewState is disabled. In this case (for example) if you change TextBox value to the default one and press enter then page will be posted back, however OnTextChanged event handler on server side will not called. This happens due to the point "b" described above.

    So, I believe I answered questions 2 and 3. As for question 1 the answer is "Yes". The page will still be reposted, however server side event handlers might not be called due to the point "b".

    There is a nice detailed explanation of how postback works in ASP.NET here.

    2. Why setting the property "Autopostback=true", will fire the Item Changed event for dropdownlist immeditely where as setting "Autopostback=false" will not fire the Item changed event for dropdownlist until the next time the page postback? How will handle this internally both scenario?

    Let's have a look what ASP.NET generates for:

    1. "Autopostback=true"

    <select name="ctl00$MainContent$DropDownList1" onchange="javascript:setTimeout('--doPostBack(\'ctl00$MainContent$DropDownList1\',\'\')', 0)" id="MainContent_DropDownList1"> ... <select>

    In this case as per my answer for the question 1 the page will be reposted immideately via --doPostBack function.

    1. "Autopostback=false"

    <select name="ctl00$MainContent$DropDownList1" id="MainContent_DropDownList1"> ... </select>

    In this case nothing happens on client side. However when page is reposted to the server ASP.NET will check if the value was changed according to scenario described in points a and b above and will call an event handler only in case if selection changed.

    It's actually interesting that in both cases if ViewState is disabled the change event handler will be called every time when page is reposted and selected item is different from a default one.

Previous 1 | 2 | 3 | 4 Next

Copyright © Rivera Informatic Private Ltd.