Showing posts with label winform app. Show all posts
Showing posts with label winform app. Show all posts

Thursday, 5 April 2018

What is the best way for read a large file into a byte array using c#

Description : In this post how to convert a file stream in a byte array using c#. this code is use for convert a file into byte array and also send this byte array into FTP or Other file storage code. in my early post of upload file in FTP using c# use this code for convert any file from stream or file path to byte array

- Below code for convert file stream to byte array from specific file path using c#

public byte[] ReadAllBytes(string fileName)
{
    byte[] buffer = null;
    using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
    {
        buffer = new byte[fs.Length];
        fs.Read(buffer, 0, (int)fs.Length);

    or

    using (var reader = new BinaryReader(filestream))
    {
        byte[] file = reader.ReadBytes((int)filestream.Length);
        }
    }
    return buffer;
}

Convert byte array to string and string to byte array using c#

Description : In this post how to convert a simple string into byte array or convert a byte array to string using c#. this code is use in my early post for Download file from FTP.

- Below code for convert string to byte array using c#

string stringToConvert = "Hello World !";

byte[] buffer = Encoding.UTF8.GetBytes(stringToConvert);

- Below code for convert byte array to string using c#

string converted = Encoding.UTF8.GetString(buffer, 0, buffer.Length);

Tuesday, 3 April 2018

How to remove queue from azure queue using c#

Description : In this post how to remove queue from azure using c#. here same steps follow in my previous post for how to add message in azure using c#. and also check how to retrive queue from azure using c#

Step 1 : Downlod below NuGet package for add message using c#. Install both package one by one in your project use NuGet console or NuGet package managerr

- WindowsAzure.Storage
- WindowsAzure.ConfigurationManager

Step 2 : Get your connection string from Azure. Go to Azure Portal
Go to Storage Account -> Click on your storage account -> Inside Setting Click on Access keys -> In this window select Copy connection string. your connection string look like below

- DefaultEndpointsProtocol=https;AccountName=YourStorageAccountName;AccountKey=YourStorageAccountKey

Step 3 : Write below code for remove message from queue using c#

string ConnectionString = "DefaultEndpointsProtocol=https;AccountName=YourStorageAccountName;AccountKey=YourStorageAccountKey"

CloudStorageAccount account = CloudStorageAccount.Parse(ConnectionString); // Cloud Storage Account

CloudQueueClient queueClient = account.CreateCloudQueueClient(); // Queue Client Create

CloudQueue messageQueue = queueClient.GetQueueReference("YourAzureQueueName"); // Get Queue Reference

// this line for remove message from azure queue
messageQueue.DeleteMessage(MessageID, PopReceipt, null, null); // here message id is queue is get from azure and PopReceipt also you can get from queue

How to retrive queue from azure using c#

Description : In this post how to retrive queue message from azure using c#. here same steps for get message in my previous post of how to get message from azure using c#

Step 1 : Downlod below NuGet package for add message using c#. Install both package one by one in your project use NuGet console or NuGet package managerr

- WindowsAzure.Storage
- WindowsAzure.ConfigurationManager

Step 2 : Get your connection string from Azure. Go to Azure Portal
Go to Storage Account -> Click on your storage account -> Inside Setting Click on Access keys -> In this window select Copy connection string. your connection string look like below

- DefaultEndpointsProtocol=https;AccountName=YourStorageAccountName;AccountKey=YourStorageAccountKey

Step 3 : Create class for add json message in azure queue using c#

public class ResponseClass
{
    public string id { get; set; }
    public string name { get; set; }
}

Step 3 : Write below code for retrive queue from azure using c#

string ConnectionString = "DefaultEndpointsProtocol=https;AccountName=YourStorageAccountName;AccountKey=YourStorageAccountKey"

CloudStorageAccount account = CloudStorageAccount.Parse(ConnectionString); // Cloud Storage Account

CloudQueueClient queueClient = account.CreateCloudQueueClient(); // Queue Client Create

CloudQueue messageQueue = queueClient.GetQueueReference("YourAzureQueueName"); // Get Queue Reference

// this line for retrive 10 messages from azure queue
List<CloudQueueMessage> retrievedMessage = messageQueue.GetMessages(10).ToList();

using for loop one by one get queue response like below code

for (int i = 0; i < retrievedMessage.Count; i++)
{
    string Message = retrievedMessage[i].AsString;
    string ID = retrievedMessage[i].Id;
    string PopReceipt = retrievedMessage[i].PopReceipt; // this PopReceipt use for delete queue

    JsonResponse obj = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponseClass>(Message);
}

How to add message in azure queue using C#

Description : In this post how to add message in azure queue storage using c# code. This code use in any .Net application like Winform application or MVC or ASP.Net. below steps for how to successfully add message in azure queue using c#

Step 1 : Downlod below NuGet package for add message using c#. Install both package one by one in your project use NuGet console or NuGet package managerr

- WindowsAzure.Storage
- WindowsAzure.ConfigurationManager


Step 2 : Get your connection string from Azure. Go to Azure Portal
Go to Storage Account -> Click on your storage account -> Inside Setting Click on Access keys -> In this window select Copy connection string. your connection string look like below

- DefaultEndpointsProtocol=https;AccountName=YourStorageAccountName;AccountKey=YourStorageAccountKey

Step 3 : Create class for add json message in azure queue using c#

public class RequestClass
{
    public string id { get; set; }
    public string name { get; set; }

    public RequestClass() { }

    public RequestClass(string _id, string _name)
    {
        this.id = _id; this.name = _name;
    }
}

Step 4 : Write below code for add message in your queue using C#.

string ConnectionString = "DefaultEndpointsProtocol=https;AccountName=YourStorageAccountName;AccountKey=YourStorageAccountKey"

CloudStorageAccount account = CloudStorageAccount.Parse(ConnectionString); // Cloud Storage Account

CloudQueueClient queueClient = account.CreateCloudQueueClient(); // Queue Client Create

CloudQueue messageQueue = queueClient.GetQueueReference("YourAzureQueueName"); // Get Queue Reference

string MessageToAdd = JsonConvert.SerializeObject(new RequestClass(GUID, Name)); // Serialize JSON for add in queue

CloudQueueMessage m = new CloudQueueMessage(MessageToAdd); // Generate Cloud Message

messageQueue.AddMessage(m); // Finally add message in queue

Thursday, 22 March 2018

Go to next control by pressing Enter Key in c# winform application

Description : In this post go to next control using Enter Key in c# windows application

- Add 2 Textbox in winform

- Generate KeyDown event of both textbox control

- Add Below code in both keydown event

private void textbox1_KeyDown(object sender, KeyEventArgs e) 
{
    if (e.KeyCode == Keys.Enter) 
        textbox2.Focus(); 
}

private void textbox2_KeyDown(object sender, KeyEventArgs e) 
{ 
    if (e.KeyCode == Keys.Enter) 
        textbox1.Focus(); 
}

Note : if focus in textbox 1 than press enter and change focus in textbox2 if again press enter than focus set in textbox1

Monday, 19 March 2018

SQL Server database backup using SQL StoreProcedure in c# winform application

Description : in this post how to take DB backup from winform using SQL Storeprocedure

- Step 1 : Create new sample database for generate backup

Database Name : SampleDBTest

- Step 2 : Create StoreProcedure for generate backup file

CREATE PROC DatabaseBackupProcedure
AS 
BEGIN 

    DECLARE @path Varchar(1000); 

    SET @path='YourDBBackupPath\SampleDBTest'+CONVERT(CHAR(10),  GETDATE(), 121)+'.bak'; 
   
    BACKUP DATABASE SampleDBTest to DISK=@path; 
END 

- Step 3 : Create winform application for call store procedure of database backup

- Step 4 : Get Connection String of SampleDBTest database and add in App.Config file

- Step 5 : Write below c# code in button click for call procedure

Code Note : Get Connection string from App.Config file and add below namespace for get connection string from App.Config and SQL Connection

using System.Data.SqlClient; 
using System.Configuration; 

SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()); 
       
private void btnBackupDB_Click(object sender, EventArgs e) 
{ 
    con.Open(); 
    SqlCommand cmd = new SqlCommand("DatabaseBackupProcedure", Connection); 
    cmd.CommandType = CommandType.StoredProcedure; 
    cmd.ExecuteNonQuery(); 
    con.Close(); 
    MessageBox.Show("Back up Done successfully");
}

Note : By using this code database direct create .bak file in your folder path set in sql storeprocedure

Sunday, 18 March 2018

How to check file exists in FTP server in C#

Description : In this post when you try to delete file from FTp but get error 550, File Unavailable to solve this first check file is exists or not in FTP.
here create one method for check file in FTP

private bool FileCheckInFTP(string fileName)   
{   
    var request = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/" + fileName);   
    request.Credentials = new NetworkCredential("username", "password");   
    request.Method = WebRequestMethods.Ftp.GetFileSize;   
       
    try   
    {   
        FtpWebResponse response = (FtpWebResponse)request.GetResponse();   
        return true;   
    }   
    catch (WebException ex)   
    {   
        FtpWebResponse response = (FtpWebResponse)ex.Response;   
        if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)   
            return false;   
    }   
    return false;   
}

- if the response get from FTP like "ActionNotTakenFileUnavailable" it means file is unavailble.

Saturday, 17 March 2018

How to delete file from FTP using c#

Description : In this post how to delete file from FTP server using c#

private string DeleteFileFromFTP(string fileName)   
{   
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/" + fileName);   
    request.Method = WebRequestMethods.Ftp.DeleteFile;   
    request.Credentials = new NetworkCredential("username", "password");   
       
    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())   
    {   
        return response.StatusDescription;       
    }   
}

- Above code is delete file from FTP in the code WebRequestMethods is "DeleteFile". when file delete from FTP server it return response and description is "250 File deleted successfully"

How to get all file and directory from FTP server using c#

Description : In this post FTP server return all files and directory in response uing c#

private List GetAllFilesnDirectory() 
{ 
    try 
    { 
         FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/"); 
         request.Method = WebRequestMethods.Ftp.ListDirectory; 
 
         request.Credentials = new NetworkCredential("username", "password"); 
         FtpWebResponse response = (FtpWebResponse)request.GetResponse(); 
         Stream responseStream = response.GetResponseStream(); 
         StreamReader reader = new StreamReader(responseStream); 
         string names = reader.ReadToEnd(); 
 
         reader.Close(); 
         response.Close(); 
 
         return names.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList(); 
    } 
    catch (Exception) 
    { 
        throw; 
    } 
}

- Above code return ListDirectory from FTP response and get in stream than parse response and get list of files and directory

Friday, 16 March 2018

How to capture desktop screenshot using c# winform application

Description : In this post how to capture desktop screen shot using windows application add below namespace and code for take screen shot.

- Add below namespace for generate image

using System.Windows.Forms;
using System.Drawing.Imaging;

- Add below code for capture image and save in specific directory

Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); 
Graphics graphics = Graphics.FromImage(bitmap as System.Drawing.Image); 
graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size); 
bitmap.Save(@"FolderPath", ImageFormat.Jpeg);