Monthly Archives: January 2020

Download file from Azure storage using Javascript

.Net is an excellent framework – if you want proof of that, try to do, even very simple things, in Javascript. It feels a bit like getting out of a Tesla and travelling back in time to drive a Robin Reliant (I’ve never actually driven either of these cars, so I don’t really know if it feels like that or not!)

If you were to, for example, want to download a file from a Blob Storage container, in .Net you’re looking at about 4 lines of strongly typed code. There’s basically nothing to do, and it consistently works. If you want to do that in Javascript, there’s a Microsoft Javascript Library.

In said library, there is a function that should get a download URL for you; it’s named getUrl:

const downloadLink = blobService.getUrl(containerName, fileId, sasKey);            

If you use this (at least, when I used this), it gave me the following error:

Signature did not match

To get around this, you can build the download link manually like this:

const downloadLink = blobUri + '/' + containerName + '/' + fileId + sasKey;

Comparing the two, the former appears to escape the question mark in the SAS.

To actually download the file, you can use this:

        // https://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery
        function downloadURI(uri, name) 
        {
            var link = document.createElement("a");
            link.download = name;
            link.href = uri;
            link.click();
        }

And the final download function looks like this:

        function downloadFile(sas, storageUri,
            containerName, fileId, destinationFileName) {

            var blobService = AzureStorage.Blob.createBlobServiceWithSas(storageUri, sas);
            
            const downloadLink = storageUri +'/' + containerName + '/' + fileId + sas;

            downloadURI(downloadLink, destinationFileName);
        }

An ADR Visual Studio Tool – Part 4 – Dependency Injection

Continuing with my little series on creating a visual studio extension, in this post, I’ll talk about how to add dependency injection to your project.

If you’d like to see the whole solution for this, it can be found here.

Unity

In this post on Azure Functions, I talked about using Unity as an IoC container, in a place where an IoC container might not necessarily fit; whilst this is no longer true for Azure functions, it does appear to be for extensions – I presume because they don’t expect you to have one big enough to warrant IoC; also, even with DI, testing is very difficult, because most of what you’re doing, you’re doing to Visual Studio.

Let’s start by installing Unity in our project:

Install-Package Unity

Rules Analyser

In our case, we were analysing the project and extracting files; however, we were extracting all files; as a result, a check needed to be made to extract only markdown files. Consequently, I created a RulesAnalyser class:

    public class RulesAnalyser : IRulesAnalyser
    {
        public bool IsProjectItemNameValid(string projectItemName) =>
            projectItemName.EndsWith("md");        
    }

We could (and I did initially) instantiate that directly in the ViewModel, but that feels quite dirty.

AdrPackage

The *Package file for the extension seems to be the entry point, so we can add the unity container to here:

    public sealed class AdrPackage : AsyncPackage
    {        
        public static Lazy<IUnityContainer> UnityContainer =
         new Lazy<IUnityContainer>(() =>
         {
             IUnityContainer container = InitialiseUnityContainer();
             return container;
         });

        private static IUnityContainer InitialiseUnityContainer()
        {
            UnityContainer container = new UnityContainer();
            container.RegisterType<IRulesAnalyser, RulesAnalyser>();
            container.RegisterType<ISolutionAnalyser, SolutionAnalyser>();
            return container;
        }

        . . .

View Model

The next thing we need to do is to inject our dependencies.

        public AdrControlViewModel() 
            : this(AdrPackage.UnityContainer.Value.Resolve<IRulesAnalyser>(),
                  AdrPackage.UnityContainer.Value.Resolve<ISolutionAnalyser>())
        {}

        public AdrControlViewModel(IRulesAnalyser rulesAnalyser, ISolutionAnalyser solutionAnalyser)
        {            
            _rulesAnalyser = rulesAnalyser;
            _solutionAnalyser = solutionAnalyser;

            Scan = new RelayCommandAsync<object>(ScanCommand);
        }

And that’s it, we now have a working DI model in our project.

References

https://stackoverflow.com/questions/2875429/iunitycontainer-resolvet-throws-error-claiming-it-cannot-be-used-with-type-par

https://www.pmichaels.net/2018/02/04/using-unity-azure-functions/

I wrote a book – here’s what I learned

I’ve recently had a book published; if you’re interested in seeing what it is, you can find it here.

This post is simply a summary of things that I wished I’d known before I started writing. As a quick disclaimer, please don’t treat this article as legal or financial advice. It’s simply a list of things that I, personally, have encountered; if you’re in a similar situation, I would encourage you to seek advice in the same way that I have, but hopefully this article will give you a starting point.

I’ll also mention that I’m in the UK, so some of the points here may be specific to location (certainly the figures that I’m giving are in sterling, and rough approximations).

Choosing a Topic

Did I mention this was all subjective?

In my case, the topic was chosen for me; however, I would suggest that, where you have a choice, you pick something that isn’t time sensitive.

Let me try to illustrate what I mean: when I started writing the above book, .Net Core 3 was available only in preview, so I’d write a chapter, test the software, and then Microsoft would release a breaking change! I can’t describe in words how frustrating that is – you spend, maybe two or three weeks preparing and writing a chapter, and then you have to re-write it, almost from scratch!

Further, .Net Core 3 had a release date: obviously, once it’s released, there’s a sweet spot, where people want to read about the new tech – I can’t help but think that the new release cadence by Microsoft, whilst helpful for those using the tech, is just too fast for anyone to write any kind of lasting documentation.

Finally, think of the books that you remember in the industry: Domain Driven Design,
Design patterns : elements of reusable object-oriented software
,
Test Driven Development: By Example
; these are all books that are not technology specific – The GOF book was released in 1994, but it’s still relevant today!

Legal

Most of this section will discuss contracts.

The Contract Itself

You may want to consult a solicitor to get professional advice on this. When I asked around, I was quoted around £200 – £300 for a solicitor to review the contract and offer me advice. However, there is another option: The Society of Authors offers contract reviews as part of the membership fee (which was around £100 at the time of writing).

Insurance

If you get a book contract, the contract itself will say that you, personally, are liable for anything: if they get sued, you’re liable. There’s essentially three approaches to address this:

1. Professional Indemnity Insurance

This is a private insurance policy that you take out, against being sued. It is not cheap, and you should account for this expense when you decide to embark on writing a book. My impression is that you are very unlikely to actually be sued: the book itself will have a disclaimer against any accidental damage; plus, providing you don’t simply copy and paste blog posts and put them in your book without attribution (that is, your work must be original, or have the permission of the author to replicate it), you’re unlikely to fall foul of any copywrite issues.

2. A Limited Company

I’ve done a lot of research into this and, to be honest, I’m still not completely sure about it. A limited company has limited liability, so if you were to be sued, providing that you signed the contract on behalf of the company, you, personally, should be safe. I have, however, seen (and received) advice saying that the director of the limited company may bear some personal liability for any losses to the company.

Additionally, setting up a limited company is not a cheap option: although setting up the company itself only costs ~£10 (in the UK), you must submit company accounts – you can actually go to prison if you get that wrong – so you may end up forking out for an accountant (budget between £500 – £1000 / year for that!)

3. Do Nothing

I strongly suspect this is what most people do. Technically it does leave you personally liable.

Financial

Once you get offered a book contract, you will be given an advance. In addition, you will be entitled to royalties of any book sales. Here’s how that works:

Imagine your advance is £1000, and you get 10% from book sales. Let’s say the book is consistently £50 retail.

After the first 200 books have sold, your royalties will reach your advance – meaning that you will start to receive some money per sale.

If the book sells 150 copies, then you still receive the advance, but no further money.

Remember as well that any money that you earn needs to be declared to HMRC – so you’ll need to request a self-assessment.

Employment

If you have a full time job, it’s worth bearing in mind that writing and publishing a book is probably in breach of your contract; consequently, you’ll have to speak to your employer before you sign any contract.

Editing

My process for editing my blog posts (and any fiction that I write – some of which can be seen here) is that I write them in One Note, or Word, and then I transfer them to the WordPress site, come back in about an hour and read the preview – if it looks good to me, then it goes out.

The editing process I encountered with a publisher was, obviously, different. There seems to be a formula to the layout that they require. For example, if you have a series of actions, they like them to be in numbered steps. I assume to a greater or lesser extent, every publisher does essentially the same thing.

It’s also worth bearing in mind that the editing process might change some of your text without your consent – you need to be aware this is a possibility. It’s also a very likely possibility that, some months after you’ve finished on a chapter, you’ll be asked to revisit it. On occasion, I found myself following my own chapter to try and remember some of the material – which I suppose is a good thing: like when you go searching for something on the internet, and you come across your own post!

Promotion

One way or another, you’re going to have to take an interest in promoting your work. If you’re a fiction writer, that means book signings, etc. However, if you publish a tech book, that means talks, podcasts, and blog posts (such as this)! While I have done a flash talk on (essentially this blog post), I would probably advise against giving a talk on “My Book”, rather, pick a subject, and simply mention that you have also written a book (if the subject you chose is in the book then that’s probably better, but not essential!)

Summary

If you do decide to embark on writing a book, it is hugely rewarding, you learn a lot of things, and make new contacts. However, be prepared for some late nights and lost weekends. Also, don’t be under the impression that you can make any money out of this: you’re very likely to be out of pocket by the time you finish.

An ADR Visual Studio Tool – Part 3 – Listing and Reading the files

In this post, I refactored a VS Extension Plug-in, that I originally started here.

We’ll get the plug-in to list the items found in the projects, and read the contents of the files. The source code for this can be found here. I won’t be listing all the source code in this article (most of it is just simple WPF and View Model binding).

To look through all the projects and folders in the solution, we’ll need to recursively scan all the files, and then read them; let’s have a look at what such a method might look like:

        private async Task ScanProjectItems(ProjectItems projectItems, ProjectData projectData)
        {
            await Microsoft.VisualStudio.Shell.ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            foreach (EnvDTE.ProjectItem pi in projectItems)
            {
                if (pi.IsKind(ProjectItemTypes.SOLUTION_FOLDER, 
                              ProjectItemTypes.PROJECT_FOLDER,
                              ProjectItemTypes.SOLUTION_ITEM)
                    && pi.ProjectItems != null)
                {                    
                    await ScanProjectItems(pi.ProjectItems, projectData);
                    return;
                }

                string text = await GetDocumentText(pi);
                if (string.IsNullOrWhiteSpace(text)) continue;

                projectData.Items.Add(new Models.ProjectItem()
                {
                    Name = pi.Name,
                    Data = text
                });
            }
        }

I wanted to look specifically into two aspects of this method: IsKind() and GetDocumentText(). None of the rest of this is particularly exciting.

Kind of File

In a VS Extension, you can read ProjectItems – they represent pretty much anything in the solution, and so it’s necessary to be able to find out exactly what the type is. As you can see above, I have an extension method, which was taken from here. Let’s have a quick look at the file that defines the ProjectItemTypes:

    public static class ProjectItemTypes
    {
        public const string MISC = "{66A2671D-8FB5-11D2-AA7E-00C04F688DDE}";
        public const string SOLUTION_FOLDER = "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}";
        public const string SOLUTION_ITEM = "{66A26722-8FB5-11D2-AA7E-00C04F688DDE}";                                            
        public const string PROJECT_FOLDER = "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}";        
    }

I’m sure there’s a better way, but after I realised what Mads was doing in the above linked project, I just stuck a breakpoint in the code, and copied the “Kind” guid from there! The IsKind method is taken from the same codebase:

        public static bool IsKind(this ProjectItem projectItem, params string[] kindGuids)
        {
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();

            foreach (var guid in kindGuids)
            {
                if (projectItem.Kind.Equals(guid, StringComparison.OrdinalIgnoreCase))
                    return true;
            }

            return false;
        }

As you can see, it’s almost not worth mentioning – except that the extensions are very particular about running in the UI thread, so you’ll find ThrowIfNotOnUIThread scattered around your code like confetti!

Reading File Contents

If you need to access the file contents in an extension, one way is to convert the project item document to a TextDocument, and then use Edit Points:

        public static async Task<string> GetDocumentText(this ProjectItem projectItem)
        {
            if (projectItem == null) return string.Empty;
            await Microsoft.VisualStudio.Shell.ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            try
            {
                TextDocument textDocument;
                if (!projectItem.IsOpen)
                {
                    var doc = projectItem.Open(EnvDTE.Constants.vsViewKindCode);
                    textDocument = (TextDocument)doc.Document.Object("TextDocument");
                }
                else
                {
                    textDocument = (TextDocument)projectItem.Document.Object("TextDocument");
                }
                EditPoint editPoint = textDocument.StartPoint.CreateEditPoint();
                return editPoint.GetText(textDocument.EndPoint);
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

Edit Point are much more powerful that this, they allow you to change the text in a document; for example, imagine your extension needed to change every local pascal cased variable into one with an underscore (myVariable to _myVariable), you may choose to use edit points there.

References

https://www.csharpcodi.com/csharp-examples/EnvDTE.Document.Object(string)/

https://github.com/madskristensen/MarkdownEditor/