Posts

Showing posts with the label C#

Donate

Windows Forms CRUD (Create/Update/Delete) Application In .NET Core And C#

Image
Hello, Here's a simple tutorial on how to create a CRUD (Create/Update/Delete) application using Windows Forms In .NET Core. The same concept is applied to a Windows Forms application in .NET Framework. First is to create a Students table on your SQL Server Database using the script below. USE [TestDatabase] GO /****** Object: Table [dbo].[Students] Script Date: 03/31/2014 14:11:36 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[Students]( [ID] [int] IDENTITY (1,1) NOT NULL , [Name] [varchar](50) NULL , [Age] [int] NULL , [Address] [varchar](50) NULL , [Contact] [varchar](50) NULL , CONSTRAINT [PK_Students] PRIMARY KEY CLUSTERED ( [ID] ASC ) WITH (PAD_INDEX = OFF , STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON ) ON [ PRIMARY ] ) ON [ PRIMARY ] GO SET ANSI_PADDING OFF GO Create a Windows Forms App called "CRUDApplicationWi

Accessing WebView2 Control And It's properties In A C# Class Library

Image
Team, In a situation wherein you need to access a WebView2 control properties in a class library and that the WebView2 control is added in a WPF project, all you need to do is to reference the Microsoft.Web.WebView2.Wpf.dll and Microsoft.Web.WebView2.Core.dll from the WPF project into the class library. The sample code below is a utility class located in a class library project which has a WebView2 control object that performs navigation to a url that is set from the WPF project. public static class WebBrowserUtility { public static readonly DependencyProperty BindableSourceProperty = DependencyProperty.RegisterAttached( "BindableSource" , typeof ( string ), typeof (WebBrowserUtility), new UIPropertyMetadata( null , BindableSourcePropertyChanged)); public static string GetBindableSource(DependencyObject obj) { return ( string )obj.GetValue(BindableSourcePr

Mocking Methods With Ref Arguments Using Moq Framework In C#

Image
Hello, Here's a straightforward post on how to mock methods with arguments that are passed by reference using the Moq framework. First, we need to create a C# Class Library and Xunit projects in Visual Studio. Create two folders in the class libary project specifically Infrastructure and Models. The structure of the application resembles the image below. Add a class to hold a person's information Person.cs inside the models folder with properties such as SocialSecurityID, FirstName and etc. Only the StatusUpdate property is used in the test project. public class Person { public int SocialSecurityID { get ; set ; } public string FirstName { get ; set ; } public string MiddleName { get ; set ; } public string LastName { get ; set ; } public string StatusUpdate { get ; set ; } public Person() { SocialSecurityID = 0; FirstName = string .Empty; MiddleName = string .Empty; LastName = string .E

How To Add Cell Borders Or Grid Lines To Filled Cells In Excel Using ClosedXML

Image
Hello, When dealing with filled cells or columns of an Excel workshet via ClosedXML, you may notice that after you produced the Excel file(s), the filled columns or cells don't have borders. This assume that your report does not apply borders to the used cells or columns such as the image below. To apply borders to certain columns within a range or not, you need to set both the Outside and Inside borders with Thin borderstyle. And then apply your preferred color to the top, bottom, left and right borders. row++; xlWSheet.Range( 1 , 1 , row, 7 ).Style.Border.SetOutsideBorder(XLBorderStyleValues.Thin) .Border.SetInsideBorder(XLBorderStyleValues.Thin) .Border.SetTopBorderColor(XLColor.LightGray) .Border.SetBottomBorderColor(XLColor.LightGray) .Border.SetLeftBorderColor(XLColor.LightGray) .Border.SetRightBorderColor(XLColor.LightGray); Filled columns or cells with borders. Cheers!

How To Extract The Node Name In The Self-Closing Tags Using Regular Expressions In C#

Image
Hello, In one of the parser that I made, I need to extract the node name which is in a self closing XML tag as part of the requirement for the output. In order to do that, you need to combine a positive lookbehind for the lesser than symbol (?<=<) and positive lookahead for the forward slash and greater than symbol (?=/>). And then perform a greedy search in between those groups. The complete pattern for that is presented on the code snippet below. var NodeValue = Regex.Match(lstTempNodes[i], @"(?<=<)(.*)(?=/>)" ).Value.Trim(); Here's the pattern matching of several self-closing XML tags. Source Code: How To Extract The Node Name In The Self-Closing Tags Using Regular Expressions In C#

How To Iterate Or Loop Through A C# Dictionary And Update It's Value

Hello, Most of us C# developers are working on Dictionaries to store multiple sets of data with unique keys. And in times that we need to modify our logic with the Dictionary object involved, we normally do that using looping construct. Given a simple Dictionary object below with int as key and string as value. Dictionary< int , string > styledLines = new Dictionary< int , string >(); We may thought that looping through this object with the code presented below may work. However, when running your app, this will cause a "Collection was modified; enumeration operation may not execute" issue. It's because we are using the collection's key directly. foreach ( var kvp in styledLines) { styledLines[kvp.key] = $ "Series# {seriesNum} "; } To fix that we have a couple of options. Given that our key is an integer type with values in sequential order such as 0...1000, we could use for loop to change the values such as below. var startI

BinaryFormatter Custom Binder Alternative Using Newtonsoft.Json.JsonSerializer In C#

Hello Everyone! In relation to the previous post on updating the serialization and deserialization using BinaryFormatter class to NewtonSoft's JsonSerializer, we also need to change the Binder functionality using NewtonSoft. The class below inherits the SerializationBinder and overrides the BindToType() function. sealed class HELPERSCustomBinder : SerializationBinder { public override Type BindToType( string assemblyName, string typeName) { if (!typeName.ToUpper().Contains( "SYSTEM.STRING" )) { throw new SerializationException( "Only List<string> is allowed" ); } return Assembly.Load(assemblyName).GetType(typeName); } } The class above will then be assigned to the Binder property of BinaryFormatter as shown from the code snippet below. public static T BuildFromSerializedBuffer<T>( byte [] buffer) where T : new () { MemoryStream MS; BinaryFormatter BF; T rtn; rtn = default (T); try { using (M

BinaryFormatter Serialize() And Deserialize() Alternative Using Newtonsoft.Json.JsonSerializer In C#

Good evening! Part of the migration of our parts cataloging WPF application to .NET 7 was to investigate obsolete code and refactor that to something acceptable and maintainable in the future. One of which that needs to be addressed is the BinaryFormatter class used for serialization and deserialization. Searching thru the internet presents tons of options but since the application has already a Newtonsoft.Json package, we decided to use it's serialization instead. So to proceed with, below are the sample serialization and deserialization functions that incorporates the BinaryFormatter class and converted to NewtonSoft.Json.JsonSerializer. Below is a function using BinaryFormatter serialization. public static byte [] GetSerializedBuffer<T>(T itemToSerialize) { byte [] rtn; MemoryStream MS; BinaryFormatter BF; if (! typeof (T).IsSerializable && !( typeof (ISerializable).IsAssignableFrom( typeof (T)))) throw new InvalidOperationException( "A ser

Process.Start() Error - An error occurred trying to start process. The specified executable is not a valid application for this OS platform.

Image
Good evening! I had an issue when opening PDF files using Process.Start() which is called in a ShowFile() method of the project. The code which isn't working is shown below. System.Diagnostics.Process.Start(Path.Combine(myDocumentsPath, fileName)); The solution for that is to pass a ProcessStartInfo() object in the Start() parameter. And then set UseShellExecute property of the ProcessStartInfo object to true. The modified code that is working is shown below. System.Diagnostics.Process.Start( new ProcessStartInfo(Path.Combine(myDocumentsPath, fileName)) { UseShellExecute = true }); Output

Insufficient Data For An Image Error - Printing PDF Books Using ImageSharp And PdfSharpCore In C#

Image
Hello and Good Day! As we continue to optimize our catalog software specifically printing of pdf books module, some of our catalogs were printed smoothly and other were not which specifically throws an Insufficient Data For An Image error when opening those books. I tried different solutions in .NET but none of them seem to resolve the problem. After investigating the images, we discovered that these photos which happens to be the templates for our books, were created using different types of graphics and CAD software. What we did was to open these images in Adobe Photoshop and save those files so that these photos program property is consistent. Since the error still persists, the next step I did was to change the image property in Photoshop specifically the Color Representation that has a value of Uncalibrated. In Photoshop, Uncalibrated is equivalent to Grayscale. Changing the image's Grayscale/Uncalibrated to RGB Color in Photoshop solved the Insufficient Data For A

PdfSharpCore And ImageSharp - Memory Keeps Increasing Or Memory Leak When Adding Hundreds Of Images To Create PDF Book

Image
Good day everyone! We are currently upgrading our WPF Cataloging application that has a feature to generate pdf books with multiple pages on the fly and each book may contain thirty or more images and may reach even a hundred from .NET Framework to .NET 7. Upon printing of a book,we discovered that it consume lots of memory even reaching to 5GB per book. Because our logic in generating a catalog involves adding texts and loading several images in memory and then print those details on a single pdf file, it may have caused to memory usage to skyrocket at a tremendous result. The code below shows how we load images using PdfSharpCore and ImageSharp. private ImageSource.IImageSource GetImageFromList<TPixel>( string key, string which, string name) where TPixel : unmanaged, IPixel<TPixel> { ImageSource.IImageSource rtn; int width; int height; width = 0; height = 0; if (ImageList.ContainsKey(key)) { rtn = ImageList[key]; } else { if (Ima

Remove Last Character Of A String From StringBuilder Added Using AppendLine() In C#

Image
Good afternoon! In a situtation where you add string values to a StringBuilder object using the AppendLine() method and you want to delete the last character, you might expect that using the Remove() method in the code below will work. But the truth is it does not. private static void RemoveLastCharacter() { StringBuilder sb = new StringBuilder(); sb.AppendLine( "Lorem ipsum dolor sit amet, consectetur adipiscing elit," ); sb.AppendLine( "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." ); sb = sb.Remove(sb.Length - 1, 1); Console.WriteLine(sb.ToString()); } Using Appendline() method to populate the StringBuilder object according to the documentation will also append the default line terminator after the string value to the end of the StringBuilder instance. Since the default line terminator has two characters specifically "\r\n", we need to include those two characters plus the last character of the string. The revise

Notepad++ Plugin GetText Method Not Getting Entire String In C#

Image
Good evening, We have this Notepad++ Plugin project that will read and parse an html document converted from a MS Word file and then change the html string into an Adobe In Design format. The issue is that the html document has over 20,000 plus lines even reaching 40,000 lines or more. The code below will get all the text from an active Notepad++ window but fails if the string content is huge. public unsafe string GetText( int length) { byte [] textBuffer = new byte [10000]; fixed ( byte * textPtr = textBuffer) { Win32.SendMessage(scintilla, SciMsg.SCI_GETTEXT, (IntPtr)length, (IntPtr)textPtr); return Encoding.UTF8.GetString(textBuffer).TrimEnd( '\0' ); } } After doing some debugging and troubleshooting, I found a solution that is to replace the size of the textBuffer variable from a static value 10000 to the actual length passed into the function parameter. public unsafe string GetText( int length) { byte [] textBuffer = new byte [length]; fix

Creating Your First Notepad++ Plugin Using Visual Studio 2019 And C#

Image
Hello, In this blog post, I'll demonstrate on how to develop a Notepad++ Plugin (64 Bit) using Visual Studio 2019 and C# assuming that you have installed a 64 Bit version of the latest Notepad++ Editor. This tutorial is based from kblisted Notepad++ Plugin Package in GitHub . The plugin's architecture can communicate with the Notepad++ or the underlying Scintilla engine using NotepadPlusPlusGateway and ScintillaGateWay and Win32 API. To start with, download the Notepad++ Plugin Pack from the GitHub page and copy the zip file to the Project Templates folder of your Visual Studio 2019 IDE. In my laptop, the path is "C:\Users\my_username\Documents\Visual Studio 2019\Templates\ProjectTemplates\Visual C#" . Open your Visual Studio 2019 IDE and create a project using the Notepad++ Plugin template. Change the Platform Target to x64. (Our OS is Windows 10 64 bit) Create a function called SetFirstCharAllWordsCap inside Main.cs that get's the entire string content

Donate