BadImageFormatException When Running 32/64 Bit Applications in Jet Brains Rider

I posted before about the error of getting BadImageFormatException and how it was associated to the processor settings. The fixed suggested were for Visual Studio only and in recent times I have now started working with Jet Brains Rider, which I then got the same issue, but found the correcting process.

If you do have Visual Studio and have this issue then you can read how to correct it on this post. BadImageFormatException When Running 32/64 Bit Applications in Visual studio

If you are using Jet Brains Rider then you can follow this instead.

  1. Open up your .Net Framework Project in Jet Brains Rider
  2. Select ‘Edit Configuration’ from the top right menu:
  1. Within the new window that opens you can then change the IIS Express path, which currently you can see is using the ‘x86’ version that is 32 bit. Update the path without this to configure the 64 bit version.

Azure REST API Scopes

When working with the Azure REST API you need to provide the scope in all API requests, so Azure knows where you are looking. However, throughout their documentation that although they ask for the scope they do not explain or link to an explanation of what a scope is and what the formats are. Therefore, I have collected them and got a simple explanation for each of them.

As mentioned above, the scope is like a search filter and also part of the permissions. For example, if you was getting a list of Resources you might use the Resource Group scope to get only them Resources, or you might go for the Subscription scope to get all Resources in the requested Subscription. This might also be due to permissions, if the Service Principle account you are using doesn’t have access to the whole Tenant, but does to specific Subscriptions.

Scopes

Subscription scope

subscriptions/{subscriptionId}

Example:

subscriptions/d7f90b53-af20-4061-8206-f05e31852a44

Resource Group scope

subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}

Example:

subscriptions/d7f90b53-af20-4061-8206-f05e31852a44/resourceGroups/my-rg-2020

Providers scope

These scopes can vary depending on what the scope is for. For example this is the scope for the Billing Account:

providers/Microsoft.Billing/billingAccounts/{billingAccountId}

You can find all of the scopes by following https://docs.microsoft.com/en-us/azure/role-based-access-control/resource-provider-operations

Tenant scope

The Tenant scope is easist, as you just don’t put anything. For example getting a list of Role Definitions

The official URL is:

GET https://management.azure.com/{scope}/providers/Microsoft.Authorization/roleDefinitions?api-version=2015-07-01

But to get the Role Definitions from the Tenant Level and below, you just remove the scope segment:

GET https://management.azure.com/providers/Microsoft.Authorization/roleDefinitions?api-version=2015-07-01

BadImageFormatException When Running 32/64 Bit Applications in Visual Studio

You might be about to run your application and suddenly you are getting ‘System.BadImageFormatException’. This is what I got when running a new application that I didn’t build. It took me a little bit to figure out what the issue was, but as below, the culprit was found and also some other interesting configurations required.

The problem I found was the application was built using a DotNet Core Console Application, but specifically using the x64 Bit processor. Now this is not a problem of course, as you want it to use the best performance processor the application can, so you can deliver that performance to your end users. However, it seems the rest of Visual Studio was not ready for this, so running Local IIS or running Unit Tests was causing a System.BadImageFormatException exception.

When I have been building application before, I have just defaulted to using the ‘AnyCpu’ configuration, which has worked perfect with no conflict or issues. What this actually does under the hood though, is it chooses the lowest configuration it can depending on the requirements of the application, which for this case was 32bit.

When an application can run fine either in 32-bit or 64-bit mode, the 32-bit mode tends to be a little faster. Larger pointers means more memory and cache consumption, and the number of bytes of CPU cache available is the same for both 32-bit and 64-bit processes. Of course the WOW layer does add some overhead, but the performance numbers I’ve seen indicate that in most real-world scenarios running in the WOW is faster than running as a native 64-bit process

Ref: Rick Byers – exMSFT June 9, 2009

Fixing This

If you still want to run specifically as 64 bit or 32 bit then there are a few places this needs to be changed for both IIS Express and Unit Tests to work.

Build Configuration

  1. Open the Configuration Manager dialog box.

    undefined
  2. In the Active solution configuration drop-down list, choose New.
    The New Solution Configuration dialog box opens.
     
    undefined
  3. In the Name text box, enter a name for the new configuration.
  4. To use the settings from an existing solution configuration, in the Copy settings from drop-down list, choose a configuration.
     
    undefined
  5. If you want to create project configurations at the same time, select the Create new project configurations check box

You can get further instructions from Microsoft Official Documentation for other setups and starting points.

IIS Express

IIS Express is what is used when running the application from Visual Studio. Each project has it’s own setting for this, so if you have multiple projects, then you will need to do the following for each of them.

  1. If you right click the required project and select properties, then the new window will open up.
  2. Under the Build tab on the left you can then see the ‘Platform target‘ selection.

Unit Tests

Yes even the tests can run under a different process, so we need to configure them as well. This is global to all test projects, so will onlt need to be done once. You can configure them seperately, but doing the about section for each project.

In the ‘Test‘ option at the top of the window select the ‘Processor Architecture for AnyCPU Projects‘ then the desired processor setting.

undefined

Microsoft Graph Client ClientCredentialProvider not Recognised

So you have downloaded the latest version of the Graph Nuget Package and your dotnet core application is all ready to start building with the Microsoft Graph Client SDK. However, when you create the client as per the documentation, Visual Studio is complaining it can’t find the ClientCredentialProvider.

This is because it required the Microsoft Graph Auth Nuget package, which is not production ready yet. When you download the Graph Nuget it does not download this, so you would need to install it seperatly as per the github repository suggests.

However, if you do not perfer adding a non-production ready package to you production code then there is an alternative method.

This method uses the Microsoft Authentication Library for .NET (MSAL) to set up the Microsoft Graph Client using the app-only provider. In the example below I am following the Client Credentials Provider as per the Authentication Providers documentation.

First you will need the Tenant ID for the Azure Subscription you wish to use the SDK with. This can be retrieved from:

// The Azure AD tenant ID  (e.g. tenantId.onmicrosoft.com)
var tenantId = "{tenant-id}";

Then you will also need the Applications Client ID and Secret. If you haven’t registered your application yet then you can follow this to get that setup and ready > https://docs.microsoft.com/en-us/graph/auth-register-app-v2. Make sure you have given the Application enough permissions on the Graph API to execute the required action for your project.

// The client ID of the app registered in Azure AD
var clientId = "{client-id}";


// Application Client Secret (Recommended this is stored safely and not hardcoded)
var clientSecret = "{client-secret}"

With this information, we can now create the MSAL client credentials to authenticate the application to Azure

var scopes = new string[] { "https://graph.microsoft.com/.default" };
var confidentialClient = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithAuthority($"https://login.microsoftonline.com/$tenantId/v2.0")
    .WithClientSecret(clientSecret)
    .Build();

Now we can create the Graph Client by passing the Authentication Provider as a variable. In this we are getting the Authentication Bearer Token from Azure for the application. Once we have this then we can add it to all the API requests headers for authentication.

This means when ever you use the SDK it will add this token, or a new token, to every request to authenticate the API request.

GraphServiceClient graphServiceClient =
new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) => {

// Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
var authResult = await confidentialClient.AcquireTokenForClient(scopes).ExecuteAsync();

// Add the access token in the Authorization header of the API
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

})
);

From there you can use the Microsoft Graph SDK just as normal.

// Make a Microsoft Graph API query
var users = await graphServiceClient.Users.Request().GetAsync();

For more information on the Microsoft Graphe SDK and API, you can read the GitHub Repository

How I split a row by columns in MS SQL

Sometimes we just want to spit the rows in a table by the columns values because that is what SQL is for. This is no easy task depending on your data structure and lead to some complex queries. So here is the road to how to separate the columns data into each row that I followed.

Let’s start with the example table to show how the table would be set, so that you know where this is all coming from. At minimal we need the primary ID that defines the unique row and the column that will be split into multiple rows, for example.

IDFirstnameLastnameHobbies
1Chris Eagle Cycling,Running,Music
2Lucy Whitehead Music,Theatre,Holiday
3Foo BarRunning,Holiday,Cycling
Example SQL Table

Like with any SQL function we start with the creation and the entry of the required variables. For this we need the identifier for referencing each row, a delimiter for how each value in the string is connected and finally the column.

CREATE FUNCTION [dbo].[SplitRowByColumn]
(
)
RETURNS @returntable TABLE
(
id int,
csvColumn varchar(max),
delimiter varchar(1)
)

To make things a little lighter we are going to put the required items into a temporary table. This way when we are referencing and processing the table, we are only calling locally and not on the full dataset. The other reason you will see later, is it is used to manage what rows have been processed. As you will see I am only using 1 field ‘csvColumn’, but you can branch these out to have extra columns if required.

— DECLARE TEMP DBs
declare @tempItemsTable TABLE (id int,
csvColumn varchar(max));

— GET ALL VALUES
INSERT @tempItemsTable
(id,csvColumn)
SELECT id, csvColumn
from [dbo].[SourceTable]

This is where the fun now happens, as we split each row by its column and piece it back together. In the loop below I use the split function found on the great Stack Overflow to separate the column for reference. https://stackoverflow.com/questions/13527537/sql-query-to-split-column-data-into-rows

In the loop we go through each item in the ‘tempItemsTable’ that we just constructed with all the rows we wish to split. Then for each row we can get the values out and split the column, while at the same time we insert each split item into a row of the returning table.

— LOOP ITEMS
WHILE (SELECT COUNT(id) from @tempItemsTable) > 0

BEGIN

DECLARE @id int
DECLARE @currentCsvColumn varchar(max)

— GET VALUES
SELECT TOP 1 @id=id, @currentCsvColumn=csvColumn FROM @tempItemsTable

— INSERT VALUES INTO TEMP DB
INSERT INTO @returntable
(id, csvColumn)
SELECT @id, splitTable.items
FROM
[Current_Database].[dbo].[Split] (@currentCsvColumn, @delimiter) AS splitTable

— REMOVE 1 STEP
DELETE @tempItemsTable WHERE id = (SELECT TOP 1 id FROM @tempItemsTable)

END

At the end of the loop we then remove the first item, so that the loop count will go down and we move onto the next row.

Finally on the output we should have the below example table:

IDHobbies
1Cycling
1Running
1Music
2Music
2Theatre
2Holiday
3Running
3Holiday
3Cycling
Processed SQL Table Result

With this table you can now link the returned table to the original table

SELECT
p.[ID], p.[First Name], p.[Last Name,], sr.[csvColumn]
FROM
[dbo].[SourceTable] AS p
INNER JOIN
[dbo].[SplitRowByColumn]() as sr ON sr id = p.id

Bonus Round

In the circumstance that we have two columns to split, there is a slight alteration that we have to make for the linking of the two split columns together. We required the Split function, from Stack Overflow, to return what index level it is currently at, so we can match it with the another column we are splitting. The full example of the new Split function is below and here is also how we then link them into the same returning table.

— INSERT VALUES INTO TEMP DB
INSERT INTO @returntable
(id, csvColumn1, csvColumn2)

SELECT @id, splitTable1.items, splitTable2.items
FROM
[Current_Database].[dbo].[Split] (@currentCsvColumn1, @delimiter) AS splitTable1
INNER JOIN
[Current_Database].[dbo].[Split] (@currentCsvColumn2, @delimiter) AS splitTable2
ON splitTable1.IndexNum = splitTable2.IndexNum

Full Examples

SplitRowByColumn Function

CREATE FUNCTION [dbo].[SplitRowByColumn]
(
)
RETURNS @returntable TABLE
(
id int,
csvColumn varchar(max),
delimiter varchar(1)
)

AS
BEGIN

— DECLARE TEMP DBs
declare @tempItemsTable TABLE (id int,
csvColumn varchar(max));

— GET ALL VALUES
INSERT @tempItemsTable
(id,csvColumn)
SELECT id, csvColumn
from [dbo].[SourceTable]

— LOOP ITEMS
WHILE (SELECT COUNT(id)
from @tempItemsTable) > 0

BEGIN
DECLARE @id int
DECLARE @currentCsvColumn varchar(max)

— GET VALUES
SELECT TOP 1 @id=id, @currentCsvColumn=csvColumn FROM @tempItemsTable

— INSERT VALUES INTO TEMP DB
INSERT INTO @returntable
(id, csvColumn)
SELECT @id, splitTable.items
FROM
[Current_Database].[dbo].[Split] (@currentCsvColumn, @delimiter) AS splitTable

— REMOVE 1 STEP
DELETE @tempItemsTable WHERE id = (SELECT TOP 1 id FROM @tempItemsTable)
END
    RETURN
END

Split Function

CREATE FUNCTION [dbo].[Split]
(@String nvarchar(4000), @Delimiter char(1))
RETURNS @Results TABLE (Items nvarchar(4000),
IndexNum int)

AS
BEGIN

DECLARE @COUNTER INT
SET @COUNTER = 0
DECLARE @INDEX INT
DECLARE @SLICE nvarchar(4000)

— HAVE TO SET TO 1 SO IT DOESNT EQUAL Z
— ERO FIRST TIME IN LOOP
SELECT @INDEX = 1
WHILE @INDEX !=0

BEGIN

— GET THE INDEX OF THE FIRST OCCURENCE OF THE SPLIT CHARACTER
SELECT @INDEX = CHARINDEX(@Delimiter,@STRING)

— NOW PUSH EVERYTHING TO THE LEFT OF IT INTO THE SLICE VARIABLE
IF @INDEX !=0
SELECT @SLICE = LEFT(@STRING,@INDEX – 1)
ELSE
SELECT @SLICE = @STRING

— PUT THE ITEM INTO THE RESULTS SET
INSERT INTO @Results
(Items, IndexNum)
VALUES(@SLICE, @COUNTER)

— INCREMENT COUNTER
SET @COUNTER = @COUNTER + 1

— CHOP THE ITEM REMOVED OFF THE MAIN STRING
SELECT @STRING = RIGHT(@STRING,LEN(@STRING) – @INDEX)

— BREAK OUT IF WE ARE DONE
IF LEN(@STRING) = 0 BREAK

END
RETURN
END