Search Chirayu Software Solutions Blog

Thursday, September 13, 2012

Data Type Conversion


Type Conversions


Conversion is based on type compatibility and data compatibility.

There are two types of conversions:

1.  Implicit Conversion
2.  Explicit Conversion

Implicit Conversion


In implicit conversion the compiler will make conversion for us without asking.

char -> int -> float is an example of data compatibility.

Complier checks for type compatibility at compilation.  

Practical demonstration of implicit conversion


using System;

namespace implicit_conversion
{
    class Program
    {
        static void Main(string[] args)
        {
            int num1 =20000;
            int num2 =50000;
            long total;
            // In this the int values are implicitly converted to long data type;
            //you need not to tell compiler to do the conversion, it automatically does.
            total = num1 + num2;

            Console.WriteLine("Total is : " + total);
            Console.ReadLine();
        }
    }
}

Below table shows the implicitly type conversions that are supported by C#:
  
From
To
sbyte
short, int, long, float, double, decimal
byte
short, ushort, int, uint, long, ulong, float, double, decimal
short
int, long, float, double, decimal
ushort
int, uint, long, ulong, float, double, decimal
int
long, float, double, decimal
uint
long, ulong, float, double, decimal
long
float, double, decimal
ulong
float, double, decimal
float
double
char
ushort, int, uint, long, ulong, float, double, decimal

Explicit Conversion


In explicit conversion we specifically ask the compiler to convert the value into another data type.

CLR checks for data compatibility at runtime.

Explicit conversion is carried out using casts. When we cast one type to another, we deliberately force the compiler to make the transformation.

You should never expect that the cast would give you best or correct result. Casts are potentially unsafe. Casting of big data type into small may lead to loosing of data.

Practical demonstration of explicit conversion


using System;

namespace explicit_conversion
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = 65;
           
            char alpha;
            alpha = (char)num;
            // In this the int values are explicitly converted to char data type;
            //you have to tell compiler to do the conversion, it uses casting.
           
            Console.WriteLine("alphabet is: " + alpha);
            Console.ReadLine();
        }
    }
}

Note: You can also use Explicit Cast Operator () and unboxing for explicit conversion.

Microsoft .NET provides three ways of type conversion:

1.  Parsing
2.  Convert Class
3.  Explicit Cast Operator ()

Parsing


Parsing is used to convert string type data to primitive value type. For this we use parse methods with value types.

Practical demonstration of parsing


using System;

namespace parsing
{
    class Program
    {
        static void Main(string[] args)
        {
            //using parsing

            int number;
            float weight;

            Console.Write("Enter any number : ");
            number = int.Parse(Console.ReadLine());

            Console.Write("Enter your weight : ");
            weight = float.Parse(Console.ReadLine());

            Console.WriteLine("You have entered : " + number);
            Console.WriteLine("You weight is : " + weight);

            Console.ReadLine();
        }
    }
}

Convert Class


One primitive type to another primitive type.

This class contains different static methods like ToInt32(), ToInt16(), ToString(), ToDateTime() etc used in type conversion.

Practical demonstration of Convert class


using System;

namespace convert_conversion
{
    class Program
    {
        static void Main(string[] args)
        {
            // example of using convert class

            string num = "23";
            int number = Convert.ToInt32(num);

            int age = 24;
            string vote = Convert.ToString(age);

            Console.WriteLine("Your number is : " + number);
            Console.WriteLine("Your voting age is : " + age);

            Console.ReadLine();
        }
    }
}

Explicit Cast Operator ()

In general this operator is used with non-primitive types to up level or down level casting. But it can also used with any type having type compatibility and data type compatibility.

using System;

namespace explicit_cast_conversion
{
    class Program
    {
        static void Main(string[] args)
        {
            int num1, num2;
            float avg;
            num1 = 10;
            num2 = 21;
            avg = (float)(num1 + num2) / 2;

            Console.WriteLine("average is : " + avg);
            Console.ReadLine();
        }
    }
}

Dilaog box in .net


Standalone applications typically have a main window that both displays the main data over which the application operates and exposes the functionality to process that data through user interface (UI) mechanisms like menu bars, tool bars, and status bars. A non-trivial application may also display additional windows to do the following:
  • Display specific information to users.
  • Gather information from users.
  • Both display and gather information.
These types of windows are known as dialog boxes, and there are two types: modal and modeless.

modal dialog box is displayed by a function when the function needs additional data from a user to continue. Because the function depends on the modal dialog box to gather data, the modal dialog box also prevents a user from activating other windows in the application while it remains open. In most cases, a modal dialog box allows a user to signal when they have finished with the modal dialog box by pressing either an OK or Cancel button. Pressing the OK button indicates that a user has entered data and wants the function to continue processing with that data. Pressing the Cancel button indicates that a user wants to stop the function from executing altogether. The most common examples of modal dialog boxes are shown to open, save, and print data.
modeless dialog box, on the other hand, does not prevent a user from activating other windows while it is open. For example, if a user wants to find occurrences of a particular word in a document, a main window will often open a dialog box to ask a user what word they are looking for. Since finding a word doesn't prevent a user from editing the document, however, the dialog box doesn't need to be modal. A modeless dialog box at least provides a Close button to close the dialog box, and may provide additional buttons to execute specific functions, such as a Find Next button to find the next word that matches the find criteria of a word search.


1. Font Dialog


FontDialog presents a font selection dialog box.Itallows the user to select a font from the list of installed fonts in the C# Windows Forms program. With the FontDialog control, we quickly add the ability for users to select their favorite fonts.
FontDialog screenshot


Get startedTo start using the FontDialog in a program, add a FontDialog instance, and also a Button and a TextBox to an empty Windows Form. Then, double-click on the Button to insert the button1_Click event handler. In the code for button1_Click, we call the ShowDialog method on the FontDialog instance.
Example program that opens FontDialog [C#]

using System;
using System.Drawing;
using System.Windows.Forms;

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

 private void button1_Click(object sender, EventArgs e)
 {
     // Show the dialog.
     DialogResult result = fontDialog1.ShowDialog();
     // See if OK was pressed.
     if (result == DialogResult.OK)
     {
  // Get Font.
  Font font = fontDialog1.Font;
  // Set TextBox properties.
  this.textBox1.Text = string.Format("Font is: {0}", font.Name);
  this.textBox1.Font = font;
     }
 }
    }
}
2.Color Dialog
ColorDialog displays a color selection window. By using the ColorDialog, you can enable a visual interface for selecting a specific color. Some options are provided through properties on this control.
ColorDialog screenshot
ExampleTo begin, we will add the ColorDialog instance to the form and then use it in some C# code. Most of the work you do with the ColorDialog will require the ShowDialog method and also the Color property. When you invoke ShowDialog, please remember to check the DialogResult; you do not want to take an action when the dialog was canceled.
Example that uses ColorDialog control [C#]

using System;
using System.Windows.Forms;

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

 private void Form1_Load(object sender, EventArgs e)
 {
     // Show the color dialog.
     DialogResult result = colorDialog1.ShowDialog();
     // See if user pressed ok.
     if (result == DialogResult.OK)
     {
  // Set form background to the selected color.
  this.BackColor = colorDialog1.Color;
     }
 }
    }
}
3.Save File Dialog
The save file dialog box, shown in the following figure, is used by file saving functionality to retrieve the name of a file to save.
Save As dialog box
Example

Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension 

// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();

// Process save file dialog box results 
if (result == true)
{
    // Save document 
    string filename = dlg.FileName;
}



String manuplation

1. Trim()
  It strips all white spaces from both the start and end of the string. 

//STRIPS WHITE SPACES FROM BOTH START + FINSIHE 
string Name = " String Manipulation " ; 
string NewName = Name.Trim(); 
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED 
MessageBox.Show("["+ NewName + "]");

2.TrimEnd()
TrimEnd works in much the same way but u are stripping characters which you specify from the end of the string, the below example first strips the space then the n so the output is String Manipulatio.
//STRIPS CHRS FROM THE END OF THE STRING 
string Name = " String Manipulation " ; 
//SET OUT CHRS TO STRIP FROM END 
char[] MyChar = {' ','n'}; 
string NewName = Name.TrimEnd(MyChar); 
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED 
MessageBox.Show("["+ NewName + "]");
3.TrimStart()
TrimStart is the same as TrimEnd apart from it does it to the start of the string.
//STRIPS CHRS FROM THE START OF THE STRING 
string Name = " String Manipulation " ; 
//SET OUT CHRS TO STRIP FROM END 
char[] MyChar = {' ','S'}; 
string NewName = Name.TrimStart(MyChar); 
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED 
MessageBox.Show("["+ NewName + "]")
4.IndexOf()
Find String within string
This code shows how to search within a string for a sub string and either returns an index position of the start or a -1 which indicates the string has not been found.
string MainString = "String Manipulation"; 
string SearchString = "pul"; 
int FirstChr = MainString.IndexOf(SearchString); 
//SHOWS START POSITION OF STRING 
MessageBox.Show("Found at : " + FirstChr );
5.Replace()
Replace string in string
Below is an example of replace a string within a string. It replaces the word Manipulatin with the correct spelling of Manipulation.
string MainString "String Manipulatin"; 
string CorrectString = MainString.Replace("Manipulatin", "Manipulation"); 
//SHOW CORRECT STRING 
MessageBox.Show("Correct string is : " + CorrectString);
6.Remove()
Strip specified number of characters from string
This example show how you can strip a number of characters from a specified starting point within the string. The first number is the starting point in the string and the second is the amount of chrs to strip. 

string MainString = "S1111tring Manipulation"; 
string NewString = MainString.Remove(1,4); 

//SHOW OUTPUT 
MessageBox.Show(NewSring);

7.Split()

Split string with delimiter
The example below shows how to split the string into seperate parts via a specified dilemeter. The results get put into the Split array and called back via Split[0].
string MainString = "String Manipulation"; 
string [] Split = MainString.Split(new Char [] {' '}); 
//SHOW RESULT 
MessageBox.Show(Convert.ToString(Split[0])); 
MessageBox.Show(Convert.ToString(Split[1]));


Intermediate language


MSIL is the intermediate language which is platform independent. High level language compilers for .Net languages compile the high level code into IL which is not hardware specific.
The use of IL allows integration of code written in different .Net languages which can be linked into one assembly. All lang compilers would produce IL code which is independent of the high level languages used.
IL uses common type system to bring data types of all .Net languages to a common platform.

Managed code ,unmanaged code and jitter in .NET


.NET supports two kind of coding

Managed Code
Unmanaged Code

Managed Code


The resource, which is with in your application domain is, managed code. The resources that are within domain are faster.

The code, which is developed in .NET framework, is known as managed code. This code is directly executed by CLR with help of managed code execution. Any language that is written in .NET Framework is managed code.

Managed code uses CLR which in turns looks after your applications by managing memory, handling security, allowing cross - language debugging, and so on.



Unmanaged Code

The code, which is developed outside .NET, Framework is known as unmanaged code.

Applications that do not run under the control of the CLR are said to be unmanaged, and certain languages such as C++ can be used to write such applications, which, for example, access low - level functions of the operating system. Background compatibility with code of VB, ASP and COM are examples of unmanaged code.

Unmanaged code can be unmanaged source code and unmanaged compile code.

Unmanaged code is executed with help of wrapper classes.

Wrapper classes are of two types: CCW (COM Callable Wrapper) and RCW (Runtime Callable Wrapper).

Wrapper is used to cover difference with the help of CCW and RCW.

jitter

The entity that compiles CIL code into meaningful CPU instructions is termed a just-in-time (JIT) compiler, which sometimes referred as Jitter.

Tuesday, September 11, 2012

Artificially Rotate a Wheel WPF

Step 1  Dowload this Image.

Step - 2  Add image tag
  <Image Margin="41,30,38,35" Name="image1" Stretch="None"  IsEnabled="True" StretchDirection="Both" Source="/WpfApplication1;component/Images/wheel.png" />
Note:Select our own Source Path
Step - 3 Add the following code in on Window_Loaded

 private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            DoubleAnimation da = new DoubleAnimation
                (360, 0, new Duration(TimeSpan.FromSeconds(3)));
            RotateTransform rt = new RotateTransform();
            image1.RenderTransform = rt;
            image1.RenderTransformOrigin = new Point(0.5, 0.5);
            da.RepeatBehavior = RepeatBehavior.Forever;
            rt.BeginAnimation(RotateTransform.AngleProperty, da);
        }
Step - 4 Run and Check the Output