Skip to main content

Posts

Showing posts with the label ASP.NET(C#)

How to write Unit Tests in .net

Unit tests are automated tests that verify the behavior code like methods and functions. Writing unit tests is crucial to clean coding, as they help ensure your code works as intended and catches bugs early in the development process. I can share some tips for writing effective unit tests: Write tests for all public methods Every public method in your code should have a corresponding unit test. This helps ensure that your code behaves correctly and catches any unexpected behavior early. public class Calculator { public int Add(int a, int b) { return a + b; } } [TestClass] public class CalculatorTests { [TestMethod] public void Add_ShouldReturnCorrectSum() { // Arrange Calculator calculator = new Calculator(); int a = 1; int b = 2; // Act int result = calculator.Add(a, b); // Assert Assert.AreEqual(3, result); } } Test boundary conditions  Make sure to test boundary conditions, such a...

What to choose between .NET Core and .NET?

 .NET Framework is a better choice if you: you don't have enough time time to learn new technology. Need a stable environment to work in. Have nearer release schedules. you are already working on an existing app and extending its functionality. If already have an existing team with .NET expertise and building production-ready software. Do not want to deal with continuous upgrades and changes. Building Windows client applications using Windows Forms or WPF .NET Core is a better choice if you: IF you wanted to deploy your app on Windows, Linux, and Mac operating systems. Are not afraid of learning new things. Are not afraid of breaking and fixing things since .NET Core is not fully matured yet. When you are learning .NET. work on open source.

How To Deploy .net Core Application On Linux

Here, I can explain steps to deploy .net core application on linux machine. Step 1 - Publish your .net Core application: First, create a .net core application on VS; you can make an MVC project or Web API project and if you already have an existing project, then open it. Right Click on your project Click on publish Now create a new publish profile, and browse the folder where you want to publish your project dll Click on publish so it will create your dll in the folder Step 2 - Install required .net Module on Linux: Now we have our web application dll and now we need to host it on the Linux environment. First, we need to understand how the deployment works in Linux. .Net applications run on Kestrel servers and we run Apache or Nginx server in Linux environments, which acts as a proxy server and handles the traffic from outside the machine and redirects it to the Kestrel server so we will have Apache or Nginx server as the middle layer. In this article, we will use Apache as a proxy ser...

Avoiding Cross-Site Scripting (XSS) attacks in C# and .NET Core

In the real world of web development, security is paramount. Cross-site scripting (XSS) remains a prevalent threat, capable of compromising the integrity and confidentiality of web applications. For developers working with C# and .NET Core, fortifying against XSS vulnerabilities is imperative. In this article, we'll delve into practical techniques and examples to safeguard your web applications against XSS attacks. Understanding Cross-Site Scripting (XSS) XSS occurs when attackers inject malicious scripts into web pages viewed by other users. These scripts exploit vulnerabilities in the application's handling of user inputs, leading to unauthorized access, data theft, or manipulation. Understanding the types of XSS (e.g., reflected, stored, DOM-based) is crucial for devising effective defence strategies. Example Scenario Consider a simple web application—a comment section where users can post messages. Without proper validation and sanitization, this application is susceptible ...

Extracting Values from PDFs in .NET Core 8 without ASP.NET

Extracting data from PDF files is a common necessity for various tasks such as data analysis, content indexing, and information retrieval. While ASP.NET Core 8 offers robust tools for PDF manipulation, there are instances where developers may prefer alternatives for flexibility or specific project requirements. In this article, we'll explore how to extract values from PDF files within the .NET Core 8 ecosystem without relying on ASP.NET, using the PdfSharpCore library. We'll provide a step-by-step guide along with examples in C# to demonstrate how to accomplish this task effectively. Understanding PdfSharpCore: PdfSharpCore is a popular .NET library for PDF document manipulation. It provides functionalities to create, modify, and extract content from PDF files. In this guide, we'll focus on utilizing PdfSharpCore to extract text from PDF documents. Installing PdfSharpCore: Before we can start using PdfSharpCore in our .NET Core application, we need to install the PdfSharpCo...

Real-Time Data Transfer with Web Sockets and SignalR in .NET Core

 In dynamic web applications, real-time data transfer has become a crucial aspect of providing a responsive and interactive user experience. Web Socket technology, along with frameworks like SignalR in .NET Core, enables bidirectional communication between clients and servers, allowing seamless data exchange. In this article, we'll explore how to implement Web Socket functionality using SignalR in a .NET Core application to retrieve data from a concurrent dictionary and push it to clients in real time. Understanding Web Sockets and SignalR Web Socket is a communication protocol that provides full-duplex communication channels over a single TCP connection, allowing for low-latency, bidirectional communication between clients and servers. It enables real-time data transfer without the overhead of HTTP polling. SignalR is a high-level library built on top of Web Socket that simplifies real-time web functionality implementation in .NET applications. It abstracts away the complexities o...

How To Access Cookie Across Sub Domain In ASP.NET(C#).

Now a days Single Sign-On is a common need of organizations. Organizations want to use the same login details across their all application. Most of the times, internal applications are hosted on the same domain using Sub-Domains. If we observe the application level, all applications are different for every sub-domain. So, for that, we need to persist the Session or User Identity while accessing the applications. Here are some steps to achieve this in ASP.NET. Below are some of the configuration settings which you need to do in Web.config. <authentication mode="Forms">    <forms loginUrl="~/" name=".ASPXFORMSAUTH" timeout="20" domain=".xxxxxxxx.xxx" path="/" protection="All" enableCrossAppRedirects="true" />  </authentication> Here, you need to specify the parent domain with (.) so that it will get access of all sub domains of the parent domain. Add the above line to all applicatio...

Steps For Installing Visual Studio 2019 Preview and its new features.

This article explains how to install Visual Studio 2019 Preview in a step by step way. We can learn about a new feature of Visual Studio 2019 through this link . New Features Visual Studio 2019 Highlights on Develop, Collaboration, Debug, Azure, Technologies. We can know about the new features of Visual Studio 2019 Preview in here . Steps for installing Visual Studio 2019 Preview Step 1 : Using this link we are downloading Visual Studio 2019 Preview. Step 2 :  Click the "Download" button for downloading the VS 2019 executable file. Step 3: Find downloaded "vs_enterprise__1653779055.1544460128.exe". Open it and click on continue button for downloading.           Step 4 :  After completing the download and installation, then workloads will open. We need to select what are the workloads we need. Here, we selected ASP.NET and web development, .NET Core cross-platform devel...

What is CLR and Major Tasks of it in .NET

The Runtime Environment of .NET Framework is Called Common Language Runtime. CLR can be considered as Virtual Machine (VM) component of Microsoft's .NET framework. It manages the execution of Managed Code (.NET Programs). CLR uses a just-in-time (JIT) compiler which converts the compiled code of .NET into Native Code. Language Compilers (e.g. C#, VB.Net, J#) convert the .NET Program Code to Microsoft Intermediate Language (MSIL) and this is further converted to Native Code by JIT Compiler of CLR. Role/Features Of CLR  it provides many features like it loads and executes the code, manages the memory, converts the MSIL code to native code, and handles the exception. Major features of CLR: Memory Mangement Code Access security Garbage Collection JIT Compilation Thread Support Debug Engine Exception Handling 

New Features in Asp.Net Core

Features List : Cross-platform & container support High performance Asynchronous via async/await Unified MVC & Web API frameworks Multiple environments and development mode Dependency Injection WebSockets & SignalR Cross-Site Request Forgery (CSRF) Protection “Self-hosted” Web Applications Action Filters Extensible Output Caching Globalization and Localization Swagger OpenAPI Click here  to learn more

Difference Between Dynamic and Object Keyword in C#

The dynamic keyword and objects don't perform compile-time type checks and identify the type of objects at runtime only and both can store any type of the variable. Objects were introduced in 1.0 C#. Later, why was Dynamic introduced in 4.0 C# when Objects already exist. Difference 1 : Object: the Compiler has little information about the type. It's not compiler safe. You need to do an explicit type casting every time you want to get the value back and forth. object  a = "Nikhil Sangani"; string a1 = a.ToString(); Dynamic: In a dynamic variable, the compiler doesn't have any information about the type of variable. dynamic  a = "Nikhil Sangani"; string a1 = a; Difference 2 : Object: When using an object, you need to cast the object variable to the original type to use it and do the desired operations. In the first difference, the following example shows an error. object  a = "Nikhil Sangani"; string a1 = a; Now you need t...

Command Query Separation (CQS) in C#

CQS is the principle of development where we need to separate command from the query. It's a basic rule that a developer must follow. Segregation of command with the query is very important. Command: Which change the state of a system. In event-driven programming, the function that affects the system's state is a command. The method whose return type is void is supposed to be command type. Example: A button click event in web form is a command as it changes the state of the system. protected void register_Click(object sender, EventArgs e) {     // your code to registeration } Query :  The query can be defined as a method that has a return type. A query must return something. This is like you are asking something from the system. Example:  public bool IsValidUserName(string UserName) {     bool validUser = false;     //code to check user from db     //if user exist set validUser=true else false     return ...

Different Types of Software Design Principles

1. SOLID : It is a combination of five basic designing principles. A. Single Responsibility Principle (SRP) This principle states that there should never be more than one reason for a class to change. This means that you should design your classes in such a way that each class should have a single purpose. Example - An Account class is responsible for managing Current and Saving Account but a CurrentAccount and a Saving Account classes would be responsible for managing current and savings accounts respectively. Hence both are responsible for a single purpose only. Hence we are moving towards specialization. B. Open/Closed Principle (OCP) This principle states that software entities (classes, modules, functions, etc.) should be open for extension but closed for modification. The "closed" part of the rule states that once a module has been developed and tested, the code should only be changed to correct bugs. The "open" part says that you should be able to e...

Getting 'Cross-Origin Request Blocked' on a GET request.

In this article, I will explain how to avoid cross-origin error in Web API. Just add "cors" packages from NuGet package manager and add this code in WebApiConfig.cs file. using System.Web.Http.Cors; public static class WebApiConfig { public static void Register(HttpConfiguration config) { var corsAttr = new EnableCorsAttribute(BusLib.Config.Configuration.CorsOrigin, "*", "*"); config.EnableCors(corsAttr); } }

Prevent Duplicate(Double) Inserts when Page is refreshed in Asp.net(C#).

In this article I will explain the most common issue faced by many ASP.Net Developers i.e. Prevent Duplicate Insertion of Record on Page Refresh in ASP.Net. Duplicate Inserts and Double updates occur when a page is refreshed after an insert or update statement of SQL Server is executed and we get a following popup from the browser. After insert or update statement is executed you can redirect the user to the same page. Response.Redirect(Request.Url.AbsoluteUri);

Rotate a image.

Here I will explain how to rotate a image. public void FlipImage(string Filename, string NewFileName) { System.Drawing.Image img = System.Drawing.Image.FromFile(System.Web.Hosting.HostingEnvironment.MapPath("/images/") + Filename); //Rotate the image in memory img.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone); System.IO.File.Delete(System.Web.Hosting.HostingEnvironment.MapPath("/images/" + NewFileName)); //save the image out to the file img.Save(System.Web.Hosting.HostingEnvironment.MapPath("/images/" + NewFileName)); //release image file img.Dispose(); }

How to apply Basic Authentication In Web API.

Here, I will explain how to maintain security in webapi Step : 1 Create a method for validate loginname and tokenkey. if exists then return true otherwise return false. public static bool Vaidatecredentials(string loginname, string tokenkey) { // Check if it is valid credential if(true)//Check login name and token key exists in DB(loginname, password)) { return true; } else { return false; } } Step : 2 add a class, which is used as Authorization filter. The class BasicAuthenticationAttribute inherits from BasicAuthenticationAttribute abstarct class. public class BasicAuthenticationAttribute : AuthorizationFilterAttribute { public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) { if (actionContext.Request.Headers.Authorization == null) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unau...

Generating serial numbers and keys in Asp.net(C#).

here we are using GUID for generate serial numbers and GUID is always unique. Example format: XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX. Guid SerialKeyGuid = Guid.NewGuid(); string AccessKey = SerialKeyGuid.ToString("N"); string AccessKeyLength = AccessKey.Substring(0, 28).ToUpper(); char[] serialArray = AccessKeyLength.ToCharArray(); string SerialNumber = ""; int P = 0; for (int B = 0; B < 28; B++) {                 for (P = B; P < 4 + B; P++)                 {                     SerialNumber += serialArray[P];                 }                 if (P == 28)                 {                     break;                 }         ...

Store and Retrive Connection string from INI file or Configuration file.

Here I will explain how to store or retrive connection string in INI file or Configuration file. Add this namespace. using System.Runtime.InteropServices; using System.Text; Add  this code on your page. [DllImport("kernel32", CharSet = CharSet.Unicode)] static extern int GetPrivateProfileString(string Section, string Key, string Default, StringBuilder RetVal, int Size, string FilePath); [DllImport("kernel32")] static extern long WritePrivateProfileString(string section, string key, string val, string filePath); public void Write(string section, string key, string value) {      WritePrivateProfileString(section, key, value, System.Web.HttpRuntime.BinDirectory + "Config.ini"); } For Write in .ini file. Write("config", "IP", IP); Write("config", "DB", DB); Write("config", "U", Username); Write("config", "P", Password); Sample Config.ini File [config] IP=jGBat...

How to Generate Excel from JSON Data Using Asp.net(C#).

Here I will explain how to generate excel from json. I am using NPOI and Newtonsoft.Json third party dll for this. Download dll from here :  https://drive.google.com/file/d/0B2UW8NPznIKsdzJSWDBDX2xLSms/view JSON For Test : [   {     "ID" : "1",     "NAME" : "Nikhil Sangani",     "MOBILENO" : "123456789",     "DESIGNATION" : "Web Developer"  } ] First of all i am create aspx page design like this. <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">     <title></title> </head> <body>     <form id="form1" runat="server">     <div>         <table>             <tr>                 <td>                     JSON STRING :<asp:TextBox runat="server" ID="txtjsonstring"></asp:T...