Thursday, December 17, 2015

What is interface in programming.



In real world, we see objects everywhere, and we interact with them by their interfaces.
For example: we start our computer by on/off button. Every computer has on/off button. User just find the on/off button and start it.  

Engineers make things, things has many complexities inside, engineers makes interface to simplify the complexities. So user can easily use those things.

Software engineers creates classes for objects, a class may have several methods, properties, events and other complexities. Software engineer provides an interface for this class, so the other software engineers can easily interact with this class by their interface.

Interface contains only signatures of methods, properties, events and indexers. Interface just a template, it does not contain definitions. Any class which implements the interface must implements the every method defined in the interface.

In real world almost every device has on/off button. So we design a simple interface for our device classes.

Interface contains only signature of methods.
Public interface IDevice{
            Public void toggleOnOff();
}

We have designed two different type of classes for our devices, both use same interface, both implements same methods but different definition as per device requirement.

Public class DesktopDevice:IDevice{
          Public void toggleOnOff(){
                        // just press the button.
                        // code.
              }
}

Public class SmartDevice:IDevice{
          Public void toggleOnOff(){
                        // press the button for 3 seconds
                        // code.
          }
} 

Usage for desktop devices.
IDevice dDevice = new DesktopDevice();
dDevice.toggleOnOff();

For Smart Devices.
IDevice sDevice = new SmartDevice();
sDevice.toggleOnOff();











Wednesday, December 9, 2015

Create custom filter in AngularJS.

AngularJS Filter is nothing but a function returns a function used as an expression by pipe sign "|"; 
AngularJS provides some built-in filters such as  
- currency
- lowercase
- orderBy

and many others but you can create your own, if you need!   
Filters are simply takes an input and parameters, you process it and return the output.

How do you create your own custom filter? 


Here is a simple example.   

//.js 

var app = angular.module("myApp",[]);
app.filter("truncateString",function( ){
        return function(input, limit){
          limit = parseInt(limit);
           return (input.length > limit)?input.substring(0,limit):input;
    }
}); 

// usage in html.  
<span ng-bind="data.description | truncateString:'30'">,</span>


- truncateString filter will define limit to the text by parameter. 


   

Monday, November 23, 2015

ng-model is not working in ng-include in AngularJs

i have split my layout and used ng-include and noticed that my scope is suddenly stop working in ng-include!, to overcome this problem i used $parent  like this. 

<input type=text ng-model="$parent.Contact.EmailAddress" />

It works great!

Find Volume

Volume is the amount of 3-dimensional space an object occupies.

             5in

   +--------+
  /        /|
 /        / |  5in
+--------+  |
|        |  |
|        |  +
|        | /
|        |/  5in 
+--------+



formula:
Length x Width x Height = Volume
5x5x5 = 125
Capacity of containing 125 object of cubic in. 

Tuesday, November 17, 2015

CSS background Stretch

Set the background-size property to the element. 
 
body {
    background-size: 100% auto; 

}

Sunday, November 15, 2015

Asp.net MVC - Application Architecture


Don't directly call your database in controller.

In your Asp.net MVC Application, you should not place your database logic inside your controller actions. Mixing your database and controller logic makes your application more difficult to maintain over time. It is recommended that you place your database logic in separate repository layer.

Don't directly call your repository in controller. 

You should create another separate layer called service layer or business logic layer, and put your application business logic. roles and validations. Service layer communicates with the repository layer, process the data into information and pass it the controller.

Don't coupled your service layer with controller.

You should isolate your service layer with controller. Service layer must be in-depended, means it should not depended on the plate-form depended objects. So any application can use it without worrying about frame-work version and plate-form.
for example: The service layer should be able to use in WinForms , WebForms , WPF or Asp.net MVC Applications.

Don't put your UI Logic in controller.

UI may have some kind of logic, such as, display the user panel if the user is logged In, show/hide buttons, show the publish button if the publisher is logged in and so on. This logic may have several conditions, functions and properties, We should avoid to put the UI logic directly in our controller because controller is not responsible for handling the logic, but the application flow.
Mixing your application flow and UI/Business logic makes more difficult to maintain your application. We should separate our UI Logic in form of view models, and view models should be called by controller.
Controller is responsible for taking the input from user and pass it to the view models, view model take the input from controller, apply some UI logic if needed, and pass it to he service layer, service layer process it and pass it to repository, and repository is responsible for manipulate the database. 



Friday, November 13, 2015

Posting JSON data to WebAPI Always Null

I was playing with the JQuery and WebAPI and posting some data in JSON format to the Action.
In the Post Action of WebApi Controller [FormBody] Attributes catches the data, and we cast it in our respective type. I felt that send data in  JSON / JSON.stringify() so i must be cast in String type. but i get my data always null?

After several tries i changed the string type to dynamic and it solved my problem! :) 

public void Post([FromBody]dynamic value)
{
}


Uncaught Error: [$injector:modulerr] AngularJS Error in console - Google Chrome.

While using routing in AngularJS, sometime we face this error in our console. 
 Uncaught Error: [$injector:modulerr]

The problem was caused by missing inclusion of ngRoute module. 

Reference this link to your page may solve this problem. 

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>

Wednesday, November 11, 2015

SignalR - Simple Implementation.

SignalR is an API Provided by Asp.net used in web applications to build real time push functionalities and "Push" content to the connected clients.

It's very simple and easy to install SignalR in your application by visual studio 2012.

 1: Go to the Visual Studio Tools > NuGet Package Manager > Manage NuGet Package for Solution.

 2: Type SignalR in Search Filed.

 

After installation, you will get these libraries in your Scripts folder.


3: Reference the jQuery library in your webpage.

    <script src="Scripts/jquery-1.6.4.min.js" ></script>
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.1.0.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>

4: Create a C# Class and inherits with Hub Class.

// Server Code.
public class MessageHub : Hub
{
    public void Send(string name, string message)
    {
           Clients.All.broadcastMessage(name, message);
    }
}

Here we have two methods. One is "Send" and other is Client.All.broadcastMessage();
"Send" Method is defined on the Server and will be consumed by client. and broadcastMessage Method will be defined on the client. when the client call the Send Method broadcastMessage will be invoked on the every connected clients.

5: Initialize MessageHub Class on Client.

// Client code.

<script>

var chat = $.connection.messageHub;
chat.client.broadcastMessage = function (name, message) {
              alert(name + " Said: " + message );
     };

  $.connection.hub.start().done(function () {
    $("#btn" ).click(fucntion(){
           chat.server.send("Zeeshan", "Hello All");
    });
    });

</script>

First line; creates a reference of a server MessageHub.cs Class. Make sure it must be in camel case means first latter must be small.

Second line; declares a function on the client which will be invoked by the "Send" Method declared on the Server.

When ever a user visits a webpage which is implemented with SignalR.
 $.connection.hub.start().done(function(){})  event automatically fires and indicate that a new connection is stared.
It takes a function as a parameter in done() function and enable us to call server methods inside it. "Server method must be in camel case on client."

When user will press the button "#btn", the name and message will be broadcast to the all connected users.


This the very simple example, use this code in your own manner.

Tuesday, November 10, 2015

Recursion Algorithm

In computer science, Recursion is a function that calls itself. 

Recursive function has two main points. one is the stopping point and 
second is calling itself until problem is solved.   

This is the most common example of returning a factorial of given input parameter 
by recursive function.



int factorial(int n) {
   if (n == 0)
      return 1;
   else
      return (n * factorial(n-1));
}
 

Thursday, October 29, 2015

What is JSON?

JSON

- JSON stands for Javascript Object Notation.
- It's a message format, used for interchanging data.
- JSON is based on the Javascript.
- JSON is lightweight than XML and modern webservices use JSON to exchange data.
- JSON can store data in Name/Value pairs and Ordered List.

Here is a simple example of JSON. 

{"employees":[
    {"firstName":"John""lastName":"Doe"},
    {"firstName":"Anna""lastName":"Smith"},
    {"firstName":"Peter""lastName":"Jones"}
]}


Monday, October 26, 2015

Advantages of using Stored Procedures.

1. They help in reducing the network traffic and latency which in turn boosts application performance. 
2. They help in promoting code reuse. 
3. They provide better security to data. 
4.  It is possible to encapsulate the logic using stored procedures. This allows to change stored procedure code without affecting clients. 
5.  It is possible to reuse stored procedure execution plans, which are cached in SQL Server's memory. This reduces server overhead.

Thursday, October 22, 2015

How to prevent partial page to access directly in asp.net MVC.

Use the ChildActionOnly Attribute on Action of your Controller. 
For example:

        [HttpGet]
        [ChildActionOnly]
        public ActionResult GetProductList() {
            var vm = new ViewModels.EntryListViewModel(Models.UIdentity.Id);
            return View(vm);
        }

ASP.NET MVC DisplayFor Html Helper Set Default Value

Use use DisplayFor Html Helper for displaying our model text in to razor view. It is actually render Span <span> tag in our html document. Sometime our Model returns null values and we required to display the text over null value like this. "Null" , "N/A" ,"$0.00" and so on...
Here is the simplest solution.

In your Model Class (C#). 


Import the namespace:
using System.ComponentModel.DataAnnotations;

Decorate the your property. 

[DisplayFormat(NullDisplayText="N/A")]
public string LabelText { get; set; }

Thats it!. 

Tuesday, October 20, 2015

Remove dash from GUID in C#

C# 
Guid.NewGuid().ToString("N");

Difference between encoding and Encryption


Encoding: transforms data into another format using a scheme that is publicly available so that it can easily be reversed and can be transmitted without danger over a communication channel or stored without danger on a storage medium. 
Algorithms Used in Encoding: ASCII, Unicode, URL Encoding, Base64. 
Example: Binary data being sent over email, or viewing special characters on a web page.

Encryption: transforms data into another format in such a way that only specific individual(s) can reverse the transformation.
Encryption method uses secret keys : the algorithm is well-known, but the encryption and decryption process requires having the same key for both operations, and the key is then kept secret.
Algorithms Used in Encryption: AES, Blowfish, RSA ...  
Example: Sending someone a secret letter that only they should be able to read, or securely sending a password over the Internet.

Monday, October 19, 2015

C#: Converting Object in to JSON

This is not the single way to serializing object into JSON, but the simple way is to do that. 

1. Download the Newtonsoft JSON serializer. 
2. Reference the DLL. 
3. Using the namespace in your class. 


C# Code. 


namespace:

using Newtonsoft.Json;


 public string GetData(string name)
        {
            person p = new person();
            p.name = name;
            return JsonConvert.SerializeObject(p);
        }
    }

Friday, October 16, 2015

WPF: Set Startup Window.

You can set your Startup page by setting StartupUri="MainWindow.xaml"  in App.xaml file. 
<Application x:Class="MyApp.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MyWindow.xaml">
    <Application.Resources>
   
    </Application.Resources>

</Application>