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