Posts

....
Technical Blog for .NET Developers ©

Thursday, July 25, 2019

Performance Profiler

Measuring the responsivity of an application on the usage of resources is quitely important, on distributed applications such as ASP.NET

Performance Profiler is an analysis tool included in Visual Studio. In this sample we are using it on a Web application, this is the process and the results:

Click Performance Profiler menú or press Alt+F2, to open the Diagnostic Session

-> Select the target, click start and open the Performance Wizard



-> We are measuring CPU sampling



-> Indicate the Url and start navigating





The result is an interactive report of CPU usage



With representation of hierarchy calls



Method Software 2018 ©

Tuesday, July 23, 2019

Threading : Implementation of ContinueWith()

In Threading tasks can be ordered to run consecutively with the implementations of ContinueWith methods

In this post we implement examples of this method and make a review of the options enumerated in TaskContinuationOptions. With three examples of continuation and its options

Consider this code: (notice the commented lines to make functions 3 and 4 run)


        static void TasksContinuationsDemo()
        {
            CancellationTokenSource tokenSource = new CancellationTokenSource();

            CancellationToken token = tokenSource.Token;

            token.Register(() =>
            {
                Console.WriteLine("Cancelation's been requested");
            });

            Task<bool> initialTask = new Task<bool>(() => 
            {
                Console.WriteLine("Tasks continuation demo");

                token.ThrowIfCancellationRequested();

                // OnlyOnFaulted option
                // throw new Exception();

                Console.WriteLine(true);

                return true;
            }, 
            token);

            Task task2 = initialTask.ContinueWith(result =>
            {
                Console.WriteLine("Initial Task ran to completion");

                Console.WriteLine("Initial Task result is {0}", result.Result);

            }, TaskContinuationOptions.OnlyOnRanToCompletion);

            Task<int> task3 = initialTask.ContinueWith<int>(result =>
            {
                Console.WriteLine("Initial task faulted");

                Console.WriteLine("Task 3 result is {0}", 1);

                return 1;

            }, TaskContinuationOptions.OnlyOnFaulted);

            Task<bool> task4 = initialTask.ContinueWith<bool>(result =>
            {
                Console.WriteLine("Initial Task's been canceled");

                Console.WriteLine("Task 4 result is {0}", true);

                return true;

            }, TaskContinuationOptions.OnlyOnCanceled);

            initialTask.Start();

            // OnlyOnCanceled option
            // tokenSource.Cancel();
        }


With this result:



Now uncomment the //OnlyOnFaulted option

With the next result:



And now uncomment the //OnlyOnCanceled option

With the next result:



The enum TaskContinuationOptions presents these options:



MSDN

Monday, July 22, 2019

Reflection : Chapter 1

.NET Reflection is the art of meta-coding, obtaining information that describes assemblies, modules and types.

By Reflection it is possible to discover the structure of an assembly, instantiating types with its methods, fields, accessors, and so on.

In this sample we get a known method in a known type: Reflection.Sample.Sample.GetMultiply:


        public decimal GetMultiply(decimal initialData, double addedData)
        {
            return (initialData * 3.14159M) / (decimal) addedData;
        }


Set the call to the function:


            Assembly asm = typeof(Sample.Sample).Assembly;

            Module module = asm.GetModule("Reflection.Sample.dll");

            Type type = module.GetType("Reflection.Sample.Sample", true, true);

            MethodInfo method = type.GetMethod("GetMultiply");

            ParameterInfo[] @params = method.GetParameters();

            Type returnType = method.ReturnType;

            var result = Activator.CreateInstance(returnType);

            object[] setParams = new object[@params.Length];

            for (int i = 0; i < @params.Length; i++)
            {
                setParams[i] = Activator.CreateInstance((@params[i]).ParameterType);

                switch (setParams[i].GetType().Name)
                {
                    case "Decimal":

                        setParams[i] = 10.40M;

                        break;

                    case "Double":

                        setParams[i] = 256.2048;

                        break;
                }
            }

            var obj = Activator.CreateInstance(type);

            result = method.Invoke(obj, setParams);





Static Constructors

Static Constructors initialize the static fields/properties of the class/static class. Static Constructors donot allow access modifiers so will work in background with the instructions of initialization of static resources in the class

In this post we exemplify the construction of a class containing static fields


    public class Particle<T> where T : new()
    {
        static T StaticElement { get; set; }

        public T Element { get; set; }

        public double Density { get; set; }

        // ctor
        public Particle(double density)
        {
            Density = density;
        }

        // static ctor
        static Particle()
        {
            StaticElement = new T();
        }

        public Particle<T> MuteParticle(Func<T, Particle<T>> muteFunction)
        {
            return muteFunction(StaticElement);
        }
    }



.2018

Saturday, July 20, 2019

Composing Functions

In this post we implement the technique of Composing Functions

The idea of composing functions is based on the concatenation of operations

Consider the next code:


            int var1 = 100;
            int var2 = var1 * 1024;
            int var3 = var2 + 2048;



We could create functions to perform this and our code would be the next:


            int var1 = 100;
            int var2 = CalcVar2(var1);
            int var3 = CalcVar3(var2);


        int CalcVar2(int a)
        {
            return a * 1024;
        }

        int CalcVar3(int b)
        {
            return b + 2048;
        }



This then would be improved with Composition, which automates this step


        public static Func<TSource, TEndResult> Compose<TSource, TIntermediateResult, TEndResult>(
            this Func<TSource, TIntermediateResult> func1,
            Func<TIntermediateResult, TEndResult> func2)
        {
            return sourceParam => func2(func1(sourceParam));
        }




            var autoCalcVar1 = extensions.Compose(CalcVar2, CalcVar3);

            int result = autoCalcVar1(var1);

            Console.WriteLine(result);





Wednesday, July 17, 2019

WCF One Way Dual Methods

WCF Services can declare methods which are invoked in one way mode, this implies the method will be called but the client side will not expect a reply, so will continue its operations without time leaks waiting for a response. This configuration is optimal for operations which don't require feedback results

OneWay methods can be bi-directionals, through a dual configuration, allowing client and server initiate invocation calls to each other. This mechanism is very useful for long-running processes in case the client expects a reply

In this post we develop a dual communication through a wsDualHttpBinding endpoint. These are the key points of the mechanism:

  • The service will expose an interface with the definition of the callback method, this method will be also marked as OneWay
  • This interface will be implemented in the client side
  • The OneWay method in the service will use this implementation to communicate with the client side once finish tasks
  • The client side must not dispose the InstanceContext with the server til the communication ends, the callback from the server will be treated as an event


The first step will be the definition of the interface in the service

    
    [ServiceContract(CallbackContract = typeof(IBookServiceCallBack))]
    public interface IBookService
    {
        [OperationContract]
        int AddBook(string title, string isbn, string synopsis, int idAuthor);

        [OperationContract]
        int AddAuthor(string firstName, string lastName, string biography);

        [OperationContract(IsOneWay = true)]
        void SendNewTitlesToSubscriptors(DateTime booksAddedAfterDate);
    }
    


And this is the definition of IBookServiceCallBack


    [ServiceContract] 
    public interface IBookServiceCallBack
    {
        [OperationContract(IsOneWay = true)]
        void NotifyClient(string message);
    }
    


We will focus on the method SendNewTitlesToSubscriptors, which will invoke the notification event on the client side

    
    public void SendNewTitlesToSubscriptors(DateTime booksAddedAfterDate)
    {
        _subscriptorManager.SendNewTitlesToSubscriptors(booksAddedAfterDate);

        INotificationServiceCallBack notificationSend =
            OperationContext.Current.GetCallbackChannel();

        notificationSend.NotifyClient(string.Format(
            "New titles added since {0} have been sent successfully", booksAddedAfterDate));
    }
    


With this configuration the client reference will add the interface IBookServiceCallBack

      <service name="BookService.BookService">
        <endpoint address="CallBackService" 
        binding="wsDualHttpBinding" contract="BookService.IBookService"/>
      </service>


Now the code in the client side:


    private InstanceContext instance
    {
        get { return new InstanceContext(new BookStoreNotificationHandler()); }
    }

    private BookServiceClient client
    {
        get { return new BookServiceClient(instance); }
    }

    private void btnSendNewTitles_Click(object sender, RoutedEventArgs e)
    {
        DateTime booksAddedAfterDate = dpBooksAddedFromDate.SelectedDate.Value;

        Thread threadSendNewTitles = new Thread(() =>
            {                    
                lblSendStep.SetContent("Sending new titles, please wait...");

                client.SendNewTitlesToSubscriptors(booksAddedAfterDate);
            });

        threadSendNewTitles.Start();
    }
    


and the implementation of IBookServiceCallBack as an event handler:

    
    public class BookStoreNotificationHandler : IBookServiceCallback
    {
        public void NotifyClient(string message)
        {
            MainWindow.lblSendStep.SetContent(message);
        }
    }
    


* Notice that in both cases we have used the extension method SetContent in order to control the content of the components in threading, as specified in this post: WPF MainWindow Instance

The result of this mechanism is the next:





<METHOD SOFTWARE © 2016>