Category: .NET

Instrumentation in C# / .NET

For many programmers a try/catch with stack trace it is enough

try
{
var p = new Person();
p.DateOfBirth = DateTime.Now.AddYears(-10);
p.Drink(10, 2);
}
catch (Exception ex)
{
Console.WriteLine("ERROR OCCURED " + ex.StackTrace);
}

Others want to see also functions arguments, like in


p.Drink(10, 2);

will produce the result

ERROR An exception occured in method InstrumentationPostSharp.Person.Drink with (beersNumber = 10 , vodkaNumber = 2)

For this you can install the package
https://www.nuget.org/packages/LoggerAspect.Nlog

that have full source code at
https://github.com/vnvizitiu/AOP/tree/master/PostSharpTutorial

and watch my video for more details
https://youtu.be/qe2kpuuWXkw

RavenDB embedabble

I have made an application with RavenDB embeddable.

The good part is that is embeddable and easy to work with – at least, at start.

What I have learned:

  • If you forgot to use using, then RavenDB will throw an exception complaining about multiple sessions. Code:
 using (var session = instanceDefault.OpenSession(DatabaseName()))
{

//code
}

 

  • If you use multiple instance of the same EmbeddableDocumentStore , even on different default databases , then will complain about “temp path already used by another database instance “ . And the generics do NOT share the same instance of a static variable. And when you dispose a static singleton instance ? At the final of the application ( do not forget , otherwise you may have again “temp path already used by another database instance ” !)

 

  • The most simple index for new databases is RavenDocumentsByEntityName . Code:
//static EmbeddableDocumentStore instanceDefault;
var dbc = instanceDefault.DatabaseCommands.ForDatabase(DatabaseName());
                var defIndex = new RavenDocumentsByEntityName();
                
                defIndex.Execute(dbc,new DocumentConvention()
                {
                    DefaultUseOptimisticConcurrency = true                    
                    
                } );

 

  • If you create an index, create in the Database that needs. Otherwise if will complain when you get the data.  ( see previous code)

 

  • To manage data / databases , there is RavenDB Management Studio – a fancy name for an application that you can access ( by default ) at http://localhost:8080 . Code:
            instanceDefault = new EmbeddableDocumentStore();
//I have put this in app.config/web.config
            //instanceDefault.Configuration.Settings.Add("Raven/MaxSecondsForTaskToWaitForDatabaseToLoad", "60");
/*
<connectionStrings>
		<add name="RavenDB" connectionString="DataDir = ~\App_Data\Database"/>
	</connectionStrings>
   <appSettings>
	<add key="Raven/MaxSecondsForTaskToWaitForDatabaseToLoad" value="60"/>
*/
            instanceDefault.ConnectionStringName = "RavenDB";
            instanceDefault.Conventions.FindIdentityPropertyNameFromEntityName = (entity) => "ID";

            try
            {
                //To try in debug mode
                NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(8080);
                instanceDefault.UseEmbeddedHttpServer = true;
                instanceDefault.Initialize();

            }
            catch (ReflectionTypeLoadException ex)
            {
                string message = "LoaderExceptions:";
                ex.LoaderExceptions.ForEach(it => message += it.Message + ";");
                throw new Exception(message, ex);
            }


 

( do not let this into Web Application if you want to deploy to a third party host)

 

  • Copy / paste database do not work. You must backup and restore data( preferably with RavenDB Management Studio )

 

  • RavenDB documentation is ok – however, embeddable database is not so represented very well

 

If you want to see a sample ( not very good, though) repository, I have created one at https://github.com/ignatandrei/RomaniaOpenData/blob/master/ROP/ROPInfrastructure/Repository.cs

Bottom line: I think that is good enough.

Export to Excel,Word , Pdf, Html,CSV

I have made an application / package that exports data ( classes/datatable/csv/json) to Word/Excel/PDF.

I have made several tries in the past , however now is the definitive source for .NET 4.x It is FULL code source, with tests and tutorials..

 

The code is at https://github.com/ignatandrei/Exporter 

The NuGet package is at https://www.nuget.org/packages/ExporterWordExcelPDF

The demo online is at http://exporter.azurewebsites.net/ 

The documentation is at https://github.com/ignatandrei/Exporter/wiki 

You can help with the project – please read https://github.com/ignatandrei/Exporter/wiki/Help-the-project 

So if you need Excel / Word / PDF to export, please consider this open source project.

Throw versus ThrowEx

 

 

When you intercept exceptions( for logging ) you can

 
catch (Exception ex)
            {
                //TODO: log : 
                //https://youtu.be/OvzcBTm3Sow
                string s = ex.Message;
                throw ex;
            }
 

or

 
catch (Exception ex)
            {
                //TODO: log : 
                //https://youtu.be/OvzcBTm3Sow
                string s = ex.Message;
                throw ;
            }

The difference is small – but the consequences are losing the original stack trace , if you

 throw ex; 

I have done a small video about this : https://youtu.be/Deigld3Bqko

I have not covered ExceptionDispatchInfo  that you can see an usage here: http://blogs.microsoft.co.il/sasha/2011/10/19/capture-transfer-and-rethrow-exceptions-with-exceptiondispatchinfo-net-45/

Useful Attributes in Visual Studio

 

For me , I like

 

 [DebuggerDisplay(&quot;FirstName={FirstName}, LastName={LastName}&quot;)] 

 

and

[DebuggerStepThrough] 

 

The code is the following:

 class Program { static void Main(string[] args) { var p = new Person(); p.FirstName = &quot;Andrei&quot;; p.LastName = &quot;Ignat&quot;; Console.WriteLine(p.Name()); //InternalsVisibleToAttribute //Obsolete //All Attributes: https://msdn.microsoft.com/en-us/library/system.attribute.aspx } } [DebuggerDisplay(&quot;FirstName={FirstName}, LastName={LastName}&quot;)] class Person { public string FirstName { get; set; } public string LastName { get; set; } [DebuggerStepThrough] public string Name() { return FirstName + &quot; &quot; + LastName; } } 

and the video is at https://youtu.be/ShBr1GgpZKs

Validation in .NET

For validating a simple class, you can add [Required] ( see https://msdn.microsoft.com/en-us/library/ee256141(v=vs.100).aspx

But how to validate same object depending on his state? For example, when it is new, the email is required. But after saving, the user mus also add FirstName( also think about workflows)

There is a simple solution in .NET : IValidatableObject
In this example , I validate differently based on the object is new or retrieved from database:

 internal class Person:IValidatableObject
    {
        public int id { get; set; }
      
        public string Email { get; set; }

        public string FirstName { get; set; }

        /// <summary>
        /// MVC and EF are calling this if the class implements  IValidatableObject
        /// </summary>
        /// <param name="validationContext"></param>
        /// <returns></returns>
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {

            if (string.IsNullOrWhiteSpace(Email))
            {
                yield return new ValidationResult("my Email is required");
            }
            if (id == 0) //new
            {
                yield break;
            }

            //existing
            if(string.IsNullOrWhiteSpace(FirstName))
            {
                yield return new ValidationResult("First name is required");
            }

        }
    }

If you want to see in action , please see https://youtu.be/rjj0jjj3rxM

IEnumerable

 

Please read the code and answer question below:

class Program
    {
        static void Main(string[] args)
        {


            IEnumerable<int> myEnum = Data().Where(it => it < 5);

            string site = "http://msprogrammer.serviciipeweb.ro/";

            int[] arr = myEnum.ToArray();

            site +=" number is "+ myEnum.Count();
            site += " number is " + myEnum.Count();
            Console.WriteLine(site);

        }


        static IEnumerable<int> Data()
        {

            int i = 5;
            i++;

            yield return i;
            yield return (i+7);
        }
    }

How many times the breakpoint at

int i = 5;

will be hit ?

Why?

And if your answer is not 3, please look at https://youtu.be/1fy_T9TCPpc

Asynchronous code and exceptions

There are 2 kinds of coding when handling asynchronous code.

The first one is  calling Result:

<

The second is async /await

public async Task<bool> TwoTask() {

//code

await Task.WhenAll(file, console);
return file.Result & console.Result;

}

As such, we will have 2 intercepting code.

For the first one we will catch AggregateException

try
            {
                Console.WriteLine(t.TwoTask().Result);
            }
            catch (AggregateException ex)
            {
                Console.WriteLine("Aggregate number of exceptions :"+ex.InnerExceptions.Count);
            }

For the second one we will catch the FIRST task  exception  ( or , more generic , Exception ) – and see what other tasks have been doing

try

try
            {
                await Task.WhenAll(file, console);
                return file.Result & console.Result;
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine("Exception is " + ex.Message);
                
                if (file.IsFaulted)
                {
                    Console.WriteLine("file is faulted exceptions :" + file.Exception.InnerExceptions.Count);
                    
                }
                if (console.IsFaulted)
                {
                    Console.WriteLine("console is faulted exceptions :" + console.Exception.InnerExceptions.Count);
                }
                
                throw;
            }

Maybe it is better when you see a video demo: Async await and exceptions at https://youtu.be/1a9s74IfSE8

Async / await transformation and pitfalls


    /// <summary>
    /// please read first http://blog.stephencleary.com/2012/02/async-and-await.html
    /// </summary>

Let’s say you want to transform this code to async / await

public bool TwoTask()
        {
            var file= WriteToFile();
            var console= ReadConsole();
            return file & console;
        }

The first version is


public async Task<bool> TwoTask()
        {
            var file=await WriteToFile();
            var console = await ReadConsole();
            return file & console;
        }

Why is not good ? Because it executes in serial the file, and then the console code

The good version is


public async Task<bool> TwoTask()
        {
            var file=WriteToFile();
            var console = ReadConsole();
            await Task.WhenAll(file, console);
            return file.Result & console.Result;
        }

You can see in action at https://youtu.be/02oO0YaTEyM

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.