Showing posts with label storage. Show all posts
Showing posts with label storage. Show all posts

A static website and some little tricks with Azure Functions Proxies

(Updated 2018-02-08)

Recently, I did few presentations about Azure functions. The reaction was always very positive and attendees leave with tons of ideas of projects in their heads. In this post, I would like to add few interesting features that I didn't have the time to talk about.

You prefer to watch a video instead of reading? No problem, skip at the end at the Explain in a Video of this post immediately.

Let's get started


From the Azure Portal (portal.azure.com) select an Azure Function domain, or create a new one. Then we need to create a Function App that we will be use as our backend. Click on the "+" sign at the side of Function. In this post, we will be using the HttpTrigger-CSharp template, but other template will work too. Once you select the template you will be able to enter the name and select the Authorization level. This last choice will affect how your function could be accessed. For exemple, if you select Anonymous then you function will be accessible to everyone directly using the url: https://notesfunctions.azurewebsites.net/api/SecretFunction, where 'notesfunctions' is my function domain name. But if you select Function or Admin level, then you will need to pass a Function Key or Master Key (ex: https://notesfunctions.azurewebsites.net/api/SecretFunction?code=I4BN6NjaZBmPNqebqnX8pQAPZwe1TI/O4TCbvB1aaaaao7uRO5yyw==). For this post let's use the Function level. When ready click the Create button.

CreateFunction

Using Postman, your favorite HTTP tool, or even the function Test section (located on the right side of the editor in the Function blade), you can now test your Function. To be able to test our function, we need to know the URL. To get the URL of your functions, once you function is selected (when you see the code), click on </> Get function URL on the top of the screen.

TestSecretDirect

Note that the querystring as a parameter named code that is receiving our function key. When this parameter is not present, you will receive an HTTP 401 Unauthorized message. The function generated by the template also expects a value 'Name' that could be passed by the querystring or by a json file with a property Name in the http request body.

Azure Functions Proxies


Functions Proxies are currently in preview. With them, any function app can now define an endpoint that serves as a reverse proxy to another [API / webhook / function App / anything else].
Before being able to create new Azure Functions Proxies, you need to enable them. From the Function blade, select the Settings tab on the top of the screen, then click the On button, under the Proxie section.

EnableProxies

Now let's create our first Function Proxy. Click on the "+" on the right of Proxies (Preview). Enter the following values.

ProxySalutation

In the Backend URL note as %Host_Name% is used in the URL; this is NOT an environment variable. In fact surrounding a key with % is a very useful tool from the Azure Function that gives us the ability to read directly in the Application settings.

PlatformFeatures

To get to the Application settings, select the Function Application domain (the root node), then the tab Platform features from the top of the screen. In the image above, Point A shows on to access the Application settings, and Point B shows how to access the App Service Editor that will use later in this post.

If it's not already done, add a new key-value in Application setting: Host_Name with his value. Then from Postman, call this new proxy function. Note that now you don't need to pass the key since this part is done under the hood by the proxy.

TestSalutation

Do more with your Proxies


Okay, now that we have a proxy up and running, let's switch to the App Service Editor to do more "advanced" stuff (the Editor is available throuth the Platform features tab). Once you are in the editor select the file proxies.json to open it.

editor

As you can see we only have one proxy defined. Let's duplicate our proxy. Rename the copy "Override", and change the route value for override too. If you test this new proxy, it will work just as the other one. Let's change that a little, under the property backendUri add a new node called: responseOverrides. It is possible with proxies to edit the HTTP properties. To change the Content-Type to text instead of json add "response.headers.Content-Type": "text/plain" inside our new node responseOverrides (be aware, it's case sensitive). Test again Override and you will constate that the content indeed has changed.

Continuing that way you count use Azure Function Proxies as mock. For example, replace the backendUri property and override the response body to return a fix value, and voila! You built yourself a great mock-up! This is very useful! To illustrate this, add a new proxy using this code:
"Fake": {
    "matchCondition": {
        "route": "fake"
    },
    "responseOverrides": {
        "response.headers.Content-Type": "text/plain",
        "response.body": "Hello from Azure"
    }
}
If you call this last proxy, no backend will be called, but the HTTP call is working.

Static WebSite


Everybody knows that Azure storage is very inexpensive. Would it be wonderful if we could put a static website in that storage? Of course, you can do it, I mean as long as the URL was complete. However, who type the URL completely with the file and file extention (ex: http://www.frankysnotes.com/index.html)? Well now with Azure Function Proxy, we could fix that! Add another proxy to the proxies.json file using this code:
"StaticNotes": {
    "matchCondition": {
        "methods": [
            "GET"
        ],
        "route": "/"
    },
    "backendUri": "https://%blob_url%/dev/index.html"
}
This new proxy will "redirect" all root HTTP GET calls to our index.html file waiting in our Azure Blob storage. For a more professional look, you just need to add a custom domain name to your Function, and you got the perfect super-light low-cost website for your promotion campaign, or event.

static


Explain in a Video





References:

  • Postman : getpostman.com
  • App Service Editor: https://{function domain name}.scm.azurewebsites.net (ex: https://notesfunctions.scm.azurewebsites.net)



Reading Notes #270

canada-mapSuggestion of the week


Cloud


Databases


Miscellaneous



Reading Notes #265

msdevMtljan31Suggestion of the week


Cloud


Programming


Databases


Miscellaneous



Reading Notes #263

IMG_20170113_162910Cloud


Programming


Databases



Reading Notes #259

three-amigos-mainCloud


Programming




Reading Notes #246

IMG_20160826_115405Cloud


Programming


Databases


Miscellaneous


Reading Notes #236


WhyAzureCLISuggestion of the week


Cloud


Programming


Miscellaneous

  • Happiness is DevOps’ Cornerstone (Alexandre Brisebois) - Interesting post that asks a lot of questions... I would like to see some graph or pie chart about our answers.
  • 5 Habits that Help Code Quality (View all posts by Erik Dietrich) - Yet another post about how to code better, but this one is refreshing. It explains why the opposite would be harmful and also give us a training plan for better chance of success.
  • What’s in your highlights folder? (Marc Gagne) - Because life is not only mistakes and bad luck.Here good tips to help you giving some sunshine into your life when needed.

Reading Notes #233

mprofileCloud


Programming


Miscellaneous



Reading Notes #232

Microsoft-Canadian-Cloud, from Lixar blobSuggestion of the week


Cloud



Reading Notes #230

15288837503_ba2b786d93_zSuggestion of the week

  • Data Locality - Great troubleshooting session explained, definitely a post to read.

Cloud


Programming


Photo credit: Claus Tom via Foter.com / CC BY-NC-ND


Reading Notes #223

P1020050Cloud


Databases


Programming


Miscellaneous



Reading Notes #222

hourglassSuggestion of the week


Cloud


Data



Reading Notes #221

logo_JavaScriptSuggestion of the week

  • Why You Should Learn JavaScript in 2016 (Ken Powers) - I eared a lot of people complaining about Javascript, this excellent post explains why you undeniably, we should all know it, an if it's not the case why 2016 is a great time to learn it.

Cloud


Programming


Data

  • Power BI Service February Update (Amanda Cofsky) - Fantastic! This update will give us the possibility to share outside ou organization... And many other things.

Miscellaneous


~Frank


Reading Notes #218

GuyAndErikSuggestion of the week


Cloud


Programming


Data



Reading Notes #217

yoman_asciiSuggestion of the week


Cloud


Programming


Miscellaneous



Reading Notes #198

P1020009Cloud


Podcast

  • .NET Rocks! - Great episode very interesting discussion about the new Azure Service Fabric.

Programming


Databases



Reading notes #183

IMG_20150425_120539[1]Suggestion of the week


Cloud


Programming


Databases


Miscellaneous



Reading Notes #172

HomeSuggestion of the week


Cloud


Miscellaneous


~Frank B.


Reading Notes #165

 

OmnisharpSuggestion of the week

 

Cloud

Programming

Integration

  • Azure BizTalk Services: An Introduction - This is the second post of a series on BizTalk. We are still in an introduction mode, but this is good, BizTalk is not a little application or system, and in this time of the Internet of things, it's good to have the good tools.
~ Frank B

Upgrade an Application Windows Azure OS Family

Recently I add to upgrade an web site running in Azure Webrole from Azure OS famille 1.6 to a more recent version. While the migration was not complicated I encounter some little particularity that I found could be interesting to share.

The Context

The website was a Visual Studio 2010 project using Azure SDK 1.6 and a library call AspNetProvider that was part of Microsoft's sample few years ago to manage session and membership. Using the AspNetProvider library the session was saved in Azure blob storage, and the membership was saved in an SQL database.

The Goal

The application must stay a Visual Studio 2010 project, but using the most-recent Azure SDK and Azure Storage Client as possible.

The Solution

  • Azure SDK 2.1
  • Azure.StorageClient 4.0
  • Universal Provider version 2.1
  • OS famille 4

The Journey


Migration from SDK 1.6 to SDK 2.1


Azure SDK version 2.1 is the higher version compatible with Visual Studio 2010. And can be downloaded from Microsoft's website. Once it is installed, just open the project in Visual Studio and right-click on the Azure Project. By clicking on the upgrade button the magic will happen. Some errors could stay but the hard work will be done for you.


Migration from AspNetProvider to UniversalProvider


we need to remove all reference to the AspNetProvider library. Just expand the resources node in the Solution Explorer and delete the reference. One thing important is that since we are using Visual Studio 2010 the latest version of the UniversalProvider we can use is 1.2. More recent version are using .Net 4.5 and this is not compatible with the present solution. To get the reference added to the project just execute the following Nugget command:
Install-Package UniversalProvider -version 1.2

Check the web.config file to clean the membership connections.

Migration of the Azure Storage Client


This one is the easiest, just remove the reference in the reference node and then execute the following Nugget Command:
Install-Package Azure.Storage.Client

Migration of the membership data


The AspNetProvider was using prefixed SQL tables: aspnet_user, aspnet_membership, etc. The new membership manager is using another sets of tables. We must migrate the data from one set to the other one. Here a SQL script that will to exactly that. The script can be run multiple times because it will only copie the unmoved data.
-- ========================================================
-- Description:    Migrate data from asp_* tables 
--                 to the new table used by Universal provider
-- ========================================================

DECLARE @CNT_NewTable AS INT
DECLARE @CNT_OldTable AS INT

-- --------------------------------------------------------
-- Applications -------------------------------------------

INSERT INTO dbo.Applications (ApplicationName, ApplicationId, Description)
    SELECT    n.ApplicationName, n.ApplicationId, n.Description 
    FROM    dbo.aspnet_Applications o 
    LEFT    JOIN dbo.Applications n ON o.ApplicationId = n.ApplicationId
    WHERE    n.ApplicationId IS NULL

SELECT @CNT_NewTable = Count(1) from dbo.Applications 
SELECT @CNT_OldTable = Count(1) from aspnet_Applications

PRINT 'Application Count: ' + CAST(@CNT_NewTable AS VARCHAR) + ' = ' + CAST(@CNT_OldTable AS VARCHAR)

-- -------------------------------------------------------- 
-- Roles --------------------------------------------------

INSERT INTO dbo.Roles (ApplicationId, RoleId, RoleName, Description)
SELECT    o.ApplicationId, o.RoleId, o.RoleName, o.Description 
FROM    dbo.aspnet_Roles o
LEFT JOIN dbo.Roles n ON o.RoleId = n.RoleId
WHERE n.RoleId IS NULL

SELECT @CNT_NewTable = Count(1) from dbo.Roles 
SELECT @CNT_OldTable = Count(1) from aspnet_Roles

PRINT 'Roles Count : ' + CAST(@CNT_NewTable AS VARCHAR) + ' = ' + CAST(@CNT_OldTable AS VARCHAR)

-- --------------------------------------------------------
-- Users --------------------------------------------------

INSERT INTO dbo.Users (ApplicationId, UserId, UserName, IsAnonymous, LastActivityDate)
SELECT o.ApplicationId, o.UserId, o.UserName, o.IsAnonymous, o.LastActivityDate 
FROM dbo.aspnet_Users o LEFT JOIN dbo.Users n ON o.UserId = n.UserID 
WHERE n.UserID IS NULL

SELECT @CNT_NewTable = Count(1) from dbo.Users 
SELECT @CNT_OldTable = Count(1) from aspnet_Users

PRINT 'Users count: ' + CAST(@CNT_NewTable AS VARCHAR) + ' >= ' + CAST(@CNT_OldTable AS VARCHAR)

-- --------------------------------------------------------
-- Memberships --------------------------------------------

INSERT INTO dbo.Memberships (ApplicationId, UserId, Password, 
PasswordFormat, PasswordSalt, Email, PasswordQuestion, PasswordAnswer, 
IsApproved, IsLockedOut, CreateDate, LastLoginDate, LastPasswordChangedDate, 
LastLockoutDate, FailedPasswordAttemptCount, 
FailedPasswordAttemptWindowStart, FailedPasswordAnswerAttemptCount, 
FailedPasswordAnswerAttemptWindowsStart, Comment) 

SELECT o.ApplicationId, o.UserId, o.Password, 
o.PasswordFormat, o.PasswordSalt, o.Email, o.PasswordQuestion, o.PasswordAnswer, 
o.IsApproved, o.IsLockedOut, o.CreateDate, o.LastLoginDate, o.LastPasswordChangedDate, 
o.LastLockoutDate, o.FailedPasswordAttemptCount, 
o.FailedPasswordAttemptWindowStart, o.FailedPasswordAnswerAttemptCount, 
o.FailedPasswordAnswerAttemptWindowStart, o.Comment 
FROM dbo.aspnet_Membership o
LEFT JOIN Memberships n ON  o.ApplicationId = n.ApplicationId
                      AND o.UserId = n.UserId
WHERE n.UserId IS NULL AND n.ApplicationId IS NULL


SELECT @CNT_NewTable = Count(1) from dbo.Memberships 
SELECT @CNT_OldTable = Count(1) from aspnet_Membership

PRINT 'Memberships count: ' + CAST(@CNT_NewTable AS VARCHAR) + ' >= ' + CAST(@CNT_OldTable AS VARCHAR)

-- -------------------------------------------------------
-- UsersInRoles ------------------------------------------
TRUNCATE TABLE dbo.UsersInRoles
INSERT INTO dbo.UsersInRoles SELECT * FROM dbo.aspnet_UsersInRoles


SELECT @CNT_NewTable = Count(1) from dbo.UsersInRoles 
SELECT @CNT_OldTable = Count(1) from aspnet_UsersInRoles

PRINT 'UsersInRoles count: ' + CAST(@CNT_NewTable AS VARCHAR) + ' >= ' + CAST(@CNT_OldTable AS VARCHAR)


Migration from OSFamilly 1 to 4

Open the file .cscfg and edit the OS Family attribute. It's in the ServiceConfiguration node.
<ServiceConfiguration servicename="MyApp" osFamily="4" osVersion="*" ...>    


Wrapping up

The only step left is to deploy in the staging environment to see if everything is working as expected. would recommend also to plan to upgrade as soon as possible because the Azure SDK 2.1 official retirement date is November 2015. I hope this post could help you, even if you are migrating from and to a different version. Any comments, suggestions and/or questions are welcome.


~ Frank Boucher