Tuesday 23 August 2022

Amazon S3 Bucket ( Wirte,Read,Delete files)

 using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Threading.Tasks;

using Amazon.S3;

using Amazon.S3.Model;

using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.Http;

using Microsoft.Extensions.Configuration;

using Newtonsoft.Json;

using SafetyHub.Api.Infrastructure.Config;

using SafetyHub.Api.Infrastructure.ExtensionMethods;


namespace SafetyHub.Api.Infrastructure.Helper

{

    public class AwsS3 : IAwsS3

    {

        public async Task<(bool IsSuccess, string Result)> WriteFile(IFormFile file, string keyName)

        {

            string extension = Path.GetExtension(file.FileName);

            var filePath = keyName + "_" + DateTime.UtcNow.Ticks + extension;


            using var newMemoryStream = new MemoryStream();

            await file.CopyToAsync(newMemoryStream).ConfigureAwait(false);

            var request = new PutObjectRequest

            {

                InputStream = newMemoryStream,

                BucketName = Configs.AWSConfigurations.S3BucketName,

                Key = filePath

            };

            var _s3Client = new AmazonS3Client(Configs.AWSConfigurations.AWSAccessKey, Configs.AWSConfigurations.AWSSecretKey, new AmazonS3Config() { ServiceURL = Configs.AWSConfigurations.S3ServiceURL });

            var response = await _s3Client.PutObjectAsync(request).ConfigureAwait(false);

            if (response?.HttpStatusCode.Equals(System.Net.HttpStatusCode.OK) == true)

            {

                return (true, filePath);

            }

            return (false, Constant.HttpResponse.ERROR);

        }


        public async Task<(bool IsSuccess, Stream Result)> ReadFile(string keyName)

        {

            try

            {

                var request = new GetObjectRequest

                {

                    BucketName = Configs.AWSConfigurations.S3BucketName,

                    Key = keyName

                };

                var _s3Client = new AmazonS3Client(Configs.AWSConfigurations.AWSAccessKey, Configs.AWSConfigurations.AWSSecretKey, new AmazonS3Config() { ServiceURL = Configs.AWSConfigurations.S3ServiceURL });

                var response = await _s3Client.GetObjectAsync(request).ConfigureAwait(false);

                if (response?.HttpStatusCode.Equals(System.Net.HttpStatusCode.OK) == true)

                {

                    return (true, response.ResponseStream);

                }

            }

            catch { }

            return (false, null);

        }


        public async Task<(bool IsSuccess, string Result)> DeleteFile(string keyName)

        {

            var request = new DeleteObjectRequest

            {

                BucketName = Configs.AWSConfigurations.S3BucketName,

                Key = keyName

            };

            var _s3Client = new AmazonS3Client(Configs.AWSConfigurations.AWSAccessKey, Configs.AWSConfigurations.AWSSecretKey, new AmazonS3Config() { ServiceURL = Configs.AWSConfigurations.S3ServiceURL });

            var response = await _s3Client.DeleteObjectAsync(request).ConfigureAwait(false);

            if (response?.HttpStatusCode.Equals(System.Net.HttpStatusCode.NoContent) == true)

            {

                return (true, "File has been deleted successfully.");

            }

            return (false, "File no exists.");

        }

    }


    public interface IAwsS3

    {

        Task<(bool IsSuccess, string Result)> WriteFile(IFormFile file, string uploadPath);

        Task<(bool IsSuccess, Stream Result)> ReadFile(string keyName);

        Task<(bool IsSuccess, string Result)> DeleteFile(string keyName);

    }

}






Saturday 6 August 2022

  1. Create a new Windows Forms application.



  2. Create a database (named Sample). Add a table tbl_Record. The following is the table schema for creating tbl_Record.



  3. Create a form (named frmMain) and drop a Label, TextBox, Button and DataGridView control from the ToolBox.

     
Now, go to the frmMain.cs code and add the System.Data and System.Data.SqlClient namespaces.
 
frmMain.cs Code
  1. using System;  
  2. using System.Data;  
  3. using System.Windows.Forms;  
  4. using System.Data.SqlClient;  
  5.   
  6. namespace InsertUpdateDeleteDemo  
  7. {  
  8.     public partial class frmMain : Form  
  9.     {  
  10.         SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");  
  11.         SqlCommand cmd;  
  12.         SqlDataAdapter adapt;  
  13.         //ID variable used in Updating and Deleting Record  
  14.         int ID = 0;  
  15.         public frmMain()  
  16.         {  
  17.             InitializeComponent();  
  18.             DisplayData();  
  19.         }  
  20.         //Insert Data  
  21.         private void btn_Insert_Click(object sender, EventArgs e)  
  22.         {  
  23.             if (txt_Name.Text != "" && txt_State.Text != "")  
  24.             {  
  25.                 cmd = new SqlCommand("insert into tbl_Record(Name,State) values(@name,@state)", con);  
  26.                 con.Open();  
  27.                 cmd.Parameters.AddWithValue("@name", txt_Name.Text);  
  28.                 cmd.Parameters.AddWithValue("@state", txt_State.Text);  
  29.                 cmd.ExecuteNonQuery();  
  30.                 con.Close();  
  31.                 MessageBox.Show("Record Inserted Successfully");  
  32.                 DisplayData();  
  33.                 ClearData();  
  34.             }  
  35.             else  
  36.             {  
  37.                 MessageBox.Show("Please Provide Details!");  
  38.             }  
  39.         }  
  40.         //Display Data in DataGridView  
  41.         private void DisplayData()  
  42.         {  
  43.             con.Open();  
  44.             DataTable dt=new DataTable();  
  45.             adapt=new SqlDataAdapter("select * from tbl_Record",con);  
  46.             adapt.Fill(dt);  
  47.             dataGridView1.DataSource = dt;  
  48.             con.Close();  
  49.         }  
  50.         //Clear Data  
  51.         private void ClearData()  
  52.         {  
  53.             txt_Name.Text = "";  
  54.             txt_State.Text = "";  
  55.             ID = 0;  
  56.         }  
  57.         //dataGridView1 RowHeaderMouseClick Event  
  58.         private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)  
  59.         {  
  60.             ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());  
  61.             txt_Name.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();  
  62.             txt_State.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();  
  63.         }  
  64.         //Update Record  
  65.         private void btn_Update_Click(object sender, EventArgs e)  
  66.         {  
  67.             if (txt_Name.Text != "" && txt_State.Text != "")  
  68.             {  
  69.                 cmd = new SqlCommand("update tbl_Record set Name=@name,State=@state where ID=@id", con);  
  70.                 con.Open();  
  71.                 cmd.Parameters.AddWithValue("@id", ID);  
  72.                 cmd.Parameters.AddWithValue("@name", txt_Name.Text);  
  73.                 cmd.Parameters.AddWithValue("@state", txt_State.Text);  
  74.                 cmd.ExecuteNonQuery();  
  75.                 MessageBox.Show("Record Updated Successfully");  
  76.                 con.Close();  
  77.                 DisplayData();  
  78.                 ClearData();  
  79.             }  
  80.             else  
  81.             {  
  82.                 MessageBox.Show("Please Select Record to Update");  
  83.             }  
  84.         }  
  85.         //Delete Record  
  86.         private void btn_Delete_Click(object sender, EventArgs e)  
  87.         {  
  88.             if(ID!=0)  
  89.             {  
  90.                 cmd = new SqlCommand("delete tbl_Record where ID=@id",con);  
  91.                 con.Open();  
  92.                 cmd.Parameters.AddWithValue("@id",ID);  
  93.                 cmd.ExecuteNonQuery();  
  94.                 con.Close();  
  95.                 MessageBox.Show("Record Deleted Successfully!");  
  96.                 DisplayData();  
  97.                 ClearData();  
  98.             }  
  99.             else  
  100.             {  
  101.                 MessageBox.Show("Please Select Record to Delete");  
  102.             }  
  103.         }  
  104.     }  
  105. }  
In the preceding code, I created a dataGridView1_RowHeaderMouseClick Event for updating and deleting the selected record. When the user clicks on the Row Header of a row then the data present in the cell of the row is stored into the TextBoxes. The DisplayData() method fills in the data in the DataGridView.
 
The Clear() method clears the data present in the TextBox as well as in the ID(int) variable.

Using extensions in Visual Studio Code

C#

Ctrl +Shit + p ( .NET :Generate Assests For build and debug)

Roslynator

.NET Core Test Explorer

C# Namespace Autocompletion

Auto-Using for C#

C# XML Documentation Comments

NuGet Reverse Package Search ("Add Package" support)

Code Spell Checker

vscode-icons

Path Intellisense

EditorConfig for VS Code

SQL Server (mssql)

GitHub Copilot

REST Client

GitLens — Git supercharged

VS Browser

Highlight Trailing White Spaces

jwt-decoder

Markdown All in One

Markdown Preview Enhanced

markdownlint

Docker

Vim


SqlDataBaseLibrary

using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using AOS.Repository.Infrastructure; using S...