Posts

Showing posts with the label C#

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

ArcGIS Server SOI - HandleRESTRequest Parameter limitations

The SOI Rest request handler method - public byte[] HandleRESTRequest(string Capabilities, string resourceName, string operationName,             string operationInput, string outputFormat, string requestProperties, out string responseProperties) HandleRESTRequest paramater provides following information inside the method capabilities Map,Query,Data   resourceName layers/0 ,  operationName query,  operationInput {"returnZ":false,"returnIdsOnly":false, "where":"","returnDistinctValues":false,"returnM":false,"returnCountOnly":false,"returnExtentsOnly":false, "returnTrueCurves":false,"returnGeometry":true, "spatialRel":"esriSpatialRelIntersects","geometryType":"esriGeometryEnvelope"}, outputFormat json,  requestProperties {"computeETag":true,"ETag":"\"c429a59c\""},  responseProperties {...

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: Identify to which polygon a point belong to?

Code sample to find point inside a polygon in shape file using GDAL/OGR 2.x and C#. using OSGeo.OGR; using OSGeo.OSR; using OSGeo.GDAL; 1: public void FindPolygonBelongsToPoint() 2: { 3: try 4: { 5: var shapePath = @"C:\Locations_WGS84.shp"; 6: Ogr.RegisterAll(); 7: OSGeo.OGR.Driver shapeDriver = Ogr.GetDriverByName("ESRI Shapefile"); 8: DataSource shape = shapeDriver.Open(shapePath, 0); 9: Layer layer = shape.GetLayerByIndex(0); 10: 11: Feature polygonFeature = layer.GetNextFeature(); 12: 13: long featureCountInLayer = layer.GetFeatureCount(1); 14: for (int i = 1; i <= featureCountInLayer; i++) { 15: 16: Geometry polygonGeom = polygonFeature.GetGeometryRef(); 17: 18: string coordinates = "POINT (-100.726 38.995)"; 19: 20: SpatialReference spatialRef = layer.GetSpatialRef(); ...

Code snippet: To highlight selected feature in ArcMap programmatically using ArcObjects

Code snippet to highlight selected feature in ArcMap programmatically using ArcObjects and return the  STGeomFromWKB    string of selected feature. To return the geometry you should import   Microsoft.SqlServer.Types   from Nuget and  SqlServerSpatial140.dll   from  C:\Windows\System32 using System; using System.Collections.Generic; using System.Data.SqlTypes; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Windows; using ESRI.ArcGIS.ArcMapUI; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Catalog; using ESRI.ArcGIS.CatalogUI; using ESRI.ArcGIS.Desktop.AddIns; using ESRI.ArcGIS.Display; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Framework; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Geometry; using Microsoft.SqlServer.Types; namespace Test.Addin.ArcCommands { class SelectFeatureTool : ESRI.ArcGIS.Desktop.AddIns.Tool { ...

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 : Create/update polygon attribute fields using Ogr and ESRI Arcobjects

A code snippet example to check if a feature is standalone ESRI Shape or featureclass inside ESRI Gdb, then add new filed or update attribute value in attribute table .... standalone shape/features are created/updated using GDAL/OGR implementation and feature/featureclass stored in ESRI personal GDB are created/updated using ESRI ArcObjects.  Any solution to replace later with GDAL/Ogr is highly appreciated.  Please comment below if you find one. public void AddUpdateAttributeField(string oldFeatureFile) { DriverUtils.RegisterOgrDriver(); DataSource dataSource; Layer layer; var isShapeFile = IsShapeInGdb(oldFeatureFile); if (isShapeFile) { dataSource = Ogr.Open(oldFeatureFile, 1); //second argument in open specifies mode of data, 1 RW & 0 readonly mode layer = dataSource.GetLayerByIndex(0); FieldDefn gdalFiedlDefn = new FieldDefn("FID_GDAL",FieldType.OFTInteger); la...

Code snippet: Create new Field in a Shape File using GDAL/OGR in C#

Add new field in existing shape file using OGR in C#. public void AddAttributeField(string oldShapeFile) { Ogr.RegisterAll(); DataSource dataSource = Ogr.Open(oldShapeFile, 1); //second argument in open specifies mode of data, 1 RW & 0 readonly mode Layer layer = dataSource.GetLayerByIndex(0); FieldDefn gdalFiedlDefn = new FieldDefn("NEW_FIELD",FieldType.OFTInteger); layer.CreateField(gdalFiedlDefn, 1); Feature feature = layer.GetNextFeature(); while (feature!= null) { feature.SetField("NEW_FIELD",feature.GetFID()); // Populate new field with feature FID layer.SetFeature(feature); feature = layer.GetNextFeature(); } dataSource.FlushCache(); }

Code snippet: Open Folder Browser Dialog in WPF

Install WPFFolderBrowser 1.0.2 from nuget gallery to use the Windows Vista / Windows 7 Folder Browser Dialog from your WPF projects, without any additional dependencies. Install-Package WPFFolderBrowser then import WPFFolderBrowser using  WPFFolderBrowser; private   void  BrowseFolder()         {              WPFFolderBrowserDialog  dd =  new   WPFFolderBrowserDialog ();              var  result = dd.ShowDialog();              if  (result.HasValue)             {                 TxtFvsAccessDbPath = dd.FileName;         ...

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

Code snippet: Data binding between ViewModel and Radio Button in WPF

Image
Following example shows the data binding between radio buttons and ViewModel in WPF. Parts of View.xaml <Grid.Resources> <Utilities:RadioHelper x:Key= "RadioConverter" /> <Utilities:RadioHelper x:Key= "InverseRadioConverter" Inverse= "True" /> </Grid.Resources> <RadioButton Name= "radFvsOracle" GroupName= "fvsStorage" Content= "Oracle" Margin= "7,0,0,0" IsChecked= "{Binding Path=RadFvsResults, Converter= {StaticResource ResourceKey=RadioConverter}}" ></RadioButton> <RadioButton Name= "radFvsAccess" GroupName= "fvsStorage" Content= "Access" Grid.Column= "2" Margin= "11,0,0,0" IsChecked= "{Binding Path=RadFvsResults, Converter= {StaticResource ResourceKey=InverseRadioConverter}}" ></RadioButton> Parts of  RadioHelper.cs public class RadioHelper :IValueConver...

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

Code Snippet: Set default database schema in Nhibernate SessionFactory

1: //Setup oracle database connection and connection pool 2: public class OracleConnectionManager 3: { 4: private static string _userName; 5: private static string _password; 6: 7: public OracleConnectionManager(string userName, string password) 8: { 9: _userName = userName; 10: _password = password; 11: } 12: 13: private static ISessionFactory _sessionFactory; 14: private static ISessionFactory SessionFactory { get 15: { 16: if(_sessionFactory == null) 17: { 18: var connectionString = DatabaseConnections.GetOracleConnectionsString(_userName,_password); 19: 20: //Nhibernate Oracle database configuration 21: var configuration = new Configuration(); 22: configuration.DataBaseIntegration(db => 23: { 24: db.ConnectionProvider<NHibernate.Connection.DriverConnectionProvider>(...

Setting up automatic product or build version increment using JENKINS for .NET projects

Image
Steps for setting up automatic product or build version increment using JENKINS Continious Integration server and Visual Studio for .NET projects Part A - Configure Visual Studio Solution 1. Copy the "AssemblyInfo.cs" from your project solutions and rename into  "AssemblyInfo.cs.template" 2. Add a file called  "AssemblyInfo.cs.template"  and replace with these two lines:               [assembly: AssemblyVersion("#VERSION_NUMBER#")]              [assembly: AssemblyFileVersion("#VERSION_NUMBER#")] 3. In project properties, insert this pre-build command:      "$(SolutionDir)builder-scripts\templates\pre-build\Stamper.exe" "$(ProjectDir)\" 4. Put the "builder-scripts" folder into your solution folder. Builder scripts source

Code snippet: Unzip the zip file in C# using DotNetZip

DotNetZip is a FAST, FREE class library and toolset for manipulating zip files. Use VB, C# or any .NET language to easily create, extract, or update zip files. 1: public static void DeCompressFile(string zipFilePath, string extractPath) 2: { 3: string zipToUnpack = zipFilePath; 4: string unpackDirectory = extractPath; 5: using (ZipFile zipfiles = ZipFile.Read(zipToUnpack)) 6: { 7: // Here, we extract every entry, but we could extract conditionally based on entry name, size, date, checkbox status, etc. 8: foreach (ZipEntry e in zipfiles) 9: { 10: e.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently); 11: } 12: } 13: 14: Console.WriteLine("Status: Done extracting the zipped Archive"); 15: }

Code snippet: Read data from Access Database in C#

Read data from Access Database in C# 1: private static void ReadFromAccess(string accessDbPath) 2: { 3: string connection = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= {0}",accessDbPath); 4: using (OleDbConnection con = new OleDbConnection(connection)) 5: { 6: try 7: { con.Open(); 8: OleDbCommand cmd = new OleDbCommand("SELECT * FROM Table_NAME", con); 9: OleDbDataReader reader = cmd.ExecuteReader(); 10: 11: while (reader.Read()) 12: { 13: Console.WriteLine(reader.GetString(0)); 14: } 15: 16: }catch(Exception ex) 17: { 18: Console.WriteLine(ex.Message); 19: }finally 20: { 21: con.Close(); 22: } 23: } 24: }