Friday, November 19, 2021

Update WPF Interaction Triggers in from .Net Framework 4.8 to .Net 5

Be The First To Comment

 

When migrating the Visual Studio projects from .Net Framework 4.8 to .Net 5, you may encounter  in the following error regarding Interaction.Triggers.

 Error      XDG0008             The name "Interaction" does not exist in the namespace "http://schemas.microsoft.com/xaml/behaviors".

 The one solution to fix it is to install “Microsoft.Xaml.Behaviors.Wpf” from Nuget

And update the namespace ( if needed)

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

to

             xmlns:i="http://schemas.microsoft.com/xaml/behaviors"

Thursday, January 28, 2021

[Snippet] Add/Remove an Assembly to/from the Global Assembly Cache using C#.Net

Be The First To Comment

 


Code snippets to add remove an assembly from GAC - 

Add reference to - System.EnterpriseServices

using System.EnterpriseServices.Internal;


var path = "the absolute path of assembly";

 Publish publish = new Publish();

 publish.GacInstall(path);

 publish.GacRemove(path);

Reference:

https://docs.microsoft.com/en-us/dotnet/framework/app-domains/install-assembly-into-gac#global-assembly-cache-tool

https://docs.microsoft.com/en-us/dotnet/framework/app-domains/how-to-remove-an-assembly-from-the-gac

Monday, May 11, 2020

[Code snippet] How to set value of private variable in Unit Test Using Reflection ?

Be The First To Comment
A sample example to set private variable to true from unit test class in C#.Net

//TestService.cs
public class TestService
{
        private bool _isInitialized = false;
}



//TestServiceUnitTest.cs
using System.Reflection;

public class TestServiceUnitTest
{
          private TestService _testService;
       
           [TestInitalize]
          private void testInitalize()
         {
            _testService = new TestService();
         }
       
         [TestMethod]
         Private void SetInitializeToTrue()
         {
                         FieldInfo field = typeof(TestService).GetField("_isInitialized",  BindingFlags.NonPublic |       BindingFlags.Instance);

          field.SetValue(_testService , true);

         }
}

Wednesday, April 22, 2020

[Code Snippet] Assert Exception in private methods using PrivateObject

1 Comment
NON ASYNC Method

Method.cs

private MyMethod(object value1)
{
      if(value1 == null)
      {
           throw new ArgumentNullException(nameof(MyMethod));
      }
}

Test.Cs

[TestMethod]
public void MyMethod_Throws_Verify()
{
         PrivateObject po = new PrivateObject(new Method())

TargetInvocationException exception = Assert.ThrowsException<TargetInvocationException>(() =>
                    privateObject.Invoke("MyMethod", new object[] { null }));

            Assert.AreEqual(typeof(ArgumentNullException), exception.InnerException.GetType());
       
}


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)
        {
            Method1(DoubleTheValue);

            Method2(DoubleTheValue);
        }

Example #2  Delegate and Action side by side

static void DisplayOnConsole(int x)
        {
            Console.WriteLine(x.ToString());
        }

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

     
        static void Method2(Action<int> func) // easier syntax
        {
            func(5);
        }

     
        static void Main(string[] args)
        {
            Method1(DisplayOnConsole);
            Method2(DisplayOnConsole);
        }

Reference:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/a1ac99ed-0801-4773-a866-4223d42422cf/how-to-pass-function-as-an-argument-to-another-function-in-c?forum=csharpgeneral

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; }
            set
            {
                _FirstName = value;
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            if(PropertyChanged!=null)
            {
                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; }
            set
            {
                _FirstName = value;
                OnPropertyChanged();
            }
        }

        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

Be The First To 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

2 Comments
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)
        {
           
          _listener.UnHookKeyboard();
          _listener.HookKeyboard();
        }

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

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

Add -

[HandleProcessCorruptedStateExceptions] 
[SecurityCritical]
on the top of function you are tying catch the exception

[HandleProcessCorruptedStateExceptions]
[SecurityCritical]
public IFeatureLayer GetOrCreateFeatureLayer(string path, esriGeometryType type, ISpatialReference sr)
{
//body
}

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:Interaction.Triggers>
            <Local:EventTrigger EventName="SelectionChanged">
                <Local:InvokeCommandAction Command="{Binding MyCommand}" CommandParameter="{Binding ElementName=MyListBox,Path=SelectedItem}"/>
            </Local:EventTrigger>
        </Local:Interaction.Triggers>
    </ListBox>
for this you have to add dll Syatem.Windows.Interactivity now u have to add references in your xaml file namespace like
 xmlns:Local="clr-namespace:System.Windows.Interactivityassembly=System.Windows.Interactivity"

Friday, August 12, 2016

Multi-item Selection WPF ListBox using Attached Property

Be The First To Comment
The attached property class looks like -
ListBoxHelper.cs
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));  
9:        
10:      public static IList GetSelectedItems(DependencyObject d)  
11:      {  
12:        return (IList)d.GetValue(SelectedItemsProperty);  
13:      }  
14:    
15:      public static void SetSelectedItems(DependencyObject d, IList value)  
16:      {  
17:        d.SetValue(SelectedItemsProperty,value);  
18:      }  
19:    
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:      }  
29:    
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 -


PasswordHelper.cs
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));  
7:     
8:    public static readonly DependencyProperty AttachProperty =  
9:      DependencyProperty.RegisterAttached("Attach",  
10:      typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false, Attach));  
11:     
12:    private static readonly DependencyProperty IsUpdatingProperty =  
13:      DependencyProperty.RegisterAttached("IsUpdating", typeof(bool),   
14:      typeof(PasswordHelper));  
15:     
16:     
17:    public static void SetAttach(DependencyObject dp, bool value)  
18:    {  
19:      dp.SetValue(AttachProperty, value);  
20:    }  
21:     
22:    public static bool GetAttach(DependencyObject dp)  
23:    {  
24:      return (bool)dp.GetValue(AttachProperty);  
25:    }  
26:     
27:    public static string GetPassword(DependencyObject dp)  
28:    {  
29:      return (string)dp.GetValue(PasswordProperty);  
30:    }  
31:     
 

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

About Me