Category: .NET

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("FirstName={FirstName}, LastName={LastName}")] 

 

and

[DebuggerStepThrough] 

 

The code is the following:

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

MVC planning poker–part 7

The latest 2 cases are

Use Case 5: Round reset
Moderator enters a round name (?) .
Participants choose a value.
Host press "reset round " and a fresh new round is created
The old one is not saved

Use Case 6: Round save
After a round is saved, the users can see the history round names and picked value
They can see also a total

 

There is not so more implementation – just save in the memory  a list and retrieve.

Next time we will be thinking about persistence – how this affect the structure of the application

Entity Framework 6 Record and play use : Unit Testing ( part 2 of 5)

 

Part 1 : What is EF record and play : http://msprogrammer.serviciipeweb.ro/2014/11/29/entity-framework-6-record-and-play-1-of-5/ 

Part 2: EF Record and play use: Testing : http://msprogrammer.serviciipeweb.ro/2014/12/08/entity-framework-6-record-and-play-use-unit-testing-part-2-of-5/

Part 3: EF Record and play use: Make demo: http://msprogrammer.serviciipeweb.ro/2014/12/14/entity-framework-6-record-and-play-use-making-demos-part-3-of-5/ 

Part 4: EF Record and play use: Record user Sql when a bug occurs: http://msprogrammer.serviciipeweb.ro/2014/12/26/ef-record-and-play-use-recording-user-sql-when-a-bug-occurred-part-4-of-5/

Part 5: EF record and play: conclusions: http://msprogrammer.serviciipeweb.ro/2015/01/05/ef-record-and-play-conclusions/

 

Let’s suppose that we have a program that have Departments and Employees.

And we want to make sure that, when we add an employee, the department must exists.

We can ensure this from database ( by foreign key) but we can pro-actively search for the department and throw a more meaningful validation .

More, I like more validation than errors.

So, let’s suppose that in the Validation for the Employee we must check in the database for the IdDepartment to see if there is such a department.

How could we make a test for that runs without a database ?

With some trick:  we first Record with a database  – then we can Play the file – and we do not need anymore the database. The test is self contained. 

 

Let’s see in action here

 

Database.SetInitializer<ContextForDatabase>(null);
            #region set record EF
            var record = new InterceptionRecordOrPlay(@"VerifyIValidatableWorks.zip", ModeInterception.Play);

            DbInterception.Add(record);
            #endregion
            var e= new Employee();
            e.ValidateEmployee = true;
            e.IDDepartment = 60000;
            var err= e.Validate(null).ToArray();
            Assert.IsNotNull(err);
            Assert.AreEqual(1, err.Length);

Source code is available at  https://github.com/ignatandrei/EFRecordAndPlay/wiki/

 

There is also a NuGet package at https://www.nuget.org/packages/EFRecordAndPlay/