Tuesday, September 24, 2019

[Code Snippet] Example of using Delegate, Func and Action side by side in C#

Be The First To Comment
Quick and dirty example of using Delegate, Func and Action
side by side in C# to show how to use function pointer  or callback in C#

Example #1  Delegate and Func side by side

     static int DoubleTheValue(int x)
            return x * 2;

        // delegate type should match the function signature  - DoubleTheValue
        public delegate int functionDelegateType(int x);
        static void Method1(functionDelegateType func)
            int doubleValue = func(5);

        static void Method2(Func<int, int> func) // easier syntax
            int doubleValue = func(5);

        static void Main(string[] args)


Example #2  Delegate and Action side by side

static void DisplayOnConsole(int x)

        // delegate type should match the function signature  - DisplayOnConsole
        public delegate void functionDelegateType (int x);
        static void Method1(functionDelegateType func)

        static void Method2(Action<int> func) // easier syntax

        static void Main(string[] args)


Tuesday, September 3, 2019

[Code snippet] INotifyPropertyChanged in the model and subscribed the PropertyChanged event of the model in ViewModel

Be The First To Comment
internal class Model:INotifyPropertyChanged
        public Model()

        string _FirstName = "Shahir";
        public string FirstName
            get { return _FirstName; }
                _FirstName = value;

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged([CallerMemberName] string propertyName = "")
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

internal class MyViewModel:INotifyPropertyChanged
        private Model myModel;

        public MyViewModel(Model model)
            this.myModel = model;
            myModel.PropertyChanged += myModel_PropertyChanged;

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged([CallerMemberName] string propertyName = "")
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

        string _FirstName;
        public string MyFirstName
            get { return myModel.FirstName; }
                _FirstName = value;

        private void myModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
            if (e.PropertyName == "FirstName")
                MyFirstName = myModel.FirstName;

REFERECE - https://www.codeproject.com/Questions/1055820/How-the-Model-changes-could-be-notified-to-ViewMod

Saturday, June 15, 2019

Flavours of .NET implementation

1 Comment

 OSOpen SourcePurpose
.NET FrameworkWindowsNoUsed for building Windows desktop applications and ASP.NET Web apps running on IIS.
.NET CoreWindows, Linux, macOSYesUsed for building cross-platform console apps and ASP.NET Core Web apps and cloud services.
XamariniOS, Android, macOSYesUsed for building mobile applications for iOS and Android, as well as desktop apps for macOS.
.NET StandardN/AYesUsed for building libraries that can be referenced from all .NET implementations, such as .NET Framework, .NET Core and Xamarin.

Friday, May 25, 2018

Remote debug environment setup for ArcGIS server extensions- SOE and SOI

In order to debug the ArcGIS server extension SOE/SOI from your development machine, you have to follow 3 steps:
           1.       Enable remote debug ( Presumption is your development machine and GIS server are different machines)
           2.       Enable sever extension for debug
           3.       Attach debugger to the process running the service

Download and install the remote debuggin tools from - https://docs.microsoft.com/en-us/visualstudio/debugger/remote-debugging 

      A.  Enable remote debug
1.       Download and configure Remote tools on the development
a.       Find msvsmon.exe in the directory matching your version of Visual Studio. For Visual Studio 2015:

Program Files\Microsoft Visual Studio 14.0\Common7\IDE\Remote Debugger\x64\msvsmon.exe
(x64 can debug both x86 and x64 but x86 can only debugs x86)

2.       On the remote computer,  copy Remote Debugger folder from development machine and put in C:\ drive. Then, run msvsmon.exe
3.       The msvsmon.exe output terminal shows

Wednesday, May 31, 2017

Prevent WPF Global Keyboard Hook from stops working after hitting keys a while C# .NET

Be The First To Comment
The article written by Dylan Currier, Low Level Global Keyboard Hook / Sink in C# .NET is one the simple, easily understandable, and and working post on Global Keyboard hook out there in internet. It worked in my WPF application and I added following line in the WPF app to refresh hook after each key press- IDK  if it is write or wrong, more likely to be a wrong practice to hook/unhook every time but it gets the job done. The primary reason to refresh hook is to prevent app hanging (not responding to the key press) after few clicks on the WPF button.

void _listener_OnKeyPressed(object sender, KeyPressedArgs e)

Following is the video from Dylan Currier  on Low Level Keyboard Hook in C# / .NET"

Friday, April 14, 2017

Code Snippet: Select feature polygon(s) on Mouse Click ArcObjects C#

Be The First To Comment
Code snippet of custom feature(s) selection tool on mouse click and highlight it using ArcObjects and C#.

 class SelectFeatureTool : ESRI.ArcGIS.Desktop.AddIns.Tool  
     protected override void OnMouseDown(MouseEventArgs arg)  
       IMxDocument mxDocument = ArcMap.Application.Document as IMxDocument;  
       IActiveView activeView = mxDocument.ActiveView;  
       IMap map = mxDocument.FocusMap;  
       ILayer layer = map.get_Layer(0); //Get 1st Layer  
       IFeatureLayer featureLayer = (IFeatureLayer) layer;  
       IPoint identifyPoint = activeView.ScreenDisplay.DisplayTransformation.ToMapPoint(arg.X, arg.Y);  
       ESRI.ArcGIS.Carto.IIdentify identifyLayer = (IIdentify)layer;  
       IArray array = identifyLayer.Identify(identifyPoint);  
       int oid = -1;  
       if (array != null)  
         object obj = array.get_Element(0);  
         IFeatureIdentifyObj fobj = obj as IFeatureIdentifyObj;  
         IRowIdentifyObject irow = fobj as IRowIdentifyObject;  
         IFeature feature = irow.Row as IFeature;  
         oid = feature.OID;  
       HighlightClickedFeature(featureLayer, oid, activeView);  

Wednesday, March 22, 2017

Catch Exception - Attempted to read or write protected memory in ESRI ArcObjects .Net 4.0 Framework

1 Comment
First - Don't write the code to throw "Attempted to read or write protected memory" ..it is bad.

Second - If you are working on legacy codes and COM objects that throws "Attempted to read or write protected memory" while writing ArcMap add-ins, catch exceptions to prevent application crash, in my case ArcMap.

Step #1 - Add following snippet to config file - app.config for Arc-addin

      <legacyCorruptedStateExceptionsPolicy enabled="true" />
Step #2

Add -

on the top of function you are tying catch the exception

public IFeatureLayer GetOrCreateFeatureLayer(string path, esriGeometryType type, ISpatialReference sr)

Friday, August 19, 2016

Code snippet: WPF UWP ListView SelectionChanged Event Handling in ViewModel

Be The First To Comment
Solution from Dhaval Patel in Sliverlight application works perfectly on my WPF application. I prefer his idea because it is more clear and cleaner than other solutions that  I have came with. The event handling approach explained as -"This is the way where You can Reach the Selection changed events in Your MVVM Application First Of all i tell you that Command Property only work in Button now we have to Explicitly binding that property in our Selection Changed event like List box or combo box in Your XMAL file"
<ListBox Name="MyListBox" ItemsSource="{Binding ListItems}" Height="150" Width="150" Margin="281,32,-31,118">

            <Local:EventTrigger EventName="SelectionChanged">
                <Local:InvokeCommandAction Command="{Binding MyCommand}" CommandParameter="{Binding ElementName=MyListBox,Path=SelectedItem}"/>
for this you have to add dll Syatem.Windows.Interactivity now u have to add references in your xaml file namespace like

Friday, August 12, 2016

Multi-item Selection WPF ListBox using Attached Property

Be The First To Comment
The attached property class looks like -
1:  public static class ListBoxHelper  
2:    {  
3:      public static readonly DependencyProperty SelectedItemsProperty =  
4:                          DependencyProperty.RegisterAttached("SelectedItems",   
5:                          typeof(IList),   
6:                          typeof(ListBoxHelper),   
7:                          new PropertyMetadata(default(List<string>),   
8:                          OnSelectedItemsChanged));  
10:      public static IList GetSelectedItems(DependencyObject d)  
11:      {  
12:        return (IList)d.GetValue(SelectedItemsProperty);  
13:      }  
15:      public static void SetSelectedItems(DependencyObject d, IList value)  
16:      {  
17:        d.SetValue(SelectedItemsProperty,value);  
18:      }  
20:      private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)  
21:      {  
22:        var listBox = (ListBox)d;  
23:        ReSetSelectedItems(listBox);  
24:        listBox.SelectionChanged += delegate  
25:        {  
26:          ReSetSelectedItems(listBox);  
27:        };  
28:      }  
30:      private static void ReSetSelectedItems(ListBox listBox)  
31:      {  
32:        IList selectedItems = GetSelectedItems(listBox);  
33:        selectedItems.Clear();  
34:        if (listBox.SelectedItems != null)  
35:        {  
36:          foreach (var item in listBox.SelectedItems)  
37:            selectedItems.Add(item.ToString());  
38:        }  
39:      }  
40:    }  

Difference between PropertyMetadata vs FrameworkPropertyMetadata in .NET

Be The First To Comment

Databind between View and ViewModel for PasswordBox WPF

Be The First To Comment
"When you try to databind the password property of a PasswordBox you will recognize that you cannot do data binding on it. The reason for this is, that the password property is not backed by a DependencyProperty.

The reason is databinding passwords is not a good design for security reasons and should be avoided. But sometimes this security is not necessary, then it's only cumbersome that you cannot bind to the password property. In this special cases you can take advantage of the following PasswortBoxHelper.

The PasswordHelper is attached to the password box by calling the PasswordHelper.Attach property. The attached property PasswordHelper.Password provides a bindable copy of the original password property of the PasswordBox control."

Published on -

1:  public static class PasswordHelper  
2:  {  
3:    public static readonly DependencyProperty PasswordProperty =  
4:      DependencyProperty.RegisterAttached("Password",  
5:      typeof(string), typeof(PasswordHelper),  
6:      new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged));  
8:    public static readonly DependencyProperty AttachProperty =  
9:      DependencyProperty.RegisterAttached("Attach",  
10:      typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false, Attach));  
12:    private static readonly DependencyProperty IsUpdatingProperty =  
13:      DependencyProperty.RegisterAttached("IsUpdating", typeof(bool),   
14:      typeof(PasswordHelper));  
17:    public static void SetAttach(DependencyObject dp, bool value)  
18:    {  
19:      dp.SetValue(AttachProperty, value);  
20:    }  
22:    public static bool GetAttach(DependencyObject dp)  
23:    {  
24:      return (bool)dp.GetValue(AttachProperty);  
25:    }  
27:    public static string GetPassword(DependencyObject dp)  
28:    {  
29:      return (string)dp.GetValue(PasswordProperty);  
30:    }  

© 2011 GIS and Remote Sensing Tools, Tips and more .. ToS | Privacy Policy | Sitemap

About Me