Posts

Showing posts with the label .NET

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

  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"

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

  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

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

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(" _isInitializ...

[Code Snippet] Assert Exception in private methods using PrivateObject

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());         }

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

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);     ...

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

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 Property...

Flavours of .NET implementation

  OS Open Source Purpose .NET Framework Windows No Used for building Windows desktop applications and ASP.NET Web apps running on IIS. .NET Core Windows, Linux, macOS Yes Used for building cross-platform console apps and ASP.NET Core Web apps and cloud services. Xamarin iOS, Android, macOS Yes Used for building mobile applications for iOS and Android, as well as desktop apps for macOS. .NET Standard N/A Yes Used for building libraries that can be referenced from all .NET implementations, such as .NET Framework, .NET Core and Xamarin. Ref -  https://msdn.microsoft.com/en-us/magazine/mt842506.aspx

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

Image
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 F...

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

Image
The article written by Dylan Currier,  Low Level Global Keyboard Hook / Sink in C# .NE T 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"

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

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 ir...

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

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 }

Code snippet: WPF UWP ListView SelectionChanged Event Handling in ViewModel

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=Selec...

Multi-item Selection WPF ListBox using Attached Property

The attached property class looks like - ListBoxHelper.cs 1: public static class ListBoxHelper 2: { 3: public static readonly DependencyProperty SelectedItems Property = 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...

Difference between PropertyMetadata vs FrameworkPropertyMetadata in .NET

Image

Databind between View and ViewModel for PasswordBox WPF

"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 - http://www.wpftutorial.net/PasswordBox.html http://blog.functionalfun.net/2008/06/wpf-passwordbox-and-data-binding.html PasswordHelper.cs 1: public static class PasswordHelper 2: { 3: public...