Settings Results in 4 milliseconds

Determine if two strings are anagrams with C# .NET
Determine if two strings are anagrams with C# .NET

Two strings are anagrams if they are made up of the same set of characters. Examples “hello” and “loleh”“123123” and “312312”“qwerty” and “wretqy” The degree of “anagram-ness” can vary ignore case?ignore non-numeric characters?ignore whitespace? In this post we’ll only consider word-characters only and the comparison will be case-insensitive to make the problem more interesting. We’ll write a function that accepts two integers and returns a boolean true if the strings are anagrams, otherwise false. We’ll look at two solutions out of many that exist out there using a character mapusing string sort What is a character map? It is a map where the key is of type char and the value if of type integer. We collect the unique characters of a string and count how many times each character occurs in the string. E.g. CharCount‘f’2‘g’1‘i’2‘d’1‘o’1 We do that for both strings and compare the counts of each unique character. Let’s start with a skeleton using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Algorithms { public class Anagram { public bool AreAnagrams(string first, string second) { if (first == null || second == null) return false; return AreAnagramsWithCharMap(first, second); //return AreAnagramsWithSortedStrings(first, second); } private bool AreAnagramsWithCharMap(string first, string second) { return false; } private bool AreAnagramsWithSortedStrings(string first, string second) { return false; } private Dictionary<char, int> MakeCharacterMap(string input) { string cleaned = CleanInput(input); return cleaned.Distinct().ToDictionary(c => c, c => cleaned.Count(s => s == c)); } private string CleanInput(string input) { return Regex.Replace(input, @"[_]+|[^\w]+|[\d-]+", "").ToLower(); } } } We start by some null-checking and return false if either of the two inputs is null. The AreAnagramsWithCharMap function has been wired up but it’s not yet implemented. The function for the second solution AreAnagramsWithSortedStrings has also been prepared. We have two private functions as well CleanInputthis one takes a string and strips all underscores, white space and non-word characters from it and returns the lower-case version of itMakeCharacterMapfirst we clean the incoming input stringsecond we use a couple of LINQ operators to build the character mapDistinct() to gather the unique characters from the stringToDictionary() to build the map itself, the key will be the character itself and for the value we count the number of occurrences of that character in the string Let’s look at the implementation of AreAnagramsWithCharMap private bool AreAnagramsWithCharMap(string first, string second) { var charMapFirst = MakeCharacterMap(first); var charMapSecond = MakeCharacterMap(second); if (charMapFirst.Count != charMapSecond.Count) { return false; } return charMapFirst.All(kvp => charMapSecond.ContainsKey(kvp.Key) ? kvp.Value == charMapSecond[kvp.Key] false); } We first create the two character maps. If they differ in size then we can immediately return false. It means that one of the strings has at least one more character than the other so it’s pointless to continue. Otherwise we make use of the All LINQ operator which return true of all the elements of a collection fulfil a certain condition. The condition is based on two parameters whether the character map contains the character as the key in the first placewhether that character occurs with the same frequency as in the source map If both conditions are fulfilled for all characters in the character maps then we return true. Here’s a set of unit tests using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Algorithms.Tests { [TestClass] public class AnagramTests { [TestMethod] public void AreAnagramsTests() { Anagram a = new Anagram(); Assert.IsTrue(a.AreAnagrams("hello", "___ hllOe!! 456 ???")); Assert.IsFalse(a.AreAnagrams("sdfs", null)); Assert.IsFalse(a.AreAnagrams(null, "sdfs")); Assert.IsFalse(a.AreAnagrams(null, null)); Assert.IsFalse(a.AreAnagrams("qwerty", "yewr")); Assert.IsFalse(a.AreAnagrams("qwerty", "qwertyuiop")); Assert.IsTrue(a.AreAnagrams("? par**lIame%%nt !", "partIAL men")); Assert.IsTrue(a.AreAnagrams("a gentleman", "elegant man")); } } } The will all pass. The second solution takes the two cleaned strings, puts them in order and compares them. This solution is slightly less performant than the first one due to the string ordering though. The map comparison doesn’t involve any ordering so it’s somewhat quicker. Here’s the implemented function private bool AreAnagramsWithSortedStrings(string first, string second) { string sortedOne = string.Concat(CleanInput(first).OrderBy(c => c)); string sortedTwo = string.Concat(CleanInput(second).OrderBy(c => c)); return sortedOne == sortedTwo; } We again clean the input string and then call the OrderBy LINQ operator. It returns an ordered collection of characters from the string, i.e. not an ordered string. Hence we need to embed this bit of code in string.Concat so that we build the string again from the characters. Finally we simply compare the two strings. Wire up this function from the main one and rerun the unit tests. They will still pass. public bool AreAnagrams(string first, string second) { if (first == null || second == null) return false; //return AreAnagramsWithCharMap(first, second); return AreAnagramsWithSortedStrings(first, second); }


[C-Sharp] Base64 Image Decoding
Category: C-Sharp

Base64 Encoding ...


Views: 349 Likes: 101
Asp.Net 5 Application is losing state when enters ...
Category: .Net 7

Question A C# Application is losing Application State e.g. IFeatureCollection, ...


Views: 196 Likes: 69
Checking a Spanish #VAT number using the #VIES webservice in C#
Checking a Spanish #VAT number using the #VIES web ...

Checking EU VAT numbers using the VIES webservice has some quirks, for example, in Germany, only the validity of the number can be verified, and in Spain, although the company name and address are not exposed, the API can be used to verify them against provided details, for this, a different service method needs to be used for Spain, than for other countries; TL; DR; here is the Github Repo showing the code in c# https//github.com/infiniteloopltd/CheckVatNumberSpain Checking a VAT number in Spain can be done by using the European Union’s VAT Information Exchange System (VIES). VIES is a web-based system that allows businesses and tax authorities in the EU to verify the validity of VAT numbers assigned to companies in other EU member states. To check a VAT number in Spain using VIES, you would need to make a SOAP web service request to the VIES web service endpoint, passing in the VAT number you wish to validate as a parameter. The request would be sent to the VIES service over HTTPS, ensuring the data transmitted is secure. The VIES service would then respond with a validation result indicating whether the VAT number is valid or not. If the VAT number is valid, the response would also include the country code of the member state that issued the VAT number. The VIES service does not expose the name or address of the company. Added in the code is a inspector that prints to the console the XML being sent and received, for use in Postman, or another client that needed to POST the XML via HTTP rather than SOAP; which would be; Sample Request <sEnvelope xmlnss="http//schemas.xmlsoap.org/soap/envelope/"> <sBody xmlnsxsi="http//www.w3.org/2001/XMLSchema-instance" xmlnsxsd="http//www.w3.org/2001/XMLSchema"> <checkVatApprox xmlns="urnec.europa.eutaxudviesservicescheckVattypes"> <countryCode>ES</countryCode> <vatNumber>B83891812</vatNumber> <traderName>Rodrisa Automoviles</traderName> <traderCompanyType /> <traderStreet>Avda. Reina Victoria</traderStreet> <traderPostcode>28430</traderPostcode> <traderCity>Madrid</traderCity> <requesterCountryCode /> <requesterVatNumber /> </checkVatApprox> </sBody> </sEnvelope> Sample Response <envEnvelope xmlnsenv="http//schemas.xmlsoap.org/soap/envelope/"> <envHeader/> <envBody> <ns2checkVatApproxResponse xmlnsns2="urnec.europa.eutaxudviesservicescheckVattypes"> <ns2countryCode>ES</ns2countryCode> <ns2vatNumber>B83891812</ns2vatNumber> <ns2requestDate>2023-01-12+0100</ns2requestDate> <ns2valid>true</ns2valid> <ns2traderName>Rodrisa Automoviles</ns2traderName> <ns2traderCompanyType></ns2traderCompanyType> <ns2traderStreet>Avda. Reina Victoria</ns2traderStreet> <ns2traderPostcode>28430</ns2traderPostcode> <ns2traderCity>Madrid</ns2traderCity> <ns2traderNameMatch>1</ns2traderNameMatch> <ns2traderCompanyTypeMatch>3</ns2traderCompanyTypeMatch> <ns2traderStreetMatch>1</ns2traderStreetMatch> <ns2traderPostcodeMatch>1</ns2traderPostcodeMatch> <ns2traderCityMatch>2</ns2traderCityMatch> <ns2requestIdentifier></ns2requestIdentifier> </ns2checkVatApproxResponse> </envBody> </envEnvelope>


Short Cut for Creating Constructor in C-Sharp
Category: C-Sharp

It is very helpful when developing software to know the shortcut to implement code snippet. For exam ...


Views: 304 Likes: 86
AspNet Core Performance Tuning and Best Practices ...
Category: .Net 7

C# Best Practices and Performance Tuning</ ...


Views: 140 Likes: 66
The Best Way to Create an Interface in AspNet 6 (C ...
Category: .Net 7

1. Create your generic Interface like this and you will never regrete <span style="backgr ...


Views: 31 Likes: 33
Neural Networks in C#
Category: Other

Neural network in C# using TensorFlow library. using Syst ...


Views: 0 Likes: 8
How to build a circular matrix with C# .NET
How to build a circular matrix with C# .NET

I assume you know what a matrix is from your maths classes. They are two-dimensional containers of usually numeric values, but they can hold any type of data. They are widely used in various mathematical and other scientific fields such as machine learning. Here’s an example of a 3×3 matrix 323446532438767 Matrices have columns and rows and their enumeration starts at 0. The coordinates of the various cells are given as row-column pairs. The top left hand cell is in row 0 and column 0, (0, 0) in short but there are other notations as well, I’ve even seen R0C0 at some point. So that’s the number 3 in the above example. Then 23 is in row 0, column 1 and so on. Here’s the coordinate table of a 4×4 matrix 0,00,10,20,31,01,11,21,32,02,12,22,33,03,13,23,3 In this post we’ll take a look at something simpler than machine learning though. Imagine that you’re tasked to build a circular matrix of integers. What do I mean by a circular matrix? The matrix starts with a certain integer in (0, 0), usually 0 or 1 and is then filled in an inward-spiraling pattern where the starting integer is incremented with every new cell. Here’s an example with a 4×4 spiraling matrix 12341213145111615610987 So we start with 1 then fill up the top row up to 4. Then we continue downwards to 7, followed by the bottom row and then back up again. We continue spiraling inwards until we reach the last cell at row 2, column 1 which has the value 16. Matrices are relatively often used in technical interviews if the interviewer wants to see how comfortable you are with arrays. Matrices can be represented as 2-dimensional arrays which are not used that often in everyday programming and some candidates may feel uncomfortable using them. The exact problem you are given can vary of course but building circular or spiraling matrices is one of the more complex ones in an interview. Knowing how to solve this particular matrix-related question will make you ready for other, similar types of question. So how do we go about solving this? In questions where you need to work out some algorithm the key to success is often to find some kind of pattern in the data set. Can we see any patterns if we just look at the rows? Hmm, the top row is easy 1, 2, 3, 4 but the second row is 12, 13, 14, 5, that doesn’t reveal anything to me. Looking at the columns is even less promising 1, 12, 11, 10 and then 2, 13, 16, 9. Frankly, I don’t see anything that catches the eye, no symmetries, no patterns that can be modelled in a loop etc. Therefore a more viable solution is to follow the index as it’s incremented and in the outer circle. We then do the same in the inner circle and continue inwards for any remaining circles. So in the first iteration we want to fill the matrix as follows In the second iteration we follow the same route with the remaining, smaller inner matrix stop This iteration will be an outer one in code. We’ll also need to iterate through the various sections top row rightwardsright column downwardsbottom row leftwardsleft column upwards We’ll write a function that accepts the dimension of the matrix. An incoming 4 means that we want to build a 4×4 matrix. Our implementation will return a list of integer lists where each list represents a row in the matrix. But wait, didn’t we say that matrices are best represented by a jagged array in code? Yes, we’ll use an array to build the matrix and then turn it into a list at the end of the function. This way you’ll be ready to build whichever data structure is required from you in the test. You’ll see why an array is better suited to hold the matrix data in just a bit. Let’s start with some basic setup code using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algorithms { public class MatrixBuilder { public List<List<int>> BuildMatrix(int n) { var result = new List<List<int>>(); var temporaryArray = new int[n][]; for (int i = 0; i < n; i++) { temporaryArray[i] = new int[n]; result.Add(new List<int>()); } //main algorithm to be implemented here for (int i = 0; i < temporaryArray.Length; i++) { result[i].AddRange(temporaryArray[i]); } return result; } } } We set up the return list and the temporary jagged array and fill them with some empty containers. We make sure that the array contents are copied to the list and return it from the function. Here’s a short test suite using Microsoft.VisualStudio.TestTools.UnitTesting; using Algorithms; using System; using System.Collections.Generic; using System.Text; namespace Algorithms.Tests { [TestClass()] public class MatrixBuilderTests { [TestMethod()] public void BuildMatrixTests() { MatrixBuilder mb = new MatrixBuilder(); var matrix = mb.BuildMatrix(2); CollectionAssert.AreEqual(new List<int>() { 1, 2 }, matrix[0]); CollectionAssert.AreEqual(new List<int>() { 4, 3 }, matrix[1]); matrix = mb.BuildMatrix(3); CollectionAssert.AreEqual(new List<int>() { 1, 2, 3 }, matrix[0]); CollectionAssert.AreEqual(new List<int>() { 8, 9, 4 }, matrix[1]); CollectionAssert.AreEqual(new List<int>() { 7, 6, 5 }, matrix[2]); matrix = mb.BuildMatrix(4); CollectionAssert.AreEqual(new List<int>() { 1, 2, 3, 4 }, matrix[0]); CollectionAssert.AreEqual(new List<int>() { 12, 13, 14, 5 }, matrix[1]); CollectionAssert.AreEqual(new List<int>() { 11, 16, 15, 6 }, matrix[2]); CollectionAssert.AreEqual(new List<int>() { 10, 9, 8, 7 }, matrix[3]); } } } We’ll need several counters. We need to know where we start and end each row and column in the main outer loop. Remember, the main outer loop serves to identify the dimensions of the array spirals 1111122112211111 In a 4×4 matrix we have 2 circles. They are denoted by purple 1’s and red 2’s in the above example. A 3×3 matrix will also have 2 circles but the inner circle has only one element, the one in the very middle of the matrix. A 2×2 matric has only a single circle. The counter starts at 1 in row 0 and column 0, those are 3 variables that we can identify right there. Those are valid for the first circle. When we’re done with the first circle then the counter will have whatever value it has got up to in the iteration, whereas start row and start column will be 1. (1, 1) is the starting point for the inner circle of a 4×4 matrix – and for any other matrix of any size for that matter. We also need to see how far out we’re allowed to go in each circular iteration. In the first iteration we’ll start at (0, 0) and the farthest we reach is at (3, 3), i.e. the bottom right hand cell of the matrix. In the second circle we start at (1, 1) and the max reach will be at (2, 2) otherwise we overwrite some of the values we have already calculated. It sounds like it’s not enough to know where we start, i.e. start column and start row, but where we end as well, i.e. the end column and end row. If you refer back to the table with the arrows then we’ll need to set these row and column pointers as follows start row 0end row n – 1, i.e. 3 in a 4×4 matrix to comply with the 0-based array indexingstart column 0end column n – 1, same as for end row We start filling up the top row, i.e. from start row to end column, (0, 0) to (0, 3) in a 4×4 matrix. When we’re done then we increment the start row to 1. At this point we’re filling up the right hand column from (1, 3) to (3, 3). Then we decrement the end column and continue filling up the bottom row from (3, 2) to (3, 0). Finally we move up, i.e. decrement the end row and fill in the cells from (2, 0) to (1, 0). Recall that we incremented the start row to 1 so we don’t return to (0, 0) when filling up the left hand column. At this point start row and start column are 1, end row and end column are 2, we’re ready for the inner circle where the same steps are taken. So we’ll need the following a main loop for each circle in the matrixinner loops for each section of the circletop rowright columnbottom rowleft column Also, the bottom row and left column are iterated backwards, i.e. we need a for-loop where the iterator integer decreases to make sure we’re moving in the right direction. We break the main outer loop when we have reached the end column and the end row, i.e. the start row and the start columns have converged to the end equivalents. This is a lot of talking that’s difficult to visualise so let’s see a partial implementation with only the counter values and the various loops using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Metadata.W3cXsd2001; using System.Text; using System.Threading.Tasks; namespace Algorithms { public class MatrixBuilder { public List<List<int>> BuildMatrix(int n) { var result = new List<List<int>>(); var temporaryArray = new int[n][]; for (int i = 0; i < n; i++) { temporaryArray[i] = new int[n]; result.Add(new List<int>()); } int counter = 1; int startColumn = 0; int endColumn = n - 1; int startRow = 0; int endRow = n - 1; while (startColumn <= endColumn && startRow <= endRow) { //top row for (int i = startColumn; i <= endColumn; i++) { } //done with the row, increase the row pointer, i.e. move down in the matrix startRow++; //right column for (int i = startRow; i <= endRow; i++) { } //done with the column, move to the left endColumn--; for (int i = endColumn; i >= startColumn; i--) { } //move up again on the right hand side of the matrix endRow--; for (int i = endRow; i >= startRow; i--) { } //move to the right for the next loop startColumn++; } for (int i = 0; i < temporaryArray.Length; i++) { result[i].AddRange(temporaryArray[i]); } return result; } } } Those loops pave the way for us to keep the index right, i.e. that we’re in the correct cell all the time. The while loop represents the circles in the matrix and is broken when the start and end indexes of the rows and columns have converged, i.e. we have reached the final cell in the matrix. The 4 for-loops represent the 4 directions we’re taking, as outlined above. Also notice the decreasing direction of the second two loops that we also hinted at above. Now that we have the correct pointers we can increase the counter variable within each for-loop, that’s simple for (int i = startColumn; i <= endColumn; i++) { counter++; } startRow++; for (int i = startRow; i <= endRow; i++) { counter++; } endColumn--; for (int i = endColumn; i >= startColumn; i--) { counter++; } endRow--; for (int i = endRow; i >= startRow; i--) { counter++; } startColumn++; We have the pointers to the cell coordinates and the integer values we want to put in them. Now we need to use those to fill in the jagged array. This is where it’s absolutely necessary to use arrays and not lists because we fill the arrays the same way as we’re traversing the matrix. Each array within temporaryArray represents a row and when we’re done with the first for-loop we’ll have the following jagged array 1234xxxxxxxxxxxx …where ‘x’ means “not yet properly filled in”. The we move on and fill in the rightmost column 1234xxx5xxx6xxx7 So we need to access the last spots of arrays 2, 3, and 4 of the 2-dimensional array. We could not do the same with a list, there’s no equivalent accessor to a list where we can set the value at position n, we can only add new values to end of the list. So this is the main reason why it’s better to go for an array. Next up we’ll fill up the bottom row 1234xxx5xxx610987 …and finally the left hand column 123412xx511xx610987 We then do the same in the “inner” matrix 12341213145111615610987 Now we need to select the correct indexes for the jagged array in the 4 for-loops. In the first loop we move from left to right, i.e. from (0, 0) to (0, 3). So the row is constant, it will be equal to startRow. The column increases from 0 to endColumn. Hence we’ll use the following accessors temporaryArray[startRow][i] In the second for loop we move from (1, 3) to (3, 3). The column is equal to end column and row moves up from startRow to and including endRow. Recall the we incremented startRow by 1 after the first loop. Therefore we won’t accidentally overwrite cell (0, 3). Here’s the accessor in the second loop temporaryArray[i][endColumn] The in the third loop we move to the left from (3, 2) to (3, 0) and in the fourth loop upwards from (2, 0) to (1, 0). Here’s the full solution using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Metadata.W3cXsd2001; using System.Text; using System.Threading.Tasks; namespace Algorithms { public class MatrixBuilder { public List<List<int>> BuildMatrix(int n) { var result = new List<List<int>>(); var temporaryArray = new int[n][]; for (int i = 0; i < n; i++) { temporaryArray[i] = new int[n]; result.Add(new List<int>()); } int counter = 1; int startColumn = 0; int endColumn = n - 1; int startRow = 0; int endRow = n - 1; while (startColumn <= endColumn && startRow <= endRow) { for (int i = startColumn; i <= endColumn; i++) { temporaryArray[startRow][i] = counter; counter++; } startRow++; for (int i = startRow; i <= endRow; i++) { temporaryArray[i][endColumn] = counter; counter++; } endColumn--; for (int i = endColumn; i >= startColumn; i--) { temporaryArray[endRow][i] = counter; counter++; } endRow--; for (int i = endRow; i >= startRow; i--) { temporaryArray[i][startColumn] = counter; counter++; } startColumn++; } for (int i = 0; i < temporaryArray.Length; i++) { result[i].AddRange(temporaryArray[i]); } return result; } } } I think that was quite a challenging problem. Make sure you study it before your next job interview so that you can quickly present your solution and move on to the next problem.


What is New in C-Sharp 9 Programming Language
Category: .Net 7

C# is one of the high-level programming languages, it is used in many business applications, Game ...


Views: 278 Likes: 102
InvalidOperationException: The 'Microsoft.AspNetCo ...
Category: Questions

Question How do you solve "InvalidOperationException The 'Microsoft-AspNetCor ...


Views: 495 Likes: 64
AvatarAPI now includes #GitHub as a source
AvatarAPI now includes #GitHub as a source

AvatarAPI.com is an API that allows you get images, names , and sometimes addresses from an email address, depending on what source / provider is used. Today, GitHub is the latest addition to the source list, which means that anyone with a public email address on their GitHub profile can be searched, returning the avatar icon, and the account name. A handful of potential use cases for this API are as follows; Social media and networking apps can use the API to automatically populate user profiles with their contact’s profile pictures and names. Email clients can use the API to display the sender’s profile picture and name in the email’s header. Customer relationship management (CRM) software can use the API to associate a customer’s email address with their profile picture and name. Online marketplaces and e-commerce platforms can use the API to show a buyer’s profile picture and name on their account page. Collaboration and productivity tools can use the API to display a team member’s profile picture and name in a shared document or project management platform. Security and authentication systems can use the API to verify the identity of a user based on their email address and associated profile picture and name. Online gaming and virtual reality platforms can use the API to display a player’s profile picture and name in-game or on a leaderboard. Educational and training platforms can use the API to associate a student’s email address with their profile picture and name in a virtual classroom.


Add a #FingerPrint reader to a C# WinForms app
Add a #FingerPrint reader to a C# WinForms app

Probably a good way to add extra security to a Windows Form app, just to make sure that there is a real human user infront of the screen, and it’s not some bot trying to interact with your software, is to add a Fingerprint / “Windows Hello” login. Of course, in the real world, generally the attacker would probably try to de-compile your software and try to attack whatever underlying API you are using. However, this is a very visible security feature, and if you’re looking for a super-quick security addition, then, this may be an interesting addition. Windows Hello is a biometric authentication feature that allows users to log into their Windows device using a fingerprint scanner, facial recognition, or other biometric methods, rather than a password. Some potential use cases for including Windows Hello in a WinForms app include Secure login By using a fingerprint scanner or other biometric method, you can add an additional layer of security to your app and make it more difficult for unauthorized users to access the app. Convenience Allowing users to log in with a fingerprint or other biometric method can make the login process more convenient for them, as they don’t have to remember a password or enter it manually. Compliance Depending on the nature of the app and the industries it serves, biometric authentication may be required by compliance regulations or industry standards. User experience For some users, biometric authentication is a preferred way to interact with their devices, and they feel more secure with that kind of security. Protecting sensitive data If your app handles sensitive information, such as financial data or personal information, biometric authentication can help ensure that only authorized users have access to this information. Here is a link to a public GitHub Repo that shows a simple example of this in action https//github.com/infiniteloopltd/FingerPrintReader The Key code being; var supported = await KeyCredentialManager.IsSupportedAsync(); if (!supported) return; var result = await KeyCredentialManager.RequestCreateAsync("login", KeyCredentialCreationOption.ReplaceExisting); if (result.Status == KeyCredentialStatus.Success) { MessageBox.Show("Logged in."); } else { MessageBox.Show("Login failed."); }


InvalidOperationException: Unable to resolve servi ...
Category: .Net 7

Question How do you solve Asp.Net 5 Error <span style="background-color #f8ca ...


Views: 217 Likes: 74
Design Parterns in C-Sharp
Category: C-Sharp

Design Patterns (C#)< ...


Views: 366 Likes: 105
What is Async Await in AspNet 6 (C-Sharp)
Category: .Net 7

Understanding Async Await in AspNet 6 1. After playing with Async Await ...


Views: 27 Likes: 73
How to Deserialize XML into Object in Asp.Net Core ...
Category: .Net 7

Question How do you Deserialize XML String into a C# Object in Asp.Net Core 3.1? Answer ...


Views: 1336 Likes: 123
PayPal Payment C-Sharp Doc
Category: Education

I ...


Views: 313 Likes: 124
An unhandled exception has occurred while executin ...
Category: .Net 7

Question Why is MemoryStream having a Null buffer even after checking if the Stream contains an ...


Views: 0 Likes: 36
VBA Error Handling
Category: C-Sharp

Inside the VBA function declare (On Error GoTo Name) ...


Views: 319 Likes: 103
How to Select only fields you care about from Elas ...
Category: Algorithms

Question How do you select only a few fields you want from Elasticsearch Query using C# in the ...


Views: 0 Likes: 66
How to Use Spans in C-Sharp ( Stackalloc, Heap and ...
Category: .Net 7

Read about Spans ...


Views: 145 Likes: 67
VBA Error Handling
Category: C-Sharp

Inside the VBA function declare (On Error GoTo Name) ...


Views: 267 Likes: 107
Software Development Refactoring Wisdom I gained t ...
Category: Software Development

Software Development Refactoring Wisdom I gained through R ...


Views: 175 Likes: 84
How to Code a Windows Service that Updates the Dat ...
Category: .Net 7

Question How do you write C-Sharp Code that runs as a Windows Background Service to update the D ...


Views: 0 Likes: 25
Clearing out #AWS #Cloudwatch in C# – Coded with help from #ChatGPT
Clearing out #AWS #Cloudwatch in C# – Coded with h ...

If you’re like me, you use AWS Cloudwatch when testing and debugging your Lambda functions on AWS, and then whenever your code is working, you end up leaving them in, “just in case” – Of course, that means you ignore them, until you get a bill from AWS for holding GB’s of logs, for no reason whatsoever. So, here’s some C# code (Coded with the help of ChatCPT OpenAI with some modifications), to clear out all your Cloudwatch logs in all regions. You can be less heavy-handed, but I wanted to delete everything. using Amazon; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; using Amazon.Runtime; class Program { static void Main(string[] args) { const string accessKey = "xxxxxxxxxxxxxxx"; const string secretKey = "xxxxxxxxxxxxxxx"; var credentials = new BasicAWSCredentials(accessKey, secretKey); foreach (var region in Amazon.RegionEndpoint.EnumerableAllRegions) { Console.WriteLine(region.SystemName); var client = new AmazonCloudWatchLogsClient(credentials, region); try { // Get a list of all log groups DescribeLogGroupsResponse logGroupsResponse = null; try { logGroupsResponse = client.DescribeLogGroupsAsync().Result; } catch(Exception ex) { Console.WriteLine(ex.Message); continue; } var logGroups = logGroupsResponse.LogGroups; // Iterate through each log group and delete it foreach (var logGroup in logGroups) { // Get a list of all streams in the log group var logStreamsResponse = client.DescribeLogStreamsAsync(new DescribeLogStreamsRequest { LogGroupName = logGroup.LogGroupName }).Result; var logStreams = logStreamsResponse.LogStreams; // Iterate through each stream and delete it foreach (var logStream in logStreams) { client.DeleteLogStreamAsync(new DeleteLogStreamRequest { LogGroupName = logGroup.LogGroupName, LogStreamName = logStream.LogStreamName }); Thread.Sleep(TimeSpan.FromMilliseconds(50)); Console.WriteLine("Deleted log stream " + logStream.LogStreamName + " in log group " + logGroup.LogGroupName); } client.DeleteLogGroupAsync(new DeleteLogGroupRequest { LogGroupName = logGroup.LogGroupName }); Thread.Sleep(TimeSpan.FromMilliseconds(50)); Console.WriteLine("Deleted log group " + logGroup.LogGroupName); } Console.WriteLine("Deleted all log groups and streams in region " + region.SystemName); } catch (AmazonCloudWatchLogsException e) { Console.WriteLine("Error while processing region " + region.SystemName); Console.WriteLine("Caught Exception " + e.Message); Console.WriteLine("Response Status Code " + e.StatusCode); Console.WriteLine("Error Code " + e.ErrorCode); Console.WriteLine("Error Type " + e.ErrorType); Console.WriteLine("Request ID " + e.RequestId); } } } } Hope this helps someone!


A local or parameter named cannot be declared in t ...
Category: Technology

Problem When declaring a variable inside a using directive in C# (C-Sharp) you might get an erro ...


Views: 4416 Likes: 144
C-Sharp Tutorials
Category: C-Sharp

Good Website for C# tutorials ...


Views: 358 Likes: 103
Learn C-Sharp Programming Language
Category: C-Sharp

C# Program ...


Views: 375 Likes: 100
Why is AspNet 6 System DateTime showing Chinese Ch ...
Category: .Net 7

Question Asp.Net 6 all of the sudden started showing dates in Chinese, what is ...


Views: 0 Likes: 32
The content in the request produced errors while p ...
Category: .Net 7

Question How do you solve for an error in Asp.Net Core that says "The content in the request pr ...


Views: 0 Likes: 33
Rounding Down to the Nearest Decimal Point in C-Sh ...
Category: .Net 7

Question How do you Round Down the number to the nearest decimal point in C#? t ...


Views: 0 Likes: 51
InvalidOperationException: An exception was thrown ...
Category: Entity Framework

What is a LINQ Query?Linq which stands for Language Integrated Query ...


Views: 0 Likes: 69
 C# 9 Deep Dive: Target Typing and Covariant Returns
C# 9 Deep Dive Target Typing and Covariant Retur ...

We’ve been quite busy, my friends. In this C# 9 deep dive series, we’ve looked at init-only features, records, pattern matching, and then top-level programs. To complete this series (before showing off everything in a single app), we’ll discuss the last two items featured in the Build 2020 announcement target typing and covariant returns. These are not related, but I’ve decided to bundle these in a single blog post.This is the fifth post in a six-post series on C# 9 features in-depthPost 1 - Init-only featuresPost 2 - RecordsPost 3 - Pattern matchingPost 4 - Top-level programsPost 5 (this post) - Target typing and covariant returnsPost 6 - Putting it all together with a scavenger huntThis post covers the following topics.Improved target typingTarget-typed new expressionsTarget typing with conditional operatorsCovariant returnsWrapping upImproved target typingC# 9 includes improved support for target typing. What is target typing, you say? It’s what C# uses, normally in expressions, for getting a type from its context. A common example would be the use of the var keyword. The type can be inferred from its context, without you needing to explicitly declare it.The improved target typing in C# 9 comes in two flavors new expressions and target-typing ?? and ?.Target-typed new expressionsWith target-typed new expressions, you can leave out the type you instantiate. At first glance, this appears to only work with direct instantiation and not coupled with var or constructs like ternary statements.Let’s take a condensed Person class from previous postspublic class Person { private string _firstName; private string _lastName; public Person(string firstName, string lastName) { _firstName = firstName; _lastName = lastName; } } To instantiate a new Person, you can omit the type on the right-hand side of the equality statement.class Program { static void Main(string[] args) { Person person = new ("Tony", "Stark"); } } A big advantage to target-typed new expressions is when you are initializing new collections. If I wanted to create a list of multiple Person objects, I wouldn’t need to worry about including the type every time I create a new object.With the same Person class in place, you can change the Main function to do thisclass Program { static void Main(string[] args) { var personList = new List<Person> { new ("Tony", "Stark"), new ("Howard", "Stark"), new ("Clint", "Barton"), new ("Captain", "America") // ... }; } } Target typing with conditional operatorsSpeaking of ternary statements, we can now infer types by using the conditional operators. This works well with ??, the null-coalescing operator. The ?? operator returns the value of what’s on the left if it is not null. Otherwise, the right-hand side is evaluated and returned.So, imagine we have some objects that shared the same base class, like thispublic class Person { private string _firstName; private string _lastName; public Person(string firstName, string lastName) { _firstName = firstName; _lastName = lastName; } } public class Student Person { private string _favoriteSubject; public Student(string firstName, string lastName, string favoriteSubject) base(firstName, lastName) { _favoriteSubject = favoriteSubject; } } public class Superhero Person { private string _maxSpeed; public Superhero(string firstName, string lastName, string maxSpeed) base(firstName, lastName) { _maxSpeed = maxSpeed; } } While the code below does not get past the compiler in C# 8, it will in C# 9 because there’s a target (base) type that is convert-ablestatic void Main(string[] args) { Student student = new Student ("Dave", "Brock", "Programming"); Superhero hero = new Superhero ("Tony", "Stark", "10000"); Person anotherPerson = student ?? hero; } Covariant returnsIt has been a long time, coming—almost two decades of begging and pleading, actually. With C# 9, it looks like return type covariance is finally coming to the language. You can now say bye-bye to implementing some interface workarounds. OK, so just saying return type covariance makes me sound super smart, but what is it?With return type covariance, you can override a base class method (that has a less-specific type) with one that returns a more specific type.Before C# 9, you would have to return the same type in a situation like thispublic virtual Person GetPerson() { // this is the parent (or base) class return new Person(); } public override Person GetPerson() { // you can return the child class, but still return a Person return new Student(); } Now, you can return the more specific type in C# 9.public virtual Person GetPerson() { // this is the parent (or base) class return new Person(); } public override Student GetPerson() { // better! return new Student(); } Wrapping upIn this post, we discussed how C# 9 makes improvements with target types and covariant returns. We discussed target-typing new expressions and their benefits (especially when initializing collections). We also discussed target typing with conditional operators. Finally, we discussed the long-awaited return type covariance feature in C# 9.


System.InvalidOperationException: 'FromSqlRaw' or ...
Category: .Net 7

Question How do you solve calling a store procedure in Asp.Net 5 C-Sharp 9 error "System.Invalid ...


Views: 306 Likes: 66
Books for Programmers Manning.com
Category: Technology

Books for High-End Software DevelopersEarly in November 2018, I spoke with a ver ...


Views: 290 Likes: 107
Cannot create a DbSet for "MyModal" because this t ...
Category: .Net 7

Question I have no idea what is going on with this error. Yes, the error is qui ...


Views: 0 Likes: 31
How to check if string is null before replacing ch ...
Category: SQL

Question How do you catch for nulls in a variable before calling String.Replace ...


Views: 382 Likes: 85
C-Sharp (Learn About C-Sharp) Very Interesting Exp ...
Category: C-Sharp

C# documentation can be <a href="https//docs.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/index ...


Views: 294 Likes: 93
What is New in C-Sharp 9 ( Developing Notes )
Category: C-Sharp

1. Instead of writing public class person, you now write public record p ...


Views: 260 Likes: 92
VBA Microsoft Application Libraries
Category: C-Sharp

Nowadays it nearly impossible to avoid Microsoft's products. Therefore, it is always helpful to lear ...


Views: 252 Likes: 100
how to use speech in asp.net core
Category: .Net 7

Question How do you use Speech ...


Views: 268 Likes: 116
C-Sharp 11 Tips and Tricks
Category: Research

Linq- Did you know you could compair two sequences by using sequence operations li ...


Views: 90 Likes: 58
Lazy Loading Objects in C-Sharp [Speed Complexity]
Category: C-Sharp

Dot Net Lazy Loading Class ...


Views: 304 Likes: 97
How to find out the Highest Number in an Array in ...
Category: .Net 7

Question How do you find out the highe ...


Views: 125 Likes: 69
[AspNet 6] Using Generic Types in an Interface MVC ...
Category: Questions

Question How do you inject an Interface with a generic Type defined? When try to inject the Inte ...


Views: 69 Likes: 54
Print Error to Immediate VBA
Category: C-Sharp

For debugging VBA Access Database (Datamart), print errors to console <span style="color inherit; f ...


Views: 380 Likes: 102
Encountered end tag "div" with no matching start t ...
Category: .Net 7

Question Encountered end tag "div" with no matching start tag. Are your start/end tags properly ...


Views: 0 Likes: 45
SQL Query Like does not work with Spaces in a Stri ...
Category: SQL

Question How do you get the TSQ ...


Views: 391 Likes: 82
How to Write to PDF using an Open Source Library c ...
Category: .Net 7

Question How do I use the #PDF Library called iText 7 to write to the pdf in C-sharp?<br / ...


Views: 400 Likes: 93
HTML Injection C-Sharp
Category: HTML5

When working with html inside code behind in asp.net, make sure the html tags have no spaces between ...


Views: 354 Likes: 102
How to create PDF Signature Box using iTextSharp i ...
Category: .NET 7

&nbsp;I can suggest some popular libraries that might fit your needs 1. **iTextSharp** ...


Views: 0 Likes: 0
Data structure in C-Sharp Software Development Not ...
Category: Algorithms

In this article, I will keep notes about different #data #structures and why I should use ...


Views: 0 Likes: 39
 C# 9: Answering your questions
C# 9 Answering your questions

Note Originally published five months before the official release of C# 9, I’ve updated this post after the release to capture the latest updates.In the last month or so, I’ve written almost 8,000 words about C# 9. That seems like a lot (and it is!) but there is so much to cover! I’ve talked about how it reduces mental energy, simplifies null validation, and took on a deep dive series featuring init-only features, records, pattern matching, top-level programs, and target typing and covariant returns.After publishing all these posts, I received a lot of great questions in my Disqus comment section. Instead of burying the conversations there, I’d like to discuss these questions in case you missed them. I learned a lot from the questions, so thank you all!Init-only featuresFrom the post on init-only features, we had two questionsFernando Margueirat asks What’s the difference between init and readonly?The big difference is that with C# 9 init-only properties you are allowed to use object initialization. With readonly properties, you cannot.The Microsoft announcement says “The one big limitation today is that the properties have to be mutable for object initializers to work … first call the object’s constructor and then assigning to the property setters.” Because readonly value types are immutable, you can’t use them with object initializers.saint4eva asks Can a get-only property provide the same level of immutability as an init-only property?Similar to the last question, using init-only properties allow for initialization, while get-only properties are read-only and do not.RecordsFrom the post on record types, we also had one and a half questionsWOBFIE says So we should use so called “records” just because… some monkey encoded “struct” as “class”?!OK, this is less of a question and more of something that made me laugh (and why I say this is half of a question, as much as I love all my readers). But let’s read between the lines of what WOBFIE might be thinking—something along the lines of this being a hacked together struct?In the post itself, I explained the rationale for adding a new construct over building on top of struct.An easy, simplified construct whose intent is to use as an immutable data structure with easy syntax, like with expressions to copy objectsRobust equality support with Equals(object), IEquatable<T>, and GetHashCode()Constructor/deconstructor support with simplified positional recordsThe endgame is not to complicate workarounds—it is to devote a construct for immutability that doesn’t require a lot of wiring up from your end.Daniel DF says I would imagine that Equals performance decreases with the size of the record particularly when comparing two objects that are actually equal. Is that true?That is a wonderful question. Since I was unsure, I reached out to the language team on their Gitter channel. I got an answer within minutes, so thanks to them!Here is what Cyrus Najmabadi saysEquals is spec’ed at the language to do pairwise equality of the record members.they have value-semanticsin general, the basic approach of implementing this would likely mean you pay more CPU for equality checks. Though the language doesn’t concern itself with that. It would be an implementation detail of the compiler.Target typing and covariant returnsFrom my post on target typing and covariant returns, we had one question from two different readers.Pavel Voronin and saint4eva ask Are covariant return types a runtime feature or is it just a language sugar?This was another question I sent to the team. Short answer covariant return types are a runtime feature.Long answer it could have been implemented as syntactic sugar only using stubs—but the team was concerned about it leading to worse performance and increased code bloat when working with a lot of nested hierarchies. Therefore, they went with the runtime approach.Also, while in the Gitter channel I learned that covariant returns are only supported for classes as of now. The team will look to address interfaces at a later time.


[Asp.Net Core 3.1] Zebra Printer SDK C# Unable to ...
Category: .Net 7

Question When programming with Zebra C-Sharp SDK and trying to implement code t ...


Views: 737 Likes: 72
nest - ElasticSearch Order By String
Category: .Net 7

Question How do you order by Date in Elasticsearch Nest C# API. Answer See the code bel ...


Views: 0 Likes: 40
How to check if the number is empty in C-Sharp Asp ...
Category: HTML5

Question Is there a way to check if the number is empty in C#? There are so ma ...


Views: 0 Likes: 27
RuntimeBinderException: The best overloaded method ...
Category: .Net 7

Question How do you resolve the C-Sharp <a class='text-decoration-none' href='https//www.ernes ...


Views: 0 Likes: 33

Login to Continue, We will bring you back to this content 0



For peering opportunity Autonomouse System Number: AS401345 Custom Software Development at ErnesTech Email Address[email protected]