Friday, March 23, 2018

Sql Server: Get count of * or distinct rows for column A grouped by column B

Scenario 1 - count of * rows:

A table has 10 records. Column B has duplicate rows with different values in Column A

then., Sql Query:


Code Snippet:
SELECT COUNT(ColumnA) AS Count_Headertext,
ColumnB AS ColumnB_Headertext
FROM Tablename
GROUP BY ColumnB



Scenario 2 - count of distinct rows:

A table has 10 records. Column B has duplicate rows with different values in Column A

then., Sql Query:


Code Snippet:
SELECT COUNT(DISTINCT ColumnA) AS Count_Headertext,
ColumnB AS ColumnB_Headertext
FROM Tablename
GROUP BY ColumnB



Tuesday, March 20, 2018

Field and Property in C#

Object orientated programming principles say that the internal workings of a class should be hidden from the outside world. If you expose a field you're in essence exposing the internal implementation of the class. So we wrap the field using the property to hide the internal working of the class.

We can see that in the above code section we define property as public and field as private, so user can only access the property but internally we are using the field, such that provides a level of abstraction and hides the field from user access.

Another  important difference is that interfaces can have properties but not fields.

Using property we can throw an event but this is not possible in field.

A private field that stores the data exposed by a public property is called a backing store or backing field.

Code Snippet:

        public class Career
        {
            // field
            private int _path; 

            // Path is Property
            public int Path
            {
                get
                {
                    return _path;
                }
                set
                {
                    _path = value;
                }
            }
        }

Friday, July 28, 2017

Unable to find the service reference in Portable class library / Also unable to update service reference in Portable Class Library

Unable to find the service reference in Portable class library / Also unable to update service reference in Portable Class Library


I have created a portable class library for my cross platform application. However my plan is to consume the WCF methods for the data access.

Now the issue is...........

When I am trying to add the service reference in the portable class library - I don't see any provision to do it.

Here is the quick solution I figured out!...


Step 1:

Go to the application (ClassLibrary) properties and uncheck the Windows Phone 8.1 and uncheck the ASP.NET Core 1.0 and check the Silverlight (This is a temporary stuff until you will be able to see the provision to add service reference.)



Step 2:

Now you could see the Add service reference. So, create the service reference by entering the Url, give a meaning full name for service reference. Click ok

Step 3:

Rename Packages.config to Packages.config.bak - We are doing this to temporarily remove the package references.

Step 4:

Now revert back the changes in the 'Change Targets' window (displayed image above).

Step 5:

Revert back the file name for Packages.config.bak to Packages.config. Finally build the project without any errors.

If still errors exist comment on the post for quick answers.


Monday, May 16, 2016

Exception handling in ASP.NET MVC

ASP.NET MVC 4

By default in asp.net MVC the exceptions are handled by the controller if you enable the customErrors in web.config. The error.cshtml in shared folder is called when ever there is an exception in actionMethod.

<system.web>
    <customErrors mode="On">
    </customErrors>
</system.web>

However if you need custom errors of you choice, then you need to use the HandleError attribute.


 [HandleError( View = "PageNotFound")]



In the below snippet, the result due to 1/0, raises the arthimetic exception then calls the ArthimeticExeView by the HandleError attribute

Code Snippet:
HomeController:

[HandleError(ExceptionType = typeof(ArithmeticException), View = "ArthimeticExeView")]
        public ActionResult TestHandleError()
        {
            var a = 1;
            var b = 0;
            var result = a / b;
            return View();
        }


ArthimeticExeView.cshtml:


<h1>Attempted to divide by zero.</h1>





The above method has a drawback of re-usability. Because it has a view name(ArthimeticExeView) that contains the message for arithmetic exception In order to keep a common view for all exceptions, then we need to pass the exception message using the custom error handling attribute. 

In CustomErrHandler we override the onException method and returns the exception message to view model.

Code Snippet:
HomeController:

             [CustomErrHandler]
        public ActionResult TestHandleError2()
        {
            var a = 1;
            var b = 0;
            var result = a / b;
            return View();
        }



CustomErrHandler.cs:


    public class CustomErrHandler : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            Exception ex = filterContext.Exception;
            filterContext.ExceptionHandled = true;
            var model = new HandleErrorInfo(filterContext.Exception, "Controller", "Action");

            filterContext.Result = new ViewResult()
            {
                ViewName = "Error1",
                ViewData = new ViewDataDictionary(model)
            };
        }
    }


Error1.cshtml:


@model System.Web.Mvc.HandleErrorInfo

@{
    ViewBag.Title = "Error";
}

<h1>@ViewData.Model.Exception.Message</h1>



In MVC the views that are not called by the specific controller ActionMethod

Below are the ways, the views are not called by the controller actionMethod.

Method 1: Having the common folder called shared. Views in shared folder donot require a controller actionMethod. When ever an action method executes and returns a view that is not located in its path. Then it will check the shared folder by that view name.

Ex: return view("NoData")

Here the NoData is searched in shared folder if is not located in the views folder corresponding to that controller.

Method 2: If there are 100 views with some static data, then does it make sense in creating 100 actionMethods in controller. Obviously no, in such a case, the MVC framework helps us with the method HandleUnknownAction that executes whenever an attempt to invoke the action method that doesnot exist.


        protected override void HandleUnknownAction(string actionName)
        {
            try
            {
                this.View(actionName).ExecuteResult(this.ControllerContext);
            }
            catch(Exception ex)
            {
                Response.Redirect("PageNotFound");
            }
        }

Code Snippet:
    public class HomeController : Controller
    {
        protected override void HandleUnknownAction(string                                                                  actionName)
        {
            try
            {                                           this.View(actionName).ExecuteResult(this.ControllerContext);

            }
            catch(Exception ex)
            {
                Response.Redirect("PageNotFound");
            }
        }

        public ActionResult Index()
        {
            return View();
        }       

    }

Sunday, October 4, 2015

Consuming SOAP WebService - Ways to create Proxy

Code Snippet:

Web reference or Service reference.

In service reference we use the CalculatorSoapClient (Click on the service reference to view the interface & SOAP implementation classesclass to create the object.
In Web reference (add service reference --> advanced  --> Then you get the web reference option) we use the Calculator i.e the asmx service name to create the object.
webserferenceCal.Calculator ww = new webserferenceCal.Calculator();
Label1.Text = Convert.ToString(ww.add(10,10));

ServiceReferenceCal.CalculatorSoapClient bb = new ServiceReferenceCal.CalculatorSoapClient();
Label2.Text = Convert.ToString(bb.add(11, 12));


Friday, July 10, 2015

Using $timeout in AngularJS developed - Kids Alphabets Tutor

Previously we posted an article for Kids Alphabets Tutor in AngularJS and here is another way using $timeout function.

Code Snippet:
<html>
<head>
    <title>Angular.js Example</title>
    <script src="Scripts/angular.js"></script>
    <script>
        var nameApp = angular.module('NameApp', []);
        nameApp.controller('NameCtrl'function ($scope, $timeout) {
            // I initialized only till alphabet 'H'.. Add more if you are topper in LKG.
            $scope.letters = ['A-Apple''B-Ball''C-Cat''D-Dog''E-Elephant''F-Frog''G-Girafee''H-Horse'];
            var i = 0, lengthSize = $scope.letters.length;
            var testname = function () {
                $scope.test = $scope.letters[i];
                if (i < lengthSize - 1)
                    i = i + 1;
                else
                    i = 0;
                $timeout(testname, 2000);
            }
            $timeout(testname, 2000);
        });
    </script>
</head>
<body ng-app="NameApp" ng-controller="NameCtrl">
    <center>
        <h1>
            Kids Alphabet Tutor<br /><br />
            {{test}}
            <img src="Images/{{test}}.PNG" width="75px" height="75px" />
        </h1>
    </center>
</body>
</html>

Points to Note: 

  • Image file Name should be the array element names initialized in the $scope.letters.
  • Below is the folder structure:











This is how it looks: