Saturday, 1 April 2023

Generate C# .NET Classes of entire database through SQL Scripts Automatically

Let's learn how to generate C# Classes from SQL Scripts. Generate C# classes automatically for the entire database.


Step 1: Copy the query below and run it in the SQL Editor (New Query).
Step 2: Pass the table name as a parameter and run the query.

You can find the entire class in the output below.

DECLARE @TableName sysname = '' 
DECLARE @objectId int=1

      WHILE EXISTS (select 1 from sys.objects where type='U' and 
		    name!='__RefactorLog' and object_id > @objectId)
      BEGIN          
        SELECT @objectId = MIN(object_id) FROM sys.objects 
			   WHERE TYPE='U' and NAME!='__RefactorLog' 
			   AND object_id > @objectId    
		
SET @TableName=(SELECT NAME FROM sys.objects WHERE object_id=@objectId)

DECLARE @Output VARCHAR(MAX) = 'public class ' + @TableName + ' {' SELECT @Output = @Output + ' public ' + ColumnType + NullSign + ' ' + ColumnName + ' { get; set; }' FROM ( SELECT replace(col.name, ' ', '_') ColumnName, column_id ColumnId, CASE typ.NAME WHEN 'bigint' THEN 'long' WHEN 'binary' THEN 'byte[]' WHEN 'bit' THEN 'bool' WHEN 'char' THEN 'string' WHEN 'date' THEN 'DateTime' WHEN 'datetime' THEN 'DateTime' WHEN 'datetime2' THEN 'DateTime' WHEN 'datetimeoffset' THEN 'DateTimeOffset' WHEN 'decimal' THEN 'decimal' WHEN 'float' THEN 'double' WHEN 'image' THEN 'byte[]' WHEN 'int' THEN 'int' WHEN 'money' THEN 'decimal' WHEN 'nchar' THEN 'string' WHEN 'ntext' THEN 'string' WHEN 'numeric' THEN 'decimal' WHEN 'nvarchar' THEN 'string' WHEN 'real' THEN 'float' WHEN 'smalldatetime' THEN 'DateTime' WHEN 'smallint' THEN 'short' WHEN 'smallmoney' THEN 'decimal' WHEN 'text' THEN 'string' WHEN 'time' THEN 'TimeSpan' WHEN 'timestamp' THEN 'long' WHEN 'tinyint' THEN 'byte' WHEN 'uniqueidentifier' THEN 'Guid' WHEN 'varbinary' THEN 'byte[]' WHEN 'varchar' THEN 'string' ELSE 'UNKNOWN_' + typ.name END ColumnType, CASE WHEN col.is_nullable = 1 and typ.name IN ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset','decimal','float','int','money',                 'numeric','real','smalldatetime','smallint','smallmoney',                 'time','tinyint','uniqueidentifier') THEN '?' ELSE '' END NullSign FROM sys.columns col INNER JOIN sys.types typ on col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id WHERE object_id = object_id(@TableName) ) temp order by ColumnId set @Output = @Output + ' }' print @Output
END
Here is the output





If you want to generate the classes of a specific table, follow the article below.


I hope you like this article.

Get Images/Files from Azure Storage Blob/Container .NET C#

There are many ways to get files from Azure Storage in .Net and C#. We will discuss 3 different ways today. Before that let's create a storage container on Azure Portal.


1. Create a Storage account in Azure Portal
2. Click on the container, create a new container, and select the public access level.











3. Click on the "Access keys" option and copy the connection string. We will use it in our code.














Let's learn different ways to get the files to Azure Storage. For that, you need to install Azure.Storage.Blobs package from Nuget and you can run the below code based on your requirements.


1. Get bytes/base64 string to Azure Storage

     [HttpGet(Name = "GetImageBytes")]
public async Task<List<BlobImageModel>> GetImageBytes() { var connectionString = "pass your connection string here"; var container = new BlobContainerClient(connectionString, "containernamehere"); var files = new List<BlobImageModel>(); await foreach (var file in container.GetBlobsAsync()) { string uri = container.Uri.ToString(); var name = file.Name; var fullUri = $"{uri}/{name}"; var blobClient = container.GetBlobClient(file.Name); if (blobClient.ExistsAsync().Result) { using (var ms = new MemoryStream()) { blobClient.DownloadTo(ms); var bytes = ms.ToArray(); files.Add(new BlobImageModel { Name = name, ImageBytes = bytes }); } } } return files; }

public class BlobImageModel { public string? Name { get; set; } public byte[]? ImageBytes { get; set; } }

2. Get Images with URLs from Azure Storage

      
[HttpGet(Name = "GetImagesURL")] public async Task<List<BlobResponseModel>> GetImagesURL() { var connectionString = "connection string here"; var container = new BlobContainerClient(connectionString, "containernamehere"); var files = new List<BlobResponseModel>(); await foreach (var file in container.GetBlobsAsync()) { string uri = container.Uri.ToString(); var name = file.Name; var fullUri = $"{uri}/{name}"; var blobClient = container.GetBlobClient(file.Name); if (blobClient.ExistsAsync().Result) { files.Add(new BlobResponseModel { Uri = fullUri, Name = name, ContentType = file.Properties.ContentType }); } } return files; }

     public class BlobResponseModel
    {
        public string? Uri { get; set; }
        public string? Name { get; set; }
        public string? ContentType { get; set; }
     }

If you want to upload the image to Azure storage, follow the article below.

Upload File to Azure Storage


This is all about getting an image from Azure Storage. 

 

Implement Authorization in Swagger with Static Value in Header .Net 8

If you want an anonymous user should not run the APIs. To run your API Endpoints From Swagger / Postman / Code the user should pass the head...