Showing posts with label dotnet. Show all posts
Showing posts with label dotnet. Show all posts

Monday, 6 February 2017

How to develop your own Text to Speech (Jarvis) Application


This post demonstrates how to develop your own Text to Speech application simply a "Jarvis".

This application is written to just show how simple it is to write text to speech in C#. This application is not fully developed (no multi-threading, no asynchronous calls).

Please follow the blog for fully functional Text to Speech application.

This is how our Jarvis looks like -











Follow these steps to create your own Jarvis -

1. Create a new project of type "Windows Forms Application" targeting .NET Framework 4

Refer to this tutorial How to add a reference to a project






2. Add a reference to System.Speech library


3. Add a System.Speech.Synthesis namespace to your application




4. Modify Form1.cs code as shown below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MetroFramework.Forms;
using System.Speech.Synthesis;

namespace Text_to_Speech
{
    public partial class Form1 : MetroForm
    {        
        private static SpeechSynthesizer synth = new SpeechSynthesizer();
        public Form1()
        {
            InitializeComponent();
        }

        private void btnRead_Click(object sender, EventArgs e)
        {

            VoiceGender voiceGender = VoiceGender.NotSet;
            int rate = trackBarRate.Value;

            //assign voice Gender based on selection
            if(rdMale.Checked)
            {
                voiceGender = VoiceGender.Male;
            }                
            else
            {
                voiceGender = VoiceGender.Female;
            }

            //set speech rate
            synth.Rate = rate;

            //set voice gender from user selection
            synth.SelectVoiceByHints(voiceGender);

            //welcome message
            synth.Speak("Welcome to Jarvis Application, Version one point oh!");                        

            //start speech
            synth.Speak(txtReadText.Text);
        }
    }
}

5. Copy some text in the text box and click the button Start. So the application starts reading the text in the selected voice type at the given rate.

At the runtime you cannot stop, change voice and rate. To support this we have to add threads in our appication. Please follow this blog for fully developed application.

Wednesday, 18 May 2016

How to add a reference to a library in Windows Forms Application


This post explains how to add a reference to a library in Windows Forms Application.

By default when we create a new Windows Forms Application, the visual studio adds references to only needed libraries to run a windows form application.





In Solution Explorer, References folder contains a list of referenced libraries.

By default, visual studio adds the list of libraries shown in the picture to win form application when you create a new project.





Depending on application requirements the application requires extra libraries (internal or external) to perform some tasks. In this case we have to add a reference to the required libraries.


Follow these simple steps to add a reference to a library for example "System.Speech". This library contains members which supports in speech related tasks.


1. Create a new project of type "Windows Forms Application" from Windows Desktop template with a name "AddSpeechRef".





2. In Solution Explorer, right-click on References folder, Click on "Add Reference" as shown here.








3. From Reference Manager dialog, enter "Speech" in search box, depending on targeted .Net Framework (here targeted .Net Framework 4.0), the corresponding library version will be shown in search results.




Select a check-box "System.Speech" and click OK.








At this point we have added a reference successfully.




4. Simply adding a reference to our application is not sufficient. To use members of added library, we have to add a namespace of library with a keyword "using".




In Form1.cs, add a line "using System.Speech.Synthesis" as shown below. Now we can use all members of the library in application.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Speech.Synthesis;  //add namespace in order to utilize members of library

namespace AddSpeechRef
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    }
}

In case of external libraries, in Reference Manager dialog, click on Browse and locate the library files (*.dll) on local machine and click on Add.

Tuesday, 17 May 2016

Change Console Foreground Color, Background Color and Title in C#


This post explains how to change foreground color, background color and title of  console window in C#.

In some cases it is required to change the text color in console window depending on the context of application. For example, green color text indicating success or red color text indicating error/warning.

Here is the sample code -

Create a new project of type console application with a name "ConsoleDemoApp" and enter the code in Program.cs as shown here.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Threading;

namespace ConsoleDemoApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // We want to save the current console color and background color so we can restore it later
            ConsoleColor oldColor = Console.ForegroundColor;
            ConsoleColor oldBackgroundColor = Console.BackgroundColor;            

            // Set the new console color to Green and background color to Gray
            Console.ForegroundColor = ConsoleColor.Green;
            Console.BackgroundColor = ConsoleColor.DarkGray;
                        
            //set title of console window
            //If you don't set the title, the console window shows the fullpath of .exe in title
            Console.Title = "Console Demo Application";

            // Tell everyone what this program is when it starts
            Console.WriteLine("Welcome to Demo Application");

            Random random = new Random();
            while (true)
            {
                Console.Write("Ask any question: ");
                string question = Console.ReadLine();
                //console window exits until u enter either quit or exit
                if (question.ToLower() == "quit" || question.ToLower() == "exit")
                {
                    break;
                }
                Console.Write("Answer: ");
                switch( random.Next(4) )
                {
                    case 0:
                        Console.WriteLine("Yes!");
                        break;
                    case 1:
                        Console.WriteLine("No!");
                        break;
                    case 2:
                        Console.WriteLine("Probably.");
                        break;
                    case 3:
                        Console.WriteLine("I don't understand!!!");
                        break;
                }
            }

            // Restore the old foreground color and background color
            Console.ForegroundColor = oldColor;
            Console.BackgroundColor = oldBackgroundColor;
        }
    }
}

Output -



Friday, 6 March 2015

SIMD in .NET

Welcome to Logically Proven blog.

This post demonstrates SIMD vector type.

What is SIMD?

SIMD stands for "Single Instruction, Multiple Data". It is a set of processor instructions that operate over vectors instead of scalars. This allows mathematical operations to execute over a set of values in parallel.

In other words, a single instruction which performs multiple operations on the data parallely.


SIMD is a technology that enables data parallelization at the CPU level.

Difference between Multi-threading and SIMD?

You might be thinking why we need SIMD when we achieve the data parallelization with multi-threading.

While multi-threading is certainly a critical part, it is important to realize that it is still important to optimize the code that runs on a single core.

Multi-threading allows parallelizing work over multiple cores while SIMD allows parallelizing work within a single core.

Hope you got answer to your question.

The next generation JIT compiler RyuJIT for .NET supports SIMD functionality.

Why do I care?

The following statistics will answer this question.

SIMD offers a significant speed-up for certain kind of applications. For example, the performance of rendering Mandelbrot (complex mathematical operations) can be improved a lot by using SIMD.

It improves up to 3 times using SSE2 capable hardware and up to 5 times using AVX (Advanced Vector Extensions) capable hardware.

SSE2 and AVX are extensions to the instruction set architecture for microprocessors from INTEL.
Click on the provided links to know more about these extensions.


Sample Code

Consider you need to increment a set of floating point numbers by a given value.
Normally, you had to write a for loop to perform this operation sequentially as shown below -

float[] values = GetValues();
float increment = GetIncrement();

// Perform increment operation as manual loop:
for (int i = 0; i < values.Length; i++)
{
    values[i] += increment;
}

SIMD allows adding multiple values simultaneously by using CPU specific instructions. This is often exposed as a vector operation:

Vector<float> values = GetValues();
Vector<float> increment = GetIncrement();

// Perform addition as a vector operation:
Vector<float> result = values + increment;


Note that there is no single SIMD specification. Rather, each processor has a specific implementation of SIMD. They differ by the number of elements that can be operated on as well as by the set of available operations. The most commonly used implementation of SIMD on Intel/AMD hardware is SSE2.

SIMD at the CPU level

1. There  are SIMD-specific CPU registers. They have a fixed size. For SSE2, the size is 128 bits.

2. The processor has SIMD-specific instructions, specific to the operand size. As far as the processor is concerned, a SIMD value is just a bunch of bits. However, a developer wants to treat those bits as a vector of, say, 32-bit integer values. For this purpose, the processor has instructions that are specific to the operation, for example consider the operand type is addition, thus 32-bit integers.

Usage

The SIMD operations are very useful in graphical and gaming applications.

Use when
  • The applications are very computation-intensive.
  • Most of the data structures are already represented as vectors.

However, SIMD is applicable to any application type that performs numerical operations on a large set of values; this also includes complex, scientific computing and finance.

How to Install?

3 steps -
  1. Download compiler.
  2. Set Environment variables.
  3. Add a reference in your project to NuGet package Microsoft.Bcl.Simd
Compiler

Download and install the latest preview of RyuJIT from http://aka.ms/RyuJIT

NuGet package

The SIMD APIs are available via NuGet package - Microsoft.Bcl.Simd

Set Environment Variables

To enable the new JIT and SIMD, we need to set some environment variables. The easiest way to do is creating a batch file that starts your application.

@echo off
set COMPLUS_AltJit=*
set COMPLUS_FeatureSIMD=1
start myapp.exe

Limitations

  • SIMD is only enabled for 64-bit processes.
  • The vector type only supports int, long, float and double.
  • Currently SIMD is taking advantage of SSE2 hardware. AVX is not supported.

SIMD Example

The example contains how to leverage SIMD from C#. Check this link from MSDN for the detailed explanation - SIMD Example from MSDN


Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.

Logically Proven
Learn, Teach, Share

Ref: Thanks to MSDN

Thursday, 5 March 2015

ASP.Net vNext - A Completely New Version




This post demonstrates PROS and CONS of the ASP.Net vNext, a completely new version of ASP.Net. There is some super exciting stuff going on in the .NET community right now. I'm going to post a few entries on my favourites.


ASP.Net vNext -


This ASP version is so awesome. It is currently under development. It combines technologies like ASP.NET MVC and Web API into a single programming model and will be cross platform.
The framework will be called ASP.NET 5 when it gets ready.


PROS -


1. It is an open source. that's right. it is on github. Go make a contribution! - Github-vNext  

2. It is totally unbound to IIS, so you can host it pretty much anywhere .net can run. Since Mono allows dotnet to run pretty much anywhere, ASP can run pretty much anywhere. like on a Mac in the console, on your Linux server, on your netduino, raspi, your grandma's old 386 in the basement she refuses to throw away.  

3. It is highly customizable and extensible with dependency injection as a first class concept so you and add and remove features and functionality as you see fit.  

4. Runtime, in memory compilation, with the Roslyn compiler means way faster start-ups. Check this link for more details on the compiler - Roslyn compiler  

5. The project system is changing, dramatically so there is a learning curve here, but IMO it is much better in the long run as it promises to ease many of the pain points of the csproj files.

 6. The new project system is also likely going to be a blacklisted project system. so you must EXCLUDE files you don't care about rather than INCLUDE all the files you do. This will make merges much cleaner.  

7. Everything is based on the best data interchange format ever! json config files* and json project files and json package manifests.  

8. An entirely new "environment" or "host" aware configuration system allows you to read config settings from multiple providers like your project-local config files, host-global files, environment variables, databases, web services, etc. you can pretty much just implement your own config provider and read from anywhere.  

9. Supports Raspberry Pi which relates to the field of embedded systems.


CONS -


1. Suppose we got to learn how to do it and that is a learning curve but it looks like a not to steep of one.

 2. ASP web forms are not supported in vNext (they are too strongly tied to the System.Web). These are my favourites. Land on the github to know your favourites.


Please share your thoughts on this post in the comments section.

Monday, 23 February 2015

Named and optional arguments in C# programming

Welcome to Logically Proven blog.

This post demonstrates Named and Optional Arguments in C# programming.

If you worked on VBA (Visual Basic for Applications) programming earlier, then you are very familiar with optional arguments which is a very well-known feature and very useful.

Microsoft introduces optional arguments as well as named arguments with Visual C# 2010 version.

Both techniques can be used with methods, indexers, constructors, and delegates.

Now we discuss in detail about named and optional arguments.

Named Arguments:

When we are passing the arguments, it is important to always remember the order of parameters they appear in the called methods. By using named arguments, we are free from the need to remember or to look up the order of parameters of called methods. It doesn't mean that you can pass the arguments in any order, but this feature allows you to specify the parameter for each argument by parameter name.

For example, consider a function that calculates the area of a rectangle. The standard way of sending arguments for length and width are

CalculateAreaOfRectangle(20,10)

If you don't remember order of the parameters, you can send the arguments like below -

CalculateAreaOfRectangle(length: 20, width: 10);
//or
CalculateAreaOfRectangle(width:10, length: 20);
//or
CalculateAreaOfRectangle(20, width:10);   //A named argument can follow positional arguments

The following statement causes a compiler error:

CalculateAreaOfRectangle(width:20, 10); // A positional argument cannot follow a named argument

Named arguments also improve the readability of code by identifying what each argument represents.

Example:


class NamedArgExample
{
    static void Main(string[] args)
    {
        // The method can be called in the normal way, by using positional arguments.
        Console.WriteLine(CalculateAreaOfRectangle(20, 10));

        // Named arguments can be supplied for the parameters in either order.
        Console.WriteLine(CalculateAreaOfRectangle(length: 20, width: 10));
        Console.WriteLine(CalculateAreaOfRectangle(width: 10, length: 20));

        // Positional arguments cannot follow named arguments. 
        // The following statement causes a compiler error. 
        //Console.WriteLine(CalculateAreaOfRectangle(width: 20, 10)); 

        // Named arguments can follow positional arguments.
        Console.WriteLine(CalculateAreaOfRectangle(20, width: 10));
    }

    static int CalculateAreaOfRectangle(int length, int width)
    {
        return (length*width);
    }
}


Optional Arguments:

Consider a case where you don't require to send arguments for every parameter. In this scenario you can use optional arguments. Optional arguments allows you to omit arguments for some parameters. The arguments are considered as optional when the parameters are initialized to a default value or a constant expression.

Each optional parameter has a default value as part of its defintion. Because if no argument is sent for that parameter, the default value is used. A default value must be one of the following types of expressions -

1. a constant expression;
2. an expression of the form new valType(), where valType is a value type, such as an enum or a struct;
3. an expression of the form default(valType), where valType is a value type.

Optional parameters should appear only at the end of the parameter list (only after required parameters).

Consider a method with 3 parameters. Among three, first parameter is required and the rest are optional parameters.

public void Example(int required, string optionalstr = "default string",
    int optionalint = 10)

The following statement causes a compiler error. Comma-separated gaps in the argument list are not supported.

anExample.Example(3, ,4); //compiler error

You can accomplish this task by using named argument  -

anExample.Example(3, optionalint:4); //using named argument

Example:Note a constructor with named argument.


namespace OptionalArgNamespace
{
    class OptionalArgExample
    {
        static void Main(string[] args)
        {
            // Instance anExample does not send an argument for the constructor's 
            // optional parameter.
            Example anExample = new Example();
            anExample.Example(1, "One", 1);
            anExample.Example(2, "Two");
            anExample.Example(3);

            // Instance anotherExample sends an argument for the constructor's 
            // optional parameter.
            Example anotherExample = new Example("Provided name");
            anotherExample.Example(1, "One", 1);
            anotherExample.Example(2, "Two");
            anotherExample.Example(3);

            // The following statements produce compiler errors. 

            // An argument must be supplied for the first parameter, and it 
            // must be an integer. 
            //anExample.Example("One", 1);
            //anExample.Example(); 

            // You cannot leave a gap in the provided arguments.  
            //anExample.Example(3, ,4); 
            //anExample.Example(3, 4); 

            // You can use a named parameter to make the previous  
            // statement work.
            anExample.Example(3, optionalint: 4);
        }
    }

    class Example
    {
        private string _name;

        // Because the parameter for the constructor, name, has a default 
        // value assigned to it, it is optional. 
        public Example(string name = "Default name")
        {
            _name = name;
        }

        // The first parameter, required, has no default value assigned 
        // to it. Therefore, it is not optional. Both optionalstr and  
        // optionalint have default values assigned to them. They are optional. 
        public void Example(int required, string optionalstr = "default string",
            int optionalint = 10)
        {
            Console.WriteLine("{0}: {1}, {2}, and {3}.", _name, required, optionalstr,
                optionalint);
        }
    }

    // The output from this example is the following: 
    // Default name: 1, One, and 1. 
    // Default name: 2, Two, and 10. 
    // Default name: 3, default string, and 10. 
    // Provided name: 1, One, and 1. 
    // Provided name: 2, Two, and 10. 
    // Provided name: 3, default string, and 10. 
    // Default name: 3, default string, and 4.

}


Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.

Logically proven
Learn, Teach, Share

Friday, 20 February 2015

Boxing and Unboxing in C#

Welcome to Logically Proven Blog.
This post demonstrates boxing and unboxing in C#.

C# type system has two varieties of data types: value type and reference type.

Value type: built-in data types like int, long, bool or user-defined structures (struct)
Reference type: string, array, objects (classes) etc.,

Let me ask you one question here - is int[] (array of integers) a value type or a reference type?

Array is a single collection of several items. Microsoft .NET CLR (Common Language Runtime) states that all array types are reference types. All arrays are implicitly derived from System.Array which itself derived from System.Object. This means all arrays are reference types.

It is very important to know how C# manages data and memory.

A value type stores its contents is allocated in a memory called the stack.
A reference type, such as an instance of an class or an array, is allocated in a memory called the heap.

For example:  int i = 123;  //allocates on stack
    TestClass obj = new TestClass(); //allocates instance of a class on heap

Boxing:

Boxing is the process of converting a value type to the object type or to any interface type implemented by this value type. When we boxes a value type, the CLR (Common Language Runtime) wraps it inside a System.Object type and stores it on the managed heap (copies the value into the new object which is allocated on a heap).

Example:

By default, the boxing process is an implicit conversion.


int i = 123;
// The following line boxes i. 
object o = i;  

Explciit boxing is an optional. But it is never required.

int i = 123;
object o = (object)i;  // explicit boxing

Changing the value type has no effect on boxed value type.

class TestBoxing
{
    static void Main()
    {
        int i = 123;

        // Boxing copies the value of i into object o. 
        object o = i;  

        // Change the value of i.
        i = 456;  

        // The change in i does not effect the value stored in o.
        System.Console.WriteLine("The value-type value = {0}", i);
        System.Console.WriteLine("The object-type value = {0}", o);
    }
}
/* Output:
    The value-type value = 456
    The object-type value = 123
*/

Unboxing:

Unboxing is a reverse process of boxing means converting an object type to a value type or from an interface type of a value type that implements the interface. Unboxing is an explicit conversion.

An unboxing operation consists of -

Checking the object instance to make sure that it is a boxed value of a given type.
Copying the value from the instance into the value-type variable.

Example:


o = 123;
i = (int)o;  // unboxing

Possible exceptions while working with unboxing:

While we are working with unboxing operation there is a possiblity of NullReferenceException and InvalidCastException

NullReferenceException: Attempting to unbox null causes an NullReferenceException.
InvalidCastException: Attempting to unbox a reference to an incompatible value type causes an InvalidCastExcpetion.

Example demonstrating InvalidCastException:


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

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

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

//output: Specified cast is not valid. Error: Incorrect unboxing.
//correct statement is int j=(int)o;

Performance:

It is best to avoid using value types in situations where they must be boxed a high number of times. Boxing and unboxing are computationally expensive process (boxing has to create a new object, this can take up to 20 times longer than a simple reference assignment and unboxing takes 4 times as long as an assignment).


Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.

Logically proven
Learn, Teach, Share

Thursday, 19 February 2015

C# list of Operators and precedence table

This post demonstrates available C# operators and their order of precedence.
C# provides a large set of operators, which are symbols that specify which type of operations to perform in an expression.
A language may contain a fixed number of built-in operators (e.g. +, -, *, < etc. in C and C++), or it may allow the creation of user-defined operators (e.g. F#, OCaml, Haskell).

In C#, we are allowed to create user-defined types for operators by using operator overloading, thus changing their meaning when applied. To know how to define your own operators – Operator Overloading
The table lists the C# operators grouped in order of precedence from highest to lowest.
Operators within each group have equal precedence. For operators with equal precedence (e.g., + and -) are evaluated in an expression based on the associativity. Please follow this link to know the associativity of operators with equal precedence - Associativity of C# Operators

 
Operator Category Operators
Primary x.y
f(x)
a[x]
x++
x--
new
typeof
checked
unchecked
default(T)
delegate
sizeof
->
Unary +x
-x
!x
~x
++x
--x
(T)x
await
&x
*x
Multiplicative x*y
x/y
x%y
Additive x+y
x-y
Shift x<
x>>y
Relational and type testing x
x>y
x<=y
x>=y
is
as
Equality x==y
x!=y
Logical AND x & y
Logical XOR x ^ y
Logical OR x | y
Conditional AND x && y
Conditional OR x || y
Null-coalescing x ?? y
Conditional ?:
Assignment and lambda expression x=y
x+=y
x-=y
x*=y
x/=y
x%=y
x&=y
x|=y
x^=y
x<<=y
x>>=y
=>

Note - The arithmetic operators e.g. addition, subtraction can produce results outside the range of possible values causes an exception depending on the execution context, which can be checked or unchecked. To know more about checked and unchecked - Click here

Please share your thoughts on this post in the comments section.

Checked and Unchecked operators in C#

This post demonstrates checked and unchecked operators in C#. While working with arithmetic operators (+, -, *, /), there is a possibility of overflow.
The arithmetic operations produce results outside the range of possible values which causes an exception depends on the execution context, which can be checked or unchecked.
C# gives an option whether to handle the exception or ignore the exception. We are achieving these two contexts by making use of checked and unchecked operators.
Warning - In checked or unchecked context; integer division by zero or decimal division by zero always throws an exception Divide By Zero Exception.

Checked -

In simple, this operator is used to throw Overflow Exception. This keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.
If we don’t specify checked/unchecked, the execution depends on the compiler options. The following operations are affected by the checked and unchecked keywords –

  • Expressions using the operators ++, --, - (unary) and arithmetic operators.
  • Explicit numeric conversions between integral types. (int, long to short)

The following are the different ways to enable overflow exception in your application – Enable overflow checking for complete application - Open the project’s Properties page. (Right click on your project -> Properties) Select Build -> Click on Advanced button -> Check the box Check for arithmetic overflow/underflow property  

Enable overflow checking for an expression -
 
//checked for an expression
checked(expression)

  Enable overflow checking for a block of statements -
 
//checked for a block
checked
{
   statement1;
   statement2;
   ...
}
 
Note : By default non-constant expressions (expressions that contain non-constant terms e.g. expression ‘a= 10+ b’ where b is a non-constant term) are not checked for overflow by the compiler at compile time and run time until unless we include the checked keyword.

For Example -

// max value of integer is 2147483647
//This statement causes compiler error beacuse of constant expression
//int i1 = 2147483647 + 10; 

// No compiler error because of non-constant expression
int ten = 10;
int i2 = 2147483647 + ten;

// By default, the overflow in the previous statement also does 
// not cause a run-time exception. 
//The following line displays -2,147,483,639 as the sum of 2,147,483,647 and 10.
Console.WriteLine(i2);
 

Unchecked -

In simple, this operator is used to ignore Overflow Exception. This keyword is used to ignore the overflow-checking for integral-type arithmetic operations and conversions.
In this context, the most significant bits of the result are discarded and execution continues.

Disable overflow checking for an expression -
 
//unchecked for an expression
unchecked(expression)
 
Disable overflow checking for a block of statements -
 
//unchecked for a block
unchecked
{
   statement1;
   statement2;
   ...
}
 

Try This Sample Code -

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

namespace OverFlowExample
{
    class OverFlowExample
    {
        // max value of integer
        static int maxInt = 2147483647;

        // checked expression. 
        static int CheckOverflow()
        {
            int x = 0;
            try
            {
                // The following line raises an exception
                x = checked(maxInt + 10);
            }
            catch (System.OverflowException e)
            {
                //information about the error.
                Console.WriteLine("CHECKED:  " + e.ToString());
            }
            // The value of x is 0. 
            return x;
        }

        //unchecked expression. 
        static int UncheckOverflow()
        {
            int x = 0;
            try
            {
                // unchecked and will not raise an exception.
                x = maxInt + 10;
            }
            catch (System.OverflowException e)
            {
                // No exception;the following line will not be executed.
                Console.WriteLine("UNCHECKED:  " + e.ToString());
            }
            //overflow is suppressed
            // the sum of 2147483647 + 10 is returned as -2147483639. 
            return x;
        }

        static void Main()
        {
            Console.WriteLine("\nCHECKED output: {0}",
                              CheckOverflow());
            Console.WriteLine("UNCHECKED output: {0}",
                              UncheckOverflow());
        }          
    }
}
/*
       Output:
       CHECKED:  System.OverflowException: Arithmetic operation resulted
       in an overflow.
          at ConsoleApplication1.OverFlowExample.CheckOverflow() 

       CHECKED output: 0
       UNCHECKED output: -2147483639
*/

Please share your thoughts on this post in the comments section.

Wednesday, 18 February 2015

Operator overloading in C#

This post demonstrates how to define your own operators by using user-defined classes that can overload operators .
Operator overloading allows user to define own operator implementations to be specified for operations where the operands are of user-defined or struct type, thus changing their meaning when applied.

The following example changes the behaviour of built-in addition operator. Let name this user-defined operator as “Complex Addition”. Consider a complex number, num = 2+3i, where 2 is a real part and 3i is an imaginary part. So the complex addition operator sums the real parts and imaginary parts of two complex numbers.


Code -


// complex.cs
using System;

public struct Complex
{
 public int real;
 public int imaginary;

 //parametrized constructor
 public Complex(int real, int imaginary)
 {
  this.real = real;
  this.imaginary = imaginary;
 }

 // Declare which operator to overload (+), the types 
 // that can be added (two Complex objects), and the 
 // return type (Complex):
 public static Complex operator +(Complex c1, Complex c2)
 {
  return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
 }
 // Override the ToString method to display an complex number in the suitable format:
 public override string ToString()
 {
  return(String.Format("{0} + {1}i", real, imaginary));
 }

 public static void Main()
 {
  Complex num1 = new Complex(2, 3);
  Complex num2 = new Complex(3, 4);

  // Add two Complex objects (num1 and num2) through the
  // overloaded plus operator:
  Complex sum = num1 + num2;

  // Print the numbers and the sum using the overriden ToString method:
  Console.WriteLine("First complex number:  {0}", num1);
  Console.WriteLine("Second complex number: {0}", num2);
  Console.WriteLine("The sum of the two numbers: {0}", sum);

 }
}
/* output:
  First complex number:  2 + 3i
  Second complex number: 3 + 4i
  The sum of the two numbers: 5 + 7i
*/

Please share your thoughts on this post in the comments section.

Wednesday, 11 February 2015

Develop Android/ iOS apps in C#

Create Android/iOS applications using C#.
Using IDEs Dot32 and Xamarin, you can build apps in C#, run and deploy them usingMicrosoft Visual Studio.

Xamarin – http://xamarin.com/

  • Free version includes: Develop apps using Xamarin Studio, deploy to device and deploy to app stores.
  • Xamarin’s Android API exposes almost 100% of the Android’s – so you can build a complete android app in C#.
  • Follow this link to know about Xamarin’s Architecture: Architecture

dot42 – https://www.dot42.com/

  • Free version includes (Community License): Develop and publish free apps on a public market place such as Google Play.
  • It is basically a Visual Studio add-in that lets you compile your C# code directly to DEX code. This means there is no run-time requirement such as Mono.

Please share your thoughts on this post in the comments section.

Tuesday, 10 February 2015

Dealing with Optimistic Concurrency in Entity Framework - dotnet

Welcome to Logically Proven Blog.
This post teaches you “How to deal with Optimistic Concurrency in Entity Framework”.

In a real world situation it is quite possible that database values might have got changed after selecting them for modification. In such cases, your update operation might be overwriting changes made by someone else. That is why it becomes important to detect if concurrency violation has occurred.

Detecting Concurrency Violation:

Entity framework can be configured to use optimistic concurrency while updating database records. That means no locks are held on the data being modified. The data is updated only if the database values at the time of fetching the data and the database values currently stored in the database match.

In your SQL Server database table, just add an extra column “UpdateToken” of type rowversion. The rowversion data type ensures that the column holds a different value every time that record is updated. A rowversion column is automatically updated by the SQL Server and it won’t play any direct role in your application data. It allows us to detect if a record has been changed after the initial selection. However, merely adding a rowversion column is not sufficient. In the entity framework designer you also need to set the ConcurrencyMode property of the UpdateToken to Fixed.

Changing this setting will cause EF (Entity Framework) to use the UpdateToken column in the WHERE clause of the UPDATE queries it generates. This way a row is updated only when the value of UpdateToken at the time of initial fetch matches with the current value in the database. If they don’t match no record is updated and EF concludes that there was a concurrency violation. 














Code: 
public void DetailsView1_UpdateItem(int EmployeeID)
{
 EmployeeDbEntities db = new EmployeeDbEntities();
 Employee item = db.Employees.Find(EmployeeID);
 TryUpdateModel(item);
 System.Threading.Thread.Sleep(15000);
 try
 {
  db.SaveChanges();
 }
 catch (DbUpdateConcurrencyException ex)
 {
  lblErr.Text = ex.Message;
 }
}
The code then halts the execution for 15 seconds. This is done purely for the sake of testing. Adding this delay will allow you to switch to the physical database table and modify its data manually to test the concurrency violation. An alternative is set a breakpoint at SaveChanges() method to halt the execution and then change the database values manually.

Handling Concurrency Violation:

Once you detected concurrency violation, the next step is to decide what action to take. There are three approaches that you can take:
  • Do nothing. Simply show the error message to the user and exit from the data modification stage.
  • Update the entity under consideration from the latest data from the database table. Then show that data to the user so that he can take the necessary action.
  • Forcefully update the database table with the values from the entity.
The first approach is quite easy and that is what you used in the preceding example. The second approach requires you to load database values in an entity and present them to the user. You can do that in the catch block as shown below:

...
catch (DbUpdateConcurrencyException ex)
{
 lblErr.Text = "Concurrency violation! Please review the latest values shown above.";
 ex.Entries.Single().Reload();
 DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
}

As you can see the DbUpdateConcurrencyException class provides access to the entity causing the error. The Reload() method called on an entity loads the values from the database into that entity. You then change the mode of the DetailsView to ReadOnly so that user can read the new values.

In the third approach, you make the current database values as the original values and then attempt SaveChanges() again. This approach is as shown below:
...
catch (DbUpdateConcurrencyException ex)
{
 lblErr.Text = "Concurrency violation! Attempting to force save to the database.";
 var emp = ex.Entries.Single();
 emp.OriginalValues.SetValues(emp.GetDatabaseValues());
 db.SaveChanges();
}

Here, you set the OriginalValues of the entity under consideration to the current values from the database (obtained by calling GetDatabaseValues()). You then attempt SaveChanges() again.

These kinds of concurrency detections are very much useful when the updates to the table are from multiple places. For example, consider a banking application.

Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.


Logically Proven,
Learn, Teach, Share

 
biz.