Skip to main content

Posts

Showing posts with the label C#

Top Level Statement

Last week, I started my technical series on my YouTube channel named 'Shweta Lodha' with the name Sip and Learn. As part of this series, I'm planning to share some of the interesting short technical tips and concepts which are very easy to grab in just few minutes. Here, I speak about Top Level Statements feature of C# 9.0 as part of my first episode. You can go through this session on my channel.

Simplifying use of Static

Hope everyone must have come across static keyword while doing development, specifically using C#. Static modifier is used to declare static member, which means it belong to the type itself. Well, as part of this article, I’m not going to discuss more about static as it will increase the length of this writeup. public   class  Logger   {         public   static   int  GetLogLevel( string  logType)       {            …       }   }   Above is a sample code snippet wherein, we have a class called Logger and it has a static method called GetLogLevel . Now in order to call this GetLogLevel(…) method, first we have to add the required namespace, where this Logger class has been defined. Something like this, using  Planner.Utilities;    Well, nothing new as of now. Next, let’s have a look at, how to make a call to this static method. int  logLevel = Logger.GetLogLevel(fileLog);   Till here, nothing that bad, but we do have a room to improve our code by making it more readable and cleaner.

Generating XML Root Node having colon - via Serialization

Recently I got a requirement to generate an XML on the fly with some defined schema. I know this requirement looks very simple in first sight, but actually it was not. The XML which was to be generated was having a very specific format as it was supposed to be the input for some 3 rd party tool. So, it means, it should be fully compliant with the prescribed XML node structure. Just have a look at the below schema: <sl:RandomWindow xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sl="http://www.ShwetaBlogs.com/Window" xsi:schemaLocation="http://www.ShwetaBlogs.com/Window wwRandomWindow.xsd">   <Title>First Window</Title>   <Border>Single</Border> </sl:RandomWindow> Below are the classes I created for serialization purpose: By using the XmlElement and XmlAttribute classes I was able to generate most of the required parts of the XML as shown below:   But the only th

Why normal .NET exception handling doesn't work in WCF?

Errors and exceptions are part of our programming life and WCF is no different. So, when we get errors in WCF, we would like to propagate those errors to our WCF client so that they can accordingly take actions. In order to demonstrate this, let’s go through the code of a simple service: public int Add(int number1, int number2) { return number1 + number2; } public double Divide(int number1, int number2) { return number1 / number2; } Both the above methods will perform some calculation and return the result to the client. Let’s say, now for some reason someone sent 2 nd parameter of Divide method as 0.  What will happen? Definitely code will throw an error or say DivideByZero exception. Isn’t it? Know how to handle this error? Most of the developers will simply decorate Divide method with Try-catch block and throw the exception, similar to our normal .NET exception handling mechanism as shown in be

Customizing debugging session - Part II

Continuing to my previous article on 'Customizing debugging session' , we can further control on how properties and fields appear in our debugger window. Based on our debugging requirement, we can show and hide properties in our debugging session using one of the useful attribute named DebuggerBrowsableAttribute . Let’s go ahead and see debug window for one of the code snippet: In above image you will notice that by default list of Awards is not in expanded form. In order to view the values of awards, one needs to expand that forcibly either by hovering the mouse or by click on the plus symbol, which will result in below screenshot: How to hide unwanted properties during debugging session? What if a developer is not interested in viewing employee’s branch? Well, that unwanted property can be made hidden by using DebuggerBrowsableState as Never as shown below: Now let’s run the code and check, whether it is h

Customizing debugging session - Part I

I hope, being a developer everyone needs to debug their code at least once a day even if it is a very small snippet. Frankly speaking, sometimes it becomes very frustrating when we are looking for a value of particular property or let’s say very few properties of a huge object and it gets TIMEOUT. Uhhh !!! This time, we feel like there should be some easy way to navigate to that particular property instead of going to the object and clicking on plus symbol to reach the required property. Well, let’s understand it via code: Aim: I have an Employee class with two members as EmployeeName and BranchName. I want to know the name and branch of an Employee during my debugging session. So, I start debugging and lend up on below screen: Now in order to view the required details, I need to expand the employee object as shown in below screenshot: Now first question is, is there any way to display customized message in debugger window?  Answer would

Microsoft Introduces Bing Code Search Add-On For Visual Studio

Microsoft has launched the 'Bing Code Search add-on'  for Visual Studio, representing companionship between the Bing, Visual Studio and Microsoft Research divisions. The Bing Code Search extension directly assimilates the code snippet search for C# with other languages, coming later into the Visual Studio.  As this add-on is a part of the Visual Studio, programmers will be able to use it to search for the code samples from a number of web-based repositories including MSDN, StackOverflow, Donnetperls and CSharp411. So, if you are using Microsoft Visual Studio for building apps, you can download the add-on, activate it, type the search string, press enter and you will get a couple of options that are suitable for your project.  You can grab the add-on from the Visual Studio directory page However, the add-on can be used to search for the code samples anywhere on the Web as well; Microsoft says that the sites it has shortlisted should be “more than sufficient” for most of

Automatic Numbering for the Primary Key Column

Many of you might have come across an issue of Auto incrementing while working with database products. Truly speaking, recently I also came across one silly problem and thought of sharing it here. Imagine that at some point of time, you might want to send your new data to a back-end database. If your application supplies the auto-increment values, then what will the database do? what if application receives duplicate values from different client applications? The answer is that these auto-increment values are never sent to the database because the auto-increment column in the database table will provide a value whenever a new row is added. After each new row is added, the back-end database table generates a new-increment number and then your application will query the database to get the newly created number. Your application will then update its primary key number to the values that came from the database. This means that all the foreign key references will need t

Const and Readonly keyword

Both these words play a very important role in defining constants in an application (C#). At one sight, it seems like, both are same but exactly it is not he case. Let's understand one by one to get the clear picture. The word const itself means, it will never change. If you are specifying any variable as a  const t hat means the value of the variable is never going to change inside the application. How we declare a constant is, by using a  const  keyword. Basically, one can define  const  only on the primitive types, like int, double, etc. One should make sure that the value should be assigned at the time of declaration itself and another important thing is whatever value is set for  const  variable, that value will be set at the compile time itself and this value will get stored inside a .dll or an .exe. In later part, I'll show u on how we can see this value inside a dll or an exe using an Ildasm. Sample code to define  const   variable is as: Another key

Optional Parameter issue with COM and C#/VB

As we all know, C# doesn't support optional parameters(till framework 3.5) whereas VB does.In the same way, COM components don't support parameter overloading , so for each value in a parameter list, we've got to pass in something, even if it does nothing. Moreover, COM parameters are always passes by reference , which means we can't pass NULL as a value. In VB 2005, this is not really as issue because it supports optional parameters and we can just leave them out. But C# doesn't support this, so one have to create object variables and pass them in. See following code sample: u sing Microsoft.Office.Core; u sing Microsoft.Office.Interop.Excel;  // Must have office installed Application NewExcelApp = new Application; NewExcelApp.Worksheets.Add();       // This will not compile So, as a workaround, the Type.Missing field can be used and this field can be passed in with the C# code and the application will work as expected.  Check it in below code sni