Validating a view model after custom model binding

Adapted from here:
https://stackoverflow.com/questions/13684354/validating-a-view-model-after-custom-model-binding

Usage:

CustomModelBinderHelper.DoValidation(bindingContext, indexViewModel);

Implementation:

    public static class CustomModelBinderHelper
    {
        /// <summary>
        /// https://stackoverflow.com/a/22652195/249895
        /// </summary>
        /// <param name="bindingContext"></param>
        /// <param name="model"></param>
        public static void DoValidation(ModelBindingContext bindingContext, IValidatableObject model)
        {
            var validationResults = new HashSet<ValidationResult>();
            var isValid = Validator.TryValidateObject(model, new ValidationContext(model, null, null), validationResults, true);
            if (!isValid)
            {
                var resultsGroupedByMembers = validationResults
                    .SelectMany(_ => _.MemberNames.Select(
                         x => new
                         {
                             MemberName = x ?? "",
                             Error = _.ErrorMessage
                         }))
                    .GroupBy(_ => _.MemberName);

                foreach (var member in resultsGroupedByMembers)
                {
                    bindingContext.ModelState.AddModelError(
                        member.Key,
                        string.Join(". ", member.Select(_ => _.Error)));
                }
            }
        }
    }

 

To be noted that objects have to implment System.ComponentModel.DataAnnotations.IValidatableObject interface.

Kendo Mvc GridHelper

Code beautifier: http://hilite.me/

Usage

@(Html.CustomKendoGrid<ViewModels.UserViewModel>("grid"))

Code:

namespace Kendo.Mvc.UI
{
    //read here about Func vs Action https://stackoverflow.com/a/12687775/249895
    public static class KendoMvcGridHelper
    {

        public static readonly int AxajPageSize = 20;
        public static readonly int AxajPageSizeSmall = 10;

        public static Kendo.Mvc.UI.Fluent.GridBuilder CustomKendoGrid(this HtmlHelper helper, string name) where T : class
        {
            var returnGridBuilder = helper.Kendo().Grid();
            returnGridBuilder = returnGridBuilder.Name(name);
            returnGridBuilder = ConfigureGridBuilder(returnGridBuilder);

            return returnGridBuilder;
        }

        private static GridBuilder ConfigureGridBuilder(GridBuilder gridBuilder) where T : class
        {
            gridBuilder = gridBuilder.Pageable(p => p.PageSizes(new List<int>() { 10, 20 }));
            gridBuilder = gridBuilder.Sortable();
            gridBuilder = gridBuilder.Resizable(r => r.Columns(true));
            gridBuilder = gridBuilder.Filterable(ConfigureGridFilterableSettingsBuilder);
            gridBuilder = gridBuilder.Pageable();
            return gridBuilder;
        }


        public static void ConfigureGridFilterableSettingsBuilder(GridFilterableSettingsBuilder config)        
        {
            config = config.Mode(GridFilterMode.Row).Extra(false);
            config = config.Operators(ConfigureFilterableOperators);
        }

        public static void ConfigureFilterableOperators(FilterableOperatorsBuilder operators)
        {
            operators = operators.ForString(str => str.Clear()
                        .IsEqualTo("Is equal to")
                        .IsNotEqualTo("Is not equal to")
                        .StartsWith("Starts with")
                        .EndsWith("Ends with")                        
                        .Contains("Contains")
                        .DoesNotContain("Does not contain")
                    )
                    .ForDate(str => str.Clear()
                        .IsEqualTo("Is Equal To")
                        .IsGreaterThan("Is Greater Than")
                        .IsGreaterThanOrEqualTo("Is Greater Than Or Equal To")
                        .IsLessThan("Is Less Than")
                        .IsLessThanOrEqualTo("Is Less Than Or Equal To")
                        .IsNotEqualTo("Is Not Equal To")
                    )
                    .ForEnums(str => str.Clear()
                        .IsEqualTo("Is Equal To")
                        .IsNotEqualTo("Is Not Equal To")
                    )
                    .ForNumber(str => str.Clear()
                        .IsEqualTo("Is Equal To")
                        .IsGreaterThan("Is Greater Than")
                        .IsGreaterThanOrEqualTo("Is Greater Than Or Equal To")
                        .IsLessThan("Is Less Than")
                        .IsLessThanOrEqualTo("Is Less Than Or Equal To")
                        .IsNotEqualTo("Is Not Equal To")
                    );
        }
    }
}

Azure BlobStorageHelper – Blob create and upload

Code beautifier: http://hilite.me/

Code: 

namespace Helpers
{
    public sealed class BlobStorageHelper : StorageHelper
    {
        private readonly CloudBlobClient _blobClient;
        public string _containerName { get; set; }

        public BlobStorageHelper() : base()
        {
            _blobClient = base.StorageAccount.CreateCloudBlobClient();
            _containerName = ConfigurationManager.AppSettings["StorageContainerName"];
        }


        public Uri CreateBlob(Stream inputStream, string blobName)
        {
            CloudBlobContainer container = _blobClient.GetContainerReference(_containerName);
            container.CreateIfNotExists();

            ICloudBlob blob = container.GetBlockBlobReference(blobName);
            blob.UploadFromStream(inputStream);

            return blob.Uri;
        }

        public Uri CreateBlob(byte[] byteArray, string blobName)
        {
            CloudBlobContainer container = _blobClient.GetContainerReference(_containerName);
            container.CreateIfNotExists();

            ICloudBlob blob = container.GetBlockBlobReference(blobName);
            blob.UploadFromByteArray(byteArray, 0, byteArray.Length);

            return blob.Uri;
        }

        public string GetBlobFileDownloadPath(string blobPath)
        {
            string blobName = blobPath.Substring(blobPath.IndexOf("/" + _containerName + "/")).Replace("/" + _containerName + "/", "");

            CloudBlobContainer container = _blobClient.GetContainerReference(_containerName);
            container.CreateIfNotExists();

            ICloudBlob cloudBlob = container.GetBlobReferenceFromServer(blobName);

            var sasConstraints = new SharedAccessBlobPolicy();
            sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(5);
            sasConstraints.Permissions = SharedAccessBlobPermissions.Read;

            var sasBlobToken = cloudBlob.GetSharedAccessSignature(sasConstraints);

            return blobPath + sasBlobToken;
        }

        public void DeleteBlob(string blobPath)
        {
            CloudBlobContainer container = _blobClient.GetContainerReference(_containerName);
            container.CreateIfNotExists();

            CloudBlob cloudBlob = container.GetBlockBlobReference(blobPath);

            cloudBlob.DeleteIfExists();
        }
    }
}

 

Azure BlobStorageHelper – Download file as byte array

Code beautifier: http://hilite.me/

Helper code: 

namespace Helpers
{
    public class BlobStorageHelper : StorageHelper
    {
        private readonly CloudBlobClient _blobClient;
        public string _containerName { get; set; }

        public BlobStorageHelper()
            : base()
        {
            _blobClient = base.StorageAccount.CreateCloudBlobClient();
            _containerName = ConfigurationManager.AppSettings["StorageContainerName"];
        }

        protected Stream DownloadBlobAsStream(string blobUri)
        {
            CloudStorageAccount account = this.StorageAccount;
            CloudBlockBlob blob = GetBlockBlobReference(account, blobUri);

            Stream mem = new MemoryStream();
            if (blob != null)
            {
                blob.DownloadToStream(mem);                
            }

            return mem;
        }

        private CloudBlockBlob GetBlockBlobReference(CloudStorageAccount account, string blobUri)
        {
            string blobName = blobUri.Substring(blobUri.IndexOf("/" + _containerName + "/")).Replace("/" + _containerName + "/", "");
            CloudBlobClient blobclient = account.CreateCloudBlobClient();
            CloudBlobContainer container = _blobClient.GetContainerReference(_containerName);
            container.CreateIfNotExists();
            CloudBlockBlob blob = container.GetBlockBlobReference(blobName);
            return blob;
        }


        public byte[] DownloadBlobAsByeArray(string blobUri)
        {
            Stream inputStream = DownloadBlobAsStream(blobUri);

            byte[] buffer = new byte[16 * 1024];

            inputStream.Position = 0; // Add this line to set the input stream position to 0

            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = inputStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

       
    }


    public abstract class StorageHelper
    {
        protected readonly CloudStorageAccount StorageAccount;

        public StorageHelper()
        {
            this.StorageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);
        }
    }
}