How to get an Enum value from a string

Lets say you have an enum like this


public enum Colors 
{
Red=1,
Blue=2,
Green=3
}

And you need to get the enum value of ‘Colors.Red’, but you only have the string “red”.

I wrote this function to return the proper enum value and it doesn’t care if you pass in “red” or “RED” or “rEd” because it is case insensitive.


 private T GetEnumValue(string caseInsensitiveStringVal)
        { 
            var properName = Enum.GetNames(typeof(T)).SingleOrDefault(x => x.ToString().Equals(caseInsensitiveStringVal, StringComparison.OrdinalIgnoreCase));
            //get value from properName
            if (properName != null)
            {
                return (T)Enum.Parse(typeof(T), properName);
            }
            throw new InvalidDataException("Invalid value."); 
        }


...

//Now call it like this
Colors myColor = GetEnumValue("rEd");

How to upload a file to ASP.Net Web API

Here is s simple function that takes a file upload and there can be other fields in the body that it will read.


        [HttpPost, Route("api/Action/UploadAFile")] 
        public async Task UploadAFile()
        {
            const string StoragePath = @"C:\Temp"; //pull from config file

            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            } 
            var provider = new MultipartFormDataStreamProvider(StoragePath);

            try
            {
                await Request.Content.ReadAsMultipartAsync(provider); //saves it

                //now we want to rename it back to the name it had originally because the upload gives a  strange name of 'BodyPart_[Guid]'
                foreach (MultipartFileData fileData in provider.FileData)
                {
                    if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
                    {
                        return BadRequest();
                    }
                    string fileName = fileData.Headers.ContentDisposition.FileName;
                    if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
                    {
                        fileName = fileName.Trim('"');
                    }
                    if (fileName.Contains(@"/") || fileName.Contains(@"\"))
                    {
                        fileName = Path.GetFileName(fileName);
                    }

                    string newFileName = Path.Combine(StoragePath, fileName);

                    if (!File.Exists(newFileName))
                    {
                        File.Move(fileData.LocalFileName, newFileName);
                        //File.Move uses the Win32Native.MoveFile function, which does a rename on the file system
                    }
                    else
                    {
                        // a file by that name already exists, so delete the one that was just uploaded, and return an error message that fits 
                        // your standards
                        try
                        {
                            File.Delete(fileData.LocalFileName);
                        }
                        catch (Exception ex)
                        { 
                            //should log that the file delete for fileData.LocalFileName failed, so that someone could verify 
                            // it should have been deleted and they can feel ok about cleaning up this file later.
                            // Don't rethrow this error.
                        }

                        return BadRequest("File already exists.");
                    }


                }

                // Show all the key-value pairs.
                foreach (var key in provider.FormData.AllKeys)
                {
                    foreach (var val in provider.FormData.GetValues(key))
                    {
                        Trace.WriteLine(string.Format("{0}: {1}", key, val));
                        
                    }
                } 
                return Ok();
            }
            catch (System.Exception e)
            {
                return BadRequest();
            }
        }

Initializing Automapper

I struggled for while with getting Automapper to register the Profiles of my sub layers (Service layer for instance), when it is setup in the App start process. I found this on StackOverflow and it was the correct answer. Saving here so I can find easily next time.

Additionally. It was not necessary to override the ProfileNames. All profiles in all layers can have the same class name as far as I can tell. No issues in my case.

Original ref: https://stackoverflow.com/questions/38555702/how-to-initialize-automapper-profiles-in-referenced-project-dlls-in-asp-net-weba/38572088#38572088

 

 var assembliesToScan = AppDomain.CurrentDomain.GetAssemblies();
        var allTypes = assembliesToScan.SelectMany(a => a.ExportedTypes).ToArray();

        var profiles =
            allTypes
                .Where(t => typeof(Profile).GetTypeInfo().IsAssignableFrom(t.GetTypeInfo()))
                .Where(t => !t.GetTypeInfo().IsAbstract);

        Mapper.Initialize(cfg =>
        {
            foreach (var profile in profiles)
            {
                cfg.AddProfile(profile);
            }
        });

Debugging Angular Typescript files

Type script is converted into Javascript at runtime. It would be nice to be able to set break points on your TypeScript in Chrome when debugging. This can be done easily.

In the Developer tools, Source tab, there are a list of Sources.
Expand the ‘webpack://’ source
Expand the ‘.’ folder
Expand the ‘src’ folder
Find your ts file that you want to set a break point in, and you are done.

Another option.. Angular Augury

Google Angular Augury.
Install it.
It is a Chrome Extension.
Now Augury should show up in your Developer tools (in your tabs with ‘Sources’).
Using Augury, you can watch what is going on with your Angular as your pages run.