Showing posts with label Asp.Net and C#. Show all posts
Showing posts with label Asp.Net and C#. Show all posts

Wednesday, March 7, 2012

Why doesn't C# support multiple inheritance?

This answer is from Chris Brumme via the following post. I've copied the text in here in case the post disappears.
There are a number of reasons we don't implement Multiple Implementation Inheritance directly. (As you know, we support Multiple Interface Inheritance).
However, I should point out that it's possible for compilers to create MI for their types inside the CLR. There are a few rough edges if you go down this path: the result is unverifiable, there is no interop with other languages via the CLS, and in V1 and V1.1 you may run into deadlocks with the OS loader lock. (We're fixing that last problem, but the first two problems remain). The technique is to generate some VTables in RVA-based static fields. In order to deposit the addresses of managed methods (which probably haven't been JITted yet), you use the VTFixup construct. This construct is a table of triplets. The triplets consist of a token to a managed method, an address in your image that should be fixed up (in this case, a slot of the VTable you are creating in the RVA-based static), and some flags. The possible flags are described in corhdr.h and they allow you to specify 32- vs. 64-bit pointer sizes, control over virtual behavior, and whether some reverse-PInvoke behavior should be applied in the form of a thunk that eventually dispatches to the managed method. If we are performing an unmanaged->managed transition, you also have some control over which AppDomain should be selected for us to dispatch the call. However, one of these options (COR_VTABLE_FROM_UNMANAGED_RETAIN_APPDOMAIN) doesn't exist in V1. We added it in V1.1.
There are several reasons we haven't provided a baked-in, verifiable, CLS-compliant version of multiple implementation inheritance:
1. Different languages actually have different expectations for how MI works. For example, how conflicts are resolved and whether duplicate bases are merged or redundant. Before we can implement MI in the CLR, we have to do a survey of all the languages, figure out the common concepts, and decide how to express them in a language-neutral manner. We would also have to decide whether MI belongs in the CLS and what this would mean for languages that don't want this concept (presumably VB.NET, for example). Of course, that's the business we are in as a common language runtime, but we haven't got around to doing it for MI yet.
2. The number of places where MI is truly appropriate is actually quite small. In many cases, multiple interface inheritance can get the job done instead. In other cases, you may be able to use encapsulation and delegation. If we were to add a slightly different construct, like mixins, would that actually be more powerful?
3. Multiple implementation inheritance injects a lot of complexity into the implementation. This complexity impacts casting, layout, dispatch, field access, serialization, identity comparisons, verifiability, reflection, generics, and probably lots of other places.
It's not at all clear that this feature would pay for itself. It's something we are often asked about. It's something we haven't done due diligence on. But my gut tells me that, after we've done a deep examination, we'll still decide to leave the feature unimplemented.
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
Now come to the actual implementation part. 


What happens when we implement tow interfaces which are having same signature for a method? Most the developers think this will give compilation error. Some people would say, we should give the interface name as the prefix in the method signature while implementing in the class. 
First of all compiler will not give compilation error. And it is not necessary that you should give the interface name as the prefix. If you just use the same signature, compiler will understand that you are giving the implementation.
But if you give the interface name as the prefix, you cannot access the method directly. You should typecast the object as the interface type to use method.


If you see the following example, you can understand this. 


public class Emp : IA, IB
{
    //1. Either dont mention the interface
    public string methodA()
    {
        return "Class Emp's output";
    }
    string IA.methodA()
    {
        return "Interface IA's output";
    }
    string IB.methodA()
    {
        return "Interface IB's output";
    }
}

Now invoking code looks like

Emp emp = new Emp();
emp.methodA();
IA a = (IA)emp;
a.methodA();
IB b = (IB)emp;
b.methodA();

Now if you print the output of the three method calls you wiil get

Class Emp's output 
Interface IA's output 
Interface IB's output

Thursday, February 16, 2012

ASP.NET Response.Redirect to new window

Method1

You need to add the following to your server side link/button:

OnClientClick="aspnetForm.target ='_blank';"

My entire button code looks something like:

<asp:LinkButton ID="myButton" runat="server" Text="Click Me!" OnClick="myButton_Click" OnClientClick="aspnetForm.target ='_blank';"/>

Method 2


In the server side OnClick I do a Response.Redirect("MyPage.aspx"); and the page is opened in a new window.

The other part you need to add is to fix the form's target otherwise every link will open in a new window. To do so add the following in the header of your POPUP window.

<script type="text/javascript">
        function fixform() {
            if (opener.document.getElementById("aspnetForm").target != "_blank") return;

            opener.document.getElementById("aspnetForm").target = "";
            opener.document.getElementById("aspnetForm").action = opener.location.href;
            }
</script>

and

<body onload="fixform()">

Tuesday, November 15, 2011

Test If Date Ranges Overlap

Test If Date Ranges Overlap

A commonly-used idiom for determining if one range of dates overlaps with another range of dates

Problem: Given two date ranges, each with start and end dates (and possibly times), how do you determine if the ranges overlap?

Solution:

Testing the range "start1 to end1" against the range "start2 to end2" is done by testing if...

	( start1 <= end2 and start2 <= end1 )
If TRUE, then the ranges overlap.

If the ranges do not include the "end" value itself, then use "<" instead of "<=" in the comparisons.

Important Assumption:

This assumes that start date <= end date in each range. This can also be stated as...

	( start1 <= end1 and start2 <= end2 )
For discussion of what to do if this is not true, see below.

Applicability: Is not limited to date/time comparisons; can also be used for ranges of numbers, names, and any other data type where ranges are meaningful.

Alternate Expression:

	not (end1 < start2 or end2 < start1)



The expression in brackets is true when one range is entirely to the left or right of the other. This condition is pretty easy to visualize. The ranges overlap if and only if it is false.
Implementation: See MartinFowler's RangePattern for implementation details. http://www.martinfowler.com/ap2/range.html

[CategoryPattern]

 

Check the original post http://c2.com/cgi/wiki?TestIfDateRangesOverlap for more information

Friday, November 11, 2011

SecurityTrimmingEnabled Issue

We Faced a weird issue in our application today. We have a horizontal menu in the header portion of our application.

In development environment all menu items are getting rendered.

WithAllMenu

Some of the menu items refered the web links which links are part of another application.

But when we drop the executables to the QA environment, above mentioned menu items are not rendered.

WithoutAllMenu

The QA environment is SSL enabled application and the outside application is non-SSL enabled.

So we found that, when the Webmenu.Sitemap constructs the menu,
it does not show the non-SSL links when those links are invoked from SSL enabled.

We did not get any warning messages. After analyzed a lot, we understand that, we have to switch off the setting

SecurityTrimmingEnabled to false since we are not using windows accounts for roled based menu.

code

To know more about that visit the following links.

http://blogs.msdn.com/b/dannychen/archive/2006/03/16/553005.aspx

Tuesday, August 9, 2011

Identifying value changed controls while submitting

Most of the application developers face the common requirement of giving alert message or showing a popup when particular set of controls are

changed. Consider the following example.

 

Requirement: The alert message or a popup should be shown only when the Language, Timezone and Country controls are changed. If those controls are not

changed, just save the imformation submitted.

 

 

<table cellspacing="0" cellpadding="0" border="0">

        <tr>

            <td>

                <asp:Label ID="Label1" runat="server" Text="Language:" AssociatedControlID="LanguageDropDownList"

                    EnableViewState="False" />

            </td>

            <td>

                <asp:DropDownList ID="DropDownList1" runat="server" EnableViewState="False">

                </asp:DropDownList>

            </td>

        </tr>

        <tr>

            <td>

                <asp:Label ID="Label2" runat="server" Text="Timezone:" AssociatedControllID="TimeZonesDropDownList"

                    EnableViewState="False" />

            </td>

            <td>

                <asp:DropDownList ID="DropDownList2" runat="server" EnableViewState="False">

                </asp:DropDownList>

            </td>

        </tr>

        <tr>

            <td>

                <asp:Label ID="CountryLabel" runat="server" Text="Country:" EnableViewState="False" />

            </td>

            <td>

                <asp:TextBox ID="CountryTextBox" runat="server" Text="">

                </asp:TextBox>

            </td>

        </tr>

    </table>

    <table cellspacing="0" cellpadding="0" border="0">

        <tr>

            <td>

                <asp:Label ID="NameLabel" runat="server" Text="Name:" EnableViewState="False" />

            </td>

            <td>

                <asp:TextBox ID="NameTextBox" runat="server" Text="">

                </asp:TextBox>

            </td>

        </tr>

        <tr>

            <td>

                <asp:Label ID="RoleLabel" runat="server" Text="Role:" AssociatedControlID="RoleDropDownList"

                    EnableViewState="False" />

            </td>

            <td>

                <asp:DropDownList ID="RoleDropDownList" runat="server" EnableViewState="False">

                </asp:DropDownList>

            </td>

            <tr>

    </table>

 

 

Logic 1: Setting a flag when control value changed

 

1. To address this requirement, developers used the logic of setting a flag to true whenever any of the required controls is changed.

 

var isChanged = false;

 

function changeStatus()

{

      if(!isChanged) isChanged=true;

}

 

The javascript method changeStatus() will be called for Language, Timezone and Country controls. Based on the flag value, the decision of

showing the alert/popup or not is taken. This logic has some flaws. When the user changes the control value and immediately set back to the old

value, the flag is still set to true. The logic fails. Then we need to find out the solution for not setting true while the value is set back to old.

 

Logic 2: Compare the populated value and current value

 

There is another different  logic for the given requirement. On server side page_load (..) method, while populating the controls get the values of

required controls and store it in a hidden field.

 

if(!IsPostback)

{

      PopulateControls();

}

 

private populateControls()

{

..

..

 

    initialValueHiddenField.Value = LanguageDropDownList.SelectedValue + TimeZonesDropDownList.SelectedValue + CountryTextBox.Text;

}

 

 

At the time of submitting, on client side get the concatenated values and compare with the populated values to decide showing the popup.

 

function SubmitButtonClientClick()

{

      var actualValue = document.getElementById('LanguageDropDownList').options ......

                  + document.getElementById('TimezonDropDownList').options ......;

                  + document.getElementById('CountryTextBox').value;

 

      if(document.getElementById('initialValueHiddenField').value == actualValue)

      {

            return ShowPopup();

      }

}

 

Logic 3: Check the initial value and current value using JQuery

 

Set an Id attribute to the table where the required controls are there.

 

<table cellspacing="0" cellpadding="0" border="0" id="settingsTable">

 

Now the following client side methods should be written.

 

$(document).ready(function() {

      initialState = getState();

}

function getState()

        {

              var state = "";

              $('#settingstable input, #settingstable select).each( function() {

                      //for checkbox controls val() method always returns "on" irrespective of the checked/unchecked state.

                      //so get the checked/unchecked value only for checkboxes. For other controls, get the val()

                      if($(this).val()=="on"){

                          state += $(this).is(':checked');

                      }

                      else{

                          state += $(this).val();

                      }

              });

              return state;

        }

function SubmitButtonClientClick()

{

      if(initialState  == getState())

      {

            return ShowPopup();

      }

}

 

Since we did not use the ID property of the controls, when new controls are introduced, we should just add to the settingstable.

So this logic will be more effective. As we are using JQuery no need to worry about the browser compatibility.

Wednesday, June 29, 2011

An OLE DB Provider was not specified in the ConnectionString. An example would be, 'Provider=SQLOLEDB;'.


We are using typed dateset in DataAccess layer. I faced a weird issue while trying to add a new column with some of the datatables in the typed dataset for eg. USER table. But I can edit datatables of some other typed datasets which are also resides in the same location.

To add the column, I right-clicked on the DataTable. In the quick menu, i have selected the Add->columns. Entered new column name. When i pressed the save option in the Visual Studio, i got the following message.
"An OLE DB Provider was not specified in the ConnectionString.  An example would be, 'Provider=SQLOLEDB;'."

Finally. we resolved this issue by simply removing some annotaion tags in the dataset. Following are the steps to do that.

1. Open the typed dataset in Xml editor( Right click the *.axd file --> open with --> Xml Editor (default))
2. Find for <xs:annotation> tag.
3. Remove entire tag.(There will be some inner tags. if you want take a back up of those lines, do it)
4. Save the file.
5. Close the Xml view.
6. Once again open the typed dataset in the Dataset designer.
7. Try to add the columns.
Now you will be able to add/edit columns. I don't know what actually happens!!

Thursday, May 19, 2011

Different ways to create excel files

I Just analyzed the methodologies used to read/write excel files and listed the pros and cons below.

OpenXML (Office 2007 .XLSX)

Pros:

  • Reliable as this is a Microsoft’s product.
  • Native Excel format
  • Supports all Excel features
  • Do not require an install copy of Excel
  • Open XML SDK 2.o Productivity tool to generate code.

Cons:

  • Limited compatibility outside Excel 2007
  • Complicated unless you're using an expensive third party component

NPOI

Pros:

  • Easy to use and similar to existing SyncFusion code.
  • Do not require an install copy of Excel
  • Excel Chart, Pivot Table, Auto filter on columns, Insert images in header or footer are supported in NPOI 1.2.3 and later versions.
  • Supports Office Open Xml (OOXML) format also.(using ExcelPackage)

Cons:    

COM Interop

Pros:

  • Uses native Microsoft libraries
  • Read support for native documents

Cons:

  • Very slow
  • Dependency/version matching issues
  • Concurrency/data integrity issues for web use when reading
  • Scaling issues for web use (different from concurrency): need to create many instances of heavy Excel app on the server
  • Requires Windows

SpreadSheetML (open format XML)

Pros:

  • Supports most Excel features: formatting, styles, formulas’, multiple sheets per workbook
  • Excel does not need to be installed to use it
  • No third party libraries needed - just write out your xml
  • Documents can be opened by Excel XP/2003/2007

Cons:

  • Lack of good documentation
  • Not supported in older versions of Excel (pre-2000)
  • Write-only, in that once you open it and make changes from Excel it's converted to native Excel.
  • Apart from these, there are some more third party tools available.
  1. Spreadsheetgear http://www.spreadsheetgear.com (License required)

They are claiming that it is faster than Open XMl SDK 2.0.  We can find a testimonial from MSN project manager saying MSN is using spreadsheetgear in the home page.

  1. Aspose (http://www.aspose.com/categories/.net-components/aspose.total-for-.net/default.aspx)  (License required)
  2. MyXls -  http://sourceforge.net/projects/myxls/ (Freeware)

Monday, May 2, 2011

Nullable Types in C#

Nullable types are instances of the System.Nullable<T> struct.

In C# 2.0 and above, you can store null value in any of your datatypes. But the datatype is little bit different.

We know that bool type will hold either true or false. But nullable bool will allow you to assign null also.

Characteristics:

Value Type

Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)

Assign a value to a nullable type in the same way as for an ordinary value type, for example

         int? i = 10;

         double? d1 = 3.14;

         bool? flag = null;

         char? letter = 'a';

         int?[] arr = new int?[10];

 

GetValueOrDefault

Use the System.Nullable.GetValueOrDefault property to return either the assigned value, or the default value for the underlying type if the value is null, for example

int x? = 10;

int j = x.GetValueOrDefault();

HasValue & Value

Use the HasValue and Value read-only properties to test for null and retrieve the value, for example

if (x.HasValue) j = x.Value;

The HasValue property returns true if the variable contains a value, or false if it is null.

The Value property returns a value if one is assigned, otherwise a System.InvalidOperationException is thrown.

The default value for a nullable type variable sets HasValue to false. The Value is undefined.

Conversions

Explicit Conversions:

A nullable type can be cast to a regular type, either explicitly with a cast, or by using the Value property. For example:

         int? n = null;

 

         //int m1 = n;      // Will not compile.

         int m2 = (int)n;   // Compiles, but will create an exception if x is null.

         int m3 = n.Value;  // Compiles, but will create an exception if x is null.

 

Implicit Conversions:

The conversion from an ordinary type to a nullable type, is implicit.

         int? n2;

         n2 = 10;  // Implicit conversion.

Operators

The predefined unary and binary operators and any user-defined operators that exist for value types may also be used by nullable types.

         int? a = 10;

         int? b = null;

 

         a++;         // Increment by 1, now a is 11.

         a = a * 10;  // Multiply by 10, now a is 110.

         a = a + b;   // Add b, now a is null.

 

 

?? operator

Use the ?? operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type.

Example 1

         int? c = null;

         // d = c, unless c is null, in which case d = -1.

         int d = c ?? -1;

 

   Example 2

         int? e = null;

         int? f = null;

 

         // g = e or f, unless e and f are both null, in which case g = -1.

         int g = e ?? f ?? -1;

 

 

 Boxing Nullable Types

                Keep in mind that nullable types are value types and can hold null values whereas Reference types hold null value by default.

Objects based on nullable types are only boxed if the object is non-null. If HasValue is false, the object reference is assigned to null instead of boxing. For example:

bool? b = null;

      object o = b;

// Now o is null.

If the object is non-null -- if HasValue is true -- then boxing occurs, but only the underlying type that the nullable object is based on is boxed. Boxing a non-null nullable value type boxes the value type itself, not the System.Nullable<T> that wraps the value type. For example:

bool? b = false;

      int? i = 44;

      object bBoxed = b; // bBoxed contains a boxed bool.

      object iBoxed = i; // iBoxed contains a boxed int.

The two boxed objects are identical to those created by boxing non-nullable types. And, just like non-nullable boxed types, they can be unboxed into nullable types, as in the following example:

bool? b2 = (bool?)bBoxed;    

      int? i2 = (int?)iBoxed;

Identifying Nullable Types

We can identify the nullable types using the following methods.

         1. System.Type

         2. System.Reflection

        3. is operator

Using System. Type

We can use the C# typeof operator to create a Type object that represents a Nullable type:

         System.Type type = typeof(int?);

Using System.Reflection

You can also use the classes and methods of the System.Reflection namespace to generate Type objects that represent Nullable types.

 

int? i = 5;

Type t = i.GetType();

      Console.WriteLine(t.FullName); //"System.Int32"

The C# is operator also operates on a Nullable's underlying type. Therefore you cannot use is to determine whether a variable is a Nullable type.

  static void Main(string[] args)

        {

            int? i = 5;

            if (i is int) // true

            {

                //

            }

        }