.net miner

something about life, me and .net
  • Home
  • Categories
    • C#
    • .Net
    • Tools
    • General
    • Visual Studio
    • Open Source Projects
  • Contact Me
.Net•C#•General•Open Source Projects

Invoke Type Members By Using Dynamic Methods

23 November 2018 by Ozcan Degirmenci No Comments

In one of my previously published article (very old 🙂 one), I mentioned briefly about reflection, and discuss how reflection is an important concept in .Net Framework. While it is a very important concept there is a performance issue related with the Reflection. If you over use reflection codes in your projects you have to face with performance issues compared with the code that is implemented in this sample project.

In that context, I have explained two methods to have a better performance when manipulating objects dynamically and I have shared code examples about them. As a summary, I created a ObjectCreateMethod class which uses DynamicMethods and creates an IL which calls type constructors. By calling that generated DynamicMethod we can create instance of types faster than traditional reflection. If you are interested in and need more information, you can access article from here.

After reviewing previous article, now you are ready to get more information about the usage of the DynamicMethods that improve the performance of traditional reflection which is the subject of this article.

In the previous article, maybe you have discerned an imperfection. The ObjectCreateMetod class – which uses DynamicMethods for creating instance of a type – is only suitable for creating instance of types which has parameter-less constructors.

While I was surfing the web, I found a feedback about my article. Someone asks if it is possible to use ObjectCreateMethod class with types which has parameterized constructors. Because of this, I decided to updated my code, and now it also supports the constructors with parameter(s).

To resolve this issue I created a dynamic method which takes object[] argument as the constructor arguments. Than I take these parameters on to the stack and call new opcode. Here is the code;

/// <summary>
///  Creates the dynamic proxy method which calls given <see cref="ConstructorInfo"/>
/// </summary>
/// <param name="methodInfo"></param>
private static DynamicMethodDelegate CreateProxyMethod(ConstructorInfo constructor)
{
    var method = new DynamicMethod(constructor.DeclaringType.Name + "_ctor_Proxy",
        typeof(object),
        new Type[] { typeof(object[]) },
        constructor.DeclaringType);

    var wrapper = new ILGeneratorWrapper(method.GetILGenerator());

    var parameters = constructor.GetParameters();
    var parameterTypes = new Type[parameters.Length + 1];
    parameterTypes[0] = constructor.DeclaringType;
    for (int i = 0; i < parameters.Length; i++)
    {
        parameterTypes[i + 1] = parameters[i].ParameterType;
    }

    wrapper.DeclareLocals(parameterTypes);

    for (int i = 1; i < parameterTypes.Length; i++)
    {
        wrapper.EmitLoadArg(0);
        wrapper.EmitLoadCons(i - 1);
        wrapper.Emit(OpCodes.Ldelem_Ref);
        wrapper.EmitCast(parameterTypes[i]);
        wrapper.EmitStoreLocal(i);
    }

    for (int i = 1; i < parameterTypes.Length; i++)
    {
        wrapper.EmitLoadLoc(i);
    }

    wrapper.Emit_NewObj(constructor);

    wrapper.EmitStoreLocal(0);
    wrapper.EmitLoadLoc(0);
    wrapper.Emit(OpCodes.Ret);

    return method.CreateDelegate(typeof(DynamicMethodDelegate)) as DynamicMethodDelegate;
}

I also added some other helper proxy classes which provides invoking other type members (fields, properties and methods) by using DynamicMethods too.

Continue reading
Share:
Reading time: 3 min
.Net•C#•General•Open Source Projects•Tools

Searchable RichTextBox Control

9 November 2018 by Ozcan Degirmenci No Comments

RichTextBox is a control which provides formatting features that TextBox control does not provide. For instance, you can customize the text’s color, style and/or size. So, you can apply formatting to a word, a line or all of the paragraph. RichTextBox is useful if you want to have more control over styling, but although it supports search in its content by the “Find” functionality, it does not have a search UI, so this reduces control’s user-friendly design. If you need to search something in RichTextBox you should add new code blocks, functions, UI controls.

With the following code blocks, we derived a searchable RichTextBox control from RichTextBox which provides search(Find) functionality with a “Find” pop-up. Searchable RichTextBox does not assist any UI customization nevertheless it allows using ‘Control + F’ function in the text content. For more, review the following blocks.

Searchable RichTextBox Control Interface Image

An example screenshot of the Searchable RichTextBox Control

You can get full source code from my git-hup page. Here is the link.

Share:
Reading time: 1 min
General•Quantum

Schrödinger’s Cat

25 September 2018 by Ozcan Degirmenci No Comments

If you are interested in Quantum Physics a bit, you’ve probably heard of Schrödinger’s Cat. Schrödinger’s Cat is a thought experiment devised by Erwin Schrödinger. Schrödinger attempted to indicate to us, the contradiction of common sense and illogical things in the very small one’s wold. Briefly, it examines the relationship of a cat, a flask of poison, a Geiger counter, a bottle crusher mechanism, and a radioactive element that are source placed in a selected box, and the relationship between them, in terms of quantum.
When radioactive decay occurs in the box, the Geiger counter will detect it. After detecting it, the mechanism will crush the poison-filled bottle and the poison will cause a cat to die.

However, since radioactive decay is at the atomic level in the world of very small ones’, quantum rules will step in. It will be thought overlapping probability wave radioactive atom decay and not decayed. By means of this, it will be both of the decay and not decayed situation until an observer observes. Therefore, the cat will be both living and dead as long as the box is closed!
If we put a cat that can survive without eating and drinking anything during 300 days to the box, what will be happen to the cat when the box will be open after 300 days?
A. Dead
B. Alive
C. Cat Bones
There is an interesting thought experiment that contradicts common sense again. If it is superposition(that means the ability in the quantum theory of an object, such as an atom or sub-atomic particle, to be in more than one quantum state at the same time.) the cat should never die until we observe, rather it should be both living and dead position.
What does it mean if we see cat bones? Or is there any possibility to see cat bones inside the box after we opened it 300 days later?

Share:
Reading time: 1 min
.Net•General•Tools

Assembly Load Exception Helper

13 September 2010 by Ozcan Degirmenci No Comments

If you get ReflectionTypeLoadException during loading an assembly to your AppDomain or running an assembly, it will be hard to find which assembly cause the problem from the given standard error.
Generally the exception says something like “Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.“

You must have a look to the LoaderExceptions in the ReflectionTypeLoadException to understand exact problem. That property contains the whole resolution fail exceptions in it. But if you don’t have source code of your program or if you can not debug your program then it will be hard for you to access LoaderExceptions during run time. To solve this problem and take some help, you can use AssemblyLoadLogger, which I developed it for this purposes.

Continue reading

Share:
Reading time: 1 min
.Net•C#•General•Tools•Visual Studio

Visual Studio Setup Project Custom Action OLE Calls And Show Dialog Support

29 August 2010 by Ozcan Degirmenci No Comments

If you are developing a setup project with visual studio which contains custom action in it, you might have problems with the OLE calls (for ex: Copy to clipboard or paste from clipboard) and showing a dialog (for ex: FolderBrowser, OpenFileDialog, SaveFileDialog etc.). This is simply because of the thread structure of the setup projects.

MSI projects does not expect that your custom actions needs OLE  calls. Therefore they are not calling your custom actions with a thread which is apartment state is STA. If you want to make OLE calls, your thread must be in STA apartment state. Therefore if you show a form in your custom action and try to call Clipboard.SetData or Clipboard.GetData in your form, then you get a STA-MTA thread exception. Also your setup project will be locked when you try to show a dialog form in your custom action form.

Continue reading

Share:
Reading time: 2 min
General•Tools

Spoon Run Apps Instantly From The Web

26 August 2009 by Ozcan Degirmenci No Comments

Spoon, which is developed by Code Systems (Xenocode) was released. You can access and try it from the http://www.spoon.net(Turbo.net)  address.

So what is spoon?

Spoon allows users to run applications instantly from their web browsers with a single click. Spoon takes only minutes to deploy and embeds directly into your existing web site.
Spoon allows most apps to launch after downloading less than 10% of the app. Adaptive background downloading continues during execution.

Continue reading
Share:
Reading time: 1 min
.Net•C#•General•Open Source Projects•Tools

Process Viewer

6 September 2008 by Ozcan Degirmenci No Comments

Download Source Code From GitHub | Watch Sample Movie(v1.0.5.0)

 What is Process Viewer?

I can say that Process Viewer is a program like Microsoft Spy++. Unlikely to Spy++ it allows you to edit some properties of the Controls and also allows you to manage its window messages. You can change Text, Visibility, Enabled, Window Styles and Window Ex Styles properties of a control by using PV during run time. There withal you can ignore window messages, change incoming message to a different message or edit parameters of any window messages by putting breakpoints to the control’s window procedure with PV.

Process Viewer Interface Image

An example screenshot of the Process Viewer

Continue reading
Share:
Reading time: 17 min
.Net•C#•General•Visual Studio

How To Permit Multiple Selections For Enum Properties

28 August 2008 by Ozcan Degirmenci No Comments
Enum - Flags Editor Example Interface Image

An example screenshot of the Flags Editor

PropertyGrid will use default editor for the properties which’s type is enum. This default editor does not allow multiple selections even the Enum has Flags attribute.

I have been prepared a new Editor for this kind of properties.

Our editor’s code is as follows;

internal class FlagsEditor : UITypeEditor
{
   FlagsEditorControl editor = null;
   public FlagsEditor()
   { }
    
   // our editor is a Drop-down editor
   public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
   {
      return UITypeEditorEditStyle.DropDown;
   } 
  
   public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
   {
       // if value is not an enum than we can not edit it
      if  (!(value is Enum))
         throw new Exception("Value doesn't support");
     
      // try to figure out that is this a Flags enum or not ?
      Type enumType = value.GetType();
      object[] attributes =  enumType.GetCustomAttributes(typeof(FlagsAttribute), true);
      if (attributes.Length == 0)
         throw new Exception("Editing enum hasn't got Flags attribute");
      // check the underlying type
      Type type = Enum.GetUnderlyingType(value.GetType());
      if (type != typeof(byte) && type != typeof(sbyte)  && 
            type != typeof(short) && type != typeof(ushort) && 
           type != typeof(int)&& type != typeof(uint))
        return value;
      if (provider != null)
      {
         // use windows forms editor service to show drop down
         IWindowsFormsEditorService edSvc = provider.GetService( 
              typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
         if (edSvc == null)
             return value;
         if (editor == null)
             editor = new FlagsEditorControl(this);
         // prepare list
         editor.Begin(edSvc, value);
         // show drop down now
         edSvc.DropDownControl(editor);
         // now we take the result
         value = editor.Value;
         // reset editor
         editor.End();
      }
      return Convert.ChangeType(value, type);
   }
}

In this code FlagsEditorControl is a UserControl which PropertyGrid hosts it in a drop down during the edit operation.
You can change your design by changing this Control.

To use this editor for a property, we have to write Editor Attribute to that property as the below;

// set editor of this property to our FlagsEditor
[Editor(typeof(FlagsEditor), typeof(UITypeEditor))]
public FileAttributes FlagsAttribute
{
       get { return _FlagsAttribute; }
       set { _FlagsAttribute = value; }
}
Share:
Reading time: 1 min
.Net•C#•General

What Is The NET Problem With EnableWindow

26 August 2008 by Ozcan Degirmenci No Comments

EnableWindow function enables or disables the mouse and keyboard input to the specified control. You can use this function from user32.dll as the follows;

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool EnableWindow(HandleRef hWnd, bool enable);
  
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool EnableWindow(IntPtr hWnd, boolenable);

Continue reading

Share:
Reading time: 2 min
.Net•C#•General•Visual Studio

CollectionEditor Something About

25 August 2008 by Ozcan Degirmenci No Comments

Today I wrote a simple example which shows how we can use CollectionEditor of the .NET. In addition to this I also made a simple example which shows how to implement custom CollectionEditor which allows us to add more than one item to the collection.

Something About CollectionEditor

An example screenshot of the Collection Editor

Continue reading
Share:
Reading time: 1 min
Page 1 of 212»

Search

Projects

  • Process Viewer
  • B-Msn
  • Runtime Member Proxies
  • Searchable RichTextBox

Categories

  • .Net (19)
  • C# (12)
  • General (13)
  • Open Source Projects (4)
  • Quantum (1)
  • Tools (9)
  • Visual Studio (6)

Archives

  • November 2018
  • September 2018
  • September 2010
  • August 2010
  • August 2009
  • September 2008
  • August 2008
  • June 2008
  • May 2008
  • April 2008
  • February 2008
  • January 2008

About me

Hi, my name is Ozcan Degirmenci. I'm co-founder and CEO at Crs Soft.

Tags

Assembly Collection Editor Dialog Support Dynamic method enum Flag Editor Loader Exceptions Ole Calls Open source project open source projects Perfornance Comparison process viewer Proxy quantum Reflection Run Apps From Web schrödinger's cat Searchable Richtextbox Spoon thought experiment thread

© 2018 copyright ÖZCAN DEĞİRMENCİ // All rights reserved.