Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, November 21, 2023

SharePoint Online - Custom Raw Http calls using Graph SDK v5

The Graph SDK is a nuget library to interact with Graph API from .Net applications. Earlier this year they released¹ Graph .Net SDK v5. That highly simplified the coding with fewer lines than v4 but has breaking changes from v4 even in the basic interactions. The good part is that the Graph SDKs simplify the HTTP operations to Graph API but in some cases, we may need to deal with Raw HTTP calls. 

This post discusses such scenarios. A basic idea about Kiota and building API clients using Kiota² is helpful to easily understand the code.

Problem - Custom Url

Support we are dealing with the cutting edge of Graph API, sometimes the API or property in the result may not be available in the Graph SDK as the SDK needs some time to catch up. Unfortunately, no examples can be included due to NDA. In such cases, we need to craft the URL ourselves but we don't need to deal with the authentication. How can we customize the URL in Graph SDK with the result object using the known types in Graph SDK?

Solution

Below is the notebook³ that has the code
Hope the code is self-explanatory. The catch here is the V5 SDK will serialize the result for us. Here we are getting the known Drive object

Problem - Custom URL and Raw JSON results

Sometimes we need to deal with totally custom URLs and the result JSON. In such scenarios, we can only leverage the authentication mechanism of Graph SDK only not even the result object. How can we have a custom HTTP URL and raw JSON result using Graph SDK?

Solution - Using IRequestAdapter

One way is to use the IRequestAdapter and have NativeResponseHandler. The code in a notebook⁴ is below. This uses a dummy object to satisfy the adapter and get the JSON via NativeResponseHander.

Solution - Using native HttpClient

The above does not fully give the native experience. To get the feel of native experience we can have the below approach⁵ that uses familiar HttpClient.

Please have a look at the warning.

References

¹ - https://devblogs.microsoft.com/microsoft365dev/microsoft-graph-net-sdk-v5-is-now-generally-available/

² - https://learn.microsoft.com/en-us/openapi/kiota/quickstarts/dotnet

³ - https://github.com/dotnet-demos/graph-sdk-sharepoint-online-notebooks/blob/main/custom-rawhttp-calls.ipynb

⁴ - https://github.com/dotnet-demos/graph-sdk-sharepoint-online-notebooks/blob/main/custom-rawhttp-IRequestAdapter-json.ipynb

⁵ - https://github.com/dotnet-demos/graph-sdk-sharepoint-online-notebooks/blob/main/custom-rawhttp-HttpClient-json.ipynb

Tuesday, November 14, 2023

SharePoint Online - Which PnP SDK to download large files greater than 2GB

As we know there are 2 PnP nuget SDKs to deal with SharePoint Online from .Net client applications. PnP.Framework and PnP.Core to name and this post discuss the approach to download files larger than 2 GB. The 2 GB is an important mark as some methods work only till the MaxValue of the integer¹ data type which is 2147483647.

PnP.Framework to download > 2GB files from SharePoint Online

Below is the code to download the file and save it as a local file.

var file = clientContext.Web.GetFileByUrl(driveItemIdOrUrl);
clientContext.Load(file);
await clientContext.ExecuteQueryAsync();
logger.LogInformation($"File exists in SharePoint. Size:{file.Length:0,#}");
ClientResult<Stream> streamFromSPO = file.OpenBinaryStream();
await clientContext.ExecuteQueryAsync();

var localFilePathToDownload = Path.Combine(localFolderPathToDownload, file.Name);
using (Stream fileStream = new FileStream(localFilePathToDownload, FileMode.Create))
{
    using (streamFromSPO.Value)
    {
        streamFromSPO.Value.CopyTo(fileStream);
    }
}
logger.LogInformation($"Downloaded to {localFilePathToDownload}");

It works fine when the file size is below the max value of the integer. 

Now let us see what happens when the file size is larger.

System.FormatException: 'Invalid MIME content-length header encountered on read.'
There is one more method called OpenBinaryStream with options² that accepts SPOpenBinaryOption' enum. But there is nothing that helps us to get more than 2 GB files.

There is another method called OpenBinaryDirect³ to download files. But it fails with 401 Unauthorized when using JWT for authentication⁴. Not even able to download smaller files.
As we can see in the above image the clientContext object is the same that was used to obtain the file details.

Up on Google, we can get different suggestions such as doing it all ourselves using raw HTTP calls⁵ to avoid it and completely ⁶ avoid and migrate to PnP.Core. 

PnP.Core to download > 2GB files from SharePoint Online

Below is the code to download a file using PnP.Core.

var file = await pnpContext.Web.GetFileByServerRelativeUrlAsync(fileUrl);
logger.LogInformation($"File exists in SharePoint. Size:{file.Length}");
Stream streamFromSPO = await file.GetContentAsync(true);
var localFilePathToDownload = Path.Combine(localFolderPathToDownload, file.Name);
using (Stream fileStream = new FileStream(localFilePathToDownload, FileMode.Create))
{
    using (streamFromSPO)
    {
        streamFromSPO.CopyTo(fileStream);
    }
}
logger.LogInformation($"{nameof(DownloadFileWithReplace)} - Downloaded to {localFilePathToDownload}");

It works fine for files smaller than the max value of the integer.


What happens when the size increases above that limit?

It works!! The Int32.MaxValue didn't cause any problem here. But there are some occasions when we may experience an issue with the stream.CopyTo method. It can even happen regardless the process is 64-bit or not. In such situations, we need to tackle them separately.

One way is to pass the Buffer Size to the stream.CopyTo method.

streamFromSPO.CopyTo(fileStream,BufferSize);

Another way is to chunk ourselves. The code is below for our own chunking.

var file = await pnpContext.Web.GetFileByServerRelativeUrlAsync(fileUrl);
logger.LogInformation($"File exists in SharePoint. Size:{file.Length}");
var buffer = new byte[PnPCoreConstants.BufferSizeToDownloadLargeFile];
           
var localFilePathToDownload = Path.Combine(localFolderPathToDownload, file.Name);
using (Stream streamFromSPO = await file.GetContentAsync(true))
{
    using (Stream fileStream = new FileStream(localFilePathToDownload, FileMode.Create))
    {
        int bytesRead; long totalBytesRead = 0; long streamLength = 0;
        if (streamFromSPO.CanSeek)
        {
            streamLength = streamFromSPO.Length;
            logger.LogInformation($"{nameof(DownloadFileWithReplace)} - File Stream length:{streamLength}");
        }
        else
        {
            streamLength = file.Length;
        }
        while ((bytesRead = await streamFromSPO.ReadAsync(buffer, 0, buffer.Length)) != 0)
        {
            totalBytesRead += bytesRead;
            fileStream.Write(buffer, 0, bytesRead);
            logger.LogInformation($"{nameof(DownloadFileWithReplace)} - Progress - Read {bytesRead:0,#} and wrote.Total {totalBytesRead:0,#} / {streamLength:0,#} to {localFilePathToDownload}");
        }
     }
}
logger.LogInformation($"{nameof(DownloadFileWithReplace)} - Downloaded to {localFilePathToDownload}");

The interesting thing is that even if we provide a 2 MB buffer size, it reads 16,384 bytes only. 

Conclusion

Use the PnP.Core to download large files.

Reference

¹ - https://learn.microsoft.com/en-us/dotnet/api/system.int32.maxvalue?view=net-7.0

² - SPOpenBinaryOptions - https://learn.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/bb802697(v=office.14)

³ - https://learn.microsoft.com/en-us/previous-versions/office/sharepoint-csom/ee537083(v=office.15)

⁴ - https://stackoverflow.com/questions/45674435/401-unauthorized-exception-while-downloading-file-from-sharepoint

⁵ - https://piyushksingh.com/2016/08/15/download-large-files-from-sharepoint-online/

⁶ - Use PnP.Core https://github.com/pnp/powershell/pull/1239

Tuesday, October 31, 2023

SharePoint Online - Graph API to get all files in a drive recursively even if it has more than 5000 items

Problem

As part of the validation, we must dump all the file details inside a SharePoint drive. Some more points below

  • The input is a drive graph id.
  • It has to be recursive
  • There can be 10,000+ files in the drive and the export needs to be done in a reasonable amount of time.
  • The expected output is CSV with the below schema.
  • FolderName, FileGraphId, FileName
  • FileGraphId is the unique id of the file that Graph API understands. It is not Guid or integer instead it uses a 34-character wide format like '01XXXXA4QGNCJMT7XXXVDKCNXXXV6LCC4E'

    Approaches

    There are 3 APIs to interact with SharePoint Online. The first Graph has no direct method to list all the files recursively. We have to go by individual Graph API calls to the list folders and make subsequent  Graph calls to get the folders and files inside recursively. It works but is very slow and high chance of getting throttled. There is a search API but that has no guarantee of returning all the files as the indexing will take some time. 

    If we use the PnP.Core or PnP.Frameworks, there is no way to get the Graph IDs.

    Solution

    So lastly we have to go via Graph API but get the List items (not drive) then get the driveItem of list item to retrieve the Graph Id. The code is as follows.

    var graphClient = new GraphServiceClient(tokenProvider);

    //Url for below looks like /v1.0/sites/{siteGraphid}}/lists/{listGuid}/items?$select=contentType&$expand=driveItem HTTP/1.1
    var listItems = await graphClient
                            .Sites[siteGraphId]
                            .Lists[listGuid] // Need to get the ListId from DriveId
                            .Items
                            .GetAsync(req=> {
                                                req.QueryParameters.Expand = new []{"driveItem"};
                                                req.QueryParameters.Select = new []{"contentType"};
                                            });
    listItems
    .Value
    .Where(item=>item.ContentType.Name == "Document")
    .ToList()
    .ForEach(item=>Console.WriteLine($"FolderName:{item.DriveItem.ParentReference.Name},File Graph Id:{item.DriveItem.Id}, File Name: {item.DriveItem.Name}"));

    The drive Id needs to be translated to ListId to get this working. The QueryParameters.Select is used to limit the data to mainly 2 elements: driveItem and contentType.

    Full code

    The above code gives the idea how the required data can be pulled. Below goes full code that can be run inside Polyglot notebook.
    #r "nuget:Microsoft.Graph"
    #r "nuget:Azure.Identity"
    #r "nuget:CsvHelper"
    using Microsoft.DotNet.Interactive;
    using Microsoft.Graph;
    using Microsoft.Graph.Models;
    using Azure.Core;
    using Azure.Identity;
    using System.Collections.Generic;
    using CsvHelper;
    using CsvHelper.Configuration;
    using System.Globalization;
    public class FooMap : ClassMap<(string  FolderName,string FileGraphId,string FileName)>
    {
        public FooMap()
        {
            Map(m => m.FolderName).Name("FolderName");
            Map(m => m.FileGraphId).Name("FileGraphId");
            Map(m => m.FileName).Name("FileName");
        }
    }
    TokenCredential tokenprovider = new UsernamePasswordCredential(
                                "{userName@tenant.onmicrosoft.com}",
                                "{password}",
                                "{AAD Tenant Id}",
                                "{AAD App registration id}");
    var siteGraphId="{3 part graph Id of site}";
    var listGuid = "{Guid of List}";// Get this using Drive.
    var graphClient = new GraphServiceClient(tokenprovider);
    //Url for below looks like /v1.0/sites/{siteGraphid}}/lists/{listGuid}/items?$select=contentType&$expand=driveItem HTTP/1.1
    ListItemCollectionResponse listItems = await graphClient
                            .Sites[siteGraphId]
                            .Lists[listGuid]
                            .Items
                            .GetAsync(req=> {
                                                req.QueryParameters.Expand = new []{"driveItem"};
                                                req.QueryParameters.Select = new []{"contentType"};
                                            });
    var finalItems = new List<(string FolderName,string FileGraphId,string FileName)>();
    var pageIterator = PageIterator<ListItem,ListItemCollectionResponse>
    .CreatePageIterator(graphClient,listItems,(item)=>{
        if(item.ContentType.Name == "Document")
        {
            finalItems.Add((FolderName:item.DriveItem.ParentReference.Name,FileGraphId:item.DriveItem.Id,FileName:item.DriveItem.Name));
        }
        return true;
    });
    await pageIterator.IterateAsync();
    using(var outputFileWriter= new StreamWriter(@"c:\temp\export.csv"))
    {
        using (var csv=new CsvWriter(outputFileWriter,CultureInfo.InvariantCulture))
        {
            csv.Context.RegisterClassMap<FooMap>();
            csv.WriteRecords(finalItems);
        }
    }
    finalItems.ForEach((item)=>Console.WriteLine($"FolderName:{item.FolderName},File Graph Id:{item.FileGraphId}, File Name: {item.FileName}"))
    Each(item=>Console.WriteLine($"FolderName:{item.DriveItem.ParentReference.Name},File Graph Id:{item.DriveItem.Id}, File Name: {item.DriveItem.Name}"));

    The authentication used here is the ROPC username password. It needs to be changed based on best practices. It uses a nuget package for writing a list as a CSV file.

    References

    Tuesday, October 24, 2023

    Enable Python preview in Polyglot notebook

    It is a big difference if anyone ever tried the Jupyter Notebook. Once we experience, we need that experience everywhere including .Net. That experience was there in terms of a Jupyter kernel for .Net¹. That requires Jupyter installed in the machine already. Finally, more native experience came for .Net in the form of a VS Code extension. That was called .Net Interactive Notebooks² which uses .Net Interactive (formerly Try.Net) behind the scene. That started supporting many languages such as PowerShell, JavaScript, SQL etc... which is kinda out of the .Net world. Finally, in Nov 2022, .Net Interactive was renamed to Polyglot notebooks³ to reflect its purpose.

    Is Python supported by Polyglot Notebooks?

    The Polyglot notebooks didn't have the support for Python. We had to switch to Jypyter to work with Python and come back. Now Polyglot Notebooks has Python support as a preview.

    How to enable Python in Polyglot Notebook?

    Obviously, we should have Polyglot notebooks up and running. The first step to enable Python preview is that we need to install Jupyter on the machine and make sure the Python kernel spec is available. Run the below command to make sure it is there.
    Once this is done, we can see 2 Kernel options at the Notebook level in Visual Studio Code.

    The enabling preview feature requires the below command to be run on the notebook cell.

    #!connect jupyter --kernel-name pythonkernel --kernel-spec python3

    The command output shows it is in preview mode.
    Command is - #!connect jupyter --kernel-name pythonkernel --kernel-spec python3

    Once we add support, we can start having Python cells alongside C#. The cell kernel type needs to be the name we have given in the connect command. Below is the final state. Here we can learn C#⁴ and Python side by side.

    We can even set up R language in Polyglot Notebooks⁵. Hereafter don't waste time creating an entire project to confirm small language or platform features.

    References

    ¹ - https://devblogs.microsoft.com/dotnet/net-core-with-juypter-notebooks-is-here-preview-1/

    ² - https://hanselman.com/blog/announcing-net-interactive-try-net-includes-net-notebooks-and-more

    ³ - https://devblogs.microsoft.com/dotnet/dotnet-interactive-notebooks-is-now-polyglot-notebooks/

    ⁴ - https://techcommunity.microsoft.com/t5/educator-developer-blog/using-visual-studio-notebooks-for-learning-c/ba-p/3580015

    ⁵ - https://github.com/dotnet/interactive/blob/main/docs/jupyter-in-polyglot-notebooks.md

    Wednesday, October 18, 2023

    [Video] SharePoint Online - Prefer PnP.Core over PnP.Framework

    This is a transcript of a video published on the blog's YouTube channel except for one section. That section was omitted to keep the video under 5 minutes. This may be helpful for fellow developers who cannot view videos during their work.


    Before discussing about PnP SDKs, please note that the first preference to interact with SharePoint Online should always be Graph SDK. That is the official stand from Microsoft. In case Graph API doesn't have the feature, go for SharePoint APIs or CSOM APIs. There are 2 different SDKs or nuget packages to interact with CSOM API from .Net applications. PnP.Framework and PnP.Core to name the nugets. Today we are talking about these 2 PnP SDKs what SDK we should choose and why one over the other?

    As per the documentation the PnP.Core is the successor of PnP.Framework. In that sense PnP.Core should be our clear preference. One benefit they are advertising is that it can seamlessly switch between the modern Graph API and old SharePoint CSOM APIs. That will hide the API complexities from the developer and the developer needs to learn only PnP.Core. But there are more reasons than that to choose PnP.Core.

    Number of lines

    First of all PnP.Core requires less number of lines to achieve a task. Take the example of Getting the title of the web.

    The left side is PnP.Framework code and the right side show PnP.Core. We can clearly see that the PnP.Core works with one less line. Compare this in an enterprise application with tens of thousands of lines.

    Ease of use

    Now let us look at the ease of use in achieving a use case. The example we are taking is the renaming of a folder in the document library. PnP.Core has a direct Rename method to do that. But PnP.Framework uses the move method with the new name.

    Support for Dependency injection

    The PnP.Core SDK has out-of-the-box dependency injection support. If we are using PnP.Framework, we need to write extra code to get the .net core model dependency injection.

    Size of the request payload

    The PnP.Framework uses one particular URL almost always. It is _vti_bin/client.svc/ProcessQuery.  This is the Fiddler screenshot of PnP.Framework making HTTP call to get a folder by relative Url. It uses HTTP POST to get data instead of HTTP GET. The request payload is XML format.Luckily response is in JSON. The XML requires more bytes than JSON for sending the same information. The different operations are achieved by changing the method attribute in the request payload. 


    Now let us see how the same use case is done by PnP.Core. As we can see it uses HTTP GET with user friendly URL. No request payload at all. The response payload is relatively smaller than the PnP.Framework

    Here is the side-by-side comparison between the two when querying for a folder by its relative Url. Left is PnP.Framework and right side is the PnP.Core.


    Logging

    Now coming to the logging aspects, PnP.Core is already following the .Net programming model and honoring the ILogger API. By adding the required configuration in the appsettings.json file we can get the logs into the required destination.

    Observability

    Observability is important to run a production workload. Tools such as Azure Application Insights normally log the URLs and their HTTP verbs. That will help us to understand the system behavior and also to troubleshoot issues. We have already seen that the Url is used by the PnP.Framework is mostly the same. Adding to that, it always uses HTTP POST with parameters to distinguish the operation which makes. We cannot distinguish the operation type by the HTTP verbs.

    Error handling

    In a normal web system, when an error happens it will return respective HTTP status codes. Never Http 200. Look a the fiddler trace when querying with non existing folder path from PnP.Framework. it always returns HTTP 200. In case it errors out, the error message will be inside. Production observability systems can never detect errors like this and proactively alert the dev team. 

    Otherside, PnP.Core error out with proper HTTP status code. In case the folder URL is not present, we get HTTP 404 back, and will be handled properly by the production monitoring systems.

    Contribution to Library

    The PnP libraries are open-source and maintained by the community. Microsoft is not giving any warranty or support for these libraries. In case we end up facing an issue and need to get fixed quickly we need to fix ourselves and give a pull request.

    Look at the source code of PnP.Core and PnP.Framework. The PnP.Core is relatively simple to understand. Meaning easy for us to fix the bugs in that library. It simply prepares the Url uses an internal method to execute that Url and returns the result.

    Can we completely avoid PnP.Framework?

    Not really. The PnP.Core is not a feature-complete SDK. There are features that are not available in PnP.Core.. In such situations, we need to use PnP.Framework. One place they are telling PnP.Core will eventually replace PnP.Framework. However, when a feature request was created to bridge the gap in CreateCopyJobs-related tasks, they informed PnP.Core is never going to implement that feature. In such situations we need PnP.Framework forever.
    Thanks for reading. Comments are welcome.

    Tuesday, September 26, 2023

    SharePoint Online - PnP.Core sample to check CopyJobProgress via Azure Storage Queue SDK for .Net

    This is the continuation of the last post in this blog related to checking the status of CopyJobs in SharePoint Online. The last post has code snippets using PnP.Framework. It is not a complete compilable and working sample. This post is to introduce a functional example. The only difference is that this sample is using PnP.Core SDK.

    If anyone wondering what is PnP.Framework and PnP.Core, please have a look at the dilemma of choosing .Net SDK to interact with SharePoint Online.

    Sample located at https://github.com/dotnet-demos/sharepoint-createcopyjob-azure-queue-tracking.

    Points of interest

    Though the code has a lot of comments, below are the areas that may bring some questions.

    Getting the job status

    There is no way to get the Copy Job status in PnP.Core SDK. Even there is no plan to implement that feature. Feature request #1277 was closed.

    So either we need to switch to PnP.Framework SDK or make a direct HTTP call. In the sample, we can see it is making a direct HTTP call.

    Determining the JSON request body for direct HTTP calls

    If we refer to any documentation related to SharePoint migration API, it is referring to the SDK which is nothing but .Net classes and methods. No HTTP request-response level documentation is available. The PnP.Framework SDK uses XML to craft the request payload and the response is JSON. That request XML is the hardest thing in the world to understand. Luckily the PnP.Core SDK uses JSON for request and response. Though there is a tutorial on basic operations to SharePoint REST endpoints, it is difficult to craft the JSON request to do a simple operation such as GetMigrationJobStatus(guide jobId).

    Raw HTTP call to GetMigrationJobStatus(guide jobId).

    The official documentation is there in 2 places. But in both places, it is talking about .Net SDK usage, not the HTTP-level request response.

    First, we have to decide what should be the HTTP method. Common sense tells us this should be GET as its read operation. Url should be something like _api/site/GetMigrationJobStatus/{JobId}. 
    We are totally wrong. It should be HTTP POST.

    Now how should we build the POST body to include the jobId? Just the id in the POST body or we should have an object as below?
    {
    "jobId":"{jobId}"
    }

    Nothing is gonna work except the below one.

    {
    "id":"{jobId}"
    }

    Refer to the GetJobStatus() in the example.

    Have fun with SharePoint. Also please give PR or create an issue in case of any improvements to be made.

    Tuesday, June 20, 2023

    Mind map of SharePoint Online APIs and .Net SDK model

    This relates somewhat to a post in this blog about the dilemma of choosing Net SDK to interact with SharePoint". Since there are multiple .Net SDKs the selection of one is tricky. Now think about multiple APIs to interact with. For simplicity, we are now concerned about only SharePoint Online by avoiding SharePoint services on-premises.

    This post tries to visually represent the APIs and corresponding .Net SDK to interact with SharePoint Online.


    Generated using PlantUML. Click on the image to get svc where the links are navigatable.

    Good luck interacting with SharePoint.

    Tuesday, May 16, 2023

    The scope of the variable in C# switch case

    If we go for interviews regularly, everything is evident when we look at the code below. Otherwise, there are chances of confusion will it work? Also as managers who didn't look at code for a while, we may get slightly confused.

    Will the above code compile?

    Why not? Oh, look where the variable msg is declared. How can it be available in case 2: and default blocks?

    That case is not a block, the switch is the block. In C# the block is associated with the curly brackets/braces. The variable will be kind of hoisted and available to the entire block following the declaration of the variable?

    Wait, what is hoisting?

    Don't remember JavaScript? Its interpreter moves all the declarations to the top of their scope. The C# compiler does something comparable to that.

    Can we have scope inside the case statement?

    Yes. Have a look at the below code.

    Is this C# feature documented anywhere?

    Yes right in the specs.

    Read the specs and happy coding

    References

    Tuesday, February 7, 2023

    Check for comments in large word document using SAX model of Open XML SDK

    Open XML SDK is the only way to work with Microsoft Office files in a managed way. It works the same regardless our code runs in a desktop application or a server-side application. The first thing to know about this SDK is its reading models. 

    Why do we care about reading models?

    This is important as the Open XML-based .docx, and .xlsx files are nothing but zip files with a different extension. 

    • When loading the file to memory the requirement may be 8x of the actual file size. 
    • When our code runs in memory-restricted containers it errors out with an Out of Memory Exception.

    What are 2 models?

    We will be seeing 2 models with an example. The example is to check for any comments in a word document.

    DOM model

    If we are sure the size will be small and the expanded size will fit in available memory, we can use the DOm model. The code to check for any comments in the word document goes as follows.

    Tuesday, August 2, 2022

    CSC : warning CS8032: An instance of analyzer RoslynBasics.MySourceGenerator cannot be created from. Could not load file or assembly 'Microsoft.CodeAnalysis, Version=4.2.0.0,

    When we are developing .Net Compiler Platform (Roslyn)¹ related code and using it in Visual Studio there are chances of getting the below exception when compiling in Visual Studio 2022.

    In my scenario, I got this exception when developing a SourceGenerator².

    CSC : warning CS8032: An instance of analyzer RoslynBasics.MySourceGenerator cannot be created from C:\..\RoslynBasics\bin\Debug\netstandard2.0\RoslynBasics.dll : Could not load file or assembly 'Microsoft.CodeAnalysis, Version=4.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified..

    There are many resolutions available on google. Below is the one that worked for me.
    Downgrade the Microsoft.CodeAnalysis to 4.1.00

    Root cause

    Though the latest version is 4.2.0.0 but the Visual Studio 2022 (17.1.1) is unaware of it. Hence it failed. We can check the version of Microsoft.CodeAnalysis that Visual Studio uses in the below folder location.

    C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin\Roslyn

    The location of Visual Studio 2019 and other versions is different.

    Solution

    The right solution can be to upgrade Visual Studio to 17.2.x. 

    Once VS 2022 is upgraded the nuget 4.2.0.0 started working fine. 

    Above is the new dll version after the upgrade of Visual Studio

    References


    Tuesday, June 21, 2022

    C# Random stories

    There will be many scenarios we have to generate random numbers, ids or strings as a developer¹. If we ever played a game we know how important is to generate random things. In the .Net world, we will normally use Guid ² struct to generate random ids. To get random numbers, we use the Random class.

    But there are more mechanisms in .Net to generate random things. That's what we are going to look in this post.

    The problem with Random class in .Net

     The Random class has a lot of use cases and well documented with samples. Before we explore let us understand what is the issue with the famous class Random? 


    The best place to understand is the "Remarks" section in the docs. The repetition happens when we initialize the Random class with same seed. 

    RNGCryptoServiceProvider

    What is "cryptographically secure random number" mentioned above? It can be an encryption key randomly generated to encrypt sensitive data. We all understand if the encryption key is guessable there is no value.
    From the documentation, we will be redirected to the RNGCryptoServiceProvider⁴ class for generating something random useful for cryptographic use cases. This class generate a random data as byte[] array. But that can be converted to base64 in case our requirement is a random string.

    But there is a catch. This class was is in use but now Obsolete⁵ and replaced with RandomNumberGenerator⁶ class.
    So it is not a good path to take.

    RandomNumberGenerator

    This is an abstract base class so in order to create object we have to call its static Create(). Below goes the code to generate.


    The code inside the extension methods goes below.

    The above sample generate random bytes and convert to Base64 for display purpose. We can generate integer as well using the same byte array generation technique but with byte array to integer conversion.

    Though it employs cryptographic methods, it is not full proof. It is again prone to prediction. If we really need unpredictable randomness we should look at external services such as random.org⁷ that uses atmospheric noise to generate randomness.

    The sample I used are available in the GitHub repo.

    References

    Tuesday, April 5, 2022

    Azure @ Enterprise - Resubmitting messages from Service Bus dead-letter queue using various .Net SDKs

    When we start using the Azure service bus for integration one of the operations job is to monitor and handle the messages in the dead-letter queue DLQ hereafter. As many of us already know, the DLQ is automatically created as a sub-queue with a naming convention. Messages will end up in DLQ when they are not deliverable or not processable. A non-processable situation occurs when the processors try to process but end up in exceptions and retry attempts exceed the Max delivery count. 

    Problem

    When we think of operations handling the DLQ, we think of manual troubleshooting of why messages failed and a PowerShell script that puts those messages back after fixing the issue. Obviously, some messages might be in the state to be reattempted. The issue here is that there is no built-in support for dealing with the data plane of Service Bus in the official library. I had written a previous post about how we can deal with the Service Bus data plane with PowerShell by writing custom snippets that interact with raw HTTP API.

    Readers may be thinking why write PowerShell for operations, why can't operations just go to Azure Portal select all messages in DLQ, and hit the re-queue button. Unfortunately, there is no such feature available in Azure Portal

    Solution

    One way is to use already available Service Bus explorers provided by third parties other than in the label of Azure or Microsoft. There are some but not much user-friendly in my research. Hence this post about resubmitting the messages from DLQ using C#.

    We can do this using PowerShell also but as I mentioned in the previous post we need to write a script to prepare raw HTTP messages. There are standard libraries in.Net that help us to write less code. 

    High-level flow

    This post is not going to have full code as the code is available in the GitHub repo. The high-level flow is as follows

    • Monitor and receive a message from DLQ using the peek and lock method.
    • Clone the message and send it to the queue again.
    • Complete the received message from DLQ. This will remove the message from DLQ
    There is no operation on the message just to toggle it to be a normal message from DLQ.

    Selecting the SDK

    There are 3 official .Net SDKs to interact with Azure Service Bus Queues. There is already a post in this blog about the Dilemma of choosing the SDK.  The general guideline is to use the latest SDK which is Azure.Messaging.ServiceBus.

    Sample location

    There are already samples to resubmit messages from DLQ using the earliest SDK WindowsAzure.ServiceBus, its successor Microsoft.Azure.ServiceBus and the latest Azure.Messaging.ServiceBus. So there will be questions, why one more sample? 

    The reason for putting together this sample was that none of the samples were fully usable when we encounter a situation of resubmitting 100+ messages from DLQ. One does support only AMQP which is blocked by the enterprise network etc... 

    There are 3 samples in the below repo that shows how to resubmit using all the 3 SDKs.

    https://github.com/ms-azure-demos/service-bus-queue-dlq-manager

    The samples are targetting the legacy .Net Framework, not .Net Core. The Azure.Messaging sample can be easily targetted to .Net Core and higher versions.

    References

    https://dzone.com/articles/azure-service-bus-dead-letter-queues-1

    https://docs.microsoft.com/en-us/samples/azure/azure-sdk-for-net/dead-letter-queues/

    Tuesday, May 4, 2021

    Uncomment section in XML file using C#.Net

    Requirement 

    As part of the installation, some XML fragments (eg: <authentication>) need to be uncommented in web.config file based on the environment,. This can be done either via PowerShell or C#.Net as this has to be triggered from MSI installation. Never during the runtime of the application.

    Alternatives

    We can either do string-based detection and replace it. Or use XML parser of .Net. Since the string parser is complex, let us stick with the .Net library to replace it.

    Solution

    The below code snippets is replacing the commented <authentication> tag in XML with its uncommented version.

    Tuesday, May 5, 2020

    Convert traditional visual studio project to multi targeting SDK-Style library project

    Background

    To directly jump to the problem this post is dealing with by skipping the story, directly jump to the last paragraph in this section.

    When we were developing .Net libraries or third-party components in the early days we had to keep one project per framework version. That is because there would be more than one version in the mainstream at any time. Though Visual Studio 2008 onwards there is some sort of multi-targeting which matured with VS 2010, it was not easy to publish libraries from one project targeting different framework versions.

    The need to target multiple versions became intense with the introduction of .Net Core. Both Full .Net Framework, as well as .Net Core, keep getting new versions.

    But it changed totally when Microsoft introduced multi-targeting library projects in Visual Studio 2017. For simplicity skipping the PCL(Portable Class Libraries) which was introduced in between to deal with common code base for Silverlight and .Net Framework. At that time, there was real confusion about what library project to choose when we create new. Later Microsoft introduced JSON based project file for .Net core which dropped with a migration path.

    The new project format really simplified the .csproj files. Initially, it was more related to the .Net Standard but later it is used for different purposes as well even for console apps. Let us not get into .Net Standard as differentiating it is another post by itself. Finally, the new project format got the name SDK-Style project which we can identify by the below tag in the project file (.csproj)

    <Project Sdk="Microsoft.NET.Sdk">

    One of the earliest blog posts explains what is the vision when they revamped the project file format. No listing of files inside the project file, can produce nuget directly without nuspec, easy modification without IDE, etc... were some. Until then the csproj was considered as only software editable file format though it is XML. But with the SDK-Style project format, though it is still XML, humans are also allowed to edit manually. More details can be found here.

    Now the csproj is more like the NodeJS development where the packge.json is human editable. Really dreaming for a day when Microsoft says "develop with NodeJS or something else and host in Azure". Just a dream.

    Let us come back to the purpose of this post. Here we are seeing how to convert existing old nuget library projects to modern SDK-Style library projects which can target multiple frameworks and versions including from .Net 4.5 to .Net Core 3.1.

    Existing approaches

    The easy way most of the internet says on converting existing projects to a multi-targeting SDK-Style library project is to create a new project. Then just copy-paste the files from old project location to new. Since the new project format doesn't require all the files to be added to the project file its easy as just copy. Links are given in the references section.
    Just compare with NodeJS development where package.json doesn't need to know all the files. 

    There is another way to convert the projects to SDK-Style. First, convert the nuget package references from the packages.config to <packagereference> tag in csproj. Then use a tool to migrate the project file. There seem multiple tools listed below though they point to the same GitHub repo. Maybe one is a wrapper over other when VS 2019 released.

    Manual approach

    However, it seems easy to convert by hand, if our project is not that much complicated and confirms the compatibility. The only problem is that we need to clean the project which is not required if we start a new project and copy files.

    Manually porting project to SDK-Style library project

    Below goes a diff of manual porting of one project. If the iFrame is not loading directly go to the GitHub URL. Another difference is that the SDK-Style doesn't really require the Assemblyinfo.cs

    Manually porting test project to SDK-Style

    The same can be applied to test projects as well. The link to the comparison is here.

    Please note that it worked smoothly as this project is simple and only one person handles all at this point. When working in Enterprise environments or a large team environment, it would not be efficient as following the steps such as evaluate compatibility, refactoring projects to smaller pieces before doing anything.

    References

    https://weblog.west-wind.com/posts/2017/jun/22/multitargeting-and-porting-a-net-library-to-net-core-20
    https://www.michaeltaylorp3.net/porting-a-net-framework-library-to-net-standard/