To set up the AWS Cognito for the registration/login flow, follow these steps: First Flow: User Registration in Cognito1. Install the following NuGet packages in your .NET project: <PackageReference Include="Amazon.AspNetCore.Identity.Cognito" Version="3.0.1" /> <PackageReference Include="Amazon.Extensions.Configuration.SystemsManager" Version="5.0.0" /> <PackageReference Include="AWSSDK.SecretsManager" Version="3.7.101.27" /> Declare AWS configuration values in appsettings: "Region": "me-south-1", "UserPoolClientId": "UserPoolClientId", "UserPoolClientSecret": "UserPoolClientSecret", "UserPoolId": "me-south-pool" Additional Configuration Add authentication in program/startup files to enable sign-in with Cognito. 2. Create a CognitoUserPool with a unique ID in the controller: private readonly CognitoUserPool _pool; private readonly CognitoUserManager<CognitoUser> _userManager; var user = _pool.GetUser(registerUserRequest.LoginId); 3.Add user attributes (email, phone number, custom attributes) using user.Attributes.Add(). user.Attributes.Add(CognitoAttribute.Email.AttributeName, registerUserRequest.Email); user.Attributes.Add(CognitoAttribute.PhoneNumber.AttributeName, registerUserRequest.Mobile); user.Attributes.Add("custom:branch_code", registerUserRequest.BranchCode); user.Attributes.Add("custom:preferred_mode", preferedMode); 4. Create the user: cognitoResponse = await _userManager.CreateAsync(user, registerUserRequest.Password); Check cognitoResponse.Succeeded to determine if the user was created successfully. Second Flow: User Login with Cognito 1.Search for the user in Cognito using the login ID: var cognitoUser = await _userManager.FindByIdAsync(loginUserRequest.LoginId); 2.Set a password for the Cognito model: var authRequest = new InitiateSrpAuthRequest { Password = loginUserRequest.Password }; 3.Use StartWithSrpAuthAsync to get the session ID: var authResponse = await cognitoUser.StartWithSrpAuthAsync(authRequest); 4.Add MFA method and validate using MFA auth if needed. For MFA validation, set the MFA settings in Cognito:v ar authRequest = new RespondToMfaRequest { SessionID = validateLoginUserRequest.SessionId, MfaCode = validateLoginUserRequest.Otp, ChallengeNameType = ChallengeNameType.SMS_MFA }; authResponse = await cognitoUser.RespondToMfaAuthAsync(authRequest); Extract tokens from Cognito: authResponse.AuthenticationResult.IdToken authResponse.AuthenticationResult.RefreshToken Forgot Password Flow 1.Search for the user with LoginId in Cognito and call ForgotPasswordAsync: var user = await _userManager.FindByIdAsync(loginUserRequest.LoginId); await user.ForgotPasswordAsync(); 2.Optionally, call ConfirmForgotPassword method in Cognito. _userManager.ConfirmForgotPassword(userID, token, newPassword, CancellationToken cancellationToken) Here, understanding AWS Cognito Authentication Methods and Utilizing Them as Needed.
In this blog I'll show how you can use a CancellationToken in your ASP.NET Core action method to stop execution when a user cancels a request from their browser. This can be useful if you have long running requests that you don't want to continue using up resources when a user clicks "stop" or "refresh" in their browser. What is Cancellation Token in c#? Cancellation tokens in C# are used to signal that a task or operation should be cancelled. They allow for the cooperative cancellation of a task or operation, rather than aborting it forcibly. Why Use Cancellation Tokens? Here are some benefits of using cancellation tokens: Avoid resource leaks by freeing up un-managed resources linked to the task Stop further processing when a task is no longer needed Improve responsiveness by quickly responding to cancellations Easy propagation of cancel requests in child tasks Without cancellation logic, long-running tasks will continue processing in the background even if no longer needed. You can use cancellaiontoken in any action method or project. Here I am taking one example of .NET web API. Here, I have created a web API project in .NET, and the above image shows the default controller for the web API, which includes the WeatherForecastController. In that, I have added some log information and added one 10-second task delay that means when this line is executed it will wait for 10 seconds after the next line is executed. I have added task delay because it is better to understand CancellationToken. If we hit the URL /GetWeatherForecast then the request will run for 10s, and eventually will return the message. So now, what happens if the user refreshes the browser, halfway through the request? The browser never receives the response from the first request, but as you can see from the logs, the action method executes to completion twice - once for the first (canceled) request, and once for the second (refresh) request. Whether this is correct behavior will depend on your application. ASP.NET Core provides a mechanism for the webserver to signal when a request has been canceled using a CancellationToken. This is exposed as HttpContext.RequestAborted, but you can also inject it automatically into your actions using model binding. Using CancellationToken in your method CancellationTokens are lightweight objects that are created by a CancellationTokenSource. When a CancellationTokenSource is cancelled, it notifies all the consumers of the CancellationToken. This allows one central location to notify all of the code paths in your app that cancellation was requested. When cancelled, the IsCancellationRequested property of the cancellation token will be set to True, to indicate that the CancellationTokenSource has been cancelled. Lets consider the previous example again. We have a long-running action method . As it as an expensive method, we want to stop executing the action as soon as possible if the request is cancelled by the user. The following code shows how we can hook into the central CancellationTokenSource for the request, by injecting a CancellationToken into the action method, and passing the parameter to the Task.Delay call. MVC will automatically bind any CancellationToken parameters in an action method to the HttpContext.RequestAborted token, using the CancellationTokenModelBinder. This model binder is registered automatically when you call services.AddMvc() (or services.AddMvcCore()) in Startup.ConfigureServices(). With this small change, we can test out our scenario again. We'll make an initial request, which starts the long-running action, and then we'll reload the page. As you can see from the logs below, the first request never completes. Instead the Task.Delay call throws a TaskCancelledException when it detects that the CancellationToken.IsCancellationRequested property is true, immediately halting execution. Summary Users can cancel requests to your web app at any point, by hitting the stop or reload button on your browser. Typically, your app will continue to generate a response anyway, even though Kestrel won't send it to the user. If you have a long-running action method, then you may want to detect when a request is canceled, and stop execution. You can do this by injecting a CancellationToken into your action method, which will be automatically bound to the HttpContext.RequestAborted token for the request. You can check this token for cancellation as usual, and pass it to any asynchronous methods that support it. If the request is canceled, an OperationCanceledException or TaskCanceledException will be thrown.
Hosting your .NET application on an IIS (Internet Information Services) server allows it to be accessed and consumed over the internet by users. IIS is commonly used to host .NET applications and web APIs. Before you can host the application, ensure you have the following: A .NET web application or API built (for example using ASP.NET Core) A Windows Server machine with IIS installed and configured Permissions to remotely access the server over a network Follow this step-by-step guide to deploy your .NET Application on the IIS Server seamlessly. Step 1: Open your .NET Application in Visual Studio Open your application or project in Visual Studio and build the application. Step 2 : Publish the Application or project. Now, Right-click on your project and select the publish option. Here, select the folder and then click on next, and finish the publish setup. Now, Click on the publish button to publish your code to one folder. After, publishing is succeeded click on the open folder. You will see your published code in this folder. Step 3: Configure IIS on the Server Carry out these steps to prepare IIS for hosting the application. If IIS is not installed in your system, then first install the IIS on your machine. Open IIS Manager on the Windows Server Right-click on the Sites folder and click Add Website 3. Provide a name for the website, Set the physical path to the app folder, and select a port where you want to host the application. 4. Click OK to create the new IIS website. Step 4: Publish code to IIS Server. Now stop the website and open the folder that you have given in the Physical path while configuring it, by right-clicking on your website and selecting explore. Now, copy all the published files into your server folder. Once all the files are copied into the publish folder Start the website and click on Browse*: {Your port} (http) under browse website. you will see the output of your code on the server. If your project is based on MVC then Recycle Application pool is required. You can find your Application pool under the Application Pool section. Right-click on your website app pool and click on recycle. Conclusion: Hosting the application on IIS allows it to be reached by users from over the network and the internet. It handles request routing and security layers for serving the application.
If you want to have a list of constraints applied on a particular table in the SQL server, this will help you to get it in one go. DECLARE @TABLENAME VARCHAR(50) = '<table_name>' SELECT ObjectName ,TypeOfObject ,TypeOfConstraint ,ConstraintName ,ConstraintDescription FROM ( SELECT schema_name(t.schema_id) + '.' + t.[name] AS ObjectName ,CASE WHEN t.[type] = 'U' THEN 'Table' WHEN t.[type] = 'V' THEN 'View' END AS [TypeOfObject] ,CASE WHEN c.[type] = 'PK' THEN 'Primary key' WHEN c.[type] = 'UQ' THEN 'Unique constraint' WHEN i.[type] = 1 THEN 'Unique clustered index' WHEN i.type = 2 THEN 'Unique index' END AS TypeOfConstraint ,ISNULL(c.[name], i.[name]) AS ConstraintName ,SUBSTRING(column_names, 1, LEN(column_names) - 1) AS [ConstraintDescription] FROM sys.objects t LEFT OUTER JOIN sys.indexes i ON t.object_id = i.object_id LEFT OUTER JOIN sys.key_constraints c ON i.object_id = c.parent_object_id AND i.index_id = c.unique_index_id CROSS APPLY ( SELECT col.[name] + ', ' FROM sys.index_columns ic INNER JOIN sys.columns col ON ic.object_id = col.object_id AND ic.column_id = col.column_id WHERE ic.object_id = t.object_id AND ic.index_id = i.index_id ORDER BY col.column_id FOR XML path('') ) D(column_names) WHERE is_unique = 1 AND t.name = @TABLENAME AND t.is_ms_shipped <> 1 UNION ALL SELECT schema_name(fk_tab.schema_id) + '.' + fk_tab.name AS foreign_table ,'Table' ,'Foreign key' ,fk.name AS fk_ConstraintName ,cols.[name] + ' REFERENCES ' + schema_name(pk_tab.schema_id) + '.' + pk_tab.name + ' (' + c2.[name] + ')' FROM sys.foreign_keys fk INNER JOIN sys.tables fk_tab ON fk_tab.object_id = fk.parent_object_id INNER JOIN sys.tables pk_tab ON pk_tab.object_id = fk.referenced_object_id INNER JOIN sys.foreign_key_columns fk_cols ON fk_cols.constraint_object_id = fk.object_id INNER JOIN sys.columns cols ON cols.object_id = fk_cols.parent_object_id AND cols.column_id = fk_cols.parent_column_id INNER JOIN sys.columns c2 ON c2.object_id = fk_cols.referenced_object_id AND c2.column_id = fk_cols.referenced_column_id WHERE fk_tab.name = @TABLENAME OR pk_tab.name = @TABLENAME UNION ALL SELECT schema_name(t.schema_id) + '.' + t.[name] ,'Table' ,'Check constraint' ,con.[name] AS ConstraintName ,con.[definition] FROM sys.check_constraints con LEFT OUTER JOIN sys.objects t ON con.parent_object_id = t.object_id LEFT OUTER JOIN sys.all_columns col ON con.parent_column_id = col.column_id AND con.parent_object_id = col.object_id WHERE t.name = @TABLENAME UNION ALL SELECT schema_name(t.schema_id) + '.' + t.[name] ,'Table' ,'Default constraint' ,con.[name] ,col.[name] + ' = ' + con.[definition] FROM sys.default_constraints con LEFT OUTER JOIN sys.objects t ON con.parent_object_id = t.object_id LEFT OUTER JOIN sys.all_columns col ON con.parent_column_id = col.column_id AND con.parent_object_id = col.object_id WHERE t.name = @TABLENAME ) a ORDER BY ObjectName ,TypeOfConstraint ,ConstraintName Output: Enjoy.!
Stored procedures are an essential part of database management systems. They are used to execute frequently used queries and reduce the load on the database server. However, if not optimized correctly, they can cause performance issues. In this blog, we will discuss how to check the performance of a stored procedure. Steps to Check Performance of a SPROC Identify the SPROC: The first step is to identify the stored procedure that needs to be optimized. You can use SQL Server Management Studio (SSMS) to identify the stored procedure. Check Execution Time: Once you have identified the stored procedure, you can check its execution time. You can use the SET STATISTICS TIME ON command to check the execution time of the stored procedure. Check Query Plan: The next step is to check the query plan of the stored procedure. You can use the SET SHOWPLAN_TEXT ON command to check the query plan. Check Indexes: Indexes play a crucial role in the performance of a stored procedure. You can use the sp_helpindex command to check the indexes of the stored procedure. Check for Blocking: Blocking can cause performance issues in a stored procedure. You can use the sp_who2 command to check for blocking. Check for Deadlocks: Deadlocks can also cause performance issues in a stored procedure. You can use the DBCC TRACEON(1204) command to check for deadlocks. Examples : Here are some examples to help you understand how to check the performance of a stored procedure: To Try this queries yourself I am sharing the Table, Data, SP query so you can direct run and perform this queries : -- Step 1: Create a dummy table CREATE TABLE dbo.Orders ( OrderID INT PRIMARY KEY, CustomerID NVARCHAR(10), OrderDate DATETIME, ProductID INT, Quantity INT ); -- Step 2: Insert dummy data into the table INSERT INTO dbo.Orders (OrderID, CustomerID, OrderDate, ProductID, Quantity) VALUES (1, N'ALFKI', '2024-01-23', 101, 5), (2, N'ALFKI', '2024-01-24', 102, 3), (3, N'BONAP', '2024-01-25', 103, 7), (4, N'BONAP', '2024-01-26', 104, 2), (5, N'COSME', '2024-01-27', 105, 4); -- Step 3: Create a stored procedure CREATE PROCEDURE dbo.usp_GetOrdersByCustomer @CustomerID NVARCHAR(10) AS BEGIN SELECT * FROM dbo.Orders WHERE CustomerID = @CustomerID; END; Example 1: Check Execution Time SET STATISTICS TIME ON EXEC dbo.usp_GetOrdersByCustomer @CustomerID = N'ALFKI' SET STATISTICS TIME OFF Example 2: Check Query Plan SET SHOWPLAN_TEXT ON EXEC dbo.usp_GetOrdersByCustomer @CustomerID = N'ALFKI' SET SHOWPLAN_TEXT OFF Example 3: Check Indexes EXEC sp_helpindex 'dbo.usp_GetOrdersByCustomer' Example 4: Check for Blocking EXEC sp_who2 Example 5: Check for Deadlocks DBCC TRACEON(1204) Conclusion In conclusion, checking the performance of a stored procedure is essential to ensure that it runs efficiently. By following the steps mentioned above, you can identify the performance issues and optimize the stored procedure. I hope this blog helps you in optimizing your stored procedures. If you have any questions or suggestions, please feel free to leave a comment below.
As in recent work with the client, I got the question of finding the indexes to be applied on a particular table in the SQL server. If you want to have listed all the indexes from a particular table from the SQL server, then now you just have to write your table name in the variable and execute the below query. And see the result. DECLARE @TABLENAME VARCHAR(50) = '<table_name>' SELECT '[' + s.name + '].[' + sObj.name + ']' AS 'TableName' ,+ ind.name AS 'IndexName' ,ind.type_desc AS 'IndexType' ,STUFF(( SELECT ', [' + sc.name + ']' AS "text()" FROM syscolumns AS sc INNER JOIN sys.index_columns AS ic ON ic.object_id = sc.id AND ic.column_id = sc.colid WHERE sc.id = Obj.object_id AND ic.index_id = sind.indid AND ic.is_included_column = 0 ORDER BY key_ordinal FOR XML PATH('') ), 1, 2, '') AS 'IndexedColumns' FROM sysindexes AS sind INNER JOIN sys.indexes AS ind ON ind.object_id = sind.id AND ind.index_id = sind.indid INNER JOIN sysobjects AS sObj ON sObj.id = sind.id INNER JOIN sys.objects AS Obj ON Obj.object_id = sObj.id AND is_ms_shipped = 0 INNER JOIN sys.schemas AS s ON s.schema_id = Obj.schema_id WHERE ind.object_id = OBJECT_ID(@TABLENAME) AND ind.is_primary_key = 0 AND ind.is_unique = 0 AND ind.is_unique_constraint = 0 ORDER BY TableName ,IndexName; Output:
Are you grappling with performance issues in your project? Look no further—Application Insights is here to help! In this blog post, I'll guide you through the process of configuring and implementing Application Insights to supercharge your application's performance monitoring. Step 1: Installing the Application Insights Package The first crucial step is to integrate the Application Insights package into your project. Simply add the following PackageReference to your project file: <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.22.0" /> And Register service in Program.cs or Startup.cs : builder.Services.AddApplicationInsightsTelemetry(); builder.Services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>((module, o) => { module.EnableSqlCommandTextInstrumentation = true; }); Add connection string in appsettings.json : "ApplicationInsights": { "InstrumentationKey": "" } This sets the stage for a seamless integration of Application Insights into your application. Step 2: Unleashing the Power of Application Insights Now that the package is part of your project, let's dive into the benefits it brings to the table: 1. Identify Performance Bottlenecks Application Insights allows you to track the execution time of individual stored procedures, queries, and API calls. This invaluable information helps you pinpoint areas that require optimization, paving the way for improved performance. 2. Monitor Database Interactions Efficiently analyze the database calls made by specific APIs within your application. With this visibility, you can optimize and fine-tune database interactions for enhanced performance. 3. Comprehensive Error and Exception Tracking Application Insights goes beyond performance monitoring by providing detailed information about errors, traces, and exceptions. This level of insight is instrumental in effective troubleshooting, allowing you to identify and resolve issues swiftly. Step 3: Integration with Azure for Data Collection and Analysis To maximize the benefits of Application Insights, consider integrating it with Azure for comprehensive data collection and analysis. This step amplifies your ability to make informed decisions regarding performance optimization and problem resolution. In conclusion, Application Insights equips you with the tools needed to elevate your application's performance. By identifying bottlenecks, monitoring database interactions, and offering comprehensive error tracking, it becomes a cornerstone for effective troubleshooting and optimization. Stay tuned for more tips and insights on how to harness the full potential of Application Insights for a high-performing application!
Hosting an Angular application on IIS involves a few straightforward steps. Follow this step-by-step guide to seamlessly deploy your Angular project on IIS. Step 1: Open Your Angular Project in Visual Studio Code Review the build command in the package.json file. By default, it's usually set to ng build. Step 2: Run the Build Command Execute the ng build command in the terminal to compile your Angular application. This command creates a 'dist' folder, typically located at the specified output path in the angular.json file. Step 3: Install IIS Ensure that IIS is installed on your machine. You can install it through the "Turn Windows features on or off" option in the Control Panel. Step 4: Create a New Site in IIS Open the IIS Manager. In the Connections pane, right-click on the "Sites" node and select "Add Website." Fill in the required information, such as the Site name, Physical path to the folder , and choose a port. Step 5: Configure URL Rewrite (Optional) If your Angular application uses routing, consider configuring URL Rewrite for proper routing. Create a 'web.config' file in your 'dist' folder with the appropriate configurations. Here's a simple example of a web.config file for an Angular application with routing.This file helps configure how the server handles URL requests. ---------------------------------------------------------------------------------------------------------------- <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="Angular Routes" stopProcessing="true"> <match url=".*" /> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="/" /> </rule> </rules> </rewrite> <staticContent> <remove fileExtension=".json" /> <mimeMap fileExtension=".json" mimeType="application/json" /> </staticContent> </system.webServer> </configuration> ---------------------------------------------------------------------------------------------------------------- Step 6: Restart IIS After making these changes, restart IIS to apply the configurations. Step 7: Access Your Angular Application Open a web browser and navigate to http://localhost:yourport (replace 'yourport' with the specified port from Step 4). Now, your Angular application is hosted on IIS. Access it through the specified port. If any issues arise, check the IIS logs for more information. Customize these instructions based on your specific requirements and environment. Thanks!
In the dynamic landscape of data processing, Apache Kafka stands out as a robust and scalable distributed event streaming platform. This blog post aims to demystify Kafka, guiding you through its installation process step by step, and unraveling the concepts of topics, producers, and consumers. Understanding Kafka: 1. What is Kafka? Apache Kafka is an open-source distributed streaming platform that excels in handling real-time data feeds. Originally developed by LinkedIn, Kafka has evolved into a powerful solution for building scalable and fault-tolerant data pipelines. Installing Kafka: 2. Step-by-Step Installation Guide: Let's dive into the installation process for Kafka: Prerequisites: Before installing Kafka, ensure you have Java installed on your machine, as Kafka is built on Java. Download Kafka: Visit the official Apache Kafka website (https://kafka.apache.org/) and download the latest stable release. Unzip the downloaded file to your preferred installation directory. Start Zookeeper: Kafka relies on Zookeeper for distributed coordination. Navigate to the Kafka installation directory and start Zookeeper: bin/zookeeper-server-start.sh config/zookeeper.properties Start Kafka Broker: Open a new terminal window and start the Kafka broker: bin/kafka-server-start.sh config/server.properties Congratulations! You now have Kafka up and running on your machine. Kafka Concepts: 3. Topics: Definition: In Kafka, a topic is a category or feed name to which messages are published by producers and from which messages are consumed by consumers. Creation: Create a topic using the following command: kafka-topics.bat --create --topic MyTopics --bootstrap-server localhost:9092 --partitions 3 --replication-factor 1 List out Topics : To see all the topics will use following command : \bin\windows\kafka-topics.bat --list --bootstrap-server localhost:9092 4. Producers and Consumers: Producers: Producers are responsible for publishing messages to Kafka topics. You can create a simple producer using the following command: bin/kafka-console-producer.sh --topic myTopic --bootstrap-server localhost:9092 Consumers: Consumers subscribe to Kafka topics and process the messages. Create a consumer with: bin/kafka-console-consumer.sh --topic myTopic --bootstrap-server localhost:9092 --from-beginning Conclusion: Apache Kafka is a game-changer in the world of real-time data processing. By following this step-by-step guide, you've successfully installed Kafka and gained insights into key concepts like topics, producers, and consumers. Stay tuned for more in-depth Kafka tutorials as you explore the vast possibilities of this powerful streaming platform.