Wednesday, October 31, 2012

Remove rows from Entity Framework dbSet based on a condition


Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/

The following extension method used to remove multiple rows (that satisfies a condition) from a dbSet:

using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;

public static class DbSetExtension
{
    public static void Remove<TEntity>(this DbSet<TEntity> dbSet,
             Expression<Func<TEntity, bool>> predicate) where TEntity: class
    {

       foreach (TEntity entity in dbSet.Where(predicate).ToList())
       {
           dbSet.Remove(entity);
       }
    }
}

For example, the extension method can be called as follows:


AppDbContext.ProductFeatures.Remove(prodFeature => prodFeature.ProductId == 1432);

The above method call removes all the rows with ProductId = 1432 from ProductFeatures DbSet.



Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com




Monday, October 29, 2012

Bind Enum constants to Dropdown control in ASP.NET


Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/



The following extension method is used to bind enumerated constants to any ListControls (DropdownList, ListBox etc) in ASP.NET:


using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.UI.WebControls;

public static class ListControlExtension{
    public static void BindEnum(this ListControl listControl,
                                Type enumType) 
        {
       string caption;
       string value;
       object[] objArray;

       foreach (var enumValue in Enum.GetValues(enumType))    
               {
           // Get the numeric value of enum member
                value ((int)enumValue).ToString(); 

           // Get the DisplayAttribute object of enum member
           objArray = enumType.GetField(enumValue.ToString())
                            .GetCustomAttributes(
typeof(DisplayAttribute),
                            false);            

         // If Display attribute is not specified
          if (objArray.Count() == 0) 
          {
             // just take the enum member text         
             caption = enumValue.ToString(); 

          }
          else         
          {
             // take the DisplayAttribute name of enum member
             caption = ((
DisplayAttribute)objArray.Single()).GetName();            
      }

          listControl.Items.Add(new ListItem(caption, value));
                      objArray =  null;
            }
       }
}

For example, the following Enum constant,

public enum EmploymentStatus{
    Active,
    Resigned,
    Retired,
    [
Display(Name = "Unpaid Long Leave")]
    LongLeave,
         [Display(Name = "Paid Long Leave")] 
    Sabbatical
}


can be bound to a Dropdown control as
     
        ddlDefectStatus.BindEnum(typeof(EmploymentStatus));


Note that the extension method binds the Display attribute's Name property value (if it is provided) to the list control.

The Display attribute is helpful when you want to show a  text other than the enum text. For example, 'Unpaid Long Leave' and 'Paid Long Leave' are shown in the list control instead of LongLeave and Sabbatical respectively.



Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Wednesday, October 24, 2012

Initialize Struct members with default values in C#

Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/

C# structs cannot have a default constructor. Writing a default parameter-less constructor would not compile, since there is one already predefined by the compiler.

For example, the following code would result in the compilation error, 'Structs cannot contain explicit parameterless constructors' :

public struct Employee
{
      public int EmpNo;
      public string LastName;
      public string FirstName;
      public DateTime HiredDate;
      public bool IsActive;

      public Employee()      {
                  EmpNo = 0;
        LastName= null;  
        FirstName=null;  
        HiredDate = new DateTime(1,1,1);        
        IsActive = false;      }
}

  The predefined constructor initializes all the members of the struct with its default values according to their types. For example, it initializes numeric types (int, long, float etc) to 0, bool types to false, reference types to null and datetime types to 1/1/0001 12:00:00 AM.

The struct variables are usually declared and used without the new operator since struct is a value type. For example:

public struct Employee
{
      public int EmpNo;
      public string LastName;
      public string FirstName;
      public DateTime HiredDate;
      public bool IsActive;}

Employee emp;
emp.EmpNo = 0;


But to initialize the members with the default values, call the predefined default constructor using the new operator as follows:

emp = new Employee();


The above code initailizes EmpNo to 0, LastName and FirstName to null, HiredDate to 1/1/0001 12:00:00 AM and IsActive to false

An another way to initializes the struct members to their default values, is to use default keyword as follows:

emp = default(Employee);



Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Tuesday, October 23, 2012

Create Custom Display Template for Boolean Datatype in ASP.NET MVC


Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://Xplore2WinSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/

The ASP.NET MVC's @Html.DisplayFor method by default displays a disabled checkbox for boolean values.
Inorder to display the text, 'Yes' or 'No' instead of a checkbox, create the custom display template for boolean types as follows:

1. Create a folder called DisplayTemplates under the folder,  ~/Views/Shared.
2. Create a file called Boolean.cshtml to have the following code:

@model System.Boolean?

@if (Model.HasValue)
{

      if (Model.Value)
      {
         <text> Yes </text>
      }

      else
      {
         <text> No </text>
      }
}

else
{
      <text> &nbsp; </text>

}


Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://Xplore2WinSqlServer.blogspot.com/

Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Wednesday, October 17, 2012

Clone Generic List in C# using an Extension method

Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/

See below the plain readable code for cloning a generic collection in C#:

namespace Org.Project.Common
{
  using System;
  using System.Collections.Generic;
   public static class CloneableExtension
   {
     public static IList<T> Clone<T>(this IList<T> list) where T : ICloneable
     {
        IList<T> clonedList;
        clonedList = new List<T>();
        foreach (T cloneable in list)
        {
          object clonedObj = cloneable.Clone();
          clonedList.Add((T)clonedObj);
        }
        return clonedList;

     }
  }
  
}

The method extends all collections that implements IList but returns instance of List always.
The objects of type T that the list consists of should implement ICloneable interface.

Here is another stylish implementation using LINQ:

namespace Org.Project.Common{
  using System;
  using System.Collections.Generic;
  using System.Linq;
  public static class CloneableExtension
  {
   public static IList<T> Clone<T>(this IList<T> list) where T : ICloneable
   {     return list.Select(item => (T)item.Clone()).ToList();    }
  }
}


Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Tuesday, October 16, 2012

Show Anchor as a Button using JQuery UI

Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/


1. Add reference to jQuery UI javascript file and CSS file along with JQuery javascript file:


<
script src="jquery-1.8.2.js" type="text/javascript"></script>

<
link href= "ui/1.9.0/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<
script src="ui/1.9.0/jquery-ui.js" type="text/javascript"></script>


Download the recent version of jQuery and jQuery UI javascript files and themes from here:

jQuery: http://jquery.com/download/
jQuery UI: http://jqueryui.com/download/


2. Add the following script block:



<
script type="text/javascript">
        $(function () {
          $("#lnkSave").button();
        });

</
script>

The above script would show the following anchor tag

<a id="lnkSave" > Save </a>

look like this button :


The color and font of the button is based on the theme downloaded.



3. Specify the parameter value to button() method in case an icon needs to be displayed along with  text:


<
script type="text/javascript">
 
$(function () {
          $("#lnkSave").button({ icons: { primary: 'ui-icon-check'} });
 });


</
script>

The above script would show the anchor as a button with a check mark icon:




Refer jquery-ui.css for the list of supported icons.

Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Saturday, October 13, 2012

Create Property Procedures quickly using Code Snippets in Visual Studio


Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://Xplore2WinSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/

The following predefined code snippets are available in Visual Studio for easy generation of a property inside the code window:

1. Type prop and press tab key twice to generate the following automatic property snippet:

public int MyProperty { get; set; }


2. Type propfull and press tab key twice to generate the following property code snippet with a private variable:

private int myVar;
 
public int MyProperty
{
       get { return myVar; }
       set { myVar = value; }
}



3. Type propg and press tab key twice to generate the following property code snippet with a public getter and private setter:

public int MyProperty { get; private set; }

Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://Xplore2WinSqlServer.blogspot.com/

 Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Friday, October 12, 2012

Create a Read-only Textbox using ASP.NET MVC Html Helper

Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/

The following razor code nugget creates a read only textbox with the Id, txtCity and the value, "Chennai" :

                 @Html.TextBox("txtCity", "Chennai", new { @readonly = "readonly" })

The nugget generates the following HTML:

                 <input id="txtCity" name="txtCity" readonly="readonly" type="text" value="Chennai" />

The following nugget is to create a read only textbox bound to the model property, City :

       @Html.TextBoxFor(model => model.City, new { @readonly = "readonly" })



Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/

Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com