Tuesday, August 15, 2017

Autocomplete textbox using Managed Metatdata and Likes/NotLike implementation in Sharepoint 2013 List.

function termSetIDS(TermSetID1) { var dfrd1 = $.Deferred(); var dfrd2 = $.Deferred(); setTimeout(function() { //Doing async stuff context = new SP.ClientContext.get_current(); session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context); termStore = session.getDefaultSiteCollectionTermStore(); RawTermSet = termStore.getTermSet(TermSetID1); RawTerms = RawTermSet.getAllTerms(); context.load(session); context.load(termStore); context.load(RawTermSet); context.load(RawTerms); context.executeQueryAsync(onTaxonomySession, onTaxonomyFailed); dfrd1.resolve(); function onTaxonomySession() { var Name = null; Name = RawTermSet.get_name(); var terms = RawTermSet.get_terms(); context.load(terms); context.executeQueryAsync( function () { var termsEnum = terms.getEnumerator(); while (termsEnum.moveNext()) { var currentTerm = termsEnum.get_current(); var termName = currentTerm.get_name(); var termId = currentTerm.get_id(); termsList += termName + ": " + termId; //Check if term has child terms if (currentTerm.get_termsCount() > 0) { //Term has sub terms. recursiveTerms(currentTerm, 1,Name); } //alert(termList); //console.log(termList); } }, function () { //failure to load terms. }); } function recursiveTerms(currentTerm, nestedLoop,Name) { //Loop count for formatting purpose. var loop = nestedLoop + 1; //Get Term child terms var terms = currentTerm.get_terms(); context.load(terms); context.executeQueryAsync( function () { var termsEnum = terms.getEnumerator(); while (termsEnum.moveNext()) { var newCurrentTerm = termsEnum.get_current(); var termName = newCurrentTerm.get_name(); termId = newCurrentTerm.get_id(); //Tab Out format. for (var i = 0; i < loop; i++) { termsList += "\t"; //alert(termsList); } termsList += termName + ": " + termId; //console.log("termset retrieving now"); console.log(termName + "First"); termsArray.push(termName); $("#autocompleteTextBoxTeamArea").autocomplete({ source: termsArray }); //alert(termsList); //Check if term has child terms. if (currentTerm.get_termsCount() > 0) { //Term has sub terms. recursiveTerms(newCurrentTerm, loop); } } }, function () { //failure to load terms } ); //termSetIDS(TermSetID2); } function onTaxonomyFailed(sender, args) { alert('Taxonomy Error:' + args.get_message()); } }, 750); setTimeout(function() { // doing async stuff context = new SP.ClientContext.get_current(); session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context); termStore = session.getDefaultSiteCollectionTermStore(); RawTermSet = termStore.getTermSet(TermSetID2); RawTerms = RawTermSet.getAllTerms(); context.load(session); context.load(termStore); context.load(RawTermSet); context.load(RawTerms); context.executeQueryAsync(onTaxonomySession, onTaxonomyFailed); dfrd2.resolve(); function onTaxonomySession() { var Name = null; Name = RawTermSet.get_name(); var terms = RawTermSet.get_terms(); context.load(terms); context.executeQueryAsync( function () { var termsEnum = terms.getEnumerator(); while (termsEnum.moveNext()) { var currentTerm = termsEnum.get_current(); var termName = currentTerm.get_name(); var termId = currentTerm.get_id(); termsList += termName + ": " + termId; //Check if term has child terms if (currentTerm.get_termsCount() > 0) { //Term has sub terms. recursiveTerms(currentTerm, 1,Name); } //alert(termList); //console.log(termList); } }, function () { //failure to load terms. }); } function recursiveTerms(currentTerm, nestedLoop,Name) { //Loop count for formatting purpose. var loop = nestedLoop + 1; //Get Term child terms var terms = currentTerm.get_terms(); context.load(terms); context.executeQueryAsync( function () { var termsEnum = terms.getEnumerator(); while (termsEnum.moveNext()) { var newCurrentTerm = termsEnum.get_current(); var termName = newCurrentTerm.get_name(); termId = newCurrentTerm.get_id(); //Tab Out format. for (var i = 0; i < loop; i++) { termsList += "\t"; //alert(termsList); } termsList += termName + ": " + termId; //console.log("termset retrieving now"); console.log(termName); sArray.push(termName); $("#autocompleteTextProcessArea").autocomplete({ source: sArray }); //alert(termsList); //Check if term has child terms. if (currentTerm.get_termsCount() > 0) { //Term has sub terms. recursiveTerms(newCurrentTerm, loop); } } }, function () { //failure to load terms } ); } function onTaxonomyFailed(sender, args) { alert('Taxonomy Error:' + args.get_message()); } }, 2000); return $.when(dfrd1, dfrd2).done(function() { // Both asyncs tasks are done //console.log('Both are Done.'); }).promise(); } function bindCategories() { $.ajax({ url: _siteUrlContext + "/_api/web/lists/getbytitle('Categories')/items", type: "GET", async:false, headers: { "Accept": "application/json;odata=verbose", "Content-Type": "application/json;odata=verbose" //"X-RequestDigest": $("#__REQUESTDIGEST").val() }, success: function(data){ var count = data.d.results.length; for(var i = 0;i < count; i++) cArray.push(data.d.results[i].Title); $("#autocompleteTextBoxCategories").autocomplete({ source: cArray }); }, error: function (err){ alert("Failed to get list items."); console.log(JSON.stringify(err)); } }); } spApp = angular.module('spng-App', ['ngSanitize']); //Create a Controller spApp.controller('spng-WebCtrl', function($scope, $http) { $scope.getListDetails = function() { var termsArrayDisplay = []; var strTeamArea = "Guideline [AGP]"; var Title = "June 2017"; var clientContext = new SP.ClientContext(siteUrl); var oList = clientContext.get_web().get_lists().getByTitle('Posts'); //Microsoft.Office.Server.ReputationModel.Reputation.setLike(clientContext, listId, itemId, isLike); var camlQuery = new SP.CamlQuery(); //var viewXml ="" + strTeamArea + "" + Title + ""; var viewXml =""; camlQuery.set_viewXml(viewXml); collListItem = oList.getItems(camlQuery); //clientContext.load(collListItem,'Title', 'Id','Body'); clientContext.load(collListItem); //clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryTfSucceeded), Function.createDelegate(this, this.onQueryTfFailed)); clientContext.executeQueryAsync(function () { var idArr = []; var listItemInfo = ''; var listItemEnumerator = collListItem.getEnumerator(); while (listItemEnumerator.moveNext()) { var oListItem = listItemEnumerator.get_current(); //alert(oListItem.get_id()); //termsArray.push(oListItem.get_id()); var ItemTitle=oListItem.get_item('Title'); var ID=oListItem.get_id(); var PublishedDate=oListItem.get_item('PublishedDate'); var Body=oListItem.get_item('Body'); var LC = oListItem.get_item("LikesCount") == null ? "0" : String(oListItem.get_item("LikesCount")); likedByy = oListItem.get_item('LikedBy'); var Isliked = false; if(likedByy != null) { if(LC !=null && LC != undefined) { for(var i=0;i $scope.LikePage = function() { var layoutsRoot = '/_layouts/15/'; $(function() { $.getScript(layoutsRoot + "MicrosoftAjax.js", function () { $.getScript(layoutsRoot + "SP.core.js", function () { $.getScript(layoutsRoot + "SP.Runtime.js", function () { $.getScript(layoutsRoot + "SP.js", function () { $.getScript(layoutsRoot + "SP.Publishing.js", function () { $.getScript(layoutsRoot + "Reputation.js", GetLikeCount) }); }); }); }); }); }); var clientContext = new SP.ClientContext(siteUrl); var oList = clientContext.get_web().get_lists().getByTitle('Posts'); EnsureScriptFunc('reputation.js', 'Microsoft.Office.Server.ReputationModel.Reputation', function () { Microsoft.Office.Server.ReputationModel.Reputation.setLike(clientContext,sList,sItem); context.executeQueryAsync(function () { GetLikeCount(); }, function (sender, args) { alert('Failed to like this. Error:' + args.get_message()); }); }); } function GetLikeCount() //Check to see if liked, get liked count, and if current user likes the item { context = new SP.ClientContext(siteUrl); list = context.get_web().get_lists().getById(sList); thisItem = list.getItemById(sItem); context.load(thisItem,"Title","ID","LikesCount","LikedBy"); context.executeQueryAsync(Function.createDelegate(this,onSuccess),Function.createDelegate(this,onFailure)); } function onFailure(sender, args) { alert('Failed to get lists items. Error:' + args.get_message()); } function onSuccess(sender, args) { var itemc = thisItem.get_item('LikesCount'); var likedBy = thisItem.get_item('LikedBy'); var ID = thisItem.get_item('ID'); console.log("ID="+ID); if(itemc == null) { itemc = 0; } var isliked = getisLiked(likedBy); if(isliked == true) { likeDisplay = true; itemc = itemc-1; } else { likeDisplay = false; itemc = itemc+1; } if(itemc < 0) itemc = 0; thisItem.set_item('LikesCount',itemc); //thisItem.set_item('LikedBy','Saroj.Panda@shell.com'); //thisItem.set_item(SP.FieldLookupValue.set_lookupId(44)); thisItem.set_item('LikedBy',44); //item.update(); thisItem.update(); context.executeQueryAsync(function () { alert('Like Updated in Posts List.'); }, function (sender, args) { console.log(args.get_message()); } ); ChangeLikeText(ID,likeDisplay,itemc); } function ChangeLikeText(ID,likeDisplay, count) { //Manage the DOM elements and presentation var text0 = ""; if (likeDisplay == true) { $("#fldr"+ID+" a.IdLike").text('Unlike'); text0 = 'Like'; } else { $("#fldr"+ID+" a.IdLike").text('Like'); text0 = 'Unlike'; } var htmlstring = "" + " " + text0 + " "; if (count > 0) { $("#fldr"+ID+" a.IdLike").html(htmlstring); $("#fldr"+ID+" .LikesCounts").html(String(count)); } else { $("#fldr"+ID+" a.IdLike").html(""); } } var getisLiked = function (likedby) { var isliked = false; if (likedby !== null && likedby !== undefined) { for (var i = 0; i < likedby.length; i++) { var like = likedby[i]; if (like.get_lookupId() === _spPageContextInfo.userId) { isliked = true; break; } } } return isliked; }; });

Thursday, September 16, 2010

ADO.NET : Record Insert and Display Using StoredProcedure

Windows Application Screenshot :

***************************



****************************

Screenshot Of StoredProcedure in SQL Server 2005
================================================

================================================
StoredProcedure : GetEmployee
================================================
USE [ANGEL]
GO
/****** Object: StoredProcedure [dbo].[GetEmployee] Script Date: 09/17/2010 08:52:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[GetEmployee]

AS SELECT EmpNo,EmpName, EmpSal,DeptNo FROM Employee
====================================================
StoredProcedure : InsertUser
====================================================

USE [ANGEL]
GO
/****** Object: StoredProcedure [dbo].[InsertUser] Script Date: 09/17/2010 08:54:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[InsertUser] (
@Username varchar(50), @Password varchar(50)
)
AS INSERT INTO Users VALUES(@Username, @Password)

==================================================

Code :
==================================================

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{

SqlConnection conn;
SqlCommand command;
SqlCommand command1;
SqlDataAdapter adapter;
DataSet ds;
public Form1()
{

InitializeComponent();
conn = new SqlConnection("Data Source=localhost; Initial Catalog=ANGEL; Integrated Security=SSPI");
conn.Open();

}

private void Form1_Load(object sender, EventArgs e)
{

command = new SqlCommand("GetEmployee", conn);
adapter = new SqlDataAdapter(command);
ds = new DataSet();
adapter.Fill(ds, "Employee");
dg_Data.DataSource = ds.Tables[0];


}

private void button1_Click(object sender, EventArgs e)
{
string username=Username.Text;
string password=Password.Text;

command1= new SqlCommand("InsertUser", conn);
command1.CommandType = CommandType.StoredProcedure;
command1.Parameters.Add("@Username", SqlDbType.VarChar).Value = username;
command1.Parameters.Add("@Password", SqlDbType.VarChar).Value = password;

int rows = command1.ExecuteNonQuery();
conn.Close();
if (rows == 1)
{
MessageBox.Show("Record Inserted successfully ...");
}
else
{
MessageBox.Show("Problem in insert !!! Check coding ");
}
Username.Text = "";
Password.Text = "";
}
}
}

=====================================================================

Tuesday, September 7, 2010

IEnumerable and Ienumerator Interfaces Details:

1) IEnumerable interface members helps foreach loop to iterate over a collection.
2) The method like GetEnumerator() of IEnumerable interface has to be defined to iterate a collection.
3) There is 1 method of IEnumerable interface. Which is IEnumerator GetEnumerator (). (Return type is Ienumerator type)
4) It returns an IEnumerator object that can be used to iterate through the collection.
5) Its not required to implement IEnumerable interface though we are overriding the GetEnumerator(), because we are using Namespace System.Collections. So it’s not mandatory to right IEnumerable interface.
6) We should implement the IEnumerable to use foreach iteration.
7) There are 2 public methods of IEnumerator Interface.
8) MoveNext() advances the enumerator to the next element of the collection.
9) Reset() sets the enumerator to its initial position, which is before the first element in the collection.
10) MoveNext() returns bool. And the Syntax is bool MoveNext().
11) If it’s true then enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
12) After an enumerator is created or after the Reset method is called, an enumerator is positioned before the first element of the collection, and the first call to the MoveNext method moves the enumerator over the first element of the collection.
If MoveNext passes the end of the collection, the enumerator is positioned after the last element in the collection and MoveNext returns false. When the enumerator is at this position, subsequent calls to MoveNext also return false until Reset is called.
13) An enumerator remains valid as long as the collection remains unchanged.
14) If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and the next call to MoveNext or Reset throws an InvalidOperationException.
15) IEnumerator.Current Property gets the current element in the collection. Its syntax is Object Current { get; }

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Example:

Employee.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ienumeratordemo
{
class Employee
{
private string name;
private int empno;


public Employee(int empno, string name)
{
this.empno = empno;
this.name = name;
}

public int Empno
{
get { return empno; }
set { empno = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
}
}

EmployeeInfo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Ienumeratordemo
{
class EmployeeInfo //: IEnumerable
{

public Employee[] empArray = new Employee[3];


public EmployeeInfo()
{
empArray[0] = new Employee(1001, "Ajit");
empArray[1] = new Employee(1002, "Sunil");
empArray[2] = new Employee(1003, "Raj");

}


public IEnumerator GetEnumerator()
{
return empArray.GetEnumerator();
}
}
}


Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Ienumeratordemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("IEnumerable / IEnumerator Demo\n");

EmployeeInfo empinfoObj = new EmployeeInfo();

// Hand over each Employee in the collection ?
foreach (Employee e in empinfoObj)
{
Console.WriteLine("{0} \t {1}",e.Empno, e.Name);
}


//manually iterate
IEnumerator i = empinfoObj.GetEnumerator();
i.MoveNext();

Employee myEmployee = (Employee)i.Current;
Console.WriteLine("{0} \t {1}", myEmployee.Empno, myEmployee.Name);
i.Reset();

Console.WriteLine(" *******************************************");

IEnumerator i1 = empinfoObj.GetEnumerator();
i1.MoveNext();


i1.MoveNext();




i1.MoveNext();

Employee myEmployee1 = (Employee)i1.Current;
Console.WriteLine("{0} \t {1}", myEmployee1.Empno, myEmployee1.Name);

Console.Read();


}
}
}

Output :


Object Sender & EventArgs Parameter in System.EventHandler Delegate

EventHandler Delegate : Represents the method that will handle an event that has no event data.
Namespace: System
Assembly: mscorlib (in mscorlib.dll)

Syntax :

public delegate void EventHandler(Object sender,EventArgs e)

sender

Type: System.Object
The source of the event.

e
Type: System.EventArgs
An EventArgs that contains event data.

************************************************************

Check the Code below :

private void btnShowDel_Click(object sender, EventArgs e)
{
int x = 6;
int y = 7;

int z = x + y;
MessageBox.Show("" + z);
MessageBox.Show(e.ToString());
}

On this above code, btnShowDel_Click is the eventhandler. Which is match with the predefined delegate System.EventHandler.

See the following code :


this.btnShowDel.Click += new System.EventHandler(this.btnShowDel_Click);

This code tells that, btnShowDel is an object and Click is the event. And btnShowDel raises the event. The event model in the .NET Framework is based on having an event delegate that connects an event with its handler. To raise an event, two elements are needed:

* A delegate that identifies the method that provides the response to the event.
* A class that holds the event data.

The delegate is a type that defines a signature, that is, the return value type and parameter list types for a method. You can use the delegate type to declare a variable that can refer to any method with the same signature as the delegate. The standard signature of an event handler delegate defines a method that does not return a value, whose first parameter is of type Object and refers to the instance that raises the event, and whose second parameter is derived from type EventArgs and holds the event data.If the event does not generate event data, the second parameter is simply an instance of EventArgs. Otherwise, the second parameter is a custom type derived from EventArgs and supplies any fields or properties needed to hold the event data.

EventHandler is a predefined delegate that specifically represents an event handler method for an event that does not generate data. If your event does generate data, you must supply your own custom event data type and either create a delegate where the type of the second parameter is your custom type, or use the generic EventHandler delegate class and substitute your custom type for the generic type parameter.

To associate the event with the method that will handle the event, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate.

The following code example demonstrates the declaration of an event handler delegate that does not use event data. The EventHandler class is the type of the event delegate, sender is the object that raises the event, and e is an event data object that contains no data. The second line of code in the example defines the event member in your class for an event that has no data.

************************************************************

public delegate void EventHandler(Object sender, EventArgs e);
public event EventHandler NoDataEventHandler;

**************************************************************

Wednesday, August 4, 2010

How to connect ADO.NET with Oracle 9i Database

Step – 1

Design a Windows application Form like the below screenshot.



# Write code to insert record into Employee table. (provided below)

# To know the connection string for oracle database, go to , Server Explorer->WriteClick on Data Connections ->Add Connection->Then provide the Global Database Name (SID), UserID and password as set at the time of installing Oracle .

Notes : User ID : Scott (Locked, So no changes)
Password: tiger (Locked, No changes)
Server : GDN (here 'GDN' in my Machine)

Only you have to provide the Global Database Name , at the time of installation.

See the below screenshot to create the connection using Server Explorer.









Then you will find the connection string which will be created automatically and set this connection string, with OracleConnection instance.

For details see the code details :

------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace ADOwithOra
{
public partial class Employee : Form
{
OracleConnection oracleConn;

public Employee()
{

InitializeComponent();
oracleConn = new OracleConnection();
oracleConn.ConnectionString = "Data Source=GDN;User ID=scott;Password=tiger;Unicode=True";
oracleConn.Open();
}

private void button1_Click(object sender, EventArgs e)
{

try
{

if (oracleConn.State == ConnectionState.Open)
{
oracleConn.Close();
}
oracleConn.Open();
//OracleCommand cmd = new OracleCommand("insert into Employee(EmpNo,EmpName,Sal) values(5,'Ravi',23000)", oracleConn); --->Hardcoding
OracleCommand cmd = new OracleCommand("insert into Employee values(" + textBox1.Text + ",'" + textBox2.Text + "'," + textBox3.Text + ")", oracleConn);
cmd.ExecuteNonQuery();
MessageBox.Show("Employee information added successfully...", "Employee Details", MessageBoxButtons.OK, MessageBoxIcon.Information);

}
catch (Exception e2)
{
MessageBox.Show(e2.ToString());
}


}

private void btnReset_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
}
}
}
--------------------------------------------------
Result screenshot:



See the Oracle database screenshot:



Now we can do more works using Oracle 9i in ADO.NET.


All the best...

Friday, July 23, 2010

Boxing and Unboxing in C#

C# provides us with Value types and Reference Types. Value Types are stored on the stack and Reference types are stored on the heap. The conversion of value type to reference type is known as boxing and converting reference type back to the value type is known as unboxing.

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. In the following example, the integer variable i is boxed and assigned to object o.


int i = 123;
object o = (object)i

The object o can then be unboxed and assigned to integer variable i:

o = 123;
i = (int)o;


Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object.

Consider the following declaration of a value-type variable:

int i = 123;

The following statement implicitly applies the boxing operation on the variable i:

object o = i;

The result of this statement is creating an object reference o, on the stack, that references a value of the type int, on the heap. This value is a copy of the value-type value assigned to the variable i. The difference between the two variables, i and o, is illustrated in the following figure.

Boxing Conversion





In the above case, I have made an implicit boxing. At first time the i value is located in stack area as actual value. But when the i value is boxed, to object type. So, the reference will be resides on the stack memory area and the value pointing to that reference will be located on heap area.
Example:

class TestBoxing
{
static void Main()
{
int i = 797;
object o = i; // Implicit boxing

i = 456; // Change the contents of i

System.Console.WriteLine("The value-type value = {0}", i);
System.Console.WriteLine("The object-type value = {0}", o);
}
}







The following example demonstrates a case of invalid unboxing and the resulting InvalidCastException. Using try and catch, an error message is displayed when the error occurs.

class TestUnboxing
{
static void Main()
{
int i = 797;
object o = i; // implicit boxing

try
{
int j = (short)o; // attempt to unbox

System.Console.WriteLine("Unboxing Possible.");
}
catch (System.InvalidCastException e)
{
System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message);
}
}
}


This program outputs:
Specified cast is not valid. Error: Incorrect unboxing.
If you change the statement:
int j = (short) o;

to:

int j = (int) o;
the conversion will be performed, and you will get the output:
Unboxing Possible.

Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. An unboxing operation consists of:
• Checking the object instance to make sure that it is a boxed value of the given value type.
• Copying the value from the instance into the value-type variable.
The following statements demonstrate both boxing and unboxing operations:
int i = 123; // a value type
object o = i; // boxing
int j = (int)o; // unboxing


Unboxing Conversion




In the above figure, i value 123 is stored in the stack, and when it is assigned to object type, the reference will be stored in stack only, but the actual value will be stored in heap. And when, it will be explicitly telecasted to int type, as per the above figure , j value will be stored in the stack.
Difference between Stack vs Heap memory
Stack
Stack memory stores variable types in address' in memory, these variables in programming are called local variables and are often stored for short amounts of time while a function/method block uses them to compute a task.
Once a function/method has completed its cycle the reference to the variable in the stack is removed.

Heap
Heap memory stores all instances or attributes, constructors and methods of a class/object.
Comparison
A Heap reference is stored in Stack memory until the life cycle of the object has completed. Inside the Heap reference all the contents of the object are stored whereas with a local variable only the variable contents are stored in the stack.
Example:
Stack
int x
ref 0x456783 (Heap reference)
int y
ref 0x498702 (Heap reference)
int z


Heap (0x456783)
name => Ali
age => 33
city => CTC
height => 5'8
sex => Male

Heap (0x498702)
name => Saroj
age => 29
city => BBSR
height => 6'0
sex => male

So, above all, I would like to say, for performance point of view, heap is works better then stack.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Monday, April 26, 2010

WebServices in ASP.NET




A Simple Example To run a WebServices :
=====================================================================================
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Factorial : System.Web.Services.WebService
{
public Factorial()
{

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public int FindFact(int x)
{
int a=1;
while (x != 0)
{
a = a * x;
x--;
}
return a;

}

}
=================================================================================

Client Program :


using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{


}
protected void btnClick_Click(object sender, EventArgs e)
{
Factorial Fct = new Factorial();
int Res = Fct.FindFact(Convert.ToInt32(txtFact.Text));
txtShowFact.Text = Convert.ToString(Res);
}
}


===========================================================================

Output:


==============================================================================