tabs

Thursday, October 31, 2013

Value Types and Reference Types in .Net

What is a Data Type?

Data Types in the programming scenario are the categorized sections,which are based on the type of data stored in them.Generally different types of data are stored in different memory with different structures such as stack or heap memories.
Some data types holds its data within its own memory allocation and some store only the address of the data[Data is present at some other location].So Data Types are categorized based on the way how they store their values .

Categories of Data Types
Generally we come across many data types in our programming journey like int, char, float,object etc. But to be clear all the Data Types are classified into two sections , they are:
  1. Value Type
  2. Reference Type
Let us discuss them in detail:

Value Type:
  • The Data Types which store their values directly in their stack memory are known as Value Types.
  • Among the built-in Data Types ,except 'String' and 'Object' all other data types are considered value types
  • Among user defined data types 'structure' and 'enum' are taken as value types.
  • Examples: All numeric data types, char bool, date, structures and enum etc.

Reference Type
  • Reference Types are those which store their values in heap memory and the address of those values are stored in stack memory as variables.
  • Among the built-in data types 'string' and 'object' are taken as Reference Types.
  • Among user defined data types Arrays, Class, Interface, and Delegate etc are taken as reference types.
  • Examples:string, object, arrays, delegates, interface etc.

Hope it helps you, Please feel free to suggest and post your valuable comments.
Read more...

How to merge or combine two tables into one?

In this post I am going to explain how to merge two tables of your web page into a single table using jQuery. This may not be a frequent practice in our daily applications but let us make use of our programming skills to meet each and every requirement according to the situation.
What we need to do here is,
  1. Create two tables in your Webform.
  2. Output is shortened to a single table with the two tables merged.
Let the following be your HTML code:
merge.aspx:
<form id="Form1" onsubmit="return merge();" runat="server">
    <div>
        <table class="primaryTable" style="border1px solid grey;">
            <thead>
                <tr>
                    <td>Name</td>
                    <td>Age</td>
                </tr>
            </thead>
            <tr>
                <td>T1-ROW1-Name</td>
                <td>T1-ROW1-Age</td>
            </tr>
            <tr>
                <td>T1-ROW2-Name </td>
                <td>T1-ROW2-Age </td>
            </tr>
        </table>
        <table class="secondaryTable">
            <tr>
                <td>T2-ROW1-Name</td>
                <td>T2-ROW1-Age</td>
            </tr>
            <tr>
                <td>T2-ROW2-Name</td>
                <td>T2-ROW2-Age</td>
            </tr>
        </table>
    </div>
</form>
 
The above code just creates two tables with the first table having id=’primaryTable’. And the second table with id=’secondaryTable’.
Now we will use simple jQuery to merge these two tables in to one.The logic we implement here is we merge the first table’s last child of its parent element with the body of the second table.
Following is my JavaScript file.
merge.js


$(document).ready(function () {
    $(".primaryTable > tbody:last").append($(".secondaryTable > tbody").html());
    $(".secondaryTable").remove();
});
 

 That’s all ,the two tables will be merged to a single table with small piece of jQuery code. Hope it helps you. Feel free to suggest and post your valuable comments.
Read more...

Tuesday, October 29, 2013

Populating GridView with Textbox values

Many times in our applications we come across storing values, Names, and some other details and display them static or dynamically. We generally use a Gridview to populate them with our values entered in our form.
In this post I will explain you with a simple example on how to populate or store values in a grid view which displays the details statically in our webpage.
Let this be my HTML Code:
<html>
<head runat="server">
    <title>Populating Grid with Form Values</title>
</head>
<body>
    <form id="myForm" runat="server">
        <div>
            My Value 1:<asp:textbox id="txtVal1" runat="server"></asp:textbox>
            <br />
            My Value 2:<asp:textbox id="txtVal2" runat="server"></asp:textbox>
            <br />
            My Value 3:<asp:textbox id="txtVal3" runat="server"></asp:textbox>
            <asp:gridview id="myGrid" runat="server">
            </asp:gridview>
            <br />
            <asp:button id="btnSave" runat="server" onclick="btnSubmit_Click" text="submit" />
        </div>
    </form>
</body>
</html>
The above html generates a form with three textboxes and a submit button and a Gridview. When I enter some values in the textboxes and click the submit button the values get populated in the grid and displayed statically.
The logic behind generating a pattern for the grid and populating the details in it goes here:
Code Behind:
protected void btnSubmit_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            if (myGrid.Rows.Count == 0)
            {
                dt = MakeTable();
 
            }
            else
            {
                dt = (DataTable)ViewState["dt"];
            }
            DataRow dr = dt.NewRow();
            dr[0] = txtVal1.Text;
            dr[1] = txtVal2.Text;
            dr[2] = txtVal3.Text;
            dt.Rows.Add(dr);
            myGrid.DataSource = null;
            myGrid.DataSource = dt;
            myGrid.DataBind();
            ViewState.Add("dt", dt);
        }
        DataTable MakeTable()
        {
            DataTable Mydt = new DataTable();
            DataColumn column1 = new DataColumn("column1");
            column1.DataType = System.Type.GetType("System.String");
            Mydt.Columns.Add(column1);
 
            DataColumn column2 = new DataColumn("column2");
            column2.DataType = System.Type.GetType("System.String");
            Mydt.Columns.Add(column2);
 
 
            DataColumn column3 = new DataColumn("column3");
            column3.DataType = System.Type.GetType("System.String");
            Mydt.Columns.Add(column3);
            return Mydt;
        }
On running this code we can see that the details from the textboxes get populated in the gridview and displayed on our web page.
Hope it helps you and especially for those who are fresh developers.

Read more...

Thursday, October 17, 2013

$broadcast (), $emit() and $on() in Angular Js

In order to understand how the events are propagated along the html DOM we use few functions that raise the events and others which behave as their listeners. Sometimes we require to enable only the parent scope elements get affected from the current scope and sometimes vice-versa.
In order to meet these two situations angular provides some event raisers and event listeners.

Event Raisers:

$broadcast(eventName, arguments) and
$emit(eventName, arguments)
//Both these functions can raise an event and can send arguments too.

Event Listener:

$on(eventName, listener)
This function gets executed whenever the respective ‘eventName’ is raised and the ‘listener’ is a function that gets executed whenever it listens to an event from the event raisers.
Now let us know about them in detail:
$broadcast(): It dispatches the event name to the registered listeners of scope downwards the current scope and their child scopes i.e. the event propagates or traverses from the scope where the event is raised to all the child scopes with valid listeners on it.

$emit(): It dispatches the event name to the registered listeners of the scope upwards from the current scope along the way to the root scope .The event traverses through all the listeners from the current scope to the parent scopes on its way to the root scope.
Let us check with an example:
Here is my html page:

Here is my javascript:
function myController($scope) {
    $scope.count = 0;
    $scope.$on('MyEvent', function () {
        $scope.count++;
    });
}
Just replicate the above code in your visual studio.Once you run it it looks like this:
  • Click on the Emit-Event button, it means that we are generating an event using $emit() in the middle scope i.e the current scope from where the event is originated.
    Now the output looks like this:
    Observation:The count in the current scope and the parent scope are incremented to 1.
    As discussed earlier the $emit() dispatched the event name to the listeners in the scope upwards the current scope .So the parent scope is incremented.
  • Now click on the Broadcast-Event button, it means that we are raising an event using $broadcast() in the mid scope ie in the current scope.
    Now the output looks like:
    Observation: The current scope and the leaf scopes are incremented whereas the parent scope remains unchanged.
    Here , $broadcast() dispatched an event which traverses to the listener downwards the current scope.
Hope this helps you to understand the very basic actions of $broadcast,$emit and $on.Please feel free to comment and your valuable suggestions are always welcome.
Read more...

Wednesday, October 16, 2013

$watch in Angular Js

Angular Js has a concept called digest cycle, which is nothing but a loop of code during which angular checks throughout the scope to determine any changes to the variables within the scope. So, if you have any variables or objects defined under the $scope, then they are subject to undergo digest cycle.

Example:
$scope.myVariable
$scope.myObject etc.

But what really keeps track on these variables inside the digest cycle?

The digest cycle internally calls $watch() function which actually takes care on the changes that occur on the variables under the $scope.
Now if you like your custom code to be run every time a change is occurred on your variables under $scope, you can call $watch() on the variable.
Let us see a small example.
Let my variables under the scope be,
$scope.myName=”Steve”;
//defining watch on my variable
$scope.$watch(“myName”,function(){ 
Alert(“My name is changed”);
//you can add the custom functionality as per your requirement
//I gave just an alert for you to understand at the moment
}

Now when an event is triggered in your page in which your variable (“myName”) is changed,
Consider a button click event,

$scope.btnclick=function(){
$scope.myName=”Albert”; // this change will trigger $scope.$watch() into action
}
Whenever the value of the variable "myName" under the scope changes the alert defined in the $watch() function gets called.
Like this you can define your custom code as per your requirement that should be triggered onchange of your desired variable.

In this way you can set $watch() on any variable you want and define the custom functionality whenever there is a change on any variable on which $watch is called on.
Hope this helps.


Read more...

Thursday, October 10, 2013

Using common directive across multiple modules in Angular Js

Angular Js has many inbuilt directives which we very often use in our html pages. Even though we are facilitated will a wide kind of directives some times we come across situations where we should design our own directives.While creating our own directive keep in mind that it should be reusable across all modules of your project.

Sharing directive among modules:

That's cool,now many fresh devolopers may find it hard to know how to make the custom directive file shared across multiple modules they build in their project.
Let us make it declarative using a simple example ,so that you would get a better figure.

First we shall create a couple of modules belonging to your project.
var myApp = angular.module('module-one',[])

var myApp = angular.module('module-two',[])

Now let us append a directive to one of the modules

var myFirstApp = angular.module('module-one',[]).

directive('myCustomDirective',function(){

// implement your custom behaviour

}

Now you need the same directive to be used in your module-two.What will you do?will you create a new directive for it.
No !you should'nt ,you have to make the directive defined in module-one reusable in the current module.
It can be done very easily, see the following piece of code below,,
var myApp = angular.module('module-two',[module-one])
That's all ,i just added module -one to the dependancies array of module-two.Now module-one's total belongings could be exposed in module-two.It can use the directive of module-one,thus avoided duplication achieved reusability.
In this way you can just add as dependancies to any number of modules and use the common functionality across multiple modules.

Sharing common directive between applications:

In the same way if two different files are present for directives in two different applications ,but belonging to the same project,you can use the same intellegence what we have done across multiple modules. Let the two different directive files be

// application 1
var myApp1=angular.module('myModue',[directive.one])

//directive1.js

myApp1.directives=angular.module('directiveRepositoryOne',[]).

directive('myDirective',function(){

//custom behaviour

}

//application 2

var myApp2=angular.module('myModule',[directive.two])

//directive2.js

myApp2.directives=angular.module('directiveRepositoryTwo',[]).

directive('myDirective',function(){

//custom behaviour

}

Note: While dealing with different applications don't forget to render the script files of the application in to your native application.

Like this we can make simple use of the dependancy array in our angular js application module and minimize redundancy and make our application less complicated.


Read more...

Wednesday, October 9, 2013

ng-blur in Angular JS

ng-blur

ng-blur is one of the directives provided by the angular framework which can trigger custom behaviour on blur. you can use it as an attribute in various html elements.
For example,

Hello world!

Let us see a simple example

Let this be my design page





If yoy observe the above example ,The user simply enters his or her name.On leaving the textbox ie on blur the user should get his username generated automatically in the next textbox.
ng-blur="myName()" is the attribute we have used in whch we raised an event which gets triggered on blur.

Now i handle the event in my javascript file, and the code here is,
$scope.myName=function()
{
if($scope.username===null || $scope.username==="")
$scope.model.username=$scope.model.name + "someId";
//here "someId" can be a sequence of numbers
}
So when the user types his Name and moves to the next field his username is automatically generated,his name attached with some id.

ng-blur not working

This is one of the major problems complained by many fresh devolopers ,that my ng-blur not working.Yes this happens,especially because of the version which you are currently using.So check out in angularjs.org official website to know perfectly which vers ions support ng-blur and then proceed.

Solution:

Evevthough we have support for ng-blur in latest versions,but if you got already started with older versions ,still you could manually get the functionality by adding the directive code manually to your application.>/br> Attach the following like this to your application:
app.directive('ngBlur', ['$parse', function($parse) {
  return function(scope, element, attr) {
    var fn = $parse(attr['ngBlur']);
    element.bind('blur', function(event) {
      scope.$apply(function() {
        fn(scope, {$event:event});
      });
    });
  }
}]);

Now your application supports ng-blur directive and you can start using this as attribute like what we have done in the example explained above.

Hope this helps you and please feel free to suggest an comment.
Read more...

Monday, October 7, 2013

dynamic keyword in c# ,How and where to use?

Dynamic type in c#:

The 'dynamic' type in c# is quite handy in situation like where the user code doesn't know the final type of data it is going to return the client. The data type for the variables,properties or metnods which are declared as dynamic are not checked at the compile time, but will try to detect only at the runtime. Thus the dynamic type ,bypasses the compile time check to the runtime.This saves you a lot of effort which involves conversion of types explicitly or implicitly at different levels of your code execution.

For example,i want to return an object as an acknowledgement to a function on its success, from clientside , say from a javascript file. But my method on server side raises another function in it which inturn returns an integer.
Now two points you have to consider:
The actual method on the server should have the type int [since the method inside it returns an integer] But the actual method should return an object to the client. In order to overcome these conflicts, generally we have to typecast the returned variables implicitly or explicitly at every level of your functionality for making the final returned value valid. Let us take an example to get better clarity: Suppose i have the following code in my javascript file.
 $scope.saveLocation = function () {       
 var orgLocationResource = $resource("api/locations");

 orgLocationResource.save($scope.model, function (data) {

 $scope.locationId=data;

 }, function (error) {

 //To display error 

        });
  • The above code is a method in my controller which is intended to save the location details of my company.[this function get called when i click on save button in my locations form in the ui]
  • I used $resource to point the data direction to my methods present in my web api controller.
  • The save method has two callback functions,one of them to collect success status and the other to display error on failure.
  • In this scenario i want my web api method to return the location id on successfully saving a location.
  • Since location id is ony of my object properties i want the web api to return the location id as an object.
Now the following is my web api methods in my api controller:
public class LocationsController : ApiController
    {
        public LocationService LocService { get; private set; }

        public LocationsController (LocationService LocService )
        {
            this.LocService  = LocService ;
        }

 [ActionName("location")]//for time being im not returning anything from here
        public void PostLocation([FromBody]Location details)
        {
            this.LocService.saveLocation(details);
        }
  • In my web api controller i had a service in which i have the method to save the location details into the database.
  • In my case i am usind petapoco as my database.Petapoco , on saving a record returns the id of the table which is an integer.
  • The PostLocation method calls for savelocation method present in the service [here in my code LocationService is what the service i used]
Save Location method in my service:
 public int saveLocation(Core.Model.Org org)
        {
         
            return Convert.ToInt32(this.DB.Insert(org.MapTo()));
        }
>
Now observe carefully, the above method in my servce returns int,so the return type for my method 'PostLocation' should be int.But this method is actually intended to return an object. Generally we should do like this,
 public int PostLocation([FromBody]Location details)
        {
           return this.LocService.saveLocation(details);  
//this need to be converted explicitly to type object[if dynamic return type is not used for our method]
        }
Now if you dont like to do the conversions you should declare your method as dynamic like this
 public dynamic PostLocation([FromBody]Location details)
        {
            return new { locationId=this.LocService.saveLocation(details)};
        }
Now its simple you can return it as an object. Eventhough the method from the service returned an int the dynamic type holds it which inturn return it as an object. Summary
  • dynamic behaves as a placeholder for a type which is unknown until the runtime
  • A variable,parameter or field declared as dynamic can hold any type.They cange their type during runtime.
  • dynamic is more simple than types var or object as they both need implicit conversions to the return type.
Hope this post helps you in understanding the main theme of using 'dynamic' keyword.If you have any queries regarding this you can leave me a comment and your suggestions are always welcome.

Read more...

Saturday, October 5, 2013

angular.copy() in AngularJs.


How to use angular.copy()

We are all familiar that AngularJs is a model driven technology.Two way binding is one of the powerful techniques implemented in it.Changes done to the model are instantly reflected to its related properties on the Ui and vice-versa.Nice functionality.But it may be annoying in some exceptional scenarios.So let us see one of the scenarios in our common web applications.

Scenario:

  1. We have a section on our page showing a list of employees with minimum details provided with select functionality.
  2. On selecting a particular employee a new section shows up displaying the total details of the corresponding employee.
  3. The new show up also contain buttons to edit and update the details.
  4. The normal requirement will be ,when the details of a particular employee are edited the actual list should not get updated instantly but should be done only after clicking the update button.
  5. But in this case instant changes will take place in the actual list on editing the full detail section.This happens due to two way binding concept in angularJs.But in this case it is not needed.
Inorder to overcome such problems angular js is provided with an excellent method called "angular.copy()".
Let us discuss in detail with some sample code for better clarity: You can solve this issue by using angular.copy. Instead of binding to a value directly , we can make a deep copy of that object and use it for editing.

Example:

consider the following html code
 
 

    Angular copy example
    
        
Name Email Mobile Address
{{emp.Name}} {{emp.email}}
And your javascript will be
var app = angular.module("app", []);  
app.controller("AppCtrl", function ($scope) {  
  $scope.employees = [  
          {"Name": "Sekhar", "mobile": "48635263469", "email": "sekhar@gmail.com"},  
          {"Name": "Abhi", "mobile": "455624512", "email": "abhi@gmail.com"},  
          {"Name": "Rani", "mobile": "6568568", "email": "rani@yahoo.com.com"},   
    ];  
  $scope.selectEmp = function (emp) {  
  $scope.selectedEmp = emp; // this is the model we use in Edit Form  
      }  
      this.saveEmp = function (empToUpdate) {  
          $scope.selectedEmp.Name =   empToUpdate.Name   
      }  
  });
When you implement the above code you will find that, whenever you try to edit the employee details you notice that the changes are reflected instaltly in the main list too.Inorde to overcome this we bring angula.copy() into picture.

Now using angular.copy() to the rescue:

Change your html and scripts to:
Design Page:
javascript file:
$scope.selectEmp = function (employee) {  
  $scope.selectedEmp = employee;  
          $scope.empCopy = angular.copy(employee);  
      }  
      this.saveEmp = function (empCopy) {  
  
        $scope.selectedEmp.Name = empCopy.Name;  
      }
Now you can find that we are taking a deep copy of the selected employee and using it as the secondary model to edit the contact without disturbing the our actual model.The edited model will be assigned to the actual model only when we press the update button.
In this way angular.copy() is quite handy in such situations.Hope this post helps you.
Read more...