Sunday, September 21, 2014

Error 25 The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'

I had a scenario where i needed to fetch Result Data from multiple tables on basis of some condition by applying joins between the tables using Entity Framework. I was using Linq queries as in EF linq query is faster than the normal string queries and stored procedures, but i was getting the exception.

Here is the query which i wrote:

I made the object of my EntitiesClass generated by EDM:


OLSContainer ols = new OLSContainer();
        var reSet = from l in ols.LEVEL_COURSE
                    join lp in ols.PACKAGES 
                    on new { l.course_ID, l.levelID } 
                    equals new { lp.course_ID, lp.level_ID }
                    select l; 
which i know was wrong and on this query i was getting this exception:

Error 25 The type of one of the expressions in the join clause is 
incorrect. Type inference failed in the call to 'Join'

The mistake i was making was pretty was pretty simple in this scenario i dont need the join because i was only selecting data from LEVEL_COURSE table which can be achieved by simple where clause in the current scenario like this:



OLSContainer ols = new OLSContainer();
        var reSet = (from l in ols.LEVEL_COURSE
                    from p in ols.PACKAGES
                    where l.course_ID == p.course_ID 
                    && l.levelID == p.level_ID 
                    &&    l.course_ID==courseID
                    select new { l.levelID, l.levelName }).Distinct();

This solved my problem and the exception that i was getting was due to column names were same. My  PACKAGES table and LEVEL_COURSE table both have column named course_ID which were of same datat type as well so it was confusing compiler to take which one, but at last i got working thing as i needed.


Reference Link:

http://stackoverflow.com/questions/14273879/error25the-type-of-one-of-the-expressions-in-the-join-clause-is-incorrect-typ/14290833#14290833

Sql NOT IN operator in LINQ query Entity Framework

Few days ago, i came across a scenario in which i needed to apply sql NOT IN operator in my project as LINQ Query, my project was in mvc and i used ADO.net Entity Data Model to interact with database.


Here is the sql query which i needed to convert to linq:


SELECT d.processid,d.name,t.test_name
FROM dc_tp_tprocess d
left outer join dc_tp_tprocedured pd on pd.processid=d.processid
left outer join dc_tp_test t on t.procedureid=pd.procedureid
where d.active='Y' and t.testid=1 
                   and d.processid not in (1,2,6,8,9,10)
order by t.testid,d.processid 


At last after posting my question on a forum i got an answer from some one and that was this:


int[] tmp=new int[]{1,2,6,8,9,10};

var query=from d in dc_tp_tprocess
          join pd in dc_tp_tprocedured on d.processid equals pd.processid 
         into leftGroup1
          from pd in leftGroup1.DefaultIfEmpty() 
          join t in dc_tp_test on pd.procedureid equals t.procedureid 
          into leftGroup2
          from t in leftGroup2.DefaultIfEmpty()
          orderby t.testid,d.processid
          where d.active=="Y" 
         && t.testid==1 
         && !tmp.Contains(d.processid)
          select new {d.processid,d.name,test_name=t==null?"":t.test_name}; 


The tmp is a temporary array taken from which i am checking that the processID coming in the current row not exists in that array then select row.

I hope it will help if you stuck or got same scenario and don't getting how to handle the situation -:).

Friday, September 12, 2014

How to Deserialize Xml using LINQ

Binding XML data to Model in C# MVCToday i saw a SO question where OP had xml in a string and OP wanted to deserialize to its specifc type using linq.

Here is the xml:


<people>  
            <person>
                <name>Mr Brown</name>
                <age>40</age>
                <hobby>
                    <title>Eating</title>
                    <description>eats a lot</description>
                </hobby>
                <hobby>
                    <title>Sleeping</title>
                    <description>sleeps a lot</description>
                </hobby>
            </person>
            <person>
                <name>Mr White</name>
                <age>40</age>
                <hobby>
                    <title>Skiing</title>
                    <description>more details on this</description>
                </hobby>
                <hobby>
                    <title>Football</title>
                    <description>watches football</description>
                </hobby>
            </person>
            </people>

First of all we need to create class type in which the data will be deserialized.We have main node people so our one class will be People with three properties Name,Age and Hobbies.As hobbies can be multiple of a person we will need a collection of hobbies and you can observe that from the xml as well that person have multiple hobbies and of course i also have many hobbies..:)


here it is:


public class People
        {
            public string Name { get; set; }
            public string Age { get; set; }
            public IList<Hobby> Hobbies { get; set; }
        }
        public class Hobby
        {
            public string Title { get; set; }
            public string Description { get; set; }
        }

First of all i will load the string xml in to XElement :


string xml = @"<people>  
            <person>
                <name>Mr Brown</name>
                <age>40</age>
                <hobby>
                    <title>Eating</title>
                    <description>eats a lot</description>
                </hobby>
                <hobby>
                    <title>Sleeping</title>
                    <description>sleeps a lot</description>
                </hobby>
            </person>
            <person>
                <name>Mr White</name>
                <age>40</age>
                <hobby>
                    <title>Skiing</title>
                    <description>more details on this</description>
                </hobby>
                <hobby>
                    <title>Football</title>
                    <description>watches football</description>
                </hobby>
            </person>
            </people>";

XElement element=XElement.Parse(xml);

Now we will write linq query to deserialize the xml. Here we go:


var person = from a in element.Descendants("person")
             select new People
             {
              Name = a.Element("name").Value,
              Age = a.Element("age").Value,
              Hobbies = a.Descendants("hobby")
                         .Select(x => new Hobby
                                 {
                                  Title = x.Element("title").Value,
                                  Description = x.Element("description").Value
                                 }).ToList()
                            };
  
foreach(var d in person)
{
  
  Console.WriteLine(String.Format("Name = {0}:Age={1}:Hobbies:{2}",d.Name,d.Age,d.Hobbies.Count()));
  
}

Here is theWorking Example on DOT NET FIDDLE of the code.


Cheers! Happy Coding.

Stackoverflow Reference Question:

Binding XML data to Model in C# MVC

Thursday, September 11, 2014

Javascript deep Copy Array (Clone Javascript array without reference)

Today i saw a SO question, in which the OP was asking about how to clone a javascript array in a variable so that it does not have reference tot the original array.


Here is the scenario:


var fruit = function (name){
    this.name = name;
}
var fruits = [];
fruits.push(new fruit('apple'));
fruits.push(new fruit('banana'));
fruits.push(new fruit('organge'));

var fruits2 = fruits;
fruits2.length = 0;

Now in the above when we assign fruits to fruits2, fruits2 actually has the reference of fruits, after that line if you see we are emptying the fruits2 array by setting its lenght to 0. But it will also make fruits array empty as well.


See here in the JSFiddle DEMO:

Now we have to make a way to do deep clone of array so that it not refers to original array, we can do it using slice() function of javascript.

Summary of slice():

The slice() method returns a shallow copy of a portion of an array into a new array object.

Description:

slice does not alter the original array, but returns a new "one level deep" copy that contains copies of the elements sliced from the original array. Elements of the original array are copied into the new array as follows:
  • For object references (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.
  • For strings and numbers (not String and Number objects), slice copies strings and numbers into the new array. Changes to the string or number in one array does not affect the other array.

EXAMPLE:




// Our good friend the citrus from fruits example
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);

// puts --> ['Orange','Lemon']

When we write slice(0)  , it returns the complete array shallow copy in return so our modified code will be:

 

var fruit = function (name){
    this.name = name;
}
var fruits = [];
fruits.push(new fruit('apple'));
fruits.push(new fruit('banana'));
fruits.push(new fruit('organge'));

var fruits2 = fruits.slice(0);
fruits2.length = 0;
console.log(fruits);

Here is the UPDATED FIDDLE  in which you can see it live working.

Evolution of C# Development from C# 1 to C# 4

Hi,


Today i started studying the book Jon Skeet's C# in Depth in which Jon Skeet explained all the key difference in how C# 1 was and how it has improved by evolving to c# 4 it is a very nice book and i would recommend every c# developer to read it once.

I came to know how c# 1 has evolved from beginning to now, and c# added features to ease the developers and make their life easier and easier.
 
So i will be sharing that how c# evolved from c# 1 to c# 4 and from a simply class i will tell the differences that came and how it's enhanced version by version to be more easy for developers.

C# 1:


First we will create a class of User that how it would be implemented in the C# 1:



public class User
{
  private string firstName;

  public string FirstName
  {
    get { return firstName; }
  }

  private string lastName;

  public string LastName
  {
    get { return lastName; }
  }

  private string gender;

  public string Gender
  {
    get { return gender; }
  }

  public User(string firstName, string lastName, string gender)
  {
    this.firstName = firstName;
    this.lastName = lastName;
    this.gender = gender;
  }

  public static ArrayList GetAllUsers()
  {
   ArrayList Users= new ArrayList();
   Users.Add(new User("Leo", "Messi", "Male"));
   Users.Add(new User("Maria", "Sharapova", "Female"));
   Users.Add(new User("Imran", "Khan", "Male"));
   Users.Add(new User("Christiano", "Ronaldo", "Male"));
   return Users;
  }

  public override string ToString()
  {
   return string.Format("{0}: {1} : {2}", firstName, lastName,gender);
  }
}

The above c# 1 code, and it is not any rocket science, all things are straight forward, we have created a class User with properties FirstName,LastName and Gender and created a static method which is returning hardcoded four users in ArrayList.


LIMITATIONS OF C# 1:

 

 According to book, there are three limitations in the above C# 1 code:

1) Array List has no compile-time information that what is exactly. If we try to put some other type of object in it, it will not give any compile time error, but on run-time it will surely bang the program flow.


2)We have provided public getters in the above code which means that if we want it setters also added that they had have to be public as well.

3)There is alot of fluff invloved in creating the properties and variables, which results in complicated code for a single task to encapsulate three string properties of the class.


To Be Continued...............................................................



Tuesday, September 9, 2014

Creating Custom Html Helper Extensions in asp.net mvc

Hi,

Today I will tell about how to write custom html helpers in asp.net mvc. I will show how to create custom html helper for ActionLink, normally we write Html.ActionLink(parameters) and it renders anchor tag in response as html on the page.

I had a requirement where I needed to check that if user is in specific role then link should render otherwise it will not render on page, so it is very akward to write if blocks in every view where I need to hide links on the basis of role so after researching a little, I came to know that we can write custom extensions according to the requirements.

So I wrote a custom helper that checked the role of the user and deciceds that it should render or not.

ActionLink method exisits inside LinkExtension class which is a static class, so we need to create a static class with name LinkExtensions:


public static class LinkExtensions
{
}

Now in it I will write one overload for my custom extension as I will utitlize that, we can create all overloads that are available for ActionLink same way we are creating this one but for this article I will just share one specific overload that I will be using:


namespace TestCustomHelper.Html
{

public static class LinkExtensions
{
public static MvcHtmlString ActionLinkAuthorized(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes, bool showActionLinkAsDisabled)
  {
     if (htmlHelper.ActionAuthorized(actionName, controllerName))
     {
       return htmlHelper.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributes);
     }
     return MvcHtmlString.Empty;
}

}

Here is the ActionAuthorized method which also an Action Extension, it returns bool value by checking that user is authorized to call this action of controller or not and on the basis of value returned by this method it decides weather render the actionlink or not:


namespace HealthAccessPoint.Extensions
{
    public static class ActionExtensions
    {
        public static bool ActionAuthorized(this HtmlHelper htmlHelper, string actionName, string controllerName)
        {
            ControllerBase controllerBase = string.IsNullOrEmpty(controllerName) ? htmlHelper.ViewContext.Controller : htmlHelper.GetControllerByName(controllerName);
            ControllerContext controllerContext = new ControllerContext(htmlHelper.ViewContext.RequestContext, controllerBase);
            ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerContext.Controller.GetType());
            ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);

            if (actionDescriptor == null)
                return false;

            FilterInfo filters = new FilterInfo(FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor));

            if (!htmlHelper.CheckAccessRight(actionName, controllerDescriptor.ControllerName))
            {
                return false;
            }

            return true;
        }
    }
}

Now in my View I will add its namespace and then use it:


@using TestCustomHelper.Html


@Html.ActionLinkAuthorized("Create New", "Create", new { org = ViewBag.OrgBranchID }, new { @id = "linkCreateEmployee" },true) 

Cheers! and Happy Coding

Friday, August 15, 2014

Count Occurence of Specific Day between two Dates in C#

Question:

I want to count occurrences, for each day of the week, between two given dates.
For example:
Between 20/07/2014 to 27/7/2014, an 8 day span, there were:
Sunday=2, monday=1, tuesday=1,...

Answer:


DateTime StartDate = DateTime.Now.AddDays(-14);
DateTime EndDate = DateTime.Now;
DayOfWeek day = DayOfWeek.Monday;

First get the all days between two dates:


List<DateTime> dates = Enumerable.Range(0, (int)((EndDate - StartDate).TotalDays) + 1)
                      .Select(n => StartDate.AddDays(n))
                      .ToList();

Now get Count on the base of day, currently it will get Count of Monday:


var MondayCount = dates.Count(x => x.DayOfWeek == day);

FIDDLE: 

https://dotnetfiddle.net/ZopkFY