Sunday, 19 August 2018

Show Progress bar in console application c#

In this post we are going to see how to show the progress bar in console application c#. For that we have to set the cursor in the console application to move in to position , then we have to set the background color .

Source code:
***********

        static void Main(string[] args)
        {
            Console.WriteLine("Uploading inprogress....");
            Console.WriteLine();
            for (int i = 0; i <= 100; i++)
            {
                ShowProgressBar( i, 100);
                Thread.Sleep(500);
            }
            Console.Read();

        }


        private static void ShowProgressBar(int progress, int total)
        {
            //draw empty progress bar
            Console.CursorLeft = 0;
            Console.Write("[");
            Console.CursorLeft = 32;
            Console.Write("]");
            Console.CursorLeft = 1;
            float oneunit = 30.0f / total;

            //draw progress
            int position = 1;
            for (int i = 0; i < oneunit * progress; i++)
            {
                Console.BackgroundColor = ConsoleColor.Green;
                Console.CursorLeft = position++;
                Console.Write(" ");
            }

            //draw strip bar
            for (int i = position; i <= 31; i++)
            {
                Console.BackgroundColor = ConsoleColor.Gray;
                Console.CursorLeft = position++;
                Console.Write(" ");
            }

            //draw totals
            Console.CursorLeft = 35;
            Console.BackgroundColor = ConsoleColor.Black;
            Console.Write(progress.ToString() + " of " + total.ToString() + "    ");

        }




Output:
***********





From this post you can learn how to show the progress bar in console application c#.

Draw a image in console window and save that as jpeg using graphics in c#

In this post we are going to see how to draw a image in console window and save that as jpeg using graphics in c#.

here we are going to draw a rectangle, line and a string in console screen as well as save that as image. For console we have to get the handle of window to draw, then get the graphics for that, to save as image get the graphics from bitmap

Source code For print in Console:

[DllImport("user32.dll", CharSet = CharSet.Auto)]

public static extern IntPtr GetDC(IntPtr hWnd);


static void DrawInConsoleFromGraphics()
        {
            Process process = Process.GetCurrentProcess();
            Graphics g = Graphics.FromHdc(GetDC(process.MainWindowHandle));

            // Create pen.
            Pen bluePen = new Pen(Color.Blue, 3);

            // Create rectangle.
            Rectangle rect = new Rectangle(0, 0, 200, 200);

            // Draw rectangle to screen.
            g.DrawRectangle(bluePen, rect);
            g.DrawLine(new Pen(Color.Red, 2), new Point(100, 100), new Point(0, 0));
            g.DrawString("Welcome to Dotnetvisio.blogspot.com", new Font("Arial", 14), 
                          new SolidBrush(Color.Orange), new Point(10, 300));
            g.Save();

        }


Source code For save as Image

static void DrawJpegImageFromGraphics()
        {
            // Create bitmap
            using (Bitmap newImage = new Bitmap(400, 400))
            {

                // Crop and resize the image.               
                using (Graphics graphic = Graphics.FromImage(newImage))
                {
                    // Create pen.
                    Pen bluePen = new Pen(Color.Blue, 3);

                    // Create rectangle.
                    Rectangle rect = new Rectangle(0, 0, 200, 200);

                    // Crop and resize the image.
                    graphic.DrawRectangle(bluePen, rect);
         graphic.DrawLine(new Pen(Color.Red, 2), new Point(100, 100), new Point(0, 0));
         graphic.DrawString("Welcome to Dotnetvisio.blogspot.com", new Font("Arial", 14), 
                       new SolidBrush(Color.Orange), new Point(10, 300));
                }
         newImage.Save(AppDomain.CurrentDomain.BaseDirectory + "ImageFromGraphics.jpg"
                             ImageFormat.Jpeg);
            }

        }


Full Source Code:
********************

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace GraphicsToImage
{
    class Program
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr GetDC(IntPtr hWnd);

        static void Main(string[] args)
        {
            DrawInConsoleFromGraphics();
            DrawJpegImageFromGraphics();
            Console.Read();
        }

        static void DrawInConsoleFromGraphics()
        {
            Process process = Process.GetCurrentProcess();
            Graphics g = Graphics.FromHdc(GetDC(process.MainWindowHandle));

            // Create pen.
            Pen bluePen = new Pen(Color.Blue, 3);

            // Create rectangle.
            Rectangle rect = new Rectangle(0, 0, 200, 200);

            // Draw rectangle to screen.
            g.DrawRectangle(bluePen, rect);
            g.DrawLine(new Pen(Color.Red, 2), new Point(100, 100), new Point(0, 0));
            g.DrawString("Welcome to Dotnetvisio.blogspot.com", new Font("Arial", 14), 
                         new SolidBrush(Color.Orange), new Point(10, 300));
            g.Save();
        }

        static void DrawJpegImageFromGraphics()
        {
            // Create bitmap
            using (Bitmap newImage = new Bitmap(400, 400))
            {

                // Crop and resize the image.               
                using (Graphics graphic = Graphics.FromImage(newImage))
                {
                    // Create pen.
                    Pen bluePen = new Pen(Color.Blue, 3);

                    // Create rectangle.
                    Rectangle rect = new Rectangle(0, 0, 200, 200);

                    // Crop and resize the image.
                    graphic.DrawRectangle(bluePen, rect);
                    graphic.DrawLine(new Pen(Color.Red, 2), new Point(100, 100), 
                                     new Point(0, 0));
                    graphic.DrawString("Welcome to Dotnetvisio.blogspot.com"
                                     new Font("Arial", 14), new SolidBrush(Color.Orange), 
                                     new Point(10, 300));
                }
                
newImage.Save(AppDomain.CurrentDomain.BaseDirectory + "ImageFromGraphics.jpg",                                 ImageFormat.Jpeg);
            }
        }
    }
}




Output:

From console


From image



From this post you can learn how to draw a image in console window and save that as jpeg using graphics

Wednesday, 15 August 2018

Sample program for Event in C#

In this post we are going to see the sample program for event model in c#, Event uses the Delegate, it is like publisher and subscriber model.

Steps to do in publisher
1. Create a Delegate
2. Create a Event
3. Raise a Event

Steps to do in subscriber
1. Subscribe the notification through event
2. Do the operation

Syntax for Event:
1. public event delegate_name event_name;

In this program we are going to create Logger class which have event Write, Logger is publisher. Now in subscriber we have subscribe the notification through write event for two subscriber one is for ConsoleLogger another one is for FileLogger.



























Publisher:
************************
   public class Logger
    {
        public delegate void WriteHandler(string message);
        public event WriteHandler Write;

        public void WriteAll(string messaage)
        {
            Write?.Invoke(messaage);
        }

    }



Subscriber:
************************
public class ConsoleLogger
    {
        public void Info(string message)
        {
            Console.WriteLine(message);
        }
    }

    public class FileLogger
    {
        StreamWriter writer;
        FileStream fileStream;

        public FileLogger()
        {
            fileStream = new FileStream(@"E:/writer.txt", FileMode.Create);
            writer = new StreamWriter(fileStream);
        }

        public void WriteInfo(string message)
        {
            writer.WriteLine(message);
            writer.Flush();
        }

    }


Main Program
**************
    class Program
    {
        static void Main(string[] args)
        {
            ConsoleLogger clogger = new ConsoleLogger();
            FileLogger flogger = new FileLogger();

            Logger _logger = new Logger();
            _logger.Write += clogger.Info;
            _logger.Write += flogger.WriteInfo;

            _logger.WriteAll("1 statement");
            _logger.WriteAll("2 statement");

            Console.Read();
        }
    }


When we call the WriteAll Method, it is triggering an event Write, so subscribed eventhandler will execute , because of this message is write in console and as well in File

Output:
*************

ConsoleLogger




 FileLogger





From this post you can learn event model in c# with sample