Wednesday, September 16, 2015

LINQ: Problem with Deferred execution

This morning I started my day googling for an exception in the code:
Some part of your SQL statement is nested too deeply. Rewrite the query or break it up into smaller queries
And as most cases, I ended up with a Stackover solution:


The code that I was cleaning up was as bellow:


This was breaking for large data but working fine for small data.

It was breaking when the Except() is used to compare large data – the reason is EF most cases does Deferred execution- so all the incompleteCourseId, completedCourseId and requeriedCourseId are evaluated when the Except() is called. For small data it can execute – but for large data it breaks.

Similar thing can happen when complex query needs to be executed through LINQ; So possibly its a good idea to split the queries into multiple ones and evaluate whenever required/whenever requires fetching large data.

So the solution is I forcefully evaluated each of the query using ToList() and it seems it is working good now. Off course cost is multiple SQL call.

Reference:
http://stackoverflow.com/questions/14163390/some-part-of-your-sql-statement-is-nested-too-deeply-rewrite-the-query-or-break


Monday, June 15, 2015

Passing EventArguments to RelayCommand in MVVM

I was to override the default behavior of the editable ComboBox control. Where if clicked the in the combobox the text will always be selected.

The View :
<ComboBox x:Name="cboList" FontSize="25"
     TabIndex="8" MaxDropDownHeight="270"
     Style="{DynamicResource ComboBoxStyleLargeScroll}"
     DisplayMemberPath="Name" SelectedValuePath="RepID"
     ItemsSource="{Binding VisitorHostList, UpdateSourceTrigger=PropertyChanged
   ,ValidatesOnExceptions=True, ValidatesOnDataErrors=True, NotifyOnValidationError=True}"
     SelectedItem="{Binding UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True, ValidatesOnDataErrors=True
   ,NotifyOnValidationError=True, Path=SelectedVisitorHost}"
     SelectedValue="{Binding Inductee.HostRepID, UpdateSourceTrigger=PropertyChanged
   ,ValidatesOnExceptions=True, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" IsEditable="True" VerticalContentAlignment="Bottom" MinWidth="0" MaxWidth="351">
                                    <ComboBox.Resources>
                                        <Style TargetType="{x:Type ScrollBar}">
                                            <Setter Property="Width" Value="50" />
                                        </Style>
                                    </ComboBox.Resources>
                                    <i:Interaction.Triggers>
                                        <i:EventTrigger EventName="GotFocus">
                                            <cmd:EventToCommand Command="{Binding GotFocusCommand, Mode=OneWay}" MustToggleIsEnabledValue="True"/>
                                        </i:EventTrigger>
                                        <i:EventTrigger EventName="PreviewMouseUp">
                                            <cmd:EventToCommand Command="{Binding PreviewMouseUpCommand, Mode=OneWay}" MustToggleIsEnabledValue="True" PassEventArgsToCommand="True" />
                                        </i:EventTrigger>

                                    </i:Interaction.Triggers>
                                </ComboBox>
The ViewModel :
#region Commands
  public ICommand PreviewMouseUpCommand { get; set; }
 #endregion
#region Constructor
        public MyViewModel()
        {
         
            PreviewMouseUpCommand = new RelayCommand<MouseButtonEventArgs>(PreviewMouseUp);
         
        }
#endregion
#region eventhandler
private void PreviewMouseUp(MouseButtonEventArgs e)
        {
            try
            {
                System.Windows.Controls.ComboBox cboHostList = e.Source as System.Windows.Controls.ComboBox;
                if (cboHostList != null)
                {
                    var cboEditableTextBox = (cboHostList.Template.FindName("PART_EditableTextBox", cboHostList) as System.Windows.Controls.TextBox);
                    if (cboEditableTextBox != null && !cboHostList.IsDropDownOpen)
                    {
                        Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            cboEditableTextBox.SelectAll();
                            cboEditableTextBox.Focus();
                        }));
                    }
                }
            }
            catch(Exception ex)
            {
                Util.Logger(typeof(MyViewModel)).Error("Error in PreviewMouseUp of ComboboxList", ex);
            }
        }
#endregion

Friday, May 22, 2015

Custom ActionFilter in ASP .Net MVC

I had a scenario like if a person doesn't have proper access to a resource he will receive a message on a page.
Initially I thought I should implement custom Authorization Filter [customize the existing Authorization Filter] - but it looked like Authorization filter is implemented [at least in my application] more like if the filter is not met you are redirected to login page - kind of session checking and stuffs like mandatory things for each of the Actions.
But in my case I was putting this check on a single Action - off course having option to reuse the filter later.
Following is the Controller with Filter:

[Authorize]
[PermittedSiteActionAttribute]
public ActionResult Siteinfo(int id = 0, string nodeType = "")
{
RASSiteDetailsModel model = null;
return View(model);
}

The  PermittedSiteActionAttribute lokked like :
public class PermittedSiteActionAttribute : FilterAttribute, IActionFilter
    {
        bool _IsAuthorised = false;
        void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
        {
            try
            {
                if (!_IsAuthorised)
                {
                    filterContext.Controller.ViewData.Model = null;
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Error in PermittedSiteActionAttribute>OnActionExecuted", ex);
            }
        }
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            try
            {
                var actionParams = filterContext.ActionParameters;
                object siteId;
                actionParams.TryGetValue("id", out siteId);
                if (siteId != null && decimal.Parse(siteId.ToString()) > 0)
                {
                    Util util = new Util();
                    _IsAuthorised = util.IsPermittedSite(decimal.Parse(siteId.ToString()));
                }
                if (!_IsAuthorised)
                {
                    filterContext.Controller.ViewBag.AuthorizationMessage = "You are not Authorised to access this resource; Please select a different site.";
                }
            }
            catch(Exception ex)
            {
                Logger.Error("Error in PermittedSiteActionAttribute>OnActionExecuting", ex);
            }
        }
    }
Here OnActionExecuting event I am checking the permission and if fails I am setting the Model to be Null at OnActionExecuted event - so that the user doesn't views the resource returned by the Action. May be not the perfect way of doing this - but a way around, I guess :)

To get started with these Asp .Net Action filters following tutorial is a good one:


Open source Push Server

  • PushSharp: [C#] :A server-side library for sending Push Notifications to iOS (iPhone/iPad APNS), OSX (APNS 10.8+) Android (C2DM and GCM - Google Cloud Message), Chrome (GCM) Windows Phone, Windows 8, Blackberry (PAP), and Amazon (ADM) devices!
  • PushSharp.Web: [C#] A web wrapper for PushSharp
  • AeoroGear UnifiedPushSeerver: [JAVA]: Easy and promising - does have a Openshift gear and can be tested over Openshift
  • Pushd:[Node.js] :Pushd is a pluggable "unified" push server for server-side notification to mobile native apps, web apps etc. With pushd you can send push notifications to any supported mobile platform, web app or HTTP server from a single entry point. Pushd takes care of which device is subscribed to which event and is designed to support an unlimited amount of subscribable events.
  • Loopback.io: [Node.js]: Loopback is basically a nodejs framework to easily create api - but it does have component to create push servers.
  • Node-Push-Server: [Node.js]: It looks like a stripped down version of Pushd.

Thursday, May 21, 2015

Logging in DotNet applications

  • log4net: log4net from Apache is a library tool to help the programmer output log statements to
    a variety of output targets. log4net is a port of the excellent Apache log4j™ framework to the Microsoft® .NET runtime. We have kept the framework similar in spirit to the original log4j while taking advantage of new features in the .NET runtime.
  • ELMAHELMAH (Error Logging Modules and Handlers) is an application-wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment.For asp.net applications to log without putting any code inside the applications

WCF vs Asp.Net Web API

When I first learnt about Web API, I got confused - as I was always doing the RESTful services using the WCF - why then another way to accomplish the same thing ?

WCF ASP.Net WEB API
  • Back-end Services
  • SOAP, WS-*
  • Transporst: HTTP, UDP, TCP, QUEUES, Custom
  • Message Patterns: request-response, one-way, duplex
  • Use WCF Web HTTP to add HTTP endpoints to existing WCF Services
  • Use WCF Data Services for full OData support
  • Front-end Services
  • Media Type: JSON, XML, form-URL-encoded, Custom
  • Request-reply only
  • REST, resource centric
  • Use SignalR for asynchronous signaling (polling, long-polling, WebSockets)

For further reference: