Tag - .NET-5

Implementing Facebook Authentication in ASP.NET: A Step-by-Step Guide
Mar 18, 2024

Introduction: Integrating Facebook authentication into your .NET project offers a user-friendly login option, allowing users to sign in with their Facebook credentials. This guide will walk you through the steps to implement Facebook login, enhancing user convenience, trust, and providing access to user data. Creating a Demo for Facebook Authentication in .NET Step 1: Set Up .NET Project  1. Create a new ASP.NET MVC project using Visual Studio or your preferred IDE.  Step 2: Create Facebook Developer App  2. Go to the [Facebook Developer Portal] : https://developers.facebook.com/ 3. Create a new app.  4. Configure the app details and obtain the App ID and App Secret.     Step 3: Configure Facebook Authentication in .NET Project  5. In your .NET project, open `Startup.cs`.  6. Configure Facebook authentication:  services.AddAuthentication(options =>     {         options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;         options.DefaultChallengeScheme = FacebookDefaults.AuthenticationScheme;     })    .AddCookie()     .AddFacebook(options =>     {         options.AppId = "Your-Facebook-App-ID";         options.AppSecret = "Your-Facebook-App-Secret";         options.CallbackPath = new PathString("/Auth/FacebookCallback");    });  Step 4: Create AuthController  7. Create an `AuthController` with actions for Facebook login and callback:  public class AuthController : Controller     {         public IActionResult Index()         {             return View();         }         [HttpGet]         [Route("signin-facebook")]         public async Task<IActionResult> FacebookCallback()         {             var result = await HttpContext.AuthenticateAsync("Facebook");             if (result.Succeeded)             {                 // Authentication succeeded. Add your logic here.                 return RedirectToAction("Index", "Home");             }             // Authentication failed. Handle the error.             return RedirectToAction("Login", "Account");         }         public IActionResult FacebookLogin()         {             var properties = new AuthenticationProperties             {                 RedirectUri = Url.Action("https://localhost:7135/Auth/FacebookCallback"),             };              return Challenge(properties, FacebookDefaults.AuthenticationScheme);         }     }  Step 5: Implement Facebook Login Button  8. In your `Index.cshtml` or another appropriate view, add a button for Facebook login: <h1>Facebook Authentication</h1>  <button class="btn btn-primary"><a style="color:white" asp-controller="Auth" asp-action="FacebookLogin">Login with Facebook</a></button>  Step 6: Update App Settings  9. In the Facebook Developer Portal, update the "Valid OAuth Redirect URIs" with `https://localhost:7135/Auth/FacebookCallback`.    Login Facebook > Settings. Step 7: Run and Test  10. Run your .NET project and test the Facebook authentication by clicking the "Login with Facebook" button.      Click on Login with Facebook > Continue. You can create Successful login in redirect logic. You Can also use JavaScript SDK to use authenticate in Your project I n our case will use MVC    Here will use the same app we already create just we will Update the controller action to JS function provided by "Meta Developer" Quick Start Add this JavaScript code in your view where your login button is available  <button class="btn btn-primary"><a style="color:white" onclick="loginWithFacebook()">Login with Facebook</button> <script> window.fbAsyncInit = function () { FB.init({ appId: '1438230313570431', xfbml: true, version: 'v19.0' }); FB.AppEvents.logPageView(); }; (function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) { return; } js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); function loginWithFacebook() { FB.login(function (response) { if (response.authResponse) { // User is logged in and authorized your app console.log('Successful login for: ' + response.authResponse.userID); console.log(response); debugger; window.location = "https://localhost:44304/Auth/SuccesfullLogin"; } else { // User cancelled login or did not authorize your app console.log('Login cancelled'); } }, { scope: 'public_profile,email' }); // Specify the required permissions } </script> Now we Have to add js.src link in your JS functions is need to be Added in Meta developer App In our case it is :   https://connect.facebook.net/en_US/sdk.js will go to again Use cases > customize > settings.  Will add our link in "Allowed Domains for the JavaScript SDK" section Make sure "Login with the JavaScript SDK" toggle is "Yes". Now, you have a comprehensive guide for creating a demo on Facebook authentication in a .NET project. Share this guide, and users can follow each step to implement Facebook login functionality in their ASP.NET applications. 

API Fixed response
Feb 03, 2024

Simplifying API Responses with AutoWrapper.Core in .NET Core. Handling API responses effectively is a crucial aspect of building robust and user-friendly applications. In .NET Core applications, the AutoWrapper.Core library comes to the rescue, providing a streamlined way to structure and standardize API responses. In this blog post, we'll explore how to use AutoWrapper.Core to create fixed responses for different status codes in your API. Firstly, you'll need to install the AutoWrapper.Core NuGet package. Add the following line to your project's .csproj file: <PackageReference Include="AutoWrapper.Core" Version="4.5.1" /> This package simplifies the process of handling API responses and ensures a consistent format for success, error, and data messages.   Example: Login Method Let's consider a common scenario, the login method, where we want to ensure fixed responses for both successful and unsuccessful attempts. [HttpPost("Login")] public async Task<ApiResponse> Login([FromBody] Login model) { var user = await _userService.GetUserByName(model.UserName); if (user != null && await _userService.CheckUserPassword(user, model.Password)) { var userResponse = await _tokenService.GenerateToken(user); return new ApiResponse(message: "Login Successfully.", result: userResponse, statusCode: 200); } return new ApiResponse(message: "Invalid Credential.", result: null, statusCode: 401); } In this example, we're using AutoWrapper.Core's ApiResponse class to encapsulate our responses. For a successful login attempt (status code 200), we return a positive message along with the user response. In case of invalid credentials (status code 401), an appropriate error message is provided. ApiResponse Class Now, let's take a closer look at the ApiResponse class from AutoWrapper.Core: namespace AutoWrapper.Wrappers; public class ApiResponse { public string Version { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int StatusCode { get; set; } public string Message { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? IsError { get; set; } public object ResponseException { get; set; } public object Result { get; set; } [JsonConstructor] public ApiResponse(string message, object result = null, int statusCode = 200, string apiVersion = "1.0.0.0") { StatusCode = statusCode; Message = message; Result = result; Version = apiVersion; } public ApiResponse(object result, int statusCode = 200) { StatusCode = statusCode; Result = result; } public ApiResponse(int statusCode, object apiError) { StatusCode = statusCode; ResponseException = apiError; IsError = true; } public ApiResponse() { } } The ApiResponse class provides flexibility in constructing responses with different components such as the message, result, and status code. It helps maintain a standardized format for all API responses. Create a Custom Wrapper: AutoWrapper allows you to create a custom wrapper by implementing the IApiResponse interface. You can create a class that implements this interface to customize the fixed response. Here's an example: Create a Custom Wrapper: AutoWrapper allows you to create a custom wrapper by implementing the IApiResponse interface. You can create a class that implements this interface to customize the fixed response. Here's an example: using AutoWrapper.Wrappers; public class CustomApiResponse<T> : ApiResponse<T> { public string CustomProperty { get; set; } public CustomApiResponse(T result, string customProperty) : base(result) { CustomProperty = customProperty; } } Configure AutoWrapper: In your Startup.cs file, configure AutoWrapper to use your custom wrapper. You can do this in the ConfigureServices method: services.AddAutoWrapper(config => { config.UseCustomSchema<CustomApiResponse<object>>(); }); Replace CustomApiResponse<object> with the custom wrapper class you created. Use Custom Wrapper in Controller Actions: Now, you can use your custom wrapper in your controller actions. For example: [ApiController] [Route("api/[controller]")] public class MyController : ControllerBase { [HttpGet] public IActionResult Get() { // Your logic here var data = new { Message = "Hello, World!" }; // Use the custom wrapper var response = new CustomApiResponse<object>(data, "CustomProperty"); return Ok(response); } } Customize the CustomApiResponse according to your needs, and use it in your controller actions. This way, you can integrate AutoWrapper with other packages and customize the fixed response format in your .NET application.   In conclusion, by incorporating AutoWrapper.Core into your .NET Core applications, you can simplify the handling of API responses, making your code more readable, maintainable, and user-friendly. Consider adopting this approach to enhance the overall developer experience and ensure consistency in your API communication.

Create SSIS Data Flow Task Package Programmatically
Jul 27, 2020

In this article, we will review how to create a data flow task package of SSIS in Console Application with an example. Requirements Microsoft Visual Studio 2017 SQL Server 2014 SSDT Article  Done with the above requirements? Let's start by launching Microsoft Visual Studio 2017. Create a new Console Project with .Net Core.  After creating a new project, provide a proper name for it. In Project Explorer import relevant references and ensure that you have declared namespaces as below: using Microsoft.SqlServer.Dts.Pipeline.Wrapper; using Microsoft.SqlServer.Dts.Runtime; using RuntimeWrapper = Microsoft.SqlServer.Dts.Runtime.Wrapper;   To import above namespaces we need to import below refrences.   We need to keep in mind that, above all references should have same version.   After importing namespaces, ask user for the source connection string, destination connection string and table that will be copied to destination. string sourceConnectionString, destinationConnectionString, tableName; Console.Write("Enter Source Database Connection String: "); sourceConnectionString = Console.ReadLine(); Console.Write("Enter Destination Database Connection String: "); destinationConnectionString = Console.ReadLine(); Console.Write("Enter Table Name: "); tableName = Console.ReadLine();   After Declaration, create instance of Application and Package. Application app = new Application(); Package Mipk = new Package(); Mipk.Name = "DatabaseToDatabase";   Create OLEDB Source Connection Manager to the package. ConnectionManager connSource; connSource = Mipk.Connections.Add("ADO.NET:SQL"); connSource.ConnectionString = sourceConnectionString; connSource.Name = "ADO NET DB Source Connection";   Create OLEDB Destination Connection Manager to the package. ConnectionManager connDestination; connDestination= Mipk.Connections.Add("ADO.NET:SQL"); connDestination.ConnectionString = destinationConnectionString; connDestination.Name = "ADO NET DB Destination Connection";   Insert a data flow task to the package. Executable e = Mipk.Executables.Add("STOCK:PipelineTask"); TaskHost thMainPipe = (TaskHost)e; thMainPipe.Name = "DFT Database To Database"; MainPipe df = thMainPipe.InnerObject as MainPipe;   Assign OLEDB Source Component to the Data Flow Task. IDTSComponentMetaData100 conexionAOrigen = df.ComponentMetaDataCollection.New(); conexionAOrigen.ComponentClassID = "Microsoft.SqlServer.Dts.Pipeline.DataReaderSourceAdapter, Microsoft.SqlServer.ADONETSrc, Version=14.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"; conexionAOrigen.Name = "ADO NET Source";   Get Design time instance of the component and initialize it. CManagedComponentWrapper instance = conexionAOrigen.Instantiate(); instance.ProvideComponentProperties();   Specify the Connection Manager. conexionAOrigen.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.GetExtendedInterface(connSource); conexionAOrigen.RuntimeConnectionCollection[0].ConnectionManagerID = connSource.ID;   Set the custom properties. instance.SetComponentProperty("AccessMode", 0); instance.SetComponentProperty("TableOrViewName", "\"dbo\".\"" + tableName + "\"");   Reinitialize the source metadata. instance.AcquireConnections(null); instance.ReinitializeMetaData(); instance.ReleaseConnections();   Now, Add Destination Component to the Data Flow Task. IDTSComponentMetaData100 conexionADestination = df.ComponentMetaDataCollection.New(); conexionADestination.ComponentClassID = "Microsoft.SqlServer.Dts.Pipeline.ADONETDestination, Microsoft.SqlServer.ADONETDest, Version=14.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"; conexionADestination.Name = "ADO NET Destination";   Get Design time instance of the component and initialize it. CManagedComponentWrapper instanceDest = conexionADestination.Instantiate(); instanceDest.ProvideComponentProperties();   Specify the Connection Manager. conexionADestination.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.GetExtendedInterface(connDestination); conexionADestination.RuntimeConnectionCollection[0].ConnectionManagerID = connDestination.ID;   Set the custom properties. instanceDest.SetComponentProperty("TableOrViewName", "\"dbo\".\"" + tableName + "\"");   Connect the source to destination component: IDTSPath100 union = df.PathCollection.New(); union.AttachPathAndPropagateNotifications(conexionAOrigen.OutputCollection[0], conexionADestination.InputCollection[0]);   Reinitialize the destination metadata. instanceDest.AcquireConnections(null); instanceDest.ReinitializeMetaData(); instanceDest.ReleaseConnections();   Map Source input Columns and Destination Columns foreach (IDTSOutputColumn100 col in conexionAOrigen.OutputCollection[0].OutputColumnCollection) {     for (int i = 0; i < conexionADestination.InputCollection[0].ExternalMetadataColumnCollection.Count; i++)     {         string c = conexionADestination.InputCollection[0].ExternalMetadataColumnCollection[i].Name;         if (c.ToUpper() == col.Name.ToUpper())         {             IDTSInputColumn100 column = conexionADestination.InputCollection[0].InputColumnCollection.New();             column.LineageID = col.ID;             column.ExternalMetadataColumnID = conexionADestination.InputCollection[0].ExternalMetadataColumnCollection[i].ID;         }     } }   Save Package into the file system. app.SaveToXml(@"D:\Workspace\SSIS\Test_DB_To_DB.dtsx", Mipk, null);   Execute package. Mipk.Execute(); Conclusion In this article, we have explained one of the alternatives for creating SSIS packages using .NET console application. In case you have any questions, please feel free to ask in the comment section below.   RELATED BLOGS: Basics of SSIS(SQL Server Integration Service)

Highlights of Upcoming .NET 5
Jul 06, 2020

Microsoft Announces .NET 5 Microsoft announces that the next release after .Net core 3.0 will be .NET 5. .NET 5 will be the big release in the .NET family. You will able to use it to target Windows, Linux, Android, iOS, macOS, tvOS, watchOS, WebAssembly, and more. Microsoft will introduce new .NET APIs, language features, and runtime capabilities as a part of .NET 5. Microsoft intends to release .NET 5 in November 2020, with the first preview available in the first half of 2020. It will be supported with future updates to Visual Studio 2019, Visual Studio for Mac, and Visual Studio Code. .Net 5 Moves Ahead with .NET Core   .NET Core Functionalities: Cross-platform implementation in any device Support all key platform features for .net core, .Net Framework, xamarin Open-source and community-Oriented Support with future updates to Visual Studio Code, Visual Studio 2019, Command Line Interface, and Visual Studio for Mac. Fast, Scalable and High Performance Side-by-side installation Support for platform-specific features like Windows Forms, & WPF on Windows Smarter Deployment & packages Small projects Files   Three New major supports for developers Java Interoperability will be available on all  Swift and Objective-C Interoperability will be supported  on all multiple operating systems CoreFX will be extended to support static compilation of .Net, smaller footprints, and support for more operating systems.   The Other Highlights Features   Desktop Development with .NET 5 .NET 5 will come up with all key desktop development functionalities and libraries. WPF, Windows Forms, UWP, and xamarin are the four key desktop platforms.   Mobile Development with .NET .Net 5 will continue to build cross-platform mobile apps for Android, iOS, tvOS, macOS, and watchOS platforms using Xamarin.   Runtime and Language with .Net 5 Mono is the original cross-platform implementation of .NET. It started out as an open-source alternative to  .NET Framework and transitioned to targeting mobile devices like Android and iOS devices popular. CoreCLR is runtime used as part of .NET Core. It has been primarily targeted at supporting cloud applications, including the largest services at Microsoft and now is also being used for windows desktop, IOT, and machine learning applications.   Cloud Development with .NET 5 The major functionality of .Net 5 is Azure app Development. With the release of the latest version of .Net, developers will continue to develop software with Azure.   Game Development with .Net 5 Visual studio 2019 and .Net 5 will support utility, a vital part of .Net gaming to develop games for mobile and other gaming platforms.