Passing Reference Type by Reference


Suppose this is our class Person, having an string property name FullName.

        class Person
        {
            public string FullName { get; set; }

        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            UnderstandingPassbyValandRef();
        }
     
        private void UnderstandingPassbyValandRef()
        {
            Person myPOriginal = new Person();
            myPOriginal.FullName = "Nishant Rana";

            PassByValue(myPOriginal);
            MessageBox.Show(myPOriginal.FullName);
            // Output : “Nishant Rana PassByVal”
            
            PassByRef(ref myPOriginal);
            MessageBox.Show(myPOriginal.FullName);
            // Output : “Srihari Radhakrishnan”

            this.Close();
        }
       

 
 
  • Here copy of the reference, which points to myPOriginal is passed to the method.So it is possible for the method to change the contents of Person.
  • However by using the new operator inside the method makes the variable pVal reference a new Person object. Thus any changes after that will not affect the orignal person myPOriginal object.
         
  •   private void PassByValue(Person pVal)
            {
                pVal.FullName = "Nishant Rana PassByVal";
                pVal = new Person();
                pVal.FullName = "Arvind Singh";
            }
 
 
 
  • Here actual reference is passed to the method.
  • All of the changes that take place inside the method affect the original person object.    
         
  •   private void PassByRef(ref Person pRef)
            {
                pRef.FullName = "Nishant Rana PassByRef";
                pRef = new Person();
                pRef.FullName = "Srihari Radhakrishnan";
            }

 

Bye..

New features in C# language


Auto-Implemented Properties

Suppose this is our Person class with two properties First Name and Last Name.

public class Person
    {
        private string firstName;
        private string lastName;
        public string FirstName
        {
            get
            {
                return firstName;
            }
            set
            {
                firstName= value;
            }
        }  
        public string LastName
        {
            get
            {
                return lastName ;
            }
            set
            {
                lastName = value;
            }

        }
    }

 

Here we are not putting any extra logic while using get and set blocks for the properties, so the above code could be written as following using Auto-Implemented Properties.

 public class Person
    {
        public string FirstName { get;set;}
        public string LastName { get; set; }

    }

 

Things to remember :-

Both get and set accessor are required.

To make it read only we can declare set accessor as private

 public string LastName { get; private set; }
 
 

Object Initializers 

To initialize our Person object normally we would be writing the following code

  Person person = new Person();
  person.FirstName = “Nishant”;
  person.LastName = “Rana”;

 

However now we could do this in much simpler manner

Person person = new Person() { FirstName = “Nishant”, LastName = “Rana” };

 

Using Object initializers we can assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.

 

 

 

Extension Methods

Using Extension methods we can add methods to existing types without creating a new derived type, recompiling or modifying the original type.

Suppose this is how we have defined our Person class with one method named GetFirstName.

public class Person
    {
        public string FirstName { get;set;}
        public string LastName { get; set; }

        public string GetFirstName()
        {
            return FirstName;
        }
    }

 

Now we will add method to this existing Person Type named GetLastName

 public static class PersonExtension
    {
        public static string GetLastName(this Person p)
        {
            return p.LastName;
        }
    }

Here we need to follow these rules

  • We need to declare our class as static.
  • We need to define the method as static and the first parameter is preceded by this keyword and specifies which type the method operates on.

Now the code that calls both these methods. GetLastName function would be called as if it was an instance method and not an static one.

   Person person = new Person() { FirstName = “Nishant”, LastName = “Rana” };
   string firstName = person.GetFirstName();
   string lastName = person.GetLastName();
           
 
 

Collection Initializers

Here instead of writing the following code to intialize the collection

   List<Person> lstPerson = new List<Person>();
   Person person1 = new Person() { FirstName = “Nishant”, LastName = “Rana” };
   Person person2 = new Person() { FirstName = “Ashutosh”, LastName = “Pandey” };
            lstPerson.Add(person1);
            lstPerson.Add(person2);
we could use the following syntax, without making use of add method
 
List<Person> lstPerson=new List<Person>()
            { 
                {new Person { FirstName=“Nishant”, LastName=“Rana”}},
                {new Person {FirstName =“Ashutosh”, LastName=“Pandey”}}                
            };

 

 

Implicitly type local variables

Now we can declare variables using var keyword (implicitly) without explicitly defining their type.

 string FullName = “Nishant Rana”;
or
var FullName = “Nishant Rana”;
 
 
var myStringArray = new[] { “a”, “b”, “c” };
 
The above two lines of code are equivalent.
Here compiler infer the type of variable from the expression on the right side. It could be built-in type, user-defined type, anonymous type or any other type defined in .NET framework.
 
 

Anonymous Types

Anonymous types are class types that contain one or more public read only properties.

var v = new { FirstName = “Nishant”, LastName = “Rana” };

The above line of code creates a anonymous class having two public read only properties named FirstName and LastName.

Things to remember :-

  • The compiler gives name to the anonymous types but our application won’t be able to access it.
  • It cannot be cast to any type except “Object’”.

Anonymous methods and Lambda expressions

Suppose this is our simple delegate

 public delegate void MySimpleDelegate();

 

And this is the function which it points to

  public void MySimpleFunction()
        {
            Response.Write(“Simple function”);
        }

 

And this is how we would be using the delegate

  MySimpleDelegate mySimpleDelegate = MySimpleFunction;
   mySimpleDelegate();

 

Now here instead of defining the MySimpleFunction separately we can make use of anonymous methods

  MySimpleDelegate mySimpleDelegate = delegate
            {
                Response.Write(“Simple function”);
            };
mySimpleDelegate();

 

Infact we can also use lambda expression over here

MySimpleDelegate mySimpleDelegate = () => Response.Write(“Simple function”); 
mySimpleDelegate();
 
 
Here       ()           –>  no input parameter
and        =>          –> lamda operator
 
 
 
Optional parameters
 

We can declare an optional parameter by specifying default value as a part of declaration

public void GetTotal(int a = 0, int b = 0)
        {
            MessageBox.Show((a + b).ToString());
        }

We can call the above method in any of the following way

 
            GetTotal(1, 1);
            GetTotal(1);
            GetTotal();

 

Named Arguements

Name the arguments to be passed
            GetTotal(a: 1, b: 2);
            GetTotal(b:2, a: 1);
This will throw error named argument must appear after fixed arugments have been specified
 
           GetTotal(a:1, 2);

Dynamic Type

New dynamic type that allows us to do things that are resolved during run time.

         dynamic dString = GetName(“a”,”b”);
         dynamic dInt = 12;

 

Bye.

Understanding Constructors (C#)


What is constructor?

Constructor is a special type of function member of a class. It is used to initialize the instance variables of the object.

Person myPerson=new Person();

Here the new operator is used to allocate the memory needed to store the data of the object.

Now suppose this is how we have defined our Person class.

  public class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }  
   

( here we have used Automatic Properties feature of C# 3.0 to declare our properties FirstName and LastName)

Here in our class we haven’t defined a constructor but we are still able to create instance variables of the Person Object using following line of code

Person p = new Person();
 

The reason it is possible is because we don’t have to explicitly declare constructor for a class, C# automatically provides a default parameterless constructor for that class. The default constructor will initialize any fields of the class to their zero-equivalent values.

We can also write our own constructors, the things to remember are

  • They don’t have a return type.
  • Their name should be same as the name of the class.
  • Should contain a parameter list, which could be left empty.

Now the question is why would we be writing our own constructors?

Well the reason is because constructors can be used to pass initial values for an object’s fields at the time when an object is being instantiated.

For our above Person class

instead of the following code 

    Person p = new Person();
    p.FirstName = "Nishant";
    p.LastName = "Rana";

 

we can do the same in single line of code

Person p = new Person("Nishant", "Rana");
 

The constructor would be defined in the following manner

 public Person(string fname, string lname)
          {
              FirstName = fname;
              LastName = lname;
          }

One thing we have to remember is that if we are defining our own Parameterized constructor the default constructor would be eliminated.

We won’t be able to create person class object using default constructor.

i.e. Person p=new Person(); // it won’t compile.

In this case then we need to explicitly write a default constructor.

public Person()
        { 

        }

bye..

Sample code for Inserting a lead record from a .NET application : Oracle CRM On Demand


First download the wsdl file for the lead record from Oracle CRM On Demand web application.

Add web references to it within a .NET windows application.

Use the following code for inserting the lead record.

We need to specify value for all the required field for the record to get inserted.

        String loginUrlString = "https://secure-ausomxapa.crmondemand.com/Services/Integration?command=login&quot;;
        String logoffUrlString ="https://secure-ausomxapa.crmondemand.com/Services/Integration?command=logoff&quot;;
        String siebelUserName = "username/password";
        String siebelPassword ="password";
        String opportunityUrl = "https://secure-ausomxapa.crmondemand.com/Services/Integration;jsessionid=&quot;;
        String sessionID = "";
      
        Private void Form1_Load(Object sender, EventArgs e)
        {            
            // Get the session from the helper Class ManageSession
             sessionID = ManageSession.Login(loginUrlString, siebelUserName, siebelPassword);

            //Create the New lead record instandce And Set its url With proper session id
             Lead myLead = New Lead();
             myLead.Url = "https://secure-ausomxapa.crmondemand.com/Services/Integration;jsessionid=&quot; + sessionID;

            // create arrary Of lead record To be inserted
             LeadData[] myLeadData = New LeadData[1];
             myLeadData[0] = New LeadData();
             myLeadData[0].LeadFirstName = "Nishant";
             myLeadData[0].LeadLastName = "Rana";
             myLeadData[0].Source = "Email";
             myLeadData[0].dLead_Generation_Date = Convert.ToDateTime("7/30/2010");
             myLeadData[0].LeadOwner = "Nishant Rana";
             myLeadData[0].dLead_Generation_dateSpecified = True;             

            // add lead data array To listofLeadData Class
             ListOfLeadData myLstLeadData = New ListOfLeadData();
             myLstLeadData.Lead = myLeadData;

            // create an instance Of leadinsert_input Class
            LeadInsert_Input myLeadRecordInput = New LeadInsert_Input();
            myLeadRecordInput.ListOfLead = myLstLeadData;
            LeadInsert_Output myLeadRecordOutput = myLead.LeadInsert(myLeadRecordInput);    
        }

 

 

The sample code for the ManageSession.cs class

 class ManageSession
    {
        public static string SessionID = "";
        public static String Login(String loginUrlString, String userName, String password)
        {
            try
            {
                // create a http request and set the headers for authentication
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(loginUrlString);
                HttpWebResponse myResponse;
                myRequest.Method = "POST";
                // passing username and password in the http header 
                // username format if it includes slash should be the forward slash /
                myRequest.Headers["UserName"] = userName;
                myRequest.Headers["Password"] = password;
                myResponse = (HttpWebResponse)myRequest.GetResponse();
                Stream sr = myResponse.GetResponseStream();
                // retrieve session id
                char[] sep = { ‘;’ };
                String[] headers = myResponse.Headers["Set-Cookie"].Split(sep);
                for (int i = 0; i <= headers.Length – 1; i++)
                {
                    if (headers[i].StartsWith("JSESSIONID"))
                    {
                        sep[0] = ‘=’;
                        SessionID = headers[i].Split(sep)[1];
                        break;
                    }
                }
                sr.Close();
                myResponse.Close();
            }
            catch (WebException webException)
            {
                return webException.Message;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            // send back the session id that should be passed to subsequent calls 
            // to webservices 
            return SessionID;
        }

        public static String Logoff(String logoffUrlString, string SessionID)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(logoffUrlString);          
            // set the session id in header
            req.Headers["JSESSIONID"] = SessionID;
            // make the HTTP call
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            return resp.StatusCode.ToString();

        }
    }

 

Hope it helps !

Bye..

Active Directory and .NET


The two best links for someone working with Active Directory using .NET

http://www.codeproject.com/KB/system/everythingInAD.aspx

http://www.ianatkinson.net/computing/adcsharp.htm

Bye..

Sort SPFolder in SharePoint


We developed a web part showing the folders hierarchy using tree view control. However the folders were not getting displayed in the tree view node in the order they are visible inside the document library i.e. sorted on name.

Creating a tree view

http://www.davehunter.co.uk/Blog/Lists/Posts/Post.aspx?List=f0e16a1a-6fa9-4130-bcab-baeb97ccc4ff&ID=115

So finally used the following code to sort the folders

List<SPFolder> folderList = new List<SPFolder>();

foreach (SPFolder myFolder in folder.SubFolders){

folderList.Add(myFolder);

}

folderList.Sort(delegate(SPFolder p1, SPFolder p2) { return p1.Name.CompareTo(p2.Name); });

For more information on sorting

http://www.developerfusion.com/code/5513/sorting-and-searching-using-c-lists/

Bye..