Tech Insights https://reactconf.org/ Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Wed, 10 Jan 2024 05:29:25 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 https://i0.wp.com/reactconf.org/wp-content/uploads/2023/11/cropped-reactconf.png?fit=32%2C32&ssl=1 Tech Insights https://reactconf.org/ 32 32 230003556 .NET 8 Release New Data Annotation in ASP.NET Core C# https://reactconf.org/net-8-release-data-annotation-in-asp-net-core-csharp/ https://reactconf.org/net-8-release-data-annotation-in-asp-net-core-csharp/#respond Wed, 10 Jan 2024 05:29:25 +0000 https://labpys.com/?p=2216 In this article, we will learn .NET 8 Release New Data Annotation in ASP.NET Core C#, along with explanations and code examples. Data Annotations in ASP.NET Core are attributes and …

The post .NET 8 Release New Data Annotation in ASP.NET Core C# appeared first on Tech Insights.

]]>
In this article, we will learn .NET 8 Release New Data Annotation in ASP.NET Core C#, along with explanations and code examples.

Data Annotations in ASP.NET Core are attributes and constraints that can be applied to an entity class or model properties to define validation rules.

  • Data Annotation attributes are used to control and validate input data either at the user interface level or at the database level.
  • Data annotations are a key feature of the .NET framework and can help make your code more efficient, easier to maintain, and more secure.

Required attribute

The Required attribute has been revised and has new parameters. In .NET 8 you can use DisallowAllDefaultValues property with the attribute so that the required attribute for the Guid member will work as expected.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {

        [Required(DisallowAllDefaultValues = true)]
        public Guid Id { get; set; }
    }
}

AllowedValues

AllowedValues is a new attribute that specifies which values are allowed for a string.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {
        [AllowedValues("Computer","Eelectronics","Mechanical")]
        public  string DepartmentName { get; set; }
        
    }
}

BASE64String

The Base64string attribute ensures that the content is a complaint Base64 string.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {
    [Base64String]
    public string Address { get; set; }     
    }
}

Range

Specify the numeric range constraints for the value of a property.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {
    [Range(0, 100, MinimumIsExclusive = true, MaximumIsExclusive = true)]
    public int Age { get; set; }        
    }
}

Length

The Length attribute has been extended so that the maximum length can now also be specified.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {
        [Length(8, 25)]
        public string Username { get; set; }
        
    }
}

DeniedValues

DeniedValues is a data annotation attribute in C# that specifies a list of values that are not allowed, it is the counterpart to allowedValues and prevents the specified values.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {

        [DeniedValues("Supervisor", "Operator")]
        public string UserRole { get; set; }
    }
}

See More: LINQ: Sort Multiple Columns using LINQ in C#

The post .NET 8 Release New Data Annotation in ASP.NET Core C# appeared first on Tech Insights.

]]>
https://reactconf.org/net-8-release-data-annotation-in-asp-net-core-csharp/feed/ 0 2216
Implement JWT Authentication and Authorization in ASP.NET Core https://reactconf.org/implement-jwt-authentication-and-authorization-in-asp-net-core/ https://reactconf.org/implement-jwt-authentication-and-authorization-in-asp-net-core/#respond Thu, 04 Jan 2024 07:06:38 +0000 https://reactconf.org/?p=290 JSON Web Token (JWT) is a common authentication method in modern web development  In this article, we will explore How to implement JWT Authentication and Authorization in ASP.NET Core application. …

The post Implement JWT Authentication and Authorization in ASP.NET Core appeared first on Tech Insights.

]]>
JSON Web Token (JWT) is a common authentication method in modern web development  In this article, we will explore How to implement JWT Authentication and Authorization in ASP.NET Core application.

Create an Asp.NET Core Web API Project

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project

  • Open the visual studio (IDE).
  • Click on the “Create new project” option.
  • Choose “ASP.NET Core Web API” from the list of available templates.
  • Click the Next button.
  • The configure a new project, specify the name and location of your project.
  • Click the “Next” button.
  • Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  • Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
  • Click the “Create” button

Install the JwtBearer NuGet Package

Add the “Microsoft.AspNetCore.Authentication.JwtBearer” NuGet package to your project.

  • Select the  project Solution in the Explorer window
  • Right-click and select “Manage NuGet Packages”
  • In the NuGet Package Manager window, search for the “Microsoft.AspNetCore.Authentication.JwtBearer”
  • Click on the Install button.

Another way to install the package “Microsoft.AspNetCore.Authentication.JwtBearer”   via Package Manager Console

Specify a Secret Key in the appsettings.json file

Add the following information in the appettings.json file.

 "JWT": {
   "key": "YouSecreteKeyforAuthenticationtovalidateApplication",
   "Issuer": "reactconf.org",
   "Audience": "reactconf.org"
 },

Configure JWT  authentication in the Program.cs file

using dotNet8CRUDWebAPI.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.


builder.Services.AddAuthentication(option =>
{
    option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    option.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(opt =>
{
    opt.TokenValidationParameters = new TokenValidationParameters
    {
     ValidIssuer = builder.Configuration["Jwt:Issuer"],
     ValidAudience= builder.Configuration["Jwt:Audience"],
     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])),
     ValidateIssuer=true,
     ValidateAudience=true,
     ValidateLifetime=false,
     ValidateIssuerSigningKey=true

    };
});
    
    
    
   
builder.Services.AddControllers();

builder.Services.AddSingleton<IDepartment,DepartmentServices>();
var app = builder.Build();

// Configure the HTTP request pipeline.


app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

Create a User Model in ASP.NET Core

For storing the login credentials of the users, we need to create a class named Login in the Model folder.

namespace dotNet8CRUDWebAPI.Model
{
    public class Login
    {
        public string username {  get; set; }
        public string password { get; set; }
    }
}

Generate JWT Tokens

We are Creating another controller named “TokenGenerate”  to generate and validate the JWT. Create action method “Post”,  this method generated token in response to an initial request to the API, then use it for authorization in all subsequent requests.

using dotNet8CRUDWebAPI.Model;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace dotNet8CRUDWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TokenGenerateController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        //private SymmetricSecurityKey _key;
       

        public TokenGenerateController(IConfiguration configuration)
        {
            _configuration = configuration;
           
        }
        [HttpPost]
        public IActionResult Post(Login  loginRequest)
        {
            if (loginRequest.username == "Admin" || loginRequest.password == "Passw0rd")
            {
                var issuer = _configuration["Jwt:Issuer"];
                var audience = _configuration["Jwt:Audience"];
                var _key =  Encoding.ASCII.GetBytes(_configuration["Jwt:Key"]);


                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new[]
                    {
                        new Claim("Id",Guid.NewGuid().ToString()),
                        new Claim(JwtRegisteredClaimNames.Sub, loginRequest.username),
                        new Claim(JwtRegisteredClaimNames.Email, loginRequest.username),
                        new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString())
                   }),

                    Expires = DateTime.UtcNow.AddMinutes(10),
                    Issuer = issuer,
                    Audience = audience,
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(_key), SecurityAlgorithms.HmacSha256Signature)
                };



                var tokenHandler = new JwtSecurityTokenHandler();
                var token = tokenHandler.CreateToken(tokenDescriptor);
                var jwttoken = tokenHandler.WriteToken(token);
                var stringToken = tokenHandler.WriteToken(token);
                return Ok(stringToken);
            }


            return Ok("Unauthorized");
        }
    }
}

Handling Authorization Checks

To handle authorization checks, you can use the [Authorize] attribute on controller and actions method.


namespace dotNet8CRUDWebAPI.Controllers
{
    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class DepartmentController : ControllerBase
    {
        private readonly IDepartment _department;

        public DepartmentController(IDepartment department)
        {
           _department = department;
        }

        [HttpGet]
        public IActionResult Get([FromQuery] bool? isActive=null)
        {
            return Ok(_department.GetAllList(isActive));
        }
   }
}

Now simply run the application or press F5 to run

Generate Token

Authorization Checks

See More: .NET 8: How to make API faster in Asp.Net Core

The post Implement JWT Authentication and Authorization in ASP.NET Core appeared first on Tech Insights.

]]>
https://reactconf.org/implement-jwt-authentication-and-authorization-in-asp-net-core/feed/ 0 290
.NET 8: How to make API faster in Asp.Net Core https://reactconf.org/net-8-how-to-make-api-faster-in-asp-net-core/ https://reactconf.org/net-8-how-to-make-api-faster-in-asp-net-core/#respond Wed, 03 Jan 2024 09:28:42 +0000 https://reactconf.org/?p=267 Developing a Web API is a common task in Web development and Mobile Apps, but improving the performance of API is the real challenge. In this article, we will explore …

The post .NET 8: How to make API faster in Asp.Net Core appeared first on Tech Insights.

]]>
Developing a Web API is a common task in Web development and Mobile Apps, but improving the performance of API is the real challenge. In this article, we will explore How to make API faster in .NET 8 Asp.Net Core using Distributed Caching (Redis).

Why Redis Cache?

Before we implementation of  Redis Cache, let’s understand why we need Redis Cache. In any application, fetching data from the database or any other different resources is a time-consuming process. To improve this, we use caching.

Redis Cache stores the frequently accessed data in-memory and retrieves it at a much faster rate compared to traditional databases.

Create an Asp.NET Core Web API Project

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project

  • Open the visual studio (IDE).
  • Click on the “Create new project” option.
  • Choose “ASP.NET Core Web API” from the list of available templates.
  • Click the Next button.
  • The configure a new project, specify the name and location of your project.
  • Click the “Next” button.
  • Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  • Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
  • Click the “Create” button

Install Redis

Install Redis Cache using NuGet Package or run the following command in Package Manager Console.

Implement distributed Caching?

Open the Program.cs file and configure.

using dotNet8CRUDWebAPI.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

builder.Services.AddOutputCache(option => option.DefaultExpirationTimeSpan = TimeSpan.FromMinutes(10))
    .AddStackExchangeRedisCache(opt =>
    {
        opt.InstanceName = "TodosWebAPI";
        opt.Configuration = "localhost";
    }
    );


var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseOutputCache();
app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Create a Model

namespace dotNet8CRUDWebAPI.Model
{
    public class TodoUserList
    {
        public int userId {  get; set; }
        public int id { get; set; }
        public string title { get; set; }
        public bool completed { get; set; }
    }
}

Create a Controller

Open the controller create action method and Add the [OutputCache] attribute.

using dotNet8CRUDWebAPI.Model;
using dotNet8CRUDWebAPI.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OutputCaching;

namespace dotNet8CRUDWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DepartmentController : ControllerBase
    {

        [HttpGet("GetDatafromOtherSource")]
        [OutputCache]
        public async Task<IActionResult> GetDatafromOtherSource()
        {
            using var httpClient = new HttpClient();
            var response = await httpClient.GetFromJsonAsync<TodoUserList[]>("https://jsonplaceholder.typicode.com/todos");
            return Ok(response); 
        }
    }
}

Now simply run the application or press F5 to run

As you can see, caching has allowed us to reduce the response time all the way down to 1.2 s.  that’s all I have to say for now, I hope you found this information helpful.

See More: .NET 8: ASP.Net Core Web API CRUD Operations

The post .NET 8: How to make API faster in Asp.Net Core appeared first on Tech Insights.

]]>
https://reactconf.org/net-8-how-to-make-api-faster-in-asp-net-core/feed/ 0 267
.NET 8: ASP.Net Core Web API CRUD Operations https://reactconf.org/net-8-asp-net-core-web-api-crud-operations/ https://reactconf.org/net-8-asp-net-core-web-api-crud-operations/#comments Tue, 02 Jan 2024 10:40:14 +0000 https://reactconf.org/?p=245 In .NET 8, Developing a CRUD (Create, Read, Update, Delete) API using In-memory collection is a common task in web development. In this article, we will explore building a complete …

The post .NET 8: ASP.Net Core Web API CRUD Operations appeared first on Tech Insights.

]]>
In .NET 8, Developing a CRUD (Create, Read, Update, Delete) API using In-memory collection is a common task in web development. In this article, we will explore building a complete .NET 8 ASP.NET Core Web API CRUD Operations. With a practical use case.

What is an API?

  • API stands for Application Programming Interface.
  • API is a software intermediary that allows different software applications to communicate and exchange data.

What is RESTful API?

  1. REST stands for Representational State Transfer.
  2. REST is a software architecture that imposes conditions on how an API should work.
  3. RESTful API is an interface that two computer systems use to exchange information securely over the internet.

Create an Asp.NET Core Web API Project

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project

  1. Open the visual studio (IDE).
  2. Click on the “Create new project” option.
  3. Choose “ASP.NET Core Web API” from the list of available templates.
  4. Click the Next button.
  5. The configure a new project, specify the name and location of your project.
  6. Click the “Next” button.
  7. Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  8. Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
  9. Click the “Create” button

Once the project is created, let’s delete the existing WeatherForecast controller and model file.

Let’s create a folder in the project named

  • Model
  • Services

Right-click on Solution -> Add-> New Folder

Creating a Model

Right-click on Model Folder and select Add then click on New Item then enter class Name (Department.cs) and press the Add button.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {

        public int Id { get; set; }
        public required string DepartmentName { get; set; }
        public string Description { get; set; } = string.Empty;
        public bool IsActive { get; set; } = true;
    }
}

For Adding and updating the department list create another model AddUpdatedepartment.cs

namespace dotNet8CRUDWebAPI.Model
{
    public class AddUpdateDepartment
    {

        public required string DepartmentName { get; set; }
        public string Description { get; set; } = string.Empty;
        public bool IsActive { get; set; } = true;
    }
}

Create Services

Create an interface, Right click on Services Folder select Add, and click on New Item then select an interface and enter Interface Name(IDepartment.cs), and press the Add button.

In the interface, we are going to define business logic.

using dotNet8CRUDWebAPI.Model;

namespace dotNet8CRUDWebAPI.Services
{
    public interface IDepartment
    {
        List<Department> GetAllList(bool? IsActive);
        Department? GetById(int id);
        Department AddDeparement(AddUpdateDepartment DeptObj);
        Department? UpdateDepartment(int id, AddUpdateDepartment DeptObj);
        bool DeleteDepartmentById(int id);

    }
}

Create a concrete class, Right click on Services Folder and select Add, and click on New Item then select the class and enter class Name(DepartmentServices.cs) and press the Add button.

In the concrete class, we are going to implement the interface.


using dotNet8CRUDWebAPI.Model;

namespace dotNet8CRUDWebAPI.Services
{
    public class DepartmentServices : IDepartment
    {
        private readonly List<Department> _departmentList;

        public DepartmentServices()
        {
            _departmentList = new List<Department>()
            {
                new Department()
                {
                    Id = 1,
                    DepartmentName= "Computer Science",
                    Description = "Head of Department",
                    IsActive = true,


                }
            };
        }
        public List<Department> GetAllList(bool? IsActive)
        {
            return IsActive== null ? _departmentList : _departmentList.Where(dept=>dept.IsActive==IsActive).ToList();
        }

        public Department? GetById(int id)
        {
            return _departmentList.FirstOrDefault(dept=>dept.Id==id);
         }


        public Department AddDeparement(AddUpdateDepartment DeptObj)
        {
            var AddDepartment = new Department()
            {
                Id = _departmentList.Max(id=> id.Id) + 1,
                DepartmentName = DeptObj.DepartmentName,
                Description = DeptObj.Description,
                IsActive =DeptObj.IsActive
            };
            _departmentList.Add(AddDepartment);

            return AddDepartment;
        }
              
        
        
        public Department? UpdateDepartment(int id, AddUpdateDepartment DeptObj)
        {
            var Deptindex = _departmentList.FindIndex(idx => idx.Id==id);

            if(Deptindex>0)
            {
                var Dept = _departmentList[Deptindex];
                Dept.DepartmentName = DeptObj.DepartmentName;
                Dept.Description = DeptObj.Description;
                Dept.IsActive = DeptObj.IsActive;

                _departmentList[Deptindex] = Dept;

                return Dept;

            }
            else
            {
                return null;
            }

        }

        public bool DeleteDepartmentById(int id)
        {
            var deptindex = _departmentList.FindIndex(idx => idx.Id == id);
            if (deptindex>0)
            {
                _departmentList.RemoveAt(deptindex);
            }
            return deptindex>0;
        }

    }
}

Creating a  Controller

Create a Controller, Right-click on Controller Folder select Add -> Controller -> API -> API Controller, and enter controller Name (DepartmentController.cs) and press the Add button.

  • Open the DepartmentController file
  • Create a constructor and inject the IDepartment interface
  • Create action methods
    • GET
    • POST
    • PUT
    • Delete
using dotNet8CRUDWebAPI.Model;
using dotNet8CRUDWebAPI.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace dotNet8CRUDWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DepartmentController : ControllerBase
    {
        private readonly IDepartment _department;

        public DepartmentController(IDepartment department)
        {
           _department = department;
        }

        [HttpGet]
        public IActionResult Get([FromQuery] bool? isActive=null)
        {
            return Ok(_department.GetAllList(isActive));
        }
        [HttpGet]
        [Route("{id}")]
        public  IActionResult Get(int id)
        {
            var dept = _department.GetById(id);
            if (dept == null)
            {
                return NotFound();
            }
            return Ok(dept);

        }

        [HttpPost]
        public IActionResult Post(AddUpdateDepartment obj)
        {
            var dept = _department.AddDeparement(obj);
            if(dept == null)
            {
                return BadRequest();
            }
            return Ok(new
            {
                message = "Deparment Created Successfully...!",
                id = dept!.Id
            });
        }

        [HttpPut]
        [Route("{id}")]
        public IActionResult Put([FromRoute] int id, [FromBody]  AddUpdateDepartment obj)
        {
            var dept = _department.UpdateDepartment(id, obj);
            if (dept == null)
            {
                return NotFound();
            }
            return Ok(new
            {
                message = "Deparement Updated Successfully...!",
                id = dept!.Id
            });
        }

        [HttpDelete]
        [Route("{id}")]
        public IActionResult Delete([FromRoute]int id)
        {
            
            if (!_department.DeleteDepartmentById(id))
            {
                return NotFound();
            }
            return Ok(new {
                message = "Department Deleted Successfully..!",
                id = id
            });
        }
    }
}

Register services

Open the Program.cs file and register IDepartment and DepartmentServices as an AddSingleton.

using dotNet8CRUDWebAPI.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

builder.Services.AddSingleton<IDepartment,DepartmentServices>();
var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Run the API Project

Get All Department List

Adding a Deparments

.NET 8: ASP.Net Core Web API CRUD Operations

Updating Department

.NET 8: ASP.Net Core Web API CRUD Operations

Delete a Department

.NET 8: ASP.Net Core Web API CRUD Operations

See More: How to Avoid Data Overload in EF Core

The post .NET 8: ASP.Net Core Web API CRUD Operations appeared first on Tech Insights.

]]>
https://reactconf.org/net-8-asp-net-core-web-api-crud-operations/feed/ 1 245
How to Avoid Data Overload in EF Core https://reactconf.org/how-to-avoid-data-overload-in-ef-core/ https://reactconf.org/how-to-avoid-data-overload-in-ef-core/#respond Fri, 29 Dec 2023 06:24:07 +0000 https://reactconf.org/?p=222 When working with Entity Framework Core. It’s very important to retrieve only the data you truly need from the database. In this article, we will learn How to avoid data …

The post How to Avoid Data Overload in EF Core appeared first on Tech Insights.

]]>
When working with Entity Framework Core. It’s very important to retrieve only the data you truly need from the database.

In this article, we will learn How to avoid data overload in EF Core, which improves the performance of applications.

It is a common mistake to retrieve the entire entities when only a subset of their properties is needed. This can lead to unnecessary data transfer, increased memory usage, and decreased performance. As you can see in the below code snippet.

           var customer = AppDbContext.Customer.ToList();

            foreach (var cust in customer)
            {
                Console.WriteLine($"{cust.Name} |  {cust.Address} | {cust.Type}");
            }         

To prevent data overload in EF Core, we will use projections to pick just the required fields and avoid retrieving unnecessary fields

 var customer = AppDbContext.Customer
                            .select(c => new { c.Name, c.Address, c.Type })
                            .ToList();

            foreach (var cust in customer)
            {
                Console.WriteLine($"{cust.Name} |  {cust.Address} | {cust.Type}");
            }

This above code snippet reduces the amount of data retrieved from the database minimizes memory usage, and improves the overall performance of your application.

See More: How to Check if a string is numeric in C#

The post How to Avoid Data Overload in EF Core appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-avoid-data-overload-in-ef-core/feed/ 0 222
C#: How to Check if a string is numeric in C# https://reactconf.org/how-to-check-if-a-string-is-numeric-in-csharp/ https://reactconf.org/how-to-check-if-a-string-is-numeric-in-csharp/#respond Wed, 27 Dec 2023 06:33:04 +0000 http://reactconf.org/?p=211 In this article, we will learn different ways to check if a string is numeric in c#. We’ll go through typical difficulties and obstacles, as well as best practices for …

The post C#: How to Check if a string is numeric in C# appeared first on Tech Insights.

]]>
In this article, we will learn different ways to check if a string is numeric in c#. We’ll go through typical difficulties and obstacles, as well as best practices for working with string and numeric data types in c#.

Create a Console Application

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new Console Application.

  • Open the visual studio (IDE).
  • Click on the “Create new project” option.
  • Choose “Console App” from the list of available templates.
  • Click the Next button.
  • The configure a new project, specify the name and location of your project.
  • Click the “Next” button.
  • Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  • Click the “Create” button

Use TryParse() method to check if a string is a numeric

The TrypParse() method is the simplest way to check if a string is numeric in c#. This method takes in a string and tries to parse it as an integer. If the string is a valid integer, then the method will return true and save the parsed integer value in the out parameter.

string stringvalue = "978912";
int numericvalue;
bool isNumber = int.TryParse(stringvalue, out numericvalue);
if (isNumber == true)
  {
    Console.WriteLine("String contain number");
}
else
{
    Console.WriteLine("String Not contain number");
}

Using Regular Expressions

Regular repression is extremely helpful when checking patterns within a string. And it makes pattern matching more versatile and powerful.

string stringvalue = "901287";
bool isNumber = Regex.IsMatch(stringvalue, @"^\d+$");

if (isNumber == true)
{
    Console.WriteLine("String contain number ");
}
else
{
    Console.WriteLine("String Not contain number");
}

The Regex.IsMatch method to check if the string contains only digits.

See More: Create a Login Form in React TypeScript

The post C#: How to Check if a string is numeric in C# appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-check-if-a-string-is-numeric-in-csharp/feed/ 0 211
AI Conference 2023 / 2024 https://reactconf.org/ai-conference-2023-2024/ https://reactconf.org/ai-conference-2023-2024/#respond Mon, 25 Dec 2023 10:03:48 +0000 http://reactconf.org/?p=144 Conference Alert is the one-stop source for the upcoming worldwide AI Conference 2023 / 2024. Discover AI-related conferences, meetings, seminars, workshops, and other events in 2023 and 2024. We provide …

The post AI Conference 2023 / 2024 appeared first on Tech Insights.

]]>
Conference Alert is the one-stop source for the upcoming worldwide AI Conference 2023 / 2024.

Discover AI-related conferences, meetings, seminars, workshops, and other events in 2023 and 2024.


We provide detailed information for each event, such as the conference name, date, location, organizer information, and conference program.

DateConferenceLocation
26 Dec, 2023International Conference on Computer Science and Artificial IntelligenceMelbourne, Australia
26 Dec, 2023International Conference on Logics in Artificial IntelligenceMontreal, Canada
26 Dec, 2023International Conference on Computer Science and Artificial IntelligenceSantiago, Chile
26 Dec, 2023International Conference on Computer Science and Artificial IntelligenceMexico City, Mexico
26 Dec, 2023International Conference on Logics in Artificial IntelligenceLas Vegas, USA
26 Dec, 2023International Conference on Advanced  Artificial IntelligenceShanghai, China
26 Dec, 2023International on Advance Artificial Intelligence and Software EngineeringTokyo, Japan  
Jan 24, 2024Data Science Salon Seattle: Retail & e-commerceSeattle, WA
Feb 21,2024DSS ATX | Using Generative AI & Machine LearningAustin, TX

See More: React Conference 2023 / 2024

The post AI Conference 2023 / 2024 appeared first on Tech Insights.

]]>
https://reactconf.org/ai-conference-2023-2024/feed/ 0 144
Create a Login Form in React TypeScript https://reactconf.org/create-a-login-form-in-react-typescript/ https://reactconf.org/create-a-login-form-in-react-typescript/#comments Mon, 25 Dec 2023 06:35:10 +0000 http://reactconf.org/?p=171 In this tutorial, we will learn How to Create a Login Form in React with Typescript and add styling and validation. in this post, we’ll use Vite to Create a …

The post Create a Login Form in React TypeScript appeared first on Tech Insights.

]]>
In this tutorial, we will learn How to Create a Login Form in React with Typescript and add styling and validation. in this post, we’ll use Vite to Create a React app for.

Prerequisites

Install Node.js and npm, the standard package manager for javascript.

Creating the React App

Once installed Node.js, create a new React app by running the following command with Vite.

Next, React app project name

√ Project name: ... Login_app

And give the package name

√ Package name: ... reactlogin

Select a Framework

? Select a framework: » – Use arrow keys. Return to submit.

Then select TypeScript

Open the application in vs code. Open the terminal in VS Code and run the following command

Create file Login.tsx and login.css

import { useState } from 'react'
import './Login.css'
import { BrowserRouter as Routers, Routes , Route, Navigate } from 'react-router-dom'
import HomePage from '../Home'
 

// eslint-disable-next-line @typescript-eslint/no-unused-vars
function Login(){

  const [email, setEmail] = useState("")
  const[password, setPassword] = useState("")
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const[emailError, setEmailError] = useState("")
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const[passwordError,setPasswordError]= useState("")
//  const navigate = useNavigate();

  const onButtonClick = () =>{
    setEmailError("")
    setPasswordError("")

    if("" === email){
      setEmailError("Please enter your email")
      return
    }

    if("" === password)
    {
      setPasswordError("Please enter a password")
      return
    }
    if(password.length<7){
      setPasswordError("password must be 8 character or longer")
      return
    }

    if(!/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/.test(email)){
      setEmailError("please enter a vlid email address")
      return
    }
   
    if(email){
      return(
      <>
      {
        <Routers>
          {
          <Routes>
            <Route path='/' element={<HomePage />}>

            </Route>
          </Routes>
    }
        </Routers>
      }
       
      </>
      )
    }else{
      return <Navigate to='/Component/Login/Login'/>
    }
  //navigate("../Home")

  }

    return(
        <div className="login-box">
  <h2>Login</h2>
  <form>
    <div className="user-box">
        <input  
        value={email}
        placeholder='Enter email address here' 
        onChange={ev=> setEmail(ev.target.value)}
        className={"user-box"}      
        
        />
      
      <label className='errorLabel'>{emailError}</label>
    </div>
    <div className="user-box">
      <input 
      value={password}
      placeholder='Enter password here'
      onChange={ev=>setPassword(ev.target.value)}
      className={'user-box'}
      
      />
      <label className='errorLabel'>{passwordError}</label>
    </div>
    <input onClick={onButtonClick}
      className={"inputButton"}
      type="button"      
      value={"Submit"}
    />
  </form>
</div>     
        
)
}

export default Login

Login.css

html {
  height: 100%;
}
body {
  margin:0;
  padding:0;
  font-family: sans-serif;
  background: linear-gradient(#141e30, #446891);
}

.login-box {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 400px;
  padding: 40px;
  transform: translate(-50%, -50%);
  background: rgba(0,0,0,.5);
  box-sizing: border-box;
  box-shadow: 0 15px 25px rgba(0,0,0,.6);
  border-radius: 10px;
}

.login-box h2 {
  margin: 0 0 30px;
  padding: 0;
  color: #fff;
  text-align: center;
}

.login-box .user-box {
  position: relative;
}

.login-box .user-box input {
  width: 100%;
  padding: 10px 0;
  font-size: 16px;
  color: #fff;
  margin-bottom: 30px;
  border: none;
  border-bottom: 1px solid #fff;
  outline: none;
  background: transparent;
}
.login-box .user-box label {
  position: absolute;
  top:0;
  left: 0;
  padding: 10px 0;
  font-size: 16px;
  color: #fff;
  pointer-events: none;
  transition: .5s;
}

.login-box .user-box input:focus ~ label,
.login-box .user-box input:valid ~ label {
  top: -20px;
  left: 0;
  color: #03e9f4;
  font-size: 12px;
}

.login-box form a {
  position: relative;
  display: inline-block;
  padding: 10px 20px;
  color: #03e9f4;
  font-size: 16px;
  text-decoration: none;
  text-transform: uppercase;
  overflow: hidden;
  transition: .5s;
  margin-top: 40px;
  letter-spacing: 4px
}

.login-box a:hover {
  background: #03e9f4;
  color: #fff;
  border-radius: 5px;
  box-shadow: 0 0 5px #03e9f4,
              0 0 25px #03e9f4,
              0 0 50px #03e9f4,
              0 0 100px #03e9f4;
}

.login-box a span {
  position: absolute;
  display: block;
}

.login-box a span:nth-child(1) {
  top: 0;
  left: -100%;
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, transparent, #03e9f4);
  animation: btn-anim1 1s linear infinite;
}

@keyframes btn-anim1 {
  0% {
    left: -100%;
  }
  50%,100% {
    left: 100%;
  }
}

.login-box a span:nth-child(2) {
  top: -100%;
  right: 0;
  width: 2px;
  height: 100%;
  background: linear-gradient(180deg, transparent, #03e9f4);
  animation: btn-anim2 1s linear infinite;
  animation-delay: .25s
}

@keyframes btn-anim2 {
  0% {
    top: -100%;
  }
  50%,100% {
    top: 100%;
  }
}

.login-box a span:nth-child(3) {
  bottom: 0;
  right: -100%;
  width: 100%;
  height: 2px;
  background: linear-gradient(270deg, transparent, #03e9f4);
  animation: btn-anim3 1s linear infinite;
  animation-delay: .5s
}

@keyframes btn-anim3 {
  0% {
    right: -100%;
  }
  50%,100% {
    right: 100%;
  }
}

.login-box a span:nth-child(4) {
  bottom: -100%;
  left: 0;
  width: 2px;
  height: 100%;
  background: linear-gradient(360deg, transparent, #03e9f4);
  animation: btn-anim4 1s linear infinite;
  animation-delay: .75s
}

@keyframes btn-anim4 {
  0% {
    bottom: -100%;
  }
  50%,100% {
    bottom: 100%;
  }
}

.mainContainer {
  flex-direction: column;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.titleContainer {
  display: flex;
  flex-direction: column;
  font-size: 64px;
  font-weight: bolder;
  align-items: center;
  justify-content: center;
}

.resultContainer, .historyItem { 
  flex-direction: row;
  display: flex;
  width: 400px;
  align-items: center;
  justify-content: space-between;
}

.historyContainer {
  flex-direction: column;
  display: flex;
  height: 200px;
  align-items: center;
  flex-grow: 5;
  justify-content: flex-start;
}

.buttonContainer {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 260px;
}

.inputContainer {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
}

.inputContainer > .errorLabel {
  color: red;
  font-size: 12px;
}

.inputBox {
  height: 48px;
  width: 400px;
  font-size: large;
  border-radius: 8px;
  border: 1px solid grey;
  padding-left: 8px;
}
input[type="button"] {
  border: none;
  background: cornflowerblue;
  color: white;
  padding: 12px 24px;
  margin: 8px;
  font-size: 15px;
  border-radius: 8px;
  cursor: pointer;
}

Open the App.tsx and call the login function

import './App.css'
import Login from './Login'

function MyApp() {

  return (
    <>
    <Login  />     
    </>
  )
}

export default MyApp

Run the application

npm run dev

Create a Login Form in React TypeScript

See More: React Conference 2023 / 2024

The post Create a Login Form in React TypeScript appeared first on Tech Insights.

]]>
https://reactconf.org/create-a-login-form-in-react-typescript/feed/ 1 171
How to Get the size of all Tables in a Database https://reactconf.org/sql-server-get-size-of-all-tables-in-a-database/ https://reactconf.org/sql-server-get-size-of-all-tables-in-a-database/#respond Tue, 19 Dec 2023 05:34:58 +0000 http://www.sqlneed.com/?p=534 In this guide, we will learn How to Get the size of all Tables in a Database using SQL Server. There are multiple ways, let’s take a look at them …

The post How to Get the size of all Tables in a Database appeared first on Tech Insights.

]]>
In this guide, we will learn How to Get the size of all Tables in a Database using SQL Server. There are multiple ways, let’s take a look at them one by one.

#Solution-1: SQL Query

The query joins information from the system catalog views such as “sys.tables”, “sys.indexes”, ”sys.partitions”, and “sys.allocation_units” to calculate the size of each table in KB(kilobytes) and as well as MB(megabytes).

It provides a detailed overview of all tables in the specified database, including the table name row count, total size, used size, and unused side. The results are ordered by total size in descending order, so you can easily identify the largest tables.

SELECT 
    t.name AS TableName,
    s.name AS SchemaName,
    p.rows,
    SUM(a.total_pages) * 8 AS TotalSpaceInKB, 
    CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS TotalSpaceInMB,
    SUM(a.used_pages) * 8 AS UsedSpaceKB, 
    CAST(ROUND(((SUM(a.used_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS UsedSpaceInMB, 
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceInKB,
    CAST(ROUND(((SUM(a.total_pages) - SUM(a.used_pages)) * 8) / 1024.00, 2) AS NUMERIC(36, 2)) AS UnusedSpaceInMB
FROM 
    sys.tables t
INNER JOIN      
    sys.indexes i ON t.object_id = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.object_id AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN 
    sys.schemas s ON t.schema_id = s.schema_id
WHERE 
    t.name NOT LIKE 'dt%' 
    AND t.is_ms_shipped = 0
    AND i.object_id > 255 
GROUP BY 
    t.name, s.name, p.rows
ORDER BY 
    TotalSpaceInMB DESC, t.name;

Results:

How to Get size of all Tables in a Database

#Solution-2:CTE Query

with CTE as (  
  SELECT  
  t.name as TableName,  
  SUM (s.used_page_count) as used_pages_count,  
  SUM (CASE  
              WHEN (i.index_id < 2) THEN (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)  
              ELSE lob_used_page_count + row_overflow_used_page_count  
          END) as pages  
  FROM sys.dm_db_partition_stats  AS s   
  JOIN sys.tables AS t ON s.object_id = t.object_id  
  JOIN sys.indexes AS i ON i.[object_id] = t.[object_id] AND s.index_id = i.index_id  
  GROUP BY t.name  
  )  
  ,cte2 as(select  
      cte.TableName,   
      (cte.pages * 8.) as TableSizeInKB,   
      ((CASE WHEN cte.used_pages_count > cte.pages   
                  THEN cte.used_pages_count - cte.pages  
                  ELSE 0   
            END) * 8.) as IndexSizeInKB  
  from CTE  
 )  
 select TableName,TableSizeInKB,IndexSizeInKB,  
 case when (TableSizeInKB+IndexSizeInKB)>1024*1024   
 then cast((TableSizeInKB+IndexSizeInKB)/1024*1024 as varchar)+'GB'  
 when (TableSizeInKB+IndexSizeInKB)>1024   
 then cast((TableSizeInKB+IndexSizeInKB)/1024 as varchar)+'MB'  
 else cast((TableSizeInKB+IndexSizeInKB) as varchar)+'KB' end [TableSizeIn+IndexSizeIn]  
 from CTE2  
 order by 2 desc

Result:

How to Get size of all Tables in a Database

#Solution-3:T-SQL |Stored Procedure

-- Using T-SQL
DECLARE @table_name sysname 
DECLARE table_list_cursor 
CURSOR FOR SELECT TABLE_NAME from INFORMATION_SCHEMA.TABLES 
where TABLE_TYPE='BASE TABLE' 
IF EXISTS ( SELECT * FROM    tempdb.INFORMATION_SCHEMA.COLUMNS WHERE    table_name = '##TABLE_RES')
BEGIN    
DROP TABLE ##TABLE_RES END CREATE TABLE ##TABLE_RES( Name nvarchar(255), 
Rows int, reserved varchar(18), Data varchar(18), index_size varchar(18),
Unused varchar(18)) OPEN table_list_cursor 
FETCH NEXT FROM table_list_cursor INTO @table_name 
INSERT INTO ##TABLE_RES exec sp_spaceused @table_name
WHILE @@FETCH_STATUS = 0 
BEGIN    FETCH NEXT FROM table_list_cursor INTO @table_name
INSERT INTO ##TABLE_RES exec sp_spaceused @table_name 
END CLOSE table_list_cursor 
DEALLOCATE table_list_cursor 
SELECT * from ##TABLE_RES order by rows desc
How to Get size of all Tables in a Database

#Solution-4: To Get the size of all tables in the SQL Server Database

In SQL Server, it is an easier way to get the size of all tables in the database is to use the Standard Report feature available in SQL Server Management Studio.

  • Open the SSMS (SQL Server Management Studio)
  • Now, Right Click on the Selected Database.
  • Select Reports
  • Next, Select Standard Reports
  • Then Click on Disk Usage by Table
How to Get size of all Tables in a Database using SQL Server

Output:

See Also:

The post How to Get the size of all Tables in a Database appeared first on Tech Insights.

]]>
https://reactconf.org/sql-server-get-size-of-all-tables-in-a-database/feed/ 0 534
React Conference 2023 / 2024 https://reactconf.org/react-conference-2023-2024/ https://reactconf.org/react-conference-2023-2024/#respond Thu, 30 Nov 2023 09:21:51 +0000 http://reactconf.org/?p=101 Every year, React developers from all around the world gather at the React Conference 2023 / 2024 to learn about the most recent developments in the React ecosystem. The conference …

The post React Conference 2023 / 2024 appeared first on Tech Insights.

]]>
Every year, React developers from all around the world gather at the React Conference 2023 / 2024 to learn about the most recent developments in the React ecosystem. The conference offers a variety of presentations, workshops, and networking opportunities.

See More: How Generative AI Impact on Software Engineering

The post React Conference 2023 / 2024 appeared first on Tech Insights.

]]>
https://reactconf.org/react-conference-2023-2024/feed/ 0 101