Thursday, October 6, 2011

Transactions in ADO.Net ( TransactionScope Class )


A transaction is a logical unit of a work. There are few ways in implementing transactions.  Either you can implement it in your T-SQL Statements or inside of the program logic. There are two ways in implementing in the .net programming code you can use DbTransaction Object or TransactionScope.
I would implement here TransactionScope class.
It creates a standard transaction called a “local lightweight transaction” that is automatically promoted to a full-fledged distributed transaction if required. You can use even multiple connection objects if you have to update tables in two databases.
First have to import System.Transactions namespace.

        public void CreateTransactionScope()
        {
            SqlCommand ObjCmd = new SqlCommand();
            try
            {

                  // TransactionScope object defined here
                using (TransactionScope Scope = new TransactionScope()) 
                {
                    // _ConnectionString is the Class globally defined string value for the
                    database connection string
                    using (SqlConnection Sqlcon = new SqlConnection(_ConnectionString))
                    {
                        Sqlcon.Open(); // Opening the connection

                        // Assign Connection Object to SQLCommand Object
                        ObjCmd.Connection = Sqlcon;

                        //SQL Statement  to execute
                        ObjCmd.CommandText = "INSERT INTO TBL_EMOPLOYEES VALUES('"+ "001"
                                       +"', '"+ "Pathum Tiranga" +"','"+ "01/01/2011" +"')";
                        ObjCmd.CommandType = CommandType.Text;   

                        //Execution happen here
                        ObjCmd.ExecuteNonQuery();
                    }

                    /* At the ending of the Scope of the Transaction Scope commiting the
                      transaction was done 

                     If couldn't reach this statement all above datachanges happened to one
                      or more tables will be RolledBack
                     */
                    Scope.Complete();
                }
            }

            /* If an exception is thrown within the TransactionScope object’s using block,
               the transaction aborts, and all work is rolled back. */
            catch (Exception ex)
            {
                throw ex;
            }
        }

When you create a TransactionScope object in a using block, the TransactionScope object assigns a transaction to this created connection, so you don’t need to add anything to your code to enlist this connection into the transaction.

Wednesday, September 21, 2011

Generic


C# generics and C++ templates are very similar but they work differently. Generic exist to write code that is reusable across different types.

Let’s imagine we need a stack of integers if we didn’t have generic types, one solution is to hard code a separate version of a class for every required type “IntStack” but when we need stack of string have do the same way “StrStack”. This would cause considerable code duplication.

However this wouldn’t work aAnother solution would be write a stack that is generalizes by using Object as element type.s well hard coded “IntStack” & “StrStack” an “ObjectStack” require boxing & down casting that could not be checked at compile time.

int x = (int)stack.Pop(); // down casting

What we need is both a general implementation of a stack that works for all element type, and a way to easily specialize that stack to a specific element type for increased type safety and reduced boxing and casing.

Generics provide this by allowing parameterize element type.  Stack<T>  has the benefits of both “ObjectStack” and “IntStack”.

Test this example for further understanding.

    class Part
    {
        private string _PartId;
        private string _PartName;
        private string _PartDescription;
        private double _Weight;

        public string PartId { get { return _PartId; } }

        public Part(string PartId, string PartName, string PartDescription, double Weight)
        {
            _PartId = PartId;
            _PartName = PartName;
            _PartDescription = PartDescription;
            _Weight = Weight;

        }

        public override string ToString()
        {
            return string.Format("Part Id: {0}, Part Name:{1}, Part Description:{2}, weight:{3}", _PartId, _PartName, _PartDescription, _Weight);
        }


    }

 

   //the actual indexer, which accepts the generic type
    //note the type must be a class (not a value type)

    class Indexer<T> where T:class
    {
        struct ItemStruct
        {
            public string Key;
            public T value;
            public ItemStruct(string key, T value)
            {
                this.Key = key;
                this.value = value;

            }

        }

        List<ItemStruct> _items = new List<ItemStruct>();

        // T must be a class so that can return null if not found
        public T Find(string key)
        {
            foreach (ItemStruct _ItemStruct in _items)
            {
                if (_ItemStruct.Key == key)
                {
                    return _ItemStruct.value;
                }
            }
            return null;
        }

        public void Add(string key, T value)
        {
            _items.Add(new ItemStruct(key, value));
        }

    }

 
// Programe to Test it

    class Program
    {
        static void Main(string[] args)
        {


            Indexer<Part> indexer = new Indexer<Part>();

            Part p1 = new Part("001", "Mother Board", "Intel Chip set Mother Board", 0.75);
            Part p2 = new Part("002", "Processor", "Intel Core i5", 0.2);

            indexer.Add(p1.PartId, p1);
            indexer.Add(p2.PartId, p2);

            Part p = indexer.Find("002");

            Console.WriteLine(p.ToString());

           
            Console.ReadKey();
        }
    }








Tuesday, September 20, 2011

Structs in C#


Struct is very similar to a class but strcut is value type and class is reference type, .Net supports the value type and reference type unlike Java, in Java you can define only reference type.  Strcuts may leads to good performance where it’s used properly.

Reference types instances allocating in the managed heap and are garbage collected when there are no further references. Value types are allocated in the stack and so allocated memory is reclaimed as soon as their scope ends.  Using a value type instead reference type may result in fewer objects on the managed heap, which results less load to garbage collector (GC) and better performance.

Since for a value type, a compiler by default doesn’t generate a default constructor, struct doesn’t have parameter less constructor. And no finalizer, no virtual members and it derives only from System.ValuType, This System.ValueType may again derives from System.Object .    But structs can implement interfaces, in C# all primitive data types are value type except System.String
However value types have their poor sides too, when passing around big struct costlier than a reference type.

An example of declaring constructors.
    struct Point
    {
       private int x;
       private int y;

        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }

An example of calling struct constructors.
              Point point1 = new Point();
            Point point2 = new Point(1,3);

Wednesday, September 14, 2011

Crystal Report Problems solving with Visual Studio 2010


CRVS2010 Beta - file not found error crdb_adoplus.dll  

An error when running the product when have installed CR 2010.

"Could not load file or assembly 'file:///C:
Program Files
SAP BusinessObjects
SAP BusinessObjects Enterprise XI 4.0
win32_x86
dotnet1
crdb_adoplus.dll' or one of its dependencies.

Solution

Setting the useLegacyV2RuntimeActivationPolicy flag to True does "solve" the problem. However, that is a hack and not a true fix. In trying to create a purely .NET 4.0 application, the end user shouldn't have to add this flag to get an application to work. Hopefully someone at SAP will note this and fix it in the core Crystal Reports functionality before the final version for VS 2010 is released.

Add following section to your config file and it may resolve the issue.
<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0"/>
</startup>

Sunday, July 31, 2011

How to add Crystal Report for Visual Studio 2010


Crystal Reports for Visual Studio 2010 will be released separately, instead of included with the product.

Follow this link to download Crystal report for Visual Studio 2010, http://www.businessobjects.com/jump/xi/crvs2010/us2_default.asp

Click this highlighted link, download and install. 


After finishing the installation you will not see any tool in the tool box. Then go to the “Project Properties” (if you have open new project in C#.net or VB.net) and find the Target Framework, you would see it as .Net Framework 4 Client Profile change this to be .NET Framework 4


Change as .NET Framework 4
 

When you change to .NET Framework 4 confirm it by click Yes

Now you can see Crystal Report Viewer in Tool Box.


Mapping data flows in Azure Data Factory

  Overview: Data flows are one of the features inside the Azure Data Factory which allows data engineers to develop data transformation logi...