A day with .Net

My day to day experince in .net

Archive for the ‘c#.net’ Category

C# Versions 8 to 6 Fetaures

Posted by vivekcek on September 14, 2017

In this post you can find the new features available in C# versions 8, 7.1, 7, 6.

Posted in c#.net | Tagged: , , , , | Leave a Comment »

C# Different Types Of Heap Memory

Posted by vivekcek on July 10, 2016

You might be heard that, reference objects are stored in heap:).
Do you know how many types of heaps are available in CLR.
Do you know that, you can pass data to another app domain with out marshaling:)

These all are .NET CLR implementation details, know to Bill Gates:)

You can explore, if you want to know more, Later i will post about memory management in CLR.

For the time being have a look at the types of heap’s below.

Loader Heap: contains CLR structures and the type system
High Frequency Heap: statics, MethodTables, FieldDescs, interface map
Low Frequency Heap: EEClass, ClassLoader and lookup tables
Stub Heap: stubs for CAS, COM wrappers, PInvoke
Large Object Heap: memory allocations that require more than 85k bytes
GC Heap: user allocated heap memory private to the app
JIT Code Heap: memory allocated by mscoreee (Execution Engine) and the JIT compiler for managed code
Process/Base Heap: interop/unmanaged allocations, native memory, etc

Usually, the “heaps” that most people refer to or know about are the “GC Heap” and the LOH.
GC Heap is shared among app-domains and GC will work only on that.

Capture

Posted in c#.net | Tagged: , , , , , , , , | Leave a Comment »

Filter datatable based on coulmns

Posted by vivekcek on June 26, 2016

If you want to build a new table from an existing table, with some columns try this

var selectedColumns = new[] {"Coulmn1","Coulmn2" };
var newTable = new DataView(oldTable).ToTable(false, selectedColumns);

Posted in c#.net | Tagged: | Leave a Comment »

Get non empty rows from a datatable

Posted by vivekcek on June 26, 2016

If you want to filter out empty rows from a datatable try this tipe

var nonEmptyRows = MyTable.Rows.Cast<DataRow>()
                                            .Where(
                                                row =>
                                                    !row.ItemArray.All(
                                                        field =>
                                                            field is System.DBNull ||
                                                            string.Compare((field as string).Trim(), string.Empty) == 0));
            MyTable = nonEmptyRows.Any() ? nonEmptyRows.CopyToDataTable() : MyTable.Clone();

Posted in c#.net | Tagged: , | Leave a Comment »

Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH)) ,COM Exception in C#

Posted by vivekcek on December 30, 2014

I was trying to use an ActiveX(OCX) control in a windows forms application, I am not sure in which language this control was developed, may be c++ or VB.

Anyway i added this control to my toolbox by browsing the OCX.

When i was trying to access a method in that control ,i got the above type mis-match COM exception.
The method signature is given below. The control is kind of grid, and i am trying to access a cell value. Here the last reference parameter will be filled with result

bool success=OcxControl.GetValue(int row, int coulmn, ref object cellValue)

i used this method as below in c#.

object value=null;
bool success=OcxControl.GetValue(1, 2, ref Value)

Then i got the exception , Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH)) ,COM Exception

The problem is with reference variable, so how to call this method. Try the below code.

ParameterModifier modifier = new ParameterModifier(3);
modifier[0] = false;
modifier[1] = false;
modifier[2] = true; // third parameter is refrence type

object value = null;

Object[] args = new Object[3];
args[0] = 1;
args[1] = 2;
args[2] = value;

Object result = OcxControl.GetType().InvokeMember(
                "GetValue",                           // name
                BindingFlags.InvokeMethod,            // invokeAttr
                null,                                 // binder
                OcxControl,                           // target
                args,                                 // args
                new ParameterModifier[] { modifier }, // modifiers
                null,                                 // culture
                null                                  // namedParameters
            );

MessageBox.Show(args[2].ToString());

ParameterModifier is used to indicate 3rd parameter is of reference type.

Posted in c#.net | Tagged: , | 2 Comments »

INotifyPropertyChanged Cross thread change notification issue solved.

Posted by vivekcek on May 7, 2013

I hope you are here beacause, your class implemented INotifyPropertyChanged and a list of the same is bind to a gridview or something.

But you tried to change the objects in that binded list in another thred, i mean out side the UI thread.

So what happend?, when the object is manipulted in another thread, change notification are fired and the other thred tried to update the gridvivew. So how can you slove this.

1. First of all i will introduce a class named ‘EntityBase’ which implement the’INotifyPropertyChanged’.

 public abstract class EntityBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual bool UpdateField<T>(ref T field, T value, string
        propertyName)
        {
            if (EqualityComparer<T>.Default.Equals(field, value)) return
            false; 
            field = value;
            if (!string.IsNullOrEmpty(propertyName))
                OnPropertyChanged(propertyName);
            return true;
        }
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

2. Your class say ‘Contact’ should be derived from EntityBase as given below.
Note the change in Set{}.

 public class Contact : EntityBase
    {
        private string _name;

        public string Name
        {
            get { return _name; }
            set { UpdateField(ref _name, value, "Name"); }
        }
           

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(object sender, string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

3. Now we will create a thread safe generic class ThreadedBindingList by extending BindingList

 public class ThreadedBindingList<T> : BindingList<T>
    {
        SynchronizationContext ctx = SynchronizationContext.Current;
        protected override void OnAddingNew(AddingNewEventArgs e)
        {
            
            if (ctx == null)
            { BaseAddingNew(e); }
            else
            { ctx.Send(delegate { BaseAddingNew(e); }, null); }
        }

        void BaseAddingNew(AddingNewEventArgs e)
        { base.OnAddingNew(e); }

        protected override void OnListChanged(ListChangedEventArgs e)
        {
            
            if (ctx == null)
            { BaseListChanged(e); }
            else
            { ctx.Send(delegate { BaseListChanged(e); }, null); }
        }

        void BaseListChanged(ListChangedEventArgs e)
        { base.OnListChanged(e); }
    }

4. Now your form class will be like this.

using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading.Tasks;
using DevExpress.XtraGrid.Views.Grid;
using System.Threading;
namespace WinFormInotyFy
{
    public partial class Form1 : Form
    {
        
        ThreadedBindingList<Contact> contacts = new ThreadedBindingList<Contact>();
        public Form1()
        {
            InitializeComponent();
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
            
            contacts.Add(new Contact() { Name="vivek" });
            contacts.Add(new Contact() { Name = "vivek" });
            contacts.Add(new Contact() { Name = "vivek" });
            contacts.Add(new Contact() { Name = "vivek" });
            contacts.Add(new Contact() { Name = "vivek" });
            gridControl1.DataSource = contacts;
        }

        private void button1_Click(object sender, EventArgs e)
        {
                       
            Parallel.ForEach(contacts, c => { c.Name += 1; c.IsProgress = false; });
          
        }

     
    }

    
}

Posted in c#.net | Leave a Comment »

Valid DICOM file checking c#

Posted by vivekcek on April 17, 2013

Normally the extension for a DICOM file is ‘.dcm’. But this extension never guarantee the file is a valid DICOM file. So in this post i will explain how to check the file is a DICOM via pure c# code.

DICOM is a binary file, in a DICOM file first 128(0-127) bytes is unused. the next 4 bytes(128-131) contain letters ‘D’,’I’,’C’,’M’.

So our logic is to ready all bytes from 128-131 using some binary reader and equate with ‘D’,’I’,’C’,’M’

128=>’D’
129=>’I’
130=>’C’
131=>’M’

header

The code is given 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 System.IO;

namespace DICOMCheck
{

    public partial class Form1 : Form

    {
        public Form1()
       
        {

            InitializeComponent();

        }
 
        private void button1_Click(object sender, EventArgs e)

        {

            openFileDialog1.ShowDialog();

            string filePath = openFileDialog1.FileName;

            BinaryReader br = new BinaryReader(new FileStream(filePath, FileMode.Open, FileAccess.Read), Encoding.ASCII);

            byte[] preamble = new byte[132];

            br.Read(preamble, 0, 132);

            if (preamble[128] != 'D' || preamble[129] != 'I' || preamble[130] != 'C' || preamble[131] != 'M')

            {

                throw new Exception("Not a valid dicom file");
              

            }

            else

                MessageBox.Show("Valid dicom file");

        }

    }

}

Posted in c#.net, DICOM | Leave a Comment »

Deep Cloning in C# by Extension Methods

Posted by vivekcek on January 11, 2013

In this code sample i will show you how to implement deep cloning by Extension methods.

1. Create a console project.

2. Add Serializable class Employee

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

namespace DeepClone
{
    [Serializable]
    class Employee
    {
        public string Name = string.Empty;
    }
}

3. Now write an Extension method by adding a static class.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace DeepClone
{
    public static class ExtensionMethods
    {
        public static T DeepClone<T>(this T toClone)
        {
            using (var stream = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(stream, toClone);
                stream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(stream);
            }
        }
    }
}

4. Now in Program.cs write this code.

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

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

            Console.WriteLine("//Normal object assigning///");
            Employee emp = new Employee();
            emp.Name = "Vivek";
            Console.WriteLine("Employee Name before shallow copy: " + emp.Name);
            Employee emp1 = emp;
            emp1.Name = "Chanthu";
            Console.WriteLine("Employee Name after shallow copy: " + emp.Name);

            Console.WriteLine("//Deep clone///");

            Employee em = new Employee();
            em.Name = "Vivek";
            Console.WriteLine("Employee Name before shallow copy: " + em.Name);
            Employee em1 = em.DeepClone();
            emp1.Name = "Chanthu";
            Console.WriteLine("Employee Name after shallow copy: " + em.Name);

            Console.Read();

        }
    }
}

Posted in c#.net | Tagged: | Leave a Comment »

Macro for copying dll to any directory visual studio

Posted by vivekcek on November 21, 2012

I have class library project in the below folder.

I:\SolutionTest\Main\Source\MyApp1\Source\ClassLibrary1

I want to copy the class library dll to the below folder

I:\SolutionTest\Main\Source\Builds

The Post-Buid macro for that

copy "$(TargetDir)\$(TargetFileName)" "$(SolutionDir)\..\Builds"

Posted in c#.net | Leave a Comment »

C# Async HelloWorld

Posted by vivekcek on August 26, 2012

You need Visual Studio 2012 to run this code

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

namespace ConsoleApplication1
{
    /// <summary>
    /// Program Class.
    /// </summary>
    public static class Program
    {
        /// <summary>
        /// Entry Point
        /// </summary>
        /// <param name="args">Command Line Parameters.</param>
        public static void Main()
        {
             Calculate();
             Console.WriteLine("Asynchronous Execution Started");
             Console.ReadLine();
        }

        /// <summary>
        /// Async Method.The method marked as async.
        /// </summary>
        public static async void Calculate()
        {
            Task<int> t = Task<int>.Factory.StartNew(() =>
                {
                    int i = 0;
                    for (; i < 100; i++)
                    {
                        System.Threading.Thread.Sleep(10);
                    }

                    return i;
                });

            await t;//At this point Calculate Method started asynchronous waiting
            Console.WriteLine(t.Result);
        }
    }
}

Posted in c#.net | Tagged: | Leave a Comment »