Thursday, March 15, 2018

How to Open Excel ( *.xls or *.xlsx) in Angular 4?

Problem

Angular is a platform to build SPA applications with web. If you want Angular application to access any files (like *.xls or *.xlsx) in a network share directly, the access will be blocked for security reasons. 

Solution 

Create A Web API Controller to return the file as StreamContent; Get the Blob using Angular http reponse.blob(); Create an object URL using createObjectURL(blob); Save the blob object to a file.


Details

1. Server - Controller Return Blob

var result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");

Here are more details: 

2. Angular Http - Get Blob

Include the RequestOptionsArgs when you send request.



Specify the field responseType : ResponseContentType inside RequestOptionsArgs to  ResponseContentType.Blob.

Here are more details: 

3  HTML - Save Blob to File


const a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.click();
window.URL.revokeObjectURL(a.href);

Here are more details: 

Friday, January 19, 2018

ReSharper Tips for .NET Developer


When I first started to use ReSharper with Visual Studio 2010, I was so impressed by its creativities and practicalities. My productivities have been boosted. My code quality has been improved. My code has become more consistent and readable. I have become a big fan of ReSharper and JetBrains. Since then ReSharper has become an indispensable tool under my toolbelt. Over the years, JetBrains added more products in its offering for .NET developers. In 2015/2016, ReSharper 10 has been bundled up with other popular .NET tools dotCover, dotTrace, dotMemory, and dotPeek and rebranded as ReSharper Ultimate. The license model changed from product to subscription.

A speaker at Houston TechFest once said that ReSharper would make developers’ mind dull because it is doing so much and the developers are losing his/her programming skills. The speaker’s argument came from that some developers can’t even write code without IDE (such as on whiteboard). I didn’t really agree with him but I can totally understand where the speaker’s concern came from. I think ReSharper is doing an amazing job to help developer write better code, easily examine, and refactor the existing code bases so that they will spend less time and produce better code.

ReSharper Tips

         Navigation:
                Ctrl + T. Then type. Or you can type also just the acronym in ALL capital letters, or  type / for more specific filters.
                It’s really easy to navigate to base symbol and derived symbol, ALT-Home or Alt-End.

-         Code Quality:
                It can detect unreachable code, unused variable, and much more.
                name conventions issues
                shorter code / more readable code, such as null propagator, string interpolation, expression bodied members
-      
           Refactoring.
                Extract to interface.
                Move to another file.
                Push members down.
                Make method non-static.

-          Unit testing is so much easier with ReSharper test sessions. You can customize what tests to be included in different test sessions.

-          ReSharper Build is cool too.  It has a visual interface to indicate which projects are going in parallel. Also, it is out of the process so your visual studio process should be slowed down.


-          Have you ever misspelled a word and got embarrassed in code review? There is one of the extension called ReSpeller. Resharper is an extension to Visual Studio. ReSpeller is an extension of Resharper. Check it out.


Saturday, July 22, 2017

Difference among .NET Mutable, Readonly, Immutable, and Freezable Collections

Mutable 
Mutable is the most common collection type in the .NET world. These are collections such as List; that allow reading, as well as adding, removing and changing items.

Read-Only
Read-Only These are collections that can't be modified from the outside. However, this notion of collections doesn't guarantee that its contents will never change. For example, a dictionary's keys and values collections can't be updated directly, but adding to the dictionary indirectly updates the keys and values collections. You can create your own read only collection by inheriting from ReadOnlyCollection.

Immutable
Immutable These are collections that, once created, are guaranteed to never be changed and thread-safe. If a complicated data structure is fully immutable, it can always be safely passed to a background worker. You don't need to worry about someone modifying it at the same time. This collection type is not provided by the Microsoft .NET Framework base class library (BCL) today. You can download from NuGet by searching for Microsoft.Immutable.Collections.

Freezable
Freezable These collections behave like mutable collections until they're frozen. Then they behave like immutable collections. Although the BCL doesn't define these collections, you can find them in Windows Presentation Foundation.

Wednesday, April 05, 2017

What’s New and Improved in Resharper 2017.1

If JetBrains is a sports team, I’d be a fan of it, just like I am a fan of Houston Rockets. JetBrains has so many good products, Resharper, dotMemory, dotCover, and dotTrace. Don’t forget TeamCity, it is really an awesome build tool.

I agreed to a saying at Houston TechFest 2016, from a great speaker Curtis Schlak, that Visual Studio and Resharper make the developer’s mind dull because the tools like Resharper do a lot and developers start to lose the skills to do it manually. Sadly that’s the side effect for using Resharper. Just like I won't be able to remember my best friend's phone number any more after my iPhone can remember the numbers for me. I guess there are always pros and cons. I  think I need to be aware of the side effects to use Reshaper. But I don’t think I’ll let Resharper go out of my developer’s life.



Way to go JetBrains Resharper. Here are the good stuff  in 2017.1. 
  • C# 7 support with new inspections and quick-fixes
  • Support for the Lightweight solution load mod
  • .NET Core unit testing support in Visual Studio 2017
  • Many code formatting improvements including support for EditorConfig
  • Filtering options in Find Results , Go to Everything , and Go to Text
  • Full support for TypeScript 2.1 and initial support for TypeScript 2.2
  • Initial support for Angular 2

Thursday, March 09, 2017

First impression on Visual Studio 2017

Visual studio 2/017 gets it right this time.
Even the icon looks cool.


VS 2017 Installation Screen Shot


Improved startup and improved project load. Lightweight solution loading, and many more enhancements come together to make Visual Studio 2017 start up to 3 times faster than Visual Studio 2015. Solution load times are 2-4 times shorter, and build performance is faster too.

Snappier XAML Editor. It  is snappier, a lot. It’s so much faster than 2015 – lighting faster. This is because Visual Studio 2017 leverages the XAML Language Service’s knowledge of the XAML file to determine the names and types of the fields to populate IntelliSense, and then update the g.i.* file using Roslyn on a background thread.

dotted lines for XAML
Dot Lines are awesome in the C# editor and XAML editor.



















Tuesday, October 25, 2016

Launch Prepopulated New Email Message in WPF/WinForm

This article discussed three options to launch prepopulated New Email Window from your WPF/WinForm desktop application. The prepopulated fields can include From, To, Subject, Content, and Attachments etc.

 

Option 1: MailTo URL

Pros: MailTo protocol is the easiest and the cleanest way to launch the New Mail Message window. All you need to do is to create the URL and launch it using in a separated process.

        var url = @"mailto:user@example.com?subject=Message Title&body=Message Content";
        System.Diagnostics.Process.Start(url);

Cons: There is no official way to attach files using "mailto" protocol, likely because of the security reasons. It’s not support HTML content. More information can be found in MSDN.

 

Option 2: EML File

Pros: Save System.Net.Mail.MailMessage to a .EML file and open the .EML file with default mail application. It supports attachment. It supports HTML content.

        var mailMessage = new MailMessage();
        mailMessage.From = new MailAddress("someone@yourdomain.com");
        mailMessage.Subject = "Your subject here";
        mailMessage.IsBodyHtml = true;
        mailMessage.Body = "<span style='font-size: 12pt; color: red;'>My HTML formatted body</span>";
        mailMessage.Attachments.Add(new Attachment("C://Myfile.pdf"));
        var filename = "C://Temp/mymessage.eml";
        mailMessage.Save(filename);
        Process.Start(filename);

        public static void Save(this MailMessage message, string filename, bool addUnsentHeader = true)
        {
            using (var filestream = File.Open(filename, FileMode.Create))
            {
                if (addUnsentHeader)
                {
                    var binaryWriter = new BinaryWriter(filestream);
                    binaryWriter.Write(System.Text.Encoding.UTF8.GetBytes("X-Unsent: 1" + Environment.NewLine));
                }

                var assembly = typeof(SmtpClient).Assembly;
                var mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");

                var mailWriterContructor = mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);

                var mailWriter = mailWriterContructor.Invoke(new object[] { filestream });
                var sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);

                sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { mailWriter, true, true }, null);

                var closeMethod = mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic);

                closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);
            }
        }

 

Cons: Some email servers can’t send out email because of security settings for From: and Sender:. You will probably get exceptions like this.

“You can't send a message on behalf of this user unless you have permission to do so. Please make sure you're sending on behalf of the correct sender, or request the necessary permission. If the problem continues, please contact your helpdesk.”

 

Option 3: Microsoft.Office.Interop.Outlook

Pros: A feasible option is to utilize Microsoft.Office.Interop.Outlook. I’ve tested different versions for Microsoft.Office.Interop.Outlook, for example 12.0.4518.1014 and 15.0.4797.1003, using the nugget packages. They all work either Office 2010 (14.0.x) or Office 365 (16.0.x). It looks like the COM API hasn’t changed from 14.0 to 16.0 to create new mail item.

With the reference property set to Embed Interop Types, the compiler will include the COM calls directly into Atlas assembly. Therefore, we don’t have to ship a specific version of a Microsoft Office Interop assembly with our product. Exceptions can be caught if any.

            
     var outlookType = Type.GetTypeFromProgID("Outlook.Application");
            if (outlookType == null)
            {
                throw new System.Exception("Microsoft Office Outlook is not installed.");
            }
            
            var oApp = new Application();
            var oMsg = (MailItem) oApp.CreateItem(OlItemType.olMailItem);
            oMsg.To = "someone@yourdomain.com";
            oMsg.Subject = subject;
            oMsg.BodyFormat = OlBodyFormat.olFormatHTML;
            oMsg.HTMLBody = ""; 
            oMsg.Attachments.Add(fullPath, OlAttachmentType.olByValue, Type.Missing, Type.Missing);
            oMsg.Display(false); 

 

Cons: It only works for Outlook.

Friday, May 06, 2016

C# Switch on Type

I want to write readable code like below to handle different sub types. Let’s say if I want to take a shower for my pets. Depending on the pet type, I will like to handle it differently. As you can tell, if statements can do the work but it will be very messy. I would like to use switch statement. However, C# compiler doesn’t want to get into this business. That’s alright. I will like to do it myself. Here is a clean solution. The ultmiate code is very easy to read. No if statements. Zero. None. Nil. There are 3 simple steps.

myPet.Switch()
     .Case<Dog>(x => HandleDog(x))
     .Case<Cat>(x => HandleCat(x))
     .Case<Parrot>(x => HandleParrot(x))
     .Default<Pet>(x => HandleDefault(x));

Step 1: Create a Switch class.

public class Switch
{
    public Switch(object o)
    {
        Target = o;
    }

    public object Target { get; set; }
}

 

Step 2: Create extension methods to support fluent API, supporting, predict, fall through, and default.

public static class SwitchExtensions
{
    public static Switch Case<T>(this Switch switcher, 
        Action<T> action) where T : class
    {
        return Case(switcher, o => true, action, false);
    }

    public static Switch Case<T>(this Switch switcher, 
        Action<T> action, 
        bool fallThrough) where T : class
    {
        return Case(switcher, o => true, action, fallThrough);
    }

    public static Switch Case<T>(this Switch switcher, 
        Func<T, bool> predicate, 
        Action<T> action) where T : class
    {
        return Case(switcher, predicate, action, false);
    }

    public static Switch Case<T>(this Switch s, 
        Func<T, bool> predicate, 
        Action<T> action, 
        bool fallThrough) where T : class
    {
        if (s == null)
        {
            return null;
        }

        var t = s.Target as T;
        if (t == null)
        {
            return s;
        }

        if (!predicate(t))
        {
            return s;
        }

        action(t);
        return fallThrough ? s : null;
    }

    public static void Default<T>(this Switch switcher, 
        Action<T> action) where T : class
    {
        if (switcher == null)
        {
            return;
        }

        var t = switcher.Target as T;
        if (t == null)
        {
            return;
        }

        action(t);
    }
}
Step 3: Finally, add an extension method for System.Object so that any object can call Switch() method.
public static class ObjectSwitchExtensions
{
    public static Switch Switch(this object Object)
    {
        return new Switch(Object);
    }
}

Is High Quality Software Worth the Cost?

I can't agree more with Martin Fowler's post on "Is High Quality Software Worth the Cost?". Here is just a repost. https:/...