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..

LINQ to Microsoft Dynamics CRM


Suppose this is our entity’s schema name “new_test

and it contains following fields

new_name

new_lastname

Using CrmSvcUtil  we have created the Entities classes and Data Context class.

https://nishantrana.wordpress.com/2010/08/11/using-crmsvcutil/

Now this is how we could use LINQ to query data using query expression as well as method based query.

Create the instace of DataContext class named xrm

var myXrm = new xrm(“CRMOnPremise”);

To loop through all the test records


foreach (var testRecord in myXrm.new_tests)
{
// print the information
}

To select a specific record


var singleRecord = (from myTest in myXrm.new_tests
where myTest.new_lastname == “Rana”
select myTest).Single();

var singleRecord1 = myXrm.new_tests
.Single(t => t.new_lastname == “Rana”);

To select all the records having last name as Rana

var allRecord = from myTest in myXrm.new_tests
where myTest.new_lastname == “Rana”
select myTest;

var allRecords1 = myXrm.new_tests.
Where(t => t.new_lastname == “Rana”);

To order the records

var allRecOrder=from myTest in myXrm.new_tests
orderby myTest.new_name  ascending
where myTest.new_lastname==“Rana”
select myTest;

var allRecOrder1 = myXrm.new_tests
.OrderBy(t => t.new_name)
.Where(t => t.new_lastname == “Rana”);

To select  specific field instead of the entire record


var singleField = from myTest in myXrm.new_tests
select myTest.new_name;

var singleField1 = myXrm.new_tests
.Select(t => t.new_name);

To return specific fields

var specificFields = from myTest in myXrm.new_tests
select new { myTest.createdby, myTest.createdon };

var specificFields1 = myXrm.new_tests
.Select(t => new { t.createdby, t.createdon });

Use of Take and Skip function
Take returns the given number of elements and ignores the rest
Skip skips the given number of elements and yielding the rest

var takeField = (from myTest in myXrm.new_tests
select myTest.new_name).Take(2);

var takeField1 = myXrm.new_tests
.Take(2)
.Select(t => t.new_name);

var skipField = (from myTest in myXrm.new_tests
select myTest.new_name).Skip(2);

var skipField1 = myXrm.new_tests
.Skip(2)
.Select(t => t.new_name);

Join – similar to inner join
The ‘select’ and ‘orderBy’ calls may only reference

a single common entity type.
We will get above error if we try to retrieve value from  the other entity involved in join
var joinRecords = from t in myXrm.new_tests
join s in myXrm.systemusers on
t.ownerid.Value equals s.systemuserid
select new {t.new_name  };

var joinRecords1=myXrm.new_tests
.Join(myXrm.systemusers,
t=>t.ownerid.Value,
s=>s.systemuserid ,
(t,s)=>new {t.new_name});

Where conditions with Contains,StartsWith, EndsWith and

Equal string functions

var test1 = from p in myXrm.new_tests
where p.new_name.Contains(“R”)
select p;
var test2 = from p in myXrm.new_tests
where p.new_name.StartsWith(“R”)
select p;
var test3= from p in myXrm.new_tests
where p.new_name.EndsWith(“D”)
select p;

var test11 = myXrm.new_tests
.Where(t => t.new_name.Contains(“R”));
var test22 = myXrm.new_tests
.Where(t => t.new_name.StartsWith(“R”));
var test32 = myXrm.new_tests
.Where(t => t.new_name.EndsWith(“D”));

Download the project :-

http://www.box.net/shared/xbg0xd5p7m

Bye..

using CrmSvcUtil


Use CrmSvcUtil to generate the strongly types entity and datacontext classes

crmsvcutil

/connectionString:"Authentication Type=Integrated; Server=http://servername/orgname"

/out:"Xrm.cs" /namespace:"Xrm.solution"

/dataContextClassName:"xrm"

conntectionString–> specifies the connection string.
out –> determines the name of the .cs or .xml output file and whether there is one file or one per entity.To generate one file per entity omit .cs or .xml from the file name.
namespace –> to specify the namespace
dataContextClassName –> to specify the name of the dataContext class.

Add references to the following dlls in the project

  • System.Data.Entity, System.Data.Services, System.Data.Services.Client.
  • System.Web.Services.
  • Microsoft.Crm.Sdk, Microsoft.Crm.SdkTypeProxy.dll, Microsoft.Crm.SdkTypeProxy.XmlSerializers
  • Microsoft.Xrm.Client, Microsoft.Xrm.Portal, Microsoft.Xrm.Portal.Files

Add the generated Xrm.cs file to the project.

Add the connection string information in the config file of the application

<add name="CRMOnPremise" connectionString="Authentication Type=Integrated; Server=http://servername/orgname" />

Add following using Statements

using Xrm;
using Xrm.solution;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;

And the code for creating a new custom entity record.

            new_test testEntity1 = new new_test();
            testEntity1.new_name = "Nishant";
            testEntity1.new_lastname = "Rana";
            myXrm.AddTonew_tests(testEntity);
            myXrm.SaveChanges();

 

or could also be written as

            // create the instace of DataContext class named xrm
            var myXrm = new xrm("CRMOnPremise");
          
// use concept of Implicitly type local variable 
           
// and object intializer
            var testEntity = new new_test()
            {
                new_name = "Nishant",
                new_lastname = "Rana"
            };
            myXrm.AddTonew_tests(testEntity);
            myXrm.SaveChanges();

 
 

Similarly to update a record and delete a record we need to use

UpdateObject() and DeleteObject() function followed by call to

SaveChanges() method.

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.

Microsoft LightSwitch: 15 Reasons Non-Programmers Should Try It Out – Application Development from eWeek


Check out this informative article !

Microsoft LightSwitch: 15 Reasons Non-Programmers Should Try It Out – Application Development from eWeek.

CrmService in CRM 3.0 and CRM 4.0.


Suppose we have a custom entity named Test

having

Name, First Name and Last Name as varchar field.

And Picklist field called Hobby with default value as Music.

If we are creating a new record for this entity using CrmService from an external application, by only specifying value of First Name field.

It would create the record for us, however the value for Hobby picklist field would be null (it won’t consider the default value set for it)

mf1CRM3

However if we create the same record in CRM 4.0 either by using CrmService’s 3.0 end point or 4.0 end point, in both the cases the value for Hobby field would be set to Music, even though we hadn’t specified any value for it while creating the record.

mf1

CRM 4.0 does take in to account the default value set for the fields. So the records created would have proper default value set for those fields even if no value has been assigned to them, while creating the record.

Bye..