Ehsan Ghanbari

Experience, DotNet, Solutions

Sinch Wrapper for sending SMS

I was recently looking for a verification system and came across with Sinch. It's been satisfactory until now. After installing the library by nuget I created a wrapper for SMS, hope it be useful!

 

 public class SinchWrapper
    {
        public static async Task<SinchWrapperResult> SendSms(string countryCode, string number, string message)
        {
            try
            {
                number = number.Replace(" ", "").Replace("-", "");
                if (string.IsNullOrEmpty(message))
                    return new SinchWrapperResult { Faild = true, Message = "Message was empty" };
                var destinationNumber = countryCode + number;
                var smsApi = SinchFactory.CreateApiFactory("Your Key", "YourSecret).CreateSmsApi()");
                var sendSmsResponse = await smsApi.Sms(destinationNumber, message).Send();
                return new SinchWrapperResult { Faild = false, Message = message };
            }
            catch (Exception ex)
            {
                return new SinchWrapperResult { Faild = true, Message = ex.Message };
            }
        }
        public static async Task<SinchWrapperResult> SendVerificationSms(string countryCode, string number, string code)
        {
            var result = await SendSms(countryCode, number, $"your verification code is: {code}");
            result.Data = code;
            return result;
        }
    }
    public class SinchWrapperResult
    {
        public bool Faild { get; set; }
        public string Message { get; set; }
        public string Data { get; set; }
    }

 

Rather than above which is available almost in every SMS panels, there is another cool option that verifies by a Missed Call! Instead of entering the receiving and entering the verification code via SMS, you enter the number that you been called with! For using that feature you simply change the configuration:

 


            var api = SinchFactory.CreateApiFactory("key", "secret").CreateVerificationApi();
            var initiate = await api.Verification(number).WithReference("A Reference number").WithCustom("A Custom number").Initiate(VerificationMethod.FlashCall);
            var report = await api.Verification(number).WithCli(initiate.FlashCall.CliFilter).Report(VerificationMethod.FlashCall);
   

 



Working with Static Files in asp.net core

In asp.net core,  the wwwroot folder treated as a web root folder. Static files can be stored in any folder under the web root and accessed with a relative path to that root. By default, static files are not accessible:

In order to access a file you should add the related configuration in Configure method of Startup class:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseStaticFiles();
         }

By running again the project, the image will be accessible:

Now if you want to do more configuration for other paths inside wwwroot, for example, directory browsing or inner static file, you can add the configuration below:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseStaticFiles();

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Images")),
                RequestPath = "/Images"
            });

            app.UseDirectoryBrowser(new DirectoryBrowserOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Images")),
                RequestPath = "/Images"
            });

            app.UseHttpsRedirection();
            app.UseMvc();
        }

It's obviously shown that the Images is a folder inside wwwroot, look at the output below:



Custom C# wrapper for calling web API

I've used a custom wrapper for calling asp.net web API services in some projects. I just wanted to share it over here. It's been tested for hundreds of times!

 

 

   public class MyCustomWrapper<T> where T : class

    {

        private static readonly HttpClient Client = new HttpClient();

 

        public async Task<T> GetItemAsync(string apiUrl, CancellationToken cancellationToken)

        {

            var result = default(T);

            try

            {

                var response = await Client.GetAsync(apiUrl, cancellationToken).ConfigureAwait(false);

                if (response.IsSuccessStatusCode)

                {

                    await response.Content.ReadAsStringAsync().ContinueWith(x =>

                    {

                        if (typeof(T).Namespace != "System")

                        {

                            var data = x?.Result;

                            result = JsonConvert.DeserializeObject<T>(data);

                        }

                        else result = (T)Convert.ChangeType(x?.Result, typeof(T));

                    }, cancellationToken);

                }

                else

                {

                    var content = await response.Content.ReadAsStringAsync();

                    response.Content?.Dispose();

                    throw new HttpRequestException($"{response.StatusCode}:{content}");

                }

            }

            catch (Exception)

            {

                return result;

            }

 

            return result;

        }

 

        public async Task<T[]> GetItemsRequestAsync(string apiUrl, CancellationToken cancellationToken)

        {

            T[] result = null;

            var response = await Client.GetAsync(apiUrl, cancellationToken).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)

            {

                await response.Content.ReadAsStringAsync().ContinueWith((Task<string> x) =>

                {

                    result = JsonConvert.DeserializeObject<T[]>(x.Result);

                }, cancellationToken);

            }

            else

            {

                var content = await response.Content.ReadAsStringAsync();

                response.Content?.Dispose();

                throw new HttpRequestException($"{response.StatusCode}:{content}");

            }

            return result;

        }

 

        public async Task<T> PostRequestAsync(string apiUrl, T postObject, CancellationToken cancellationToken)

        {

            T result = default(T);

            var json = JsonConvert.SerializeObject(postObject);

            var content = new StringContent(json.ToString(), Encoding.UTF8, "application/json");

            var response = await Client.PostAsync(apiUrl, content);

 

            if (response.IsSuccessStatusCode)

            {

                await response.Content.ReadAsStringAsync().ContinueWith((Task<string> x) =>

                {

                    result = JsonConvert.DeserializeObject<T>(x.Result);

                }, cancellationToken);

            }

            else

            {

                var unSuccesscontent = await response.Content.ReadAsStringAsync();

                response.Content?.Dispose();

                throw new HttpRequestException($"{response.StatusCode}:{unSuccesscontent}");

            }

            return result;

        }

 

        public async Task PutRequestAsync(string apiUrl, T putObject, CancellationToken cancellationToken)

        {

            var response = await Client.PutAsync(apiUrl, new JsonContent(putObject), cancellationToken).ConfigureAwait(false);

            if (!response.IsSuccessStatusCode)

            {

                var content = await response.Content.ReadAsStringAsync();

                response.Content?.Dispose();

                throw new HttpRequestException($"{response.StatusCode}:{content}");

            }

        }

 

        public async Task DeleteRequestAsync(string apiUrl, CancellationToken cancellationToken)

        {

            var response = await Client.DeleteAsync(apiUrl, cancellationToken).ConfigureAwait(false);

            if (!response.IsSuccessStatusCode)

            {

                var content = response.Content.ReadAsStringAsync();

                response.Content?.Dispose();

                throw new HttpRequestException($"{response.StatusCode}:{content}");

            }

        }

    }

 

    public class JsonContent : StringContent

    {

        public static JsonContent From(object data) => data == null ? null : new JsonContent(data);

 

        public JsonContent(object data)

            : base(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json")

        {

        }

    }

 

And about the usage of this wrapper:

 

 var wrapperResult = new MyCustomWrapper<YourClass>();

        var result = wrapperResult.GetItemAsync("https://localhost/api/user/GetInfo?username=" + "userName", new CancellationToken());

        var data = result.Result;

that's it! 



Communicate between Windows Service and SignalR Client

Today I had to make a connection between an old windows service and SignalR client. After tackling for an hour I decided to reference the Microsoft.AspNet.SignalR.Client library to my web service project and use it like below by overriding the OnStart method, actually I created the SignalR hub connection in the web service method:

 

 protected override async void OnStart(string[] args)
        {
               var hubConnection = new HubConnection("http://www.MySignalRDomain.com/signalr", useDefaultUrl: false);
               IHubProxy myProjectHub= hubConnection.CreateHubProxy("myProjectHub");

               await hubConnection.Start();

               await myProjectHub.Invoke("HiToYou", "an invoked message, for example");
         }

 

And in the SignalR service, I created the target hub to get the string ("an invoked message,  for example") from the web service in HiToYou method :

 
   

 public class myProjectHub: Hub
    {
       public void HiToYou(string message)
        {
                  Clients.All.addNewMessageToPage(message);

         }

       }

 

Needless to say, if you are using OwinStartup, you need to register SignalR middleware:

 

 

using Microsoft.Owin;

using Owin;

 

[assembly: OwinStartup(typeof(MyApplication.Startup))]

namespace MyApplication

{

    public class Startup

    {

        public void Configuration(IAppBuilder app)

        {                  

            app.MapSignalR("/signalr", new HubConfiguration());

        }

    }

}

 

Hope it would be useful!



Simple command handler in .net

 

I want to introduce a simple command handler pattern in order to separate commands and queries of your applications if it’s needed. Sometimes especially in large-scale applications, you need to have two layers for reading and write separated and assign two teams to work on them.

You can use the pattern in this post based on the complexity and needs of your application. I recommend that don’t call this CQRS pattern as it’s something completely different and more complex.

 

Get started and Create an interface with no any member:

public interface ICommand

    {

    }

You will see later in this blog post that ICommand is just a flag to determine the commands for the handler. Every command which is trying to make a change in application’s state should return a result. so create another interface named ICommandResult

public interface ICommandResult

    {

        string Message { get; }

        bool Success { get; }

    }

implement the above interface as CommandResult and derive the FailureResult and SuccessResult classes from:

internal abstract class CommandResult : ICommandResult

    {

        public string Message { get; protected set; }

        public bool Success { get; protected set; }

    }



internal class FailureResult : CommandResult

    {

        public FailureResult(string message)

        {

            Success = false;

            Message = message;

        }

    }



    internal class SuccessResult : CommandResult

    {

        public SuccessResult(string message)

        {

            Success = true;

            Message = message;

        }

    }

Now create an interface for handling the validations in CommandBus class:

internal interface IValidationHandler<in TCommand> where TCommand : ICommand

    {

        IEnumerable<ValidationResult> Validate(TCommand command);

    }

 And create a class for validations:

public class ValidationResult

    {

        /// <summary>

        /// Initializes a new instance of the <see cref="ValidationResult"/> class.

        /// </summary>

        public ValidationResult()

        {

        }



        /// <summary>

        /// Initializes a new instance of the <see cref="ValidationResult"/> class.

        /// </summary>

        /// <param name="memeberName">Name of the memeber.</param>

        /// <param name="message">The message.</param>

        public ValidationResult(string memeberName, string message)

        {

            MemberName = memeberName;

            Message = message;

        }



        /// <summary>

        /// Initializes a new instance of the <see cref="ValidationResult"/> class.

        /// </summary>

        /// <param name="message">The message.</param>

        public ValidationResult(string message)

        {

            Message = message;

        }



        /// <summary>

        /// Gets or sets the name of the member.

        /// </summary>

        /// <value>

        /// The name of the member.  May be null for general validation issues.

        /// </value>

        public string MemberName { get; set; }



        /// <summary>

        /// Gets or sets the message.

        /// </summary>

        /// <value>

        /// The message.

        /// </value>

        public string Message { get; set; }

    }

And now create the most used interface in this pattern. ICommandBus will be called as bus handler in every command:

public interface ICommandBus

    {

        ICommandResult Send<TCommand>(TCommand command) where TCommand : ICommand;

        IEnumerable<ValidationResult> Validate<TCommand>(TCommand command) where TCommand : ICommand;

    }

To implementing this interface, create a class again with the following definition:

  internal class CommandBus : ICommandBus

    {

        public ICommandResult Send<TCommand>(TCommand command) where TCommand : ICommand

        {

            var handler = DependencyResolver.Current.GetService<ICommandHandler<TCommand>>();



            if (!((handler != null) && handler != null))

            {

                throw new CommandHandlerNotFoundException(typeof(TCommand));

            }

            return handler.Execute(command);

        }



        public IEnumerable<ValidationResult> Validate<TCommand>(TCommand command) where TCommand : ICommand

        {

            var handler = DependencyResolver.Current.GetService<IValidationHandler<TCommand>>();

         

            if (!((handler != null) && handler != null))

            {

                throw new ValidationHandlerNotFoundException(typeof(TCommand));

            }

            return handler.Validate(command);

        }

    }

The above class will handle every command received from the bus. And now for executing the handler or so-called for implementing the business, you need an interface:

internal interface ICommandHandler<in TCommand> where TCommand : ICommand

    {

        ICommandResult Execute(TCommand command);

    }

And finally as I’m personally interested in to have my own exception handler, so I create a customized handler:

public class CommandHandlerNotFoundException : Exception

    {

        public CommandHandlerNotFoundException(Type type)

            : base(string.Format("Command handler not found for command type: {0}", type))

        {

        }

    }



    internal class ValidationHandlerNotFoundException : Exception

    {

        public ValidationHandlerNotFoundException(Type type)

            : base(string.Format("Validation handler not found for command type: {0}", type))

        {

        }

    }

Finished! Now let’s use the above codes in a real work application. We are going to handle the products of an e-commerce application as its business is easier to comprehend for everybody:

    public interface IProductCommand : ICommand

    {

        string Name { get; set; }



        string OriginalName { get; set; }



        string Description { get; set; }



        decimal Price { get; set; }

     

    }

  

    public class ProductCommand : IProductCommand

    {

        public string Name { get; set; }



        public string OriginalName { get; set; }



        public string Description { get; set; }



        public decimal Price { get; set; }     

    }



    public class CreateProductCommand : ProductCommand

    {

    }



    public class EditProductCommand : ProductCommand

    {

        public Guid ProductId { get; set; }



        public DateTime CreationDate { get; set; }



        public DateTime LastUpdateDate { get; set; }

    }



public class DeleteProductCommand : ICommand

    {

        public Guid[] ProductIds { get; set; }

    }

You can see that I created an interface derived from ICommand named IProductCommand and finally created the target classes. And at the end we should create the Product handler class:

internal partial class ProductCommandHandler :

        ICommandHandler<CreateProductCommand>,

        ICommandHandler<EditProductCommand>,   

        ICommandHandler<DeleteProductCommand>       

    {

        private readonly IProductRepository _productRepository;

        private readonly IMembershipRepository _membershipRepository;     

        private readonly IUnitOfWork _unitOfWork;

        private readonly ICacheManager _cacheManager;

        private readonly ILogger _logger;



        public ProductCommandHandler(

            IProductRepository productRepository,        

            IUnitOfWork unitOfWork,

            ILogger logger,

            ICacheManager cacheManager)

        {

            _productRepository = productRepository;          

            _unitOfWork = unitOfWork;

            _logger = logger;

            _cacheManager = cacheManager;        

        }

       

        public ICommandResult Execute(CreateProductCommand command)

        {

            try

            {

                if (command == null)

                {

                    throw new ArgumentNullException();

                }



                var product = new Product();

                AddProductAppurtenance(command, product);

                _productRepository.Add(product);

                _unitOfWork.Commit();

                return new SuccessResult(ProductCommandMessage.ProductCreatedSuccessfully);

            }

            catch (Exception exception)

            {

                _logger.Error(exception.Message);

                return new FailureResult(ProductCommandMessage.ProductCreationFailed);

            }

        }



        public ICommandResult Execute(EditProductCommand command)

        {

            try

            {

                if (command == null)

                {

                    throw new ArgumentNullException();

                }



                var product = _productRepository.GetProductDetailById(command.ProductId);

                ClearProductAppurtenance(product);

                AddProductAppurtenance(command, product);

                _productRepository.Edit(product);

                _unitOfWork.Commit();



                return new SuccessResult(ProductCommandMessage.ProductEditedSuccessfully);

            }

            catch (Exception exception)

            {

                _logger.Error(exception.Message);

                return new FailureResult(ProductCommandMessage.ProductEditionFailed);

            }

        }



        public ICommandResult Execute(DeleteProductCommand command)

        {

            if (command.ProductIds == null)

            {

                throw new ArgumentNullException();

            }



            var exceptions = new List<Exception>();

            foreach (var productId in command.ProductIds)

            {

                try

                {

                    var product = DeleteProduct(productId);

                    _productRepository.Edit(product);

                }

                catch (Exception exception)

                {

                    exceptions.Add(exception);

                    return new FailureResult(ProductCommandMessage.ProductDeletionFailed);

                }

            }



            if (exceptions.Any())

            {

                throw new AggregateException(exceptions);

            }



            _unitOfWork.Commit();

            return new SuccessResult(ProductCommandMessage.ProductsDeletedSuccessufully);

        }  

 

We used all of the classes introduced in infrastructure.

Note 1: so you need to have an IOC container tool, to the best of my Knowledge, AsClosedTypesOf in Autofac resolves the ICommandHandler. This a piece of code I wrote for IOC handler:

  public class CommandModule : Module

    {

        protected override void Load(ContainerBuilder builder)

        {

            builder.RegisterModule<RepositoryModule>();

            builder.RegisterType<CommandBus>().As<ICommandBus>().InstancePerRequest();

            builder.RegisterAssemblyTypes(ThisAssembly).AsClosedTypesOf(typeof(ICommandHandler<>)).InstancePerRequest();

        }

    }

Note 2: a penny for your thoughts! how to use ICommandBus!? See the below piece of code as an example:

[HttpPost]

        public JsonResult DeleteProduct(DeleteProductCommand command)

        {

            var result = _commandBus.Send(command);

            return JsonMessage(result);

        }

have fun.



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
Peridic pattern
How to query over Icollection<> of a type with linq
How to use PagedList In asp.net MVC
Using Generic type for type casting in F#
Domain driven design VS model driven architecture
What's the DDD-lite?