Tuesday, 23 October 2018

Read DB data to create a file and store in the Azure Storage

Code to read DB data


        public async void getData()

        {

          var dbList = dbContext.TESTs.ToList();

            await generateFile(dbList);

        }



To Generate File and store in Azure Container


public async Task generateFile(List data)

        {

            string AccountName = "XXXXXXX";

            string AccountKey = "xxxxxxxx";

            string ContainerName = "xxxxxxxx";

           



            string storageConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", AccountName, AccountKey);

            var blobClient = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(storageConnectionString).CreateCloudBlobClient();

            Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer _BlobContainer = blobClient.GetContainerReference(ContainerName);

            OperationContext context = new OperationContext();

            BlobRequestOptions options = new BlobRequestOptions();

            CloudBlockBlob result = null;



            // Create a file in your local MyDocuments folder to upload to a blob.

            string localPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            string localFileName = "QuickStart_" + Guid.NewGuid().ToString() + ".txt";

            var sourceFile = Path.Combine(localPath, localFileName);

            // Write text to the file.

            string dataString="";

            data.ForEach(x => { dataString = dataString + x.Fname; });

            File.WriteAllText(sourceFile, dataString);





            // Get a reference to the blob address, then upload the file to the blob.

            // Use the value of localFileName for the blob name.

            CloudBlockBlob cloudBlockBlob = _BlobContainer.GetBlockBlobReference(localFileName);

            cloudBlockBlob.UploadFromFile(sourceFile);



           

            

        }

Wednesday, 17 October 2018

Swagger Configuration for Asp.Net Core projects



Package installation

Swashbuckle can be added with the following approaches:
  • From the Package Manager Console window:
    • Go to View > Other Windows > Package Manager Console
    • Navigate to the directory in which the TodoApi.csproj file exists
    • Execute the following command:
      PowerShell
      Install-Package Swashbuckle.AspNetCore
      
  • From the Manage NuGet Packages dialog:
    • Right-click the project in Solution Explorer > Manage NuGet Packages
    • Set the Package source to "nuget.org"
    • Enter "Swashbuckle.AspNetCore" in the search box
    • Select the "Swashbuckle.AspNetCore" package from the Browse tab and click Install

Add and configure Swagger middleware

Add the Swagger generator to the services collection in the Startup.ConfigureServices method:
C#
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext(opt =>
        opt.UseInMemoryDatabase("TodoList"));
    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    // Register the Swagger generator, defining 1 or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
    });
}
Import the following namespace to use the Info class:
C#
using Swashbuckle.AspNetCore.Swagger;
In the Startup.Configure method, enable the middleware for serving the generated JSON document and the Swagger UI:
C#
public void Configure(IApplicationBuilder app)
{
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();

    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });

    app.UseMvc();
}
The preceding UseSwaggerUI method call enables the Static Files Middleware. If targeting .NET Framework or .NET Core 1.x, add the Microsoft.AspNetCore.StaticFiles NuGet package to the project.
Launch the app, and navigate to http://localhost:/swagger/v1/swagger.json. The generated document describing the endpoints appears as shown in Swagger specification (swagger.json).
The Swagger UI can be found at http://localhost:/swagger. Explore the API via Swagger UI and incorporate it in other programs.
Tip
To serve the Swagger UI at the app's root (http://localhost:/), set the RoutePrefix property to an empty string:
C#
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    c.RoutePrefix = string.Empty;
});

Customize and extend

Swagger provides options for documenting the object model and customizing the UI to match your theme.

API info and description

The configuration action passed to the AddSwaggerGen method adds information such as the author, license, and description:
C#
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info
    {
        Version = "v1",
        Title = "ToDo API",
        Description = "A simple example ASP.NET Core Web API",
        TermsOfService = "None",
        Contact = new Contact
        {
            Name = "Shayne Boyer",
            Email = string.Empty,
            Url = "https://twitter.com/spboyer"
        },
        License = new License
        {
            Name = "Use under LICX",
            Url = "https://example.com/license"
        }
    });
});
The Swagger UI displays the version's information:
Swagger UI with version information: description, author, and see more link
Source: https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-2.1&tabs=visual-studio%2Cvisual-studio-xml

Tuesday, 3 April 2018

Azure ServiceBus Queue - DeadLetterQueue (DLQ)

Azure Service Bus queues and topic subscriptions provide a secondary sub-queue, called a dead-letter queue (DLQ). The dead-letter queue does not need to be explicitly created and cannot be deleted or otherwise managed independent of the main entity.

The dead-letter queue

The purpose of the dead-letter queue is to hold messages that cannot be delivered to any receiver, or messages that could not be processed. Messages can then be removed from the DLQ and inspected. An application might, with help of an operator, correct issues and resubmit the message, log the fact that there was an error, and take corrective action.
From an API and protocol perspective, the DLQ is mostly similar to any other queue, except that messages can only be submitted via the dead-letter operation of the parent entity. In addition, time-to-live is not observed, and you can't dead-letter a message from a DLQ. The dead-letter queue fully supports peek-lock delivery and transactional operations.
Note that there is no automatic cleanup of the DLQ. Messages remain in the DLQ until you explicitly retrieve them from the DLQ and call Complete() on the dead-letter message.

Moving messages to the DLQ

There are several activities in Service Bus that cause messages to get pushed to the DLQ from within the messaging engine itself. An application can also explicitly move messages to the DLQ.
As the message gets moved by the broker, two properties are added to the message as the broker calls its internal version of the DeadLetter method on the message: DeadLetterReason and DeadLetterErrorDescription.
Applications can define their own codes for the DeadLetterReason property, but the system sets the following values.
ConditionDeadLetterReasonDeadLetterErrorDescription
AlwaysHeaderSizeExceededThe size quota for this stream has been exceeded.
!TopicDescription.
EnableFilteringMessagesBeforePublishing and SubscriptionDescription.
EnableDeadLetteringOnFilterEvaluationExceptions
exception.GetType().Nameexception.Message
EnableDeadLetteringOnMessageExpirationTTLExpiredExceptionThe message expired and was dead lettered.
SubscriptionDescription.RequiresSessionSession id is null.Session enabled entity doesn't allow a message whose session identifier is null.
!dead letter queueMaxTransferHopCountExceededNull
Application explicit dead letteringSpecified by applicationSpecified by application

Exceeding MaxDeliveryCount

Queues and subscriptions each have a QueueDescription.MaxDeliveryCount and SubscriptionDescription.MaxDeliveryCount property respectively; the default value is 10. Whenever a message has been delivered under a lock (ReceiveMode.PeekLock), but has been either explicitly abandoned or the lock has expired, the message BrokeredMessage.DeliveryCount is incremented. When DeliveryCount exceeds MaxDeliveryCount, the message is moved to the DLQ, specifying the MaxDeliveryCountExceeded reason code.
This behavior cannot be disabled, but you can set MaxDeliveryCount to a very large number.

Exceeding TimeToLive

When the QueueDescription.EnableDeadLetteringOnMessageExpiration or SubscriptionDescription.EnableDeadLetteringOnMessageExpiration property is set to true (the default is false), all expiring messages are moved to the DLQ, specifying the TTLExpiredException reason code.
Note that expired messages are only purged and moved to the DLQ when there is at least one active receiver pulling from the main queue or subscription; that behavior is by design.

Errors while processing subscription rules

When the SubscriptionDescription.EnableDeadLetteringOnFilterEvaluationExceptions property is enabled for a subscription, any errors that occur while a subscription's SQL filter rule executes are captured in the DLQ along with the offending message.

Application-level dead-lettering

In addition to the system-provided dead-lettering features, applications can use the DLQ to explicitly reject unacceptable messages. This can include messages that cannot be properly processed due to any sort of system issue, messages that hold malformed payloads, or messages that fail authentication when some message-level security scheme is used.

Dead-lettering in ForwardTo or SendVia scenarios

Messages will be sent to the transfer dead-letter queue under the following conditions:
  • A message passes through more than 3 queues or topics that are chained together.
  • The destination queue or topic is disabled or deleted.
  • The destination queue or topic exceeds the maximum entity size.
To retrieve these dead-lettered messages, you can create a receiver using the FormatTransferDeadletterPath utility method.

Example

The following code snippet creates a message receiver. In the receive loop for the main queue, the code retrieves the message with Receive(TimeSpan.Zero), which asks the broker to instantly return any message readily available, or to return with no result. If the code receives a message, it immediately abandons it, which increments the DeliveryCount. Once the system moves the message to the DLQ, the main queue is empty and the loop exits, as ReceiveAsync returns null.
C#
var receiver = await receiverFactory.CreateMessageReceiverAsync(queueName, ReceiveMode.PeekLock);
while(true)
{
    var msg = await receiver.ReceiveAsync(TimeSpan.Zero);
    if (msg != null)
    {
        Console.WriteLine("Picked up message; DeliveryCount {0}", msg.DeliveryCount);
        await msg.AbandonAsync();
    }
    else
    {
        break;
    }
}

Clearing the Dead Letter Queue  

[TestMethod]
public void ClearDeadLetterQueue()
{
    string deadLetterQueueName = "myQueue/$DeadLetterQueue";
    QueueClient client = QueueClient.CreateFromConnectionString("connectionString",
            deadLetterQueueName, ReceiveMode.PeekLock);
     while (client.Receive() != null)
    {
        var receivedMessage = client.Receive();
//do something with the message here
        receivedMessage?.Complete();
    }
}

sources: https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dead-letter-queues

https://medium.com/@DomBurf/clearing-the-dead-letter-queue-on-an-azure-service-bus-queue-3c942b312f98

Sunday, 4 February 2018

Console Web Server using OWIN

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Owin;
using Microsoft.Owin.Hosting;
using System.Web.Http;

namespace OwinConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "http://localhost:8080";
            using (WebApp.Start<Startup>(url))
            {
                Console.WriteLine("starting server");
                Console.ReadKey();
                Console.WriteLine("Stoppig server");
            }
        }


    }

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureWebAPI(app);
            //app.UseWelcomePage();
           // app.Run(ctx =>
           //ctx.Response.WriteAsync("Hello pooja"));
        }

        private void ConfigureWebAPI(IAppBuilder app)
        {
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute("DefaultApi", "api/{Controller}/{id}"
            new { id = RouteParameter.Optional });
            app.UseWebApi(config);
        }
    }
}



Monday, 29 January 2018

Azure AD: Tenant and Audience


The single parameter passed to the middleware, WindowsAzureActiveDirectoryBearerAuthenticationOptions, supplies the settings for determining a token’s validity. It captures the raw values during project creation and stores them in the web.config file. The Audience value is the identifier by which the Web API is known to Windows Azure AD. Any tokens carrying a different Audience are meant for another resource and should be rejected.


The Tenant property indicates the Windows Azure AD tenant used to outsource authentication. The middleware uses that information to access the tenant and read all the other properties (such as which key should be used to verify the token’s signatures) that determine the validity of a token.

Friday, 26 January 2018

Simple Multi Tasking program in C#


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; 

namespace multitasking
{
    class Program
    {
        static void Main(string[] args)
        {
            execute();
            Console.WriteLine("end of the program");
            Console.Read();
        } 

        static async Task execute()
        {
            Program p1 = Activator.CreateInstance(typeof(multitasking.Program)) as Program;
            Task t = p1.run1();
            Task t1 = p1.run2();
            await Task.WhenAll(t, t1);
            Console.WriteLine("end of the program class");
        }

        async Task run1()
        {
            await Task.Run(() =>
             {
                 for (int i = 0; i < 100; i++)
                 {
                     Console.WriteLine("Run 1:" + i);
                     Task.Delay(5000);
                 }
             });
        }

        async Task run2()
        {
            await Task.Run(() =>
             {
                 for (int i = 0; i < 100; i++)
                 {
                     Console.WriteLine("Run 2:" + i);
                     Task.Delay(1000);
                 }
             });
        }
    }
}