Udemy

asp.net mvc Adding Custom direcotry for Views (asp.net mvc How to specify which folder the View pages reside in?)

Sunday, October 26, 2014 0 Comments A+ a-


Introduction :


In asp.net mvc by default when we create application, our Views reside in Views directory for our Controller actions. For Example, by default it create Home controller with Index action, and if we see in Solution Explorer in Views directory we can see directory Views -->> Home --> Index.cshtml  and we have its action like this:

 
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

and we have this action's Views in Views folder see the following screen :




Now by default it will first look for Index.cshtml file in Views/Home folder and it is unable to find it there then it will find in View/Shared folder, if it also not finds it there it will throw exception that view file is not found, here is the exception text which is thrown:


The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/Index.aspx
~/Views/Home/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Home/Index.cshtml
~/Views/Home/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml

 

See:


The same is the case for partial view when we call return PartialView() it first looks in the respective controller's Views/Home  directory in the case of HomeController and in case of failure it looks in the View/Shared folder.

Using Custom Directories:

Now what if i had make a separate directory for partial views in my Views folder and Shared folder like : 



Views/Home/Partials and Views/Shared/Partial then we have to tell the ViewEngine  to look in that directory as well by writing the following code in Gloabl.asax  file in  Application_Start event.

For Example i have this code and i am returning _LoginPartial.cshtml from Index action of HomeController , now what will happen it will look in View/Home directory first and in failure it will look in View/Shared , but this time i have my partial views in seperate directory named Partial for every controller and for shared as well, In this case HomeController partial views are in Views/Home/Partials  and in Views/Shared/Partials:


public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

In this case also i will get the same exception as Engine will not be able to find the View file _LoginPartial.cshtml.

The beauty of asp.net mvc framework is the  extensiblity which you can do according to your needs and business requirements, one of them is that  if you want your own directories structure for organizing your views you can register those directories with razor view engine, doing that will make your life easy as you will not have to specify fully qualified path of the view, as razor will know that it needs to look for the view in those directories as well which you have registered with it. 

So what we have to do is to register this directory pattern in the application so that every time call any View it should look in those direcotries as well in which we have placed the View files. So here is the code for that

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();

        RazorViewEngine razorEngine = ViewEngines.Engines.OfType<RazorViewEngine>().FirstOrDefault();
        if (razorEngine != null)
        {
            var newPartialViewFormats = new[] 
          { 
            "~/Views/{1}/Partials/{0}.cshtml",
            "~/Views/Shared/Partials/{0}.cshtml"
          };

            razorEngine.PartialViewLocationFormats = razorEngine.PartialViewLocationFormats.Union(newPartialViewFormats).ToArray();
        }
    }
}

Now whenever we will call return PartialView("SomeView") it will look in that Controller Views directory's subdirectiry named Partials as well and in case it not finds there it will look in both Views/Shared and Views/Shared/Partials.

Points of Interest:

We saw how we can include other directories as well to be looked when getting View.The same way you can register other directories or your own Custom directory structure if you need to, so doing this way you will not need to specify complete path for like return View("~/Views/Shared/Paritals/Index.cshtml") instead of that you can just write then return View() if you want to load Index View and your action name is also Index which is being called, or if you want some other view to be rendered or some other action is invoked and you want to return Index view then you can write now return View("Index")

Udemy

Application UI hangs on long running operation in C# WindowsForm and WPF (BackgroundWorker in C#)

Thursday, October 23, 2014 0 Comments A+ a-

Once i came across a scenario in a Windows Presentation Foundation where on click of a button i needed to call a Restful Service which returns JSON and then i needed to deserialize the JSON and do soemthing with that, but when i wrote the code in the button event, it worked successfully but one thing that i noted that unitl the all operation completes my button remains pressed and UI also not responsive , so after researching a little i came to know this:

When we have some long running code that can take much time than normal time we should execute in a background thread not on UI thread, becasue executing it in UI thread will make our application un responsive and user will get irritated, here is my code which was executing directly on UI thread in button event:



This worked fine but as it is executing all the code on UI thread the application becomes unresponsive and user has to wait for the process to complete which is not a good user experience in any software or web application, after a  little reasearch i came to know about BackgroundWorker class which executes the code in separate thread not in UI thread.

This is the first version in which it was all happening on the UI thread all was fine but my button state was in pressed state and UI blocked until the service call completed and GridView populated.


private void btnLookup_Clicked(object sender, RoutedEventArgs e)
{

    string url = "http://www.lyfechannel.com/channels/allscripts/allscripts_institutions.php?allscripts=XXXX&user=YYYY&password=ZZZZ";

    WebRequest request = WebRequest.Create(url);

    request.Timeout = 500000;

    WebResponse response = request.GetResponse();

    var reader = new StreamReader(response.GetResponseStream());

    string json = reader.ReadToEnd();

    var jsonAsCSharp = JsonConvert.DeserializeObject<JSONWrapper>(json);

    PatientGrid.DataSource = jsonAsCSharp.Patients;
}

Now i am showing the version in which i used BackgroundWorker class, First of all create BackgroudWorker instance assign its events:


private void MyMethodToCallExpansiveOperation()
{
    //Call method to show wait screen
    BackgroundWorker workertranaction = new BackgroundWorker();
    workertranaction.DoWork += new DoWorkEventHandler(workertranaction_DoWork);
    workertranaction.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
        workertranaction_RunWorkerCompleted);
    workertranaction.RunWorkerAsync();
}

Now write the expensive operation code in workertranaction_DoWork method:


private void workertranaction_DoWork(object sender, DoWorkEventArgs e)
{
    string url ="http://www.lyfechannel.com/channels/allscripts/allscripts_institutions.php?allscripts=XXXX&user=YYYY&password=ZZZZ";

    WebRequest request = WebRequest.Create(url);

    request.Timeout = 500000;

    WebResponse response = request.GetResponse();

    var reader = new StreamReader(response.GetResponseStream());

    string json = reader.ReadToEnd();

    var jsonAsCSharp = JsonConvert.DeserializeObject<JSONWrapper>(json);

    patients = jsonAsCSharp.Patients;
}


and in  workertranaction_RunWorkerCompleted  bind List of Patients with Grid, as Do_Work does not executes in UI thread so we cannot access them in this method:


private void workertranaction_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    PatientGrid.DataSource = patients;
}

Now on button click we need to just call MyMethodToCallExpansiveOperation method:


private void btnLookup_Clicked(object sender, RoutedEventArgs e)
{
    MyMethodToCallExpansiveOperation();
}
Udemy

difference between ~= and *= in jquery

Wednesday, October 15, 2014 0 Comments A+ a-

Few days back, i saw a SO question, that what is the difference between [attribute~=value] and [attribute*=value]?



*= is attributeContains selector , From jquery docs:
Selects elements that have the specified attribute with a value containing a given substring.
~= is attributeContainsWord selector , From jquery docs:
Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.


The attributeContains selector is for the string to be contained in the attribute value while attributeContainsWord selector is for string seperated with delimeted space. The official jquery examples clearly explain it.



Attribute Contains Selector [name*="value"]

HTML:

<input name="man-news">
<input name="milkman">
<input name="letterman2">
<input name="newmilk">
JQUERY:

$( "input[name*='man']" ).val( "has man in it!" );
OUTPUT:


Here is the fiddle demonstrating the Attribute Contains Selector [name*="value"] behavior

Attribute Contains Word Selector [name~="value"]

HTML:

<input name="man-news">
<input name="milk man">
<input name="letterman2">
<input name="newmilk">
JQUERY:


$( "input[name~='man']" ).val( "mr. man is in it!" );

OUTPUT:

Here is example demonstrating the behavior of  Attribute Contains Word Selector [name~="value"] 

Udemy

Deserializing JSON returned by Restful Service in C#

Saturday, September 27, 2014 0 Comments A+ a-

Nowa days Restful services are more used which mostly return xml or json as reponse. The advantage of restful services are platform independence, a service made restful can be accessed from any platform like Java, c#,php, ruby etc.


I have a service  at this url : http://www.lyfechannel.com/channels/allscripts/allscripts_institutions.php?allscripts=XXXX&user=YYYY&password=ZZZZ  which returns following json as response:


{
"connections":"72", 
"incomplete":"319", 
"qualified":"14", 
"loggedin":"Dr. Frederick Banting | One Medical | San Francisco, Embarcadero", 
"red": "40", 
"yellow": "12", 
"green": "20"
}

First of all we need to create a C# class for deserializing json  to that spcific type, the current json object is not very complex so we can easily write class against this json with properties but mostly we will not have json simple like this, so most of the time i use json2csharp.com to generate classes against the json returned by service.


Our class for this json will look like this:


public class JSONWrapper
{
   public string connections { get; set; }
   public string incomplete { get; set; }
   public string qualified { get; set; }
   public string loggedin { get; set; }
   public string red { get; set; }
   public string yellow { get; set; }
   public string green { get; set; }
}

For deserializing json we have a library available Newtonsoft JSON which we will use for deserializing json to specific type.

We can install it in our project by going to Nuget Package Manager Console in Tools of Visual Studio and writing this command on Nuget Package Manager Console:

PM> Install-Package Newtonsoft.Json 

 If you have dll downloaded on your system you can also add reference by going in to References and click Add Reference from context menu:


 After clicking Add Reference browse to the location where the dll is present and check it and click ok.



Now we will write the code to call the specific url and we will deserialize the returned response to the specific class.


Here we go:


using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;

class Program
{
   static void Main(string[] args)
   {
      try
      {
          string url = "http://www.lyfechannel.com/channels/allscripts/allscripts_institutions.php?allscripts=XXXX&user=YYYY&password=ZZZZ";

          WebRequest request = WebRequest.Create(url);

          request.Timeout = 500000;

          WebResponse response = request.GetResponse();

          var reader = new StreamReader(response.GetResponseStream());

          string json = reader.ReadToEnd();

          var jsonAsCSharp = JsonConvert.DeserializeObject<JSONWrapper>(json);

          Console.WriteLine(jsonAsCSharp);
       }

      catch (Exception e)
      {
         Console.WriteLine("Error Occured:"+e.Message);
      }
   }
}


Here is the  attached sample project console application

Udemy

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

Sunday, September 21, 2014 0 Comments A+ a-

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 
                    &amp;&amp; l.levelID == p.level_ID 
                    &amp;&amp;    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

Udemy

Sql NOT IN operator in LINQ query Entity Framework

Sunday, September 21, 2014 0 Comments A+ a-

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&nbsp;
         into leftGroup1
          from pd in leftGroup1.DefaultIfEmpty() 
          join t in dc_tp_test on pd.procedureid equals t.procedureid&nbsp;
          into leftGroup2
          from t in leftGroup2.DefaultIfEmpty()
          orderby t.testid,d.processid
          where d.active=="Y"&nbsp;
         &amp;&amp; t.testid==1&nbsp;
         &amp;&amp; !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 -:).
Udemy

How to Deserialize Xml using LINQ

Friday, September 12, 2014 0 Comments A+ a-

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

Udemy

Javascript deep Copy Array (Clone Javascript array without reference)

Thursday, September 11, 2014 0 Comments A+ a-

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.
Udemy

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

Thursday, September 11, 2014 0 Comments A+ a-

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...............................................................



Udemy

Creating Custom Html Helper Extensions in asp.net mvc

Tuesday, September 09, 2014 0 Comments A+ a-

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
Udemy

Count Occurence of Specific Day between two Dates in C#

Friday, August 15, 2014 0 Comments A+ a-

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 

Udemy

db exception was unhandled ( {"An error occurred while updating the entries. See the inner exception for details."} )

Friday, August 15, 2014 0 Comments A+ a-

Question:


I am getting this (dbexception unhandled by user code)
{"An error occurred while updating the entries. See the inner exception for details."}
System.Data.UpdateException
exception on
db.SaveChanges();
 

Answer:

Sometimes in Entity Framework we get weird exception while inserting,updating 
or deleting data but developers are unable to understand the exception it does 
not show details where is actually things messed up, so i am sharing a tip that 
always put the code of EF operation in try catch while inserting,updating or 
deleting like below, and log the exception details in a text file.



try
{
    // Your code...
    // Could also be before try if you know the exception occurs in SaveChanges

    db.SaveChanges();
}
    catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
    var outputLines = new List<string>();
    foreach (var eve in e.EntityValidationErrors)
    {
        outputLines.Add(string.Format(
            "{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:",
            DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
        foreach (var ve in eve.ValidationErrors)
        {
            outputLines.Add(string.Format(
                "- Property: \"{0}\", Error: \"{1}\"",
                ve.PropertyName, ve.ErrorMessage));
        }
    }
    System.IO.File.AppendAllLines(@"c:\temp\errors.txt", outputLines);

}
Udemy

Null-propagating operator / Null-Conditional Operator feature in C# 6.0

Saturday, August 09, 2014 0 Comments A+ a-

Hi,

I am telling today about  Null-propagating operator / Null-Conditional Operator ?. a new proposed feature in C# 6.0, it is a very nice feature what i think is because it makes things more simpler and one liner.

Suppose i have some class X and in which i have a property which is another class Y and then in Y and i have a property Z.

and if i am accessing somewhere in code i would have to check if X is not null then access Y and if Y is not null then access Z.

Normally we would do it this way:


if(X != null && X.Y != null)
{
   string value = X.Y.Z.ToString();
}



but now we have a very simpler solution for this:


string value = X?.Y?.Z;

and thats it, now this will make sure that X and Y are not null before getting the Z, it is now safe way to access the Z.

X?.Y?.Z means: 
  • first, check if X is not null, then check Y otherwise return null,
  • second, when X is not null then check Y, if it is not null then return Z otherwise return null.
The ultimate return value will be Z or null.

Without this operator if x is null, then accessing X.Y would raise a Null Reference Exception, the Null-Conditional operator helps to avoid explicitly checking for null.

It is a way to avoid Null Reference Exception.
Udemy

Asp.net mvc Check User is Logged In and authorized Before Access to Page

Saturday, August 02, 2014 0 Comments A+ a-

Hi,

today i am sharing that how you can implement something that needs to be executed before every action is called. In asp.net mvc every thing is action, so we have to check in web application if user is logged in or not to restrict the users to authenticate before they view or do some action.

i also came across this scenario where i needed to check that if user is logged in and also is user authorized to view this page, i implemented this using built- in feature of asp.net mvc which is CustomActionFilterAttribute.

 First of all we need to create class which inherits from ActionFilterAttribute class:

public class AuthorizationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        string actionName = filterContext.ActionDescriptor.ActionName;
        string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

        if (filterContext != null)
        {
            HttpSessionStateBase objHttpSessionStateBase = filterContext.HttpContext.Session;
            var userSession = objHttpSessionStateBase["userId"];
            if (((userSession == null) && (!objHttpSessionStateBase.IsNewSession)) || (objHttpSessionStateBase.IsNewSession))
            {
                objHttpSessionStateBase.RemoveAll();
                objHttpSessionStateBase.Clear();
                objHttpSessionStateBase.Abandon()
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                   filterContext.HttpContext.Response.StatusCode = 403;
                   filterContext.Result = new JsonResult { Data = "LogOut" };
                }
                else
                {
                   filterContext.Result = new RedirectResult("~/Home/Index");
                }

             }
             else
             {
                if (!CheckAccessRight(actionName, controllerName))
                {
                    string redirectUrl = string.Format("?returnUrl={0}", filterContext.HttpContext.Request.Url.PathAndQuery);
                    filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl + redirectUrl, true);
                }
                else
                {
                    base.OnActionExecuting(filterContext);
                }
             }
       }
   }
}

 

Explanation:

Whenever any action will be called which is decorated with AuthorizationAttribute, our overriden method of  OnActionExecuting will be called.

First of all we are getting the controller and action name which is being called from the ActionExecutingContext object as it holds the context of the call:

string actionName = filterContext.ActionDescriptor.ActionName;
string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

then i am getting the current Session and getting userId of current User which is stored in Session at the time of login:

HttpSessionStateBase objHttpSessionStateBase = filterContext.HttpContext.Session;
var userSession = objHttpSessionStateBase["userId"];

and after that i check that if  userId is null or the Session is new which means a new user has accessed the application, in that case clear all Session and abandon it::

objHttpSessionStateBase.RemoveAll();
objHttpSessionStateBase.Clear();
objHttpSessionStateBase.Abandon();

and redirect the user to login page, but before doing that we have two cases:

1) Normal Request
2)Ajax Request

So, we need to check that if it is a normal request simply redirect to login page, but if it is a ajax request then we will return json response that will tell at client side that it is not an authenticated request, and on client side after reading the response we can display user friendly message that "Please Login To Continue":

if (filterContext.HttpContext.Request.IsAjaxRequest())
{
     filterContext.HttpContext.Response.StatusCode = 403;
     filterContext.Result = new JsonResult { Data = "LogOut" };
}
else
{
     filterContext.Result = new RedirectResult("~/Home/Index");
}
To Be Continued.....................

Udemy

MyFamily For AllScripts

Monday, June 16, 2014 0 Comments A+ a-

This is my new free lance project in Windows Presentation Foundation using Restful Services. I am enjoying working in it.


Udemy

Pathway For AllScripts with New Look

Thursday, May 08, 2014 0 Comments A+ a-





Udemy

PathWay For AllScripts

Tuesday, February 11, 2014 1 Comments A+ a-

This is a Desktop Application developed in Windows Presentation Foundation  and by utilizing WCF Services. I have done this project as freelancer for a company who outsourced to me to do it. I am feeling very happy about it that i have successfully accomplished it.



After Clicking Patient Connect, this screen is displayed :










Cheers........:)
Udemy

Searchable Dropdown in Asp.net mvc 4

Saturday, January 04, 2014 0 Comments A+ a-


Today i am writing about how to implement searchable dropdown list in asp.net mvc 4. Actually i came across a scenario where the drop down elements were too large and its troublesome for user to find the option that user wants to select to i needed to add searching so that it becomes easy for user.


To Implement this i used a jquery library namely Jquery chosen you can find it by searching on google or can download from here,Its pretty simple actually you just need to include the jquery chosen js file and css file in your porject and after that one simple step to do and you are done.

You have to add css classattribute value  "chosen-select" in the dropdown select attribute.

For Example, Here is my dropdown html:

<select class="chosen-select" id="SubDepartmentsDDL" name="SubDepartmentsDDL">

  <option value="1">Hematology (2)</option>
  <option value="2">Clinical Chemistry (0)</option>
  <option value="3">Histopatholgy (0)</option>
  <option value="8">Molecular Lab (0)</option>
  <option value="9">General Radiology (0)</option>
  <option value="10">Ultrasound (0)</option>
  <option value="12">ECG (0)</option>
  <option selected="selected" value="13">Microbiology (0)</option>
  <option value="14">Blood Bank (0)</option>
  <option value="16">Special Chemistry (1)</option>
  <option value="18">Services (0)</option>
  <option value="19">International Send Outs - India (0)</option>
  <option value="20">National Send Outs (0)</option>
  <option value="21">Vaccination (0)</option>
  <option value="22">ABC (0)</option>

</select>




you will have to include the follwing js and css files you will find the downloaded jquery chosen folder:

<link href="/PulseBeta/css/chosen.css" rel="stylesheet" type="text/css">
<link href="/PulseBeta/css/prism.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="/PulseBeta/js/chosen.jquery.js"></script>
<script type="text/javascript" src="/PulseBeta/js/prism.js"></script>

Now in the page write this script and you are done:

<script type="text/javascript">

         var config = {
             '.chosen-select': {},
             '.chosen-select-deselect': { allow_single_deselect: true },
             '.chosen-select-no-single': { disable_search_threshold: 10 },
             '.chosen-select-no-results': { no_results_text: 'Oops, nothing found!' },
             '.chosen-select-width': { width: "95%"}//,
             //'.chosen-search': {disable_search: false}
         }
         for (var selector in config) {
             $(selector).chosen(config[selector]);
         }

</script>


Before this my dropdown like this:







and after applying chosen plugin the result is:





Cheers...