Thursday, March 23, 2017

Salesforce (SFDC) as an Identity Provider (Idp)

Started to implement SSO for one of my project without knowing anything.
Trying to note down to identify the bits and pieces here.
Steps followed :

  1. Set up a dev account with Salesforce. https://developer.salesforce.com/signup
  2. Playing with Salesforce how SAML based authentication works in there : https://developer.salesforce.com/docs/atlas.en-us.identityImplGuide.meta/identityImplGuide/identity_quickstart_SAMLgen.htm
  3. Set up a custom web application (SP-service provider) to work with Salesforce (Idp) : https://developer.salesforce.com/page/Configuring-SAML-SSO-to-Custom-.Net-Application
  4. Step 4 din cover how I can actually redirect to a particular page after successful login. Utilising the  RelayState parameter.

When sending Authentication request pass the RelayState parameter as below :
On AssertionConsumerServiceUrl check for the RelayState url parameter is passed back :

Issues I will be working on next are :
1. Registration - how it works from custom website
2. How it will works for manual approval for registered users.Any api or else ?
3. How the authentication works through this custom site wide - do I need to ping every time to Idp ?

Ultimate goal is to prepare a project template that can be reused.

Thursday, April 21, 2016

Opensource PDF generator : wkhtmltopdf

wkhtmltopdf and wkhtmltoimage are open source (LGPLv3) command line tools to render HTML into PDF and various image formats using the Qt WebKit rendering engine. These run entirely "headless" and do not require a display or display service.
There is also a C library, if you're into that kind of thing.
I am writhing this post just to keep record of what actually worked for me - the command I mean.

PATH_TO_wkhtmltopdf\bin\wkhtmltopdf --header-spacing 14 -T 22mm --header-html header.html cover cover.html toc --xsl-style-sheet toc-default.xsl article.html article_to_publish.pdf 
The command above prints a page as pdf with cover page, table of contents and header The TOC layout used is generated using a command as bellow:
PATH_TO_wkhtmltopdf\bin\wkhtmltopdf --dump-default-toc-xsl >> toc-default.xsl
Full document can be found here, which definitely I din find quite qood. 

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:

Friday, May 9, 2014

Opensource tools for Analyzing Website Traffic Stats

While developing reports fr one of my applications I have got some interest in data and analytic - while googling I have got some of the good works that are open sourced :) [There are always some good folks online :B] . I am listing couple of the tools here:


"Hummingbird lets you see how visitors are interacting with your website in real time."
Hummingbird is built on top of Node.js, and utilizes Websocket to provide 'Live' stats.
Platform : Node.js and javascript





Pikwik
"Piwik is the leading open source web analytics platform that gives you valuable insights into your website’s visitors, your marketing campaigns and much more, so you can optimize your strategy and online experience of your visitors."
Platform: PHP- MySql



For more of them check the list in the following link :

http://en.wikipedia.org/wiki/List_of_web_analytics_software