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

How to pass OUTPUT parameter in MS SQL StoreProcedure

Description : In this post how to pass OUTPUT parameter in procedure and how to return value from procedure

- Create Simple StoreProcedure

CREATE PROCEDURE [dbo].[MyOUTPUTParamCheck]
    @Name Varchar(100)
    ,@OUTPARAMETER Varchar(100) OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

        SET @OUTPARAMETER = 'Hi ' + @Name

    PRINT @OUTPARAMETER
END

- Call procedure

[dbo].[MyOUTPUTParamCheck] 'Test',''

- Result : Hi Test

Tuesday, 20 March 2018

How to display browser notification in website using javascript

Description : In this post how to display notification in website using javascript. this notfication display if your browser is open or minimized. write below javascript for display browser notfication

Step 1 : add below javascript for notfication display

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Step 2 : add below javascript code for display notfication

<script>
        $(document).ready(function () {

            document.addEventListener('DOMContentLoaded', function () {
                if (Notification.permission !== "granted") {
                    Notification.requestPermission();
                }
            }); 

        });

        function NotifyMe(title, desc, url) {
            if (Notification.permission !== "granted") {
                Notification.requestPermission();
            }
            else {
                var notification = new Notification(title, {
                    icon: url,
                    body: desc,
                });

                /* Remove the notification from Notification Center when clicked.*/
                notification.onclick = function () {
                    window.open(url);
                };

                /* Callback function when the notification is closed. */
                notification.onclose = function () {
                    console.log('Notification closed');
                };
            }
        } 
</script>

Step : Add HTML button if click on button it call function NotfiyMe. here 3 parameter for set dynamic text in notfication 1st is notficiation title, 2nd is description of notficiation and last 3rd is URL for display image in notification

<button onclick="NotifyMe('Browser Notification', 'This is testing browser notification.','https://png.icons8.com/color/260/comedy.png')">Display Notification</button>

- Below screenshot for Notification looks like

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 parse json data in table row using MS SQL OPENJSON

Description : In this post how to parse json data in MS SQL using OPENJSON first we need json here declare one json variable and set static json in this variable. write one select querye with OPENJSON for convert json to SQL Table

DECLARE @json NVARCHAR(MAX)

SET @json = 
N'[ 
       { "name": "Test 1", "surname": "Testing" },
       { "name": "Test 2", "surname": "Testing Again" }
 ]' 

SELECT * FROM OPENJSON(@json) 
WITH (
    FirstName nvarchar(50) '$.name'
    , LastName nvarchar(50) '$.surname'
)

Below screen shot display how to write query of OPENJSON



Below screen shot display how result look like

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); 

Tuesday, 13 March 2018

C# Input / Output classes [I/O Class]

Description : System.IO some classes for perform a create, delete, read and write files. below are some classes in the System.IO

- BinaryReader : Reads primitive data from a binary stream.
- BinaryWriter : Writes primitive data in binary format.
- BufferedStream : temporary storage for a stream of bytes.
- Directory : manipulating a directory structure.
- DirectoryInfo : performing operations on directories.
- DriveInfo : Provides information for the drives.
- File : performing operations on files.
- FileStream : read from and write to any location in a file.
- MemoryStream : random access to streamed data stored in memory.
- Path : Performs operations on path information.
- StreamReader : reading characters from a byte stream.
- StreamWriter : writing characters to a stream.
- StringReader : reading from a string buffer.
- StringWriter : writing into a string buffer.

How to use AngularJS filters in html controls

Description : in this post how to convert datem currency, lowercase and uppercase in angular js simple pass filter from filter list

Filters List :

- currency : format number in currency format
- date : format date to formated date
- lowercase : fromat string to lowercase
- uppercase : format string to uppercase

How to create table using SQL CREATE TABLE

Description : CREATE TABLE statement use for create a table in your existsing SQL database

Syntax :

CREATE TABLE YourTableName (
    TableColumn1 DataType,
    TableColumn2 DataType,
    TableColumn3 DataType,
)

Example :

CREATE TABLE Employee (
    EmployeeID Int,
    EmployeeName Varchar(50),
    City Varchar(50),
    PhoneNo Varchar(50)
)

Syntax : Syntax for how to create table using another table of database

CREATE TABLE YourTableName AS
SELECT Column1,
Column2 FROM CreatedTableName

How to DROP Database using SQL DROP DATABASE

Description : SQL DROP DATABASE statement drop existing database from your SQL

Syntax :

DROP DATABASE YourDatabaseName

Example :

DROP DATABASE EmployeeDB

How to create database in SQL using CREATE DATABASE Statement

Description : SQL CREATE DATABASE statement use for create Database in SQL

Syntax :

CREATE DATABASE YourDatabaseName

Example :

CREATE DATABASE EmployeeDB

How to fix VS2017 missing XAML tools build error

Error :

The "Microsoft.Build.Tasks.Xaml.PartialClassGenerationTask" task could not be loaded from the assembly C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\amd64\XamlBuildTask.dll. Could not load file or assembly 'file:///C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\amd64\XamlBuildTask.dll' or one of its dependencies. The system cannot find the file specified. Confirm that the <UsingTask> declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask

To solve this issue just open visual studio installer and go to Individual Components tab and select "Windows Workflow Foundation"


Thursday, 1 March 2018

How to call function after complete page load in javascript

Description : in this post how to call function after complete page load in aspx, html, cshtml page just add below code in script

Write below code and add your function in setInterval

<script>
        document.addEventListener("DOMContentLoaded", function () {
            setInterval(calculateTotalFees(), 0);
        }, false);
</script>

How to upercase / lowercase text in SQL query

Description : in this post how to get result of state name in upper case  or in lower case

Query Syntax for upper case text return in result

- SELECT UPPER(sta_StateName) AS State FROM StateMaster

Result :

DISTRICT OF COLUMBIA
TEXAS
NEW MEXICO

Query Syntax for lower case text return in result

- SELECT LOWER(sta_StateName) AS State FROM StateMaster

Result :

district of columbia
texas
new mexico

Screen Shot :