Showing posts with label .NET enviroment. Show all posts
Showing posts with label .NET enviroment. Show all posts

"Connecting ... " screen for C# and WPF

Recently i came across a situation where i had to create a screen which showed a establishing connection , i searched the "interweb" for this but found no good resource that provided me with the code ready to use. hence i decided to create one by my own.


What did i do? 

Well i used a canvas and ellipses within that. This  did the job for me and below are the screen shots





How to do it? 

I have provided inline comments with the code below,

The XAML code is below 


<Window x:Class="EstablishConn.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        WindowState="Normal" WindowStyle="ToolWindow"
        Title="Connecting ..." Height="125" Width="525">
    <Grid>
        <Canvas Name="MyCanvas"> </Canvas>
    </Grid>
</Window>



Your code Behind will be as below

You will have to include the below namespaces


using System.Windows.Shapes;
using System.Windows.Threading;

namespace EstablishConn
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
    }
}

The Main Logic 

/*
Global declaration
*/
int ELLIPSE_COUNT = 25;
int CURRENT_ELLIPSE_ID = 0;
private List<Ellipse> ellipseList;
Brush DEFAULT_ELLIPSE_COLOR = Brushes.LightSteelBlue;
Brush ELLIPSE_COLOR = Brushes.Blue;
Brush LIGHT_ELLIPSE_COLOR = Brushes.SkyBlue;
Brush DARK_ELLIPSE_COLOR = Brushes.DarkBlue;

/*
The dispatch timer object will be a timer that will raise a tick event every specified interval given in timespan
*/
DispatcherTimer timer = new DispatcherTimer { Interval =   TimeSpan.FromSeconds(0.05) };

/*
Constructor
*/
public MainWindow()
{
   InitializeComponent();
   ellipseList = new List<Ellipse>();
   CreateEllipseList();
   /*
   assign an handler for the DispatchTimer
   then start the timer
   */
   this.timer.Tick += new EventHandler(timer_Tick);
   this.timer.Start();
}


/*
this method will create the Ellipse s and allocate it to the 
Canvas
The created ellipses will also be added to a list to be    handled later
*/
private void CreateEllipseList()
{
   double LEFT = 10;
   for (int i = 0; i < ELLIPSE_COUNT; i++)
   {
       Ellipse e = new Ellipse();
       e.Height = 10;
       e.Width = 10;
       e.Fill = DEFAULT_ELLIPSE_COLOR;
       Canvas.SetLeft(e, LEFT);
       Canvas.SetTop(e, 50);
       MyCanvas.Children.Add(e);
       ellipseList.Add(e);
       LEFT = LEFT + 20;
   }
}

/*
This is the event handler for the timer 
Here the actual animation takes place
*/
private void timer_Tick(object sender, EventArgs e)
{
   ellipseList[CURRENT_ELLIPSE_ID].Fill = LIGHT_ELLIPSE_COLOR;
   ellipseList[CURRENT_ELLIPSE_ID + 1].Fill = ELLIPSE_COLOR;
   if (!(CURRENT_ELLIPSE_ID >= ELLIPSE_COUNT - 2))
      ellipseList[CURRENT_ELLIPSE_ID + 2].Fill = DARK_ELLIPSE_COLOR;

   if (CURRENT_ELLIPSE_ID > 0)
      ellipseList[CURRENT_ELLIPSE_ID - 1].Fill = DEFAULT_ELLIPSE_COLOR;

   CURRENT_ELLIPSE_ID = CURRENT_ELLIPSE_ID + 1;
   if (CURRENT_ELLIPSE_ID >= ELLIPSE_COUNT - 2)
   {
      ellipseList[CURRENT_ELLIPSE_ID - 1].Fill    = DEFAULT_ELLIPSE_COLOR;
      ellipseList[CURRENT_ELLIPSE_ID].Fill        = DEFAULT_ELLIPSE_COLOR;
      ellipseList[CURRENT_ELLIPSE_ID + 1].Fill    = DEFAULT_ELLIPSE_COLOR;

      CURRENT_ELLIPSE_ID = 0;
   }
}

Could not load file or assembly #MyAssembly# or one of its dependencies. An attempt was made to load a program with an incorrect format.


Could not load file or assembly #MyAssembly# or one of its dependencies. An attempt was made to load a program with an incorrect format. - PHIXED

This could be happening due to two reasons.

First. you are trying to build one of the projects within the solution in the wrong way!
Second. If your app is a webapp/XBAP app. then your application pools requires some additional settings.

So how to solve it? well if its the first case, then you will have to configure your solution in the below manner..

  • Right click on your project solution and click on properties. 
  • Expand the Configuration properties and select the Configuration
  • Then specify the platform as ANY CPU or depending on the CPU you are working on.As shown below

Now in the below solution i was referencing a project that was built on x86 architecture, hence i was getting the exception. 





Second case : If you are working on a XBAP app and your application is deployed/ published, then probably you may need to do this 

  • Open  IIS-Manager type inetmgr in run
  • Click on Application Pools






  • Right click on the application pool related to your published application, and select Advanced Settings






  • Set Enable 32-Bit Applications from False to True




This will enable the x86 32 Bit Assemblies (dll) to load in your application pool.

WPF: TreeView in WPF/XAML

How to use the TreeView Element and loading it through code.

The XAML is as below. We can have any number of nodes in a tree. there is no limit for that Each new TreeViewItem that is added is made into blue color for easy understanding.

<Page 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >

<TreeView>

 <TreeViewItem>
<TreeViewItem.Header>
  <TextBlock Text ="Hello"></TextBlock>
</TreeViewItem.Header>
     <TreeViewItem Header="First element"/> 
     <TreeViewItem Header="Second element"/>
     <TreeViewItem Header="Third element"/> 
     <TreeViewItem Header="Fourth element">
<TreeViewItem>
            <TreeViewItem.Header>
<TextBlock Text ="Inside Fourth"></TextBlock>
            </TreeViewItem.Header>
            <TreeViewItem Header="Is there an end to this?"/>
</TreeViewItem>
  </TreeViewItem>
  <TreeViewItem Header="World"> 
<TreeViewItem Header="Again a first element"/> 
  </TreeViewItem>

</TreeView>

</Page>

The Output will be as follows:
Both the nodes are not expanded








First Node(Hello ) is expanded










The Node inside the node is expanded. (Fourth element)












The Node inside the node inside Node is expanded. (Inside Fourth Node)














The Tree is expanded entirely


How to check the Windows OS registry if a software is installed in the system using C#

Many a times it might be required that the Windows OS registry be checked to find out if a software is installed. we can do this very easily using C# as follows.

using System;
using System.Text;
using Microsoft.Win32;

namespace Logiphix
{
    class Program
    {
         static void Main(string[] args)
         {
                bool isInstalled = false;
                string registry_key = @"SOFTWARE\7-Zip";
                using (Microsoft.Win32.RegistryKey key = Registry.CurrentUser.OpenSubKey(registry_key))
                {
                      if (key != null)
                      {
                               isInstalled = true
                               /* This is the place where you may want to put the code if the software is installed
                                  i am just setting a flag here to be true.
                               */
                      }
                      else
                      {
                               isInstalled = false;
                      }
                }

                Console.WriteLine(isInstalled ? "The software is installed" : "The Software is not installed");
                Console.ReadKey();
         }
     }
}

This is a simple console app, Here i am trying to check if the 7-ZIP software is installed in my local machine. You can use the regedit to find out the registry key for that particular software on a machine where it is already installed and then use it in your code as above.

To use Regedit type regedit in the run window the following window will open




Copy the registry key as below.(as shown for 7-Zip , you can find the required software key by just navigating as below and then right click on the folder and select Copy Key Name


To use the copied key name:
For example if the current key name is as  for 7-Zip    HKEY_CURRENT_USER\Software\7-Zip
use only the string from       Software\       followed by the remaining string.
The    HKEY_CURRENT_USER\    can be discarded. 
Use a little of trial and error for your requirements

For example:   string registry_key = @"SOFTWARE\7-Zip";

This Should do the job for you.




Content Model : GroupBox Headers other than just a plain text in WPF

How to have a Group box in WPF / XAML with a header other than just plain text?

We know that  WPF / XAML supports Content Model that allows us to have elements arranged in a way that makes it possible to have anything to be used as a caption!
It could be just a plain text or some graphics or some data aswell.

For example,


<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >

  <Grid>
<GroupBox>
    <GroupBox.Header>
          <StackPanel Orientation="Horizontal">
                       <Button><TextBlock Text="Click Me!" /></Button>
          </StackPanel>
    </GroupBox.Header>
</GroupBox>
 </Grid>

</Page>

Here in the xaml above, the groupbox header is not just a plain text , it is a button with the text Click Me! in it, this is done within the <GroupBox.Header> </GroupBox.Header>

Events in C#


EVENT  IN C#
An event is a mechanism via which a class can notify its clients when something happens.

Here i will explain c# events with a very simple yet an effective example, i hope after reading this post you will have a clear idea on how events work in C#.

First of all what is an EVENT?
Well, in simple terms, its a moment when something happens. this is true even in a real life scenario and not only in programming. when some thing happens how are you notified or how will you be acknowledged about it? This happens with an event handler. where the event is handled processed may be, and may also trigger more events.

Lets start with the code, shall we?
To begin with, lets have a idea as to what do we do here.

1  We create a class of type EventArgs.
2  Then we declare a delegate , this will have the event declaration.
3  We create the event.
4  We Handle this event.
5  We Fire(call) this event with the example code.

STEP 1 :We create a class of type EventArgs.

    public class MyCustomEventArgs : EventArgs
    {
        public int MyValue ;

        public MyCustomEventArgs(int input)
        {
             MyValue  = input;
        }
    }

This is a custom class here we inherit the class EventArgs which becomes the base class for eventarguments in C#. If you need to pass arguments to the event handler, a specific EventArgs class has to be made, Eventually, a suitable  EventArgs class might already be available, but in most cases, you will have to create one to tailor your specific arguments.

STEP 2 :Then we declare a delegate , this will have the event declaration.

public delegate void MyCustomEvent(object o,  MyCustomEventArgs  e);

Here this is created using delegates, for each subclass of EventArgs class u create this suitable delegate has to be created the best practice is to create this delegate inside the same scope.


STEP 3 :We declare the event and write the code how and when it is fired.

public event  MyCustomEvent myEvent1;

The event is declared as of type it's delegate ,  the event is declared inside the class which has to implement the events.

For example:

    public class MyEventDemo
    {
        public event  MyCustomEvent myEvent1; //Event is declared here
     
        /*
             write other code part here
         */
    }

STEP 4  :We Handle this event.

This involves two steps
1 registering the event
2 Handling the event

In the previous step we had declared the event inside the MyEventClass class. when we create an instance of this class in another class. we can also register the events involved with it. this is done with the overloaded += as shown below.

MyEventDemo myEventDemoObject = new  MyEventDemo ();
myEventDemoObject.myEve1 +=new myEventHandler(myEventDemoObject_myEve1);

Also we can unregister it by using the overloaded  -=
for Ex
myEventDemoObject.myEve1 -=new myEventHandler(myEventDemoObject_myEve1);

Next to handle the event
Note that we had given the method name object_myEve1 inside the deligate as an argument, this is the handler for the event. this handler method will take two parameters.
object sender and myEventArgs e

It is as shown below

        void  myEventDemoObject_myEve1(object sender, myEventArgs e)  // This is the handler
        {
            Console.WriteLine("event 1 called and the value is :"+ e.MyValue.ToString()) ;
        }


The complete code is given below
--------------------------------------------------------------------------------------

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

namespace caEventsInCSharp

{
    public delegate void MyCustomEvent(object o, MyCustomEventArgs e);

    class Program

    {
        static void Main(string[] args)
        {
            MyEventHandlerClass rec = new MyEventHandlerClass();
            rec.CallEvent();
            Console.ReadKey();
        }
    }

    public class MyEventHandlerClass

    {
        MyEventClass obj = new  MyEventClass ();

        public void CallEvent()

        {
            obj.myEvent1 +=new  MyCustomEvent( obj_myEve1);  // Handler is assigned
            Console.WriteLine("Before event");
            obj.DoSomething ();
            Console.WriteLine("After event");
        }

        void obj_myEve1(object sender, MyCustomEventArgs e)  // This is the handler

        {
            Console.WriteLine("event 1 called and the value is :"+ e.MyValue.ToString()) ;
        }

    }


    public class MyEventClass

    {
        public event MyCustomEvent myEvent1; //Event is declared here
        public void DoSomething()
        {
            if (myEvent1 != null)
            {
                int i = 0;
                for (; i < 1000000000; i++) // Make the execution pause for a while
                    ;
             
                MyCustomEventArgs e = new MyCustomEventArgs(i);
                myEvent1(null, e);            // call the event
            }
        }
    }

    public class MyCustomEventArgs : EventArgs
    {
        public int MyValue;
        public MyCustomEventArgs(int input)
        {
            MyValue = input;
        }
    }
 
}

--------------------------------------------------------------------------------------

Output

Select operation using LINQ

As we have seen before , we can perform a lot of sql like operations using LINQ, here i will explain you about how we can perform the select operation using LINQ

This program will have a list of integers with 10 integers added into the list from 1 to 10
we can perform the basic select operations on this list by using LINQ

Please import the System.Linq namespace else you may not be able to use this program.

------------------------------ the code-------------------------------------

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


namespace caLinqSelect
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> intList = new List<int>();
            intList.Add(1);
            intList.Add(2);
            intList.Add(3);
            intList.Add(4);
            intList.Add(5);
            intList.Add(6);
            intList.Add(7);
            intList.Add(8);
            intList.Add(9);
            intList.Add(10);


            IEnumerable<int> queryResult = from myInts in intList where myInts > 5 select myInts;


            foreach (int i in queryResult)
            {
                Console.WriteLine(i);
            }


            Console.ReadKey();
        }
    }
}
-------------------------------------------------------------------------------

The program
This program has a list of integers called intList , there are few integers loaded into the list (1,2,3 ...10).
The program has something called IEnumerable, yes you have guessed it right, its an interface that exposes the enumerator, which supports a simple iteration over a non-generic collection.in our case its  int , but that's not the main concern here.
Next, we have the query, " from myInts in intList where myInts > 5 select myInts" now what does this do? this will select all the integers from the list intList whose value is greater than 5 and store it into the   IEnumerable<int> queryResult  
Now we have a new resultset which has the integers that have values greater than 5. we can easily iterate over this resultset to do what ever operation we want to.


















The O/P:    6,7,8,9,10













we can use any type of operator to perform the filtering of the select. like <, > ,== ,!= etc 
you can download the solution files from here  or copy paste this URL into your browser (https://www.box.com/s/8f20dc961cc2893b9fdf)

Thanks for reading the post, Please comment if you find it difficult to understand or if you have any queries..

What is LINQ

LINQ stands for Language Integrated Query ,  this is a .NET framework component that adds  native data querying capabilities to .NET supported languages

LINQ makes querying on objects like lists, Data-tables etc easy by allowing you to create SQL like statements and helping retrieving selected or all objects from them(the lists etc) or performing such actions on them. thus making the manipulation of such objects way to easy for you which in turn helps you with less code writing and faster application development

LINQ is very robust and powerful.

Using LINQ you can perform a lot of operations like aggregation, grouping, ordering, joining etc , apart from the simple select.

Examples of using LINQ



Select operation using LINQ

As we have seen before , we can perform a lot of sql like operations using LINQ, here i will explain you about how we can perform the select operation using LINQ

This program will have a list of integers with 10 integers added into the list from 1 to 10
we can perform the basic select operations on this list by using LINQ

Please import the System.Linq namespace else you may not be able to use this program.

------------------------------ the code-------------------------------------

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


namespace caLinqSelect
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> intList = new List<int>();
            intList.Add(1);
            intList.Add(2);
            intList.Add(3);
            intList.Add(4);
            intList.Add(5);
            intList.Add(6);
            intList.Add(7);
            intList.Add(8);
            intList.Add(9);
            intList.Add(10);


            IEnumerable<int> queryResult = from myInts in intList where myInts > 5 select myInts;


            foreach (int i in queryResult)
            {
                Console.WriteLine(i);
            }


            Console.ReadKey();
        }
    }
}
-------------------------------------------------------------------------------

The program
This program has a list of integers called intList , there are few integers loaded into the list (1,2,3 ...10).
The program has something called IEnumerable, yes you have guessed it right, its an interface that exposes the enumerator, which supports a simple iteration over a non-generic collection.in our case its  int , but that's not the main concern here.
Next, we have the query, " from myInts in intList where myInts > 5 select myInts" now what does this do? this will select all the integers from the list intList whose value is greater than 5 and store it into the   IEnumerable<int> queryResult  
Now we have a new resultset which has the integers that have values greater than 5. we can easily iterate over this resultset to do what ever operation we want to.



















The O/P:    6,7,8,9,10













we can use any type of operator to perform the filtering of the select. like <, > ,== ,!= etc 

Binding a list with a dataGridView in windows forms using DataTable

How to bind a list with a dataGridView in windows forms?

Here i will show you to how to bind a list with a dataGridView Object in windows forms, i will be using a simple string list , this list will have a few strings in it which will be displayed in the dataGridView

Create a windows forms application with the name "wfaBindingGridView" , add the DataGridView tool from the toolbox into your form as shown below. and add a button into the form .





Double click on the Bind Grid button and you will be taken to the the codebehind c# file of this form with the event that handles this button click.


  • Create a method called BindGrid as below
  •  Declare a List of strings as below , then add some data into it .
  • The method will be called inside the click event of the button.




The code will be as 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;

namespace wfaBindingGridView
{
    public partial class Form1 : Form
    {
        List<String> strList = new List<string>();

        public Form1()
        {
            InitializeComponent();
        }

        void BindGrid()
        {
            strList.Add("Str 1");
            strList.Add("Str 2");
            strList.Add("Str 3");
            strList.Add("Str 4");
            strList.Add("Str 5");
            strList.Add("Str 6");

            DataTable dt = new DataTable();
            dt.Columns.Add("Strings");
            foreach (String s in strList)
            {
                DataRow dr = dt.NewRow();

                dr["Strings"] = s;

                dt.Rows.Add(dr);
            }

            dataGridView1.DataSource = dt;
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            BindGrid();
        }
    }
}


The output:


 Click on the Bind Grid button and you will see the below data coming into the grid.




You can tweak the same program to work with lists of any type of objects.

Thanks for visiting this Post, please comment if this needs any more information for easy understanding.


Adding a DLL to the Global Assembly Cache(GAC)


 Adding a DLL to the Global Assembly Cache(GAC)
Open the visual studio command prompt in administrative mode as shown below and navigate to the directory containing the .dll file (class library file) that is built.

 Navigate to the directory that contains the .dll file as shown below and type the command: gacutil /i followed by the name of the .dll file. here in the command the i stands for install. you can use the /u  to uninstall a dll from the GAC.
To navigate to the directory use the “cd” command in the command line 
for example:
Cd D:\Enlistment\Dax6HFSTABVMS\source\Application\VMSModel\Visual Studio Projects\C Sharp Projects\VMSRegressionBugDetails\bin\Debug
Command to add the assembly to the global assembly cache will be similar to this:
gacutil /i VMSRegressionBugDetails.dll

Click on the image to enlarge
 Press enter and the following screen will be displayed with the message saying
 “Assembly successfully added to cache”.
                                                          Click on the image to enlarge
 The dll is now added to the Global Assembly Cache.
This was successfully tested for a dll that was added to the GAC for the use in Dynamics Ax environment.