Tuesday, October 27, 2015

Get top 2 rows per group by

Given a Commissions table with a Commission (decimal) and an employeeID primary key columns,  list the top 2 commissions of each employee:

Best is to use a CTE with either the ROW_NUMBER() or RANK() partitions:

 ;With CTE_MyRank as (
SELECT [Commission]
      ,[EmployeeId]
      ,[CommissionID]
 , ROW_NUMBER() over (partition by employeeID order by commission desc) as Rankx
  FROM [Training].[dbo].[Commissions] 
  )

  select  EmployeeID, commission, Rankx from CTE_MyRank where rankx < 3 order  by [EmployeeId] desc, commission desc



OR the less favorite way is to use MAX , Group By and a UNION:

  Select  Max([Commission]) xMax, [EmployeeId] from [Training].[dbo].[Commissions]
   Group by [EmployeeId] 
  UNION
 Select Max(Commission) xMax, [EmployeeId] from [Training].[dbo].[Commissions] 
 where (Commission) not in (select Max([Commission]) from [Training].[dbo].[Commissions] 
 Group by [EmployeeId] )

Group by [EmployeeId] 
   order by [EmployeeId] desc, xMAx desc

Monday, October 19, 2015

Get the values of all fields/properties of a C# object using reflection

using System.Reflection;     


 private List GetPropertyList(object obj)
        {
            List propertyList = new List();

            Type type = obj.GetType();
            PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance |
                                                            BindingFlags.Public);
            foreach (PropertyInfo property in properties)
            {
                object o = property.GetValue(obj, null);
                propertyList.Add(o == null ? "" : o.ToString());
            }
            return propertyList;
        }

Link to one of the best bootstrap validators

http://1000hz.github.io/bootstrap-validator/

Also angular validations:

https://scotch.io/tutorials/angularjs-form-validation-with-ngmessages

Tuesday, September 15, 2015

Open modal is shifting fixed navbar to the right

Solution:

body.modal-open {
overflow-y: scroll;
padding-right: 0 !important;
}

Reference:
https://github.com/twbs/bootstrap/issues/14040

Friday, September 11, 2015

Copying long path names in Windows - robocopy to the rescue

To copy from long path names use the robocopy command provided in Windows 8.1:

For example to mirror a folder and its sub-folders issue:

robocopy Z:\Dev\GruntDemo C:\DevNew\GruntDemo /mir

Monday, September 7, 2015

CORS, access denied issue resolved in IE11


1) Remove both server and client from Trusted sites. This solved my problems:
http://devmohd.blogspot.com/2013/09/cross-domain.html

2) If using JQuery, optionally add this for older versions of IE

                jQuery.support.cors = true;

3) Optionally add this in angular config:
      $httpProvider.defaults.useXDomain = true;
      delete $httpProvider.defaults.headers.common['X-Requested-With'];

Saturday, September 5, 2015

Installing Grunt, Bower, Node.js, Ruby and Yoman

Installing Grunt, Bower, Node.js, Ruby and Yoman

Things you need

1. install NPM(https://nodejs.org/download/)

https://nodejs.org/download/release/latest/

Download and run the MSI:

node-v4.2.1-x64.msi 

After running msi you could check your installation on CMD prompt:
 node --version && npm --version

2. git (http://git-scm.com/download/win)
In git installation I (personally) selected:
- Use Git form Windows Command Line"
- Use Windws efault windows console


After installation you could verify the git version on CMD prompt:
git --version

3. Install ruby(http://rubyinstaller.org/)

During installation select "Add ruby executable to your path"


4) Yoman Angular generator

http://yeoman.io/codelab/setup.html

Run this:

npm install --global yo bower grunt-cli

To run AngularDemo-Master OR  the RPortal Application
(By now you should have cloned your project files from GIT into a local folder.)

1. Open a cmd prompt as admin and run the following commands in the root folder of your project (the root folder is the parent of the/app folder)

gem install ruby
gem install compass

2. Open cmd prompt as admin and run the following commands. Some of these take a long time - let them run until they return to the CMD prompt.

a. npm install
b. npm install bower
c. npm install --save-dev grunt-wiredep
d. bower install jQuery –save
(If it asks for version of angular then choose the highest version 1.4.7 for my case)
e. grunt wiredep
f. grunt serve


3. In the future in CMD prompt just type the below command from the root of your project (the root folder is the parent of the /app folder)  to bring up the localhost app:
grunt serve


Sunday, August 23, 2015

Partial page updates in MVC

In this article I will review 3 ways of rendering partial views:

1)  The most basic form is rendering static html using Html.RenderPartial.  For example below the content of StaticView.cshtml is rendered onto the page:

@{ Html.RenderPartial("StaticView"); }

2)  Another way is to use Html.RenderAction to render an action that returns a partial view. For example:
In .cshtml razor you may have:
@{Html.RenderAction("ShowPartialProduct", "Product");} 

and in the C# server side code you would have an action method:
        public PartialViewResult ShowPartialProduct()
        {
            _logger.Log("hello ShowPartialProduct");
           CompanyProduct prody = (CompanyProduct)  db.products.Take(1).ToList()[0];
            return PartialView("_PartialView", prody);
        }

Notice that the method returns the content of _PartialView.cshtml. So the content o the .cshtml gets rendered right away on the page that issues Html.RenderAction.


3) Another way is to use Ajax.ActionLink HTML helper. the content of the partial view will be displayed after a user clicks on an ajax enabled link.

But first, you need to install jquery unobtrusive ajax package. In the Nuget Package Manager Console issue:
Install-Package Microsoft.jQuery.Unobtrusive.Ajax


Then in your .cshtml (razor file) would be like the following:

@Ajax.ActionLink("New Products", 
                 "ShowPartialProduct", 
                 new AjaxOptions
                 {
                     UpdateTargetId = "CustomerList", 
                     InsertionMode = InsertionMode.Replace, 
                     HttpMethod = "GET" 
                 })



Your .cshtml file will contain an element such as a div that has the "CustomerList"target  id specified above:


You server side code should have an action method nmed "ShowPartialProduct" as specified above:

        public PartialViewResult ShowPartialProduct()
        {
            _logger.Log("hello ShowPartialProduct");
           CompanyProduct prody = (CompanyProduct)  db.products.Take(1).ToList()[0];
            return PartialView("_PartialView", prody);
        }


So when the user clicks on "New Products" the content of _PartialView.cshtml will be displayed.

Notice that a partial view is being returned. The _PartialView.cshtml should reside in the Views folder. It may be as follows:

@model AsyncWithScaffold.Models.CompanyProduct

@Html.LabelFor(model => model.Desc)
@Html.DisplayFor(model => model.Desc)

Live undefined after installing jquery.Unobtrusive.Ajax

If you install the old versions  of jquery.Unobtrusive.Ajax you may get a slew of error such as "live" undefined.

To resolve go to the you Nuget Package Manager Console (In Visual Studio: Tools -> Nuget  Package Manage -> Package Manager Console) and issue (or re-issue) the following command


 Install-Package Microsoft.jQuery.Unobtrusive.Ajax

   
Nuget will uninstall the faulty old package and install the corrected one:
Added package 'Microsoft.jQuery.Unobtrusive.Ajax.3.2.3' to 'packages.config'
    Successfully installed 'Microsoft.jQuery.Unobtrusive.Ajax 3.2.3' to AsyncWithScaffold
    Removing package 'Microsoft.jQuery.Unobtrusive.Ajax.2.0.20710' from folder 'C:\Training\SecurityWithEmail\packages'
    Removed package 'Microsoft.jQuery.Unobtrusive.Ajax.2.0.20710' from folder 'C:\Training\SecurityWithEmail\packages'


Of course if you have references to "live" in your Javascript code you need to resolve them manually.

Saturday, August 22, 2015

Rows were detected. The schema update is terminating because data loss might occur

When deploying an updated database you could encounter the following error:
"Rows were detected. The schema update is terminating because data loss might occur"

You could turn off the check for data loss as follows:

1) In the solution explorer, right click on you project and choose "Publish ..."
2) I the Publish dialog box choose "Advanced ..."
3) Uncheck "Block incremental deployment if data loss occurs"

Tuesday, August 11, 2015

wcf registration and activation alternative to aspnet_regiis -i on Windows 8 and Server 2012

http://stackoverflow.com/questions/11460142/cannot-serve-wcf-services-in-iis-on-windows-8

http://www.codeproject.com/Articles/167159/How-to-create-a-JSON-WCF-RESTful-Service-in-sec

Sunday, July 5, 2015

mvc

http://www.4guysfromrolla.com/articles/121510-1.aspx

https://msdn.microsoft.com/en-us/magazine/hh288075.aspx

illustrates output:
http://weblogs.asp.net/scottgu/linq-to-sql-part-6-retrieving-data-using-stored-procedures


 " alt="Discontinued" title="Discontinued" />

Tuesday, June 30, 2015

example conversion from json string passed to c#
Assume we have a class names Spec and and array of Specs is passed from javascript. Then convert as follows:


        [ValidateInput(false)]
        [HttpPost]
        public JsonResult UpdateSpecs(int SkuID, string Specs)
{

Spec[] args = (Spec[])JsonConvert.DeserializeObject(Specs);

}


The calling Javascript code was as follows:


        var dreq = $.ajax({
            url: "/Create/UpdateSpecs",
            cache: false,
            data: { "SkuID": PID, "Specs": JSON.stringify(aspecs)

            },
            type: "POST"
        });


Another One:

* Server-side:

       [ValidateInput(false)]
        [HttpPost]
        public JsonResult Create(string NewPriceAsJson)
        {
            NewPrice Depo = (NewPrice)JsonConvert.DeserializeObject(NewPriceAsJson);
            Depo.CommandName = CommandType.Insert;
            PriceBinder Binder = new PriceBinder();
            return Json(Binder.Create(Depo));
        }


         [ValidateInput(false)]
        [HttpPost]
        public JsonResult UpdatePPrice(string NewPriceAsJson)
        {
            NewPrice Depo = (NewPrice)JsonConvert.DeserializeObject(NewPriceAsJson);
            Depo.CommandName = CommandType.Edit;
            Depo.isDigital = false;
            PriceBinder Binder = new PriceBinder();
            return Json(Binder.Create(Depo)); // CommandType.Edit
        }

* Client-side:
    function pricePCreate(endPoint, price, fromd, tod) {
        showWait();
        var request = $.ajax({
            url: "/Price/" + endPoint,
            cache: false,
            data: {
                "NewPriceAsJson": JSON.stringify({
                    "PID": $("#PID").html(), "isDigital": false, "SiteDefID": $("#SelectedSite").val(),
                    "price": price, "effectiveFromDate": fromd, "effectiveToDate": tod, "ShippingClassID": $("#shipClassID").val(),
                    "ScheduledTaskSKUId": $("#speditID").html()
                })
            },
            type: "POST"
        });



* The Model:

    [Serializable]
    public enum CommandType
    {
        Insert=1,
        Edit=2
    }

    // passed from UI
    [Serializable]
    public class NewPrice
    {
        public int PID;
        public CommandType CommandName;
        public bool isDigital;
        public int SiteDefID;
        public int ShippingClassID;
        public string effectiveFromHour;
        public string effectiveFromMinute;
        public string effectiveToHour;
        public string effectiveToMinute;
        public DateTime effectiveFromDate;
        public DateTime effectiveToDate;
        public string price;
        public string publisher;
        public string revShare;
        public string msrp;
     

        public string DefaultPrice;
        public string DefaultPublisherPrice;
        public string DefaultMSRP;
        //public string txtRevenueShare;
       

       
       
        public string currency;
        public string headbandText;
        public string designText;
        public string description;
        public bool isonSale;

        public int ScheduledTaskSKUId;

        public string[] AuthFiles;
        public string AuthId;
        public string[] AuthGui;
     //   public bool sponsored;

       
    }

Sunday, May 24, 2015

Webapi issues on IIS


Ran into issues when WebApi app was deployed to IIS. For example got this error:
Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

To Resolve:

1) Need to register asp.net. But aspnet_regiis.exe -did not work on Windows 8.1

However, this worked:

If you're running into this error with Windows 8/Windows Server 2012 and .Net 4.5 follow these instructions here: http://www.britishdeveloper.co.uk/2013/01/handler-extensionlessurlhandler.html
Go to "turn Windows features on or off" Then Internet Information Services Then World Wide Web Services Then Application Development Features And then enable ASP.NET 4.5
http://www.britishdeveloper.co.uk/2013/01/handler-extensionlessurlhandler.html

2)
Also did this:

I also was getting the same problem but after brain storming with IIS and google for many hours . I found out the solution. This error is coming because some setting is disabled in IIS "applicationHost.config" Below are the steps to solution:
step 1: Go to C:\Windows\System32\inetsrv\config\applicationHost.config and open in notepad
step 2: change the follwing key value present in
a) 
change this value from "Deny" to "Allow"
b) 
 change this value from "Deny" to "Allow"
It worked for me.
Per this article:
http://stackoverflow.com/questions/20048486/http-error-500-19-and-error-code-0x80070021

Tuesday, May 12, 2015

Decorate Controller Actions with [ChildActionOnly]
/In the controller: [ChildActionOnly] [OutputCache(Duration=2000)] public ActionResult TagsForPost(int postId) { return View(); }

Notice the ChildActionOnly attribute. From MSDN:
Any method that is marked with ChildActionOnlyAttribute can be called only with the Action or RenderAction HTML extension methods.
This means people can’t see your child action by manipulating the URL (if you’re using the default route).