Showing posts with label Csharp. Show all posts
Showing posts with label Csharp. Show all posts

Thursday 7 November 2013

How to Detect Listen port Bitvise Ssh Client

Hi, finally i'm back to share posting "How to Detect Listen port Bitvise Ssh Client".

Why I'm share this posting?
Because i'm always use Bitvise to access my VPS on desktop, and i has build application that used Bitvise SSH. Then i have problem how to detect listen port of my bitvise profile is connected or not. I'm already looking on google how to that, but at the end I can not found it. So I have an idea with used third party application, that's "Paping".
What is Paping
Paping (pronounced pah ping) is a computer network administration utility used to test the reachability of a host on an Internet Protocol (TCP/IP) network and to measure the time it takes to connect to a specified port.

Syntax: paping [options] destination
Options:
  • -?, --help
  • -p, --port N
  •  -t, --timeout
  • -c, --count N
Bitvise services socks is TCP/IP listen interface, so that why i use paping command.
SSH port forwarding https://www.bitvise.com/port-forwarding


As you can see my SSH port forwarding is listen on 127.0.0.1 port 1081, below is the log if my SSH server success connected.
Question is how to automation my ssh with other application.
Oke let's begin, you must read our current article :
Our Application :
After that open our project "RedirectStandardOutput-Paping" , do some modified in Method OutputHandler 
I will send command paping to ping localhost/127.0.0.1 with port 1081
Command : 127.0.0.1 -p 1081

public void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
        {
            SetText(outLine.Data);
//Add if conditional
if(outLine.Data.Contains("Connected")) MessageNox.Show("Your SSH Connected");
else(outLine.Data.Contains("Connection timed out")) MessageNox.Show("Your SSH Disconnected");
        }

Finally , rebuild your project.
Thank You

Tuesday 8 October 2013

Csharp - Redirect Output of Process

RedirectStandardOutput eliminates the need for output files. It allows us to use a console program directly inside a C# program.

Related Article Process in C#:
C# (CSharp) Process - .NET Framework

I wanted to launch a script from a Windows Form application and display the standard output in a text box as the process was running. Surely you're not surprised to learn that multithreading is involved. It turns out you'll have at least four threads running to do this simple task.

A script or executable can be run using System.Diagnostics.Process. The string FileName is set to the executable (e.g. perl.exe, Run.bat, ConsoleApplication.exe). The string Arguments is set to the command-line arguments for that executable (e.g. perlscript.pl, filename1.txt filename2.txt, etc). The following code will start that executable.

I will use Paping executable on this example.
Here are syntax option paping.exe command
Now download Paping here and paste in your project folder bin\Debug
Design your Windows Form project

We have 1 Label , 2 TextBox and 2 Button
Code inside Form is

        delegate void SetTextCallback(string text);

        public Form1()
        {
            InitializeComponent();
        }
 
        private void SetText(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.textBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.textBox2.AppendText(text + Environment.NewLine);
            }
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            Process process;
            process = new Process();
            process.StartInfo.FileName = Application.StartupPath + "\\paping.exe";
            process.StartInfo.Arguments = textBox1.Text;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);

            process.Start();
            process.BeginOutputReadLine();
        }

        public void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
        {
            SetText(outLine.Data);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Process[] pcs_check = Process.GetProcessesByName("paping");
            if (pcs_check.Length > 0)
                foreach (var p in pcs_check)
                    p.Kill();
        }

The ouput of paping command
www.google.com -p 80 -c 4
it's mean ping address google with port 80 and count until 4 time.


Download full source project "RedirectStandardOutput-Paping"

Monday 16 September 2013

C# (CSharp) Process - .NET Framework



Starts a process resource and associates it with a Process component.
Namespace: System.Diagnostics
Assembly: System (in System.dll)

The System.Diagnostics namespace contains functions that allow you to manage processes, threads, eventlogs and performance information.

The System.Diagnostics.Process object gives you access to functionality enabling you to manage system processes. We will use this object to get a list of running processes.

Add this line to your using list:

using System.Diagnostics;

Process. A process starts. It does something important. And then it terminates. With processes, we run separate programs at the level of the operating system.
Start, a static method, calls external applications. It allows users to view documents and web pages. It also executes EXE programs and command-line utilities.
A Project - Arguments:
The Process.Start method has overloaded forms. So you can call it with more than argument.

C# program that open notepad
using System.Diagnostics;

class Program
{
        static void Main()
       {
               // Use Process.Start here.
               Process.Start("Notepad.exe");
       }
}


For more information about this example, here.

ProcessStartInfo:
In this example we use ProcessStartInfo. In it, we can store a process' properties: details of its execution.
C# program that open notepad with argument
using System.Diagnostics;

class Program
{
      static void Main()
     {
           ProcessStartInfo startInfo = new ProcessStartInfo();
           startInfo.FileName = "notepad.exe";
           startInfo.Arguments = "/A C:\filetext.txt";
           Process.Start(startInfo);
      }
}


Properties. To refresh our memory, here is a partial listing of Process properties. We will use most of these when starting programs from a program.
ProcessStartInfo:
Stores information about the process—specifically how the process is started and its configuration.
FileName:
The program or filename you want to run. It can be a program such as "NOTEPAD.EXE". Sometimes we can just specify a file name.
Arguments: Stores the arguments, such as -flags or filename. This is a string property.
CreateNoWindow: Allows you to silently run a command line program. It does not flash a console window.
WindowStyle: Use this to set windows as hidden. ProcessWindowStyle.Hidden is often useful.
UserName, WorkingDirectory, Domain: These control OS-specific parameters—for more complex situations.

You can learn more Process Properties List on msdn here. ^_^
Oke I think it's enough simple information about "C# (CSharp) Process -  .NET Framework"

Read another related article :
How to redirect output of Process on C# (Csharp) .Net Framework

Tuesday 7 May 2013

Get Windows Architecture in Dot NET

How to Determine if 64bit or 32bit OS Version


There are a lot of ways to Get Windows Architecture in .NET, the .NET Framework v4.0 already has this method on their libraries, but many people still are using previous versions (as v3.5 or v2.0).

For .NET v4.0 or higher, it is really simple, just call the ‘Environment.Is64BitOperatingSystem’ property and check if is true or false.:

C# Code :
if (Environment.Is64BitOperatingSystem)
    Console.WriteLine("Your OS is 64 bits.");
else Console.WriteLine("Your OS is 32 bits.");

But for the people using v3.5 or previous, We have this simple way compatible with ‘x86′, ‘x64′ and ‘AnyCPU’ architectures:

//C# Code :
public static bool Is64BitOperatingSystem()
{
    if (!Environment.GetFolderPath(Environment.SpecialFolder.SystemX86).ToUpper().Contains("SYSTEM32"))
        return true; //Check for the SystemX86 variable. If is not 'SYSTEM32' then the Operating System is x64 (SystemX86 = SYSWOW64).
    return false; //Return false when the method was not blocked by the if statement.
}


Public Shared Function Is64BitOperatingSystem() As Boolean
    If Not Environment.GetFolderPath(Environment.SpecialFolder.SystemX86).ToUpper().Contains("SYSTEM32") Then
        Return True
    End If
    'Check for the SystemX86 variable. If is not 'SYSTEM32' then the Operating System is x64 (SystemX86 = SYSWOW64).
    Return False
    'Return false when the method was not blocked by the if statement.
End Function

We also have a way to do it by checking the IntPtr Size:

if (IntPtr.Size == 8)
    Console.WriteLine("Your OS is 64 bits.");
else Console.WriteLine("Your OS is 32 bits.");

‘IntPtr.Size’ always will be eight when the process is running in memory as x64, but only will work if your project was made using the ‘AnyCPU’ platform.


For another Class that using 'kernel32'

//C# Code :
using System;
using System.Runtime.InteropServices;
 
namespace com0do99.library
{
    public static class OsVersionHelper
    {
 
        // Will return result of 64but OS on all versions of windows that support .net
        public static bool Is64BitOperatingSystem()
        {
            if ( IntPtr.Size == 8 ) //64bit will only run on 64bit
            {
                return true;
            }
            bool flag;
            return (DoesWin32MethodExist("kernel32.dll", "IsWow64Process") && IsWow64Process(GetCurrentProcess(), out flag)) && flag;
        }
 
        private static bool DoesWin32MethodExist(string moduleName, string methodName)
        {
            IntPtr moduleHandle = GetModuleHandle(moduleName);
            if (moduleHandle == IntPtr.Zero)
            {
                return false;
            }
 
            return GetProcAddress(moduleHandle, methodName) != IntPtr.Zero;
        }
 
        [DllImport("kernel32.dll")]
        private static extern IntPtr GetCurrentProcess();
 
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr GetModuleHandle(string moduleName);
 
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetProcAddress(IntPtr module, [MarshalAs(UnmanagedType.LPStr)]string procName);
 
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool IsWow64Process(IntPtr process, out bool wow64Process);
    }
}



Thank You

Monday 8 April 2013

Passing Value Between Form in Csharp (C#) and VB.Net

Passing Value Between Form in Csharp (C#) and VB.Net

In C# and vb.net, there are many situations the new programmers face the same problem about how to pass data and values from one form to another. We can pass values from one form to another in a number of ways. Here you can see one of the easiest method to pass values from one form to another.

Passing Value Form1 to Form2 in Csharp (C#) and VB.Net
  • Here we send the value with calling object properties.
Csharp (C#)
In Form1
private void button1_Click(object sender, EventArgs e)
   {
      Form2 frm = new Form2();
            frm.textBox1.Text = "Hi";
            frm.Show();
        }

  • Send the value as arguments of the constructor.

Csharp (C#)
In Form2
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {

        }
        public Form2(string txt)
        {
            InitializeComponent();
            textBox1.Text = txt;
        }
    }
}

VB.Net
Private Sub button1_Click(sender As Object, e As EventArgs)
 Dim frm As New Form2()
 frm.textBox1.Text = "Hi"
 frm.Show()
End Sub

Public Class Form2
    Public Sub New(ByVal sText As String)
        InitializeComponent()
        Me.textBox1.Text = sText
    End Sub
End Class


Passing Value Form2 to Form1 in Csharp (C#) and VB.Net

Csharp (C#)
In Form1
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        Form2 frm;
        public Form1()
        {
            InitializeComponent();
        }

        public string GetValueForm2
        {
            get { return m_value; }
            set
            {
                m_value = value;
            }
        }
        private string m_value;
        
        //Open Form2
        private void Button1_Click(object sender, EventArgs e)
        {
            frm = new Form2(this);
            frm.Show();
        }
        //Click Button2 to Get Passed Value
        private void Button2_Click(object sender, EventArgs e)
        {
            textBox1.Text = m_value;
        }

    }
}

In Form2
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        Form1 ParForm;
        public Form2(Form1 myParForm)
        {
            ParForm = myParForm;
            InitializeComponent();
        }
        
        //Click Button1 to Passing Value to Form1
        private void Button1_Click(object sender, EventArgs e)
        {
            ParForm.GetValueForm2 = textBox1.Text;
        }

    }
}



VB.Net
Public Class Form1

 Private frm As Form2

 Public Property GetValueForm2() As String
  Get
   Return m_value
  End Get
  Set
   m_value = value
  End Set
 End Property
 Private m_value As String

   'Open Form2
 Private Sub Button1_Click(sender As Object, e As EventArgs)
  frm = New Form2(Me)
  frm.Show()
 End Sub
 'Click Button2 to Get Passed Value
 Private Sub Button2_Click(sender As Object, e As EventArgs)
  TextBox1.Text = m_value
 End Sub

End Class

In Form2
Public Class Form2

    'In Form2 add a "New" constructor
    Dim ParForm As Form1
    Public Sub New(ByVal myParForm As Form1)
        MyBase.New()
        ParForm = myParForm
        InitializeComponent()
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        ParForm.GetValueForm2 = TextBox1.Text
    End Sub
End Class

Thank You

Download Sample Application using Microsoft Visual Studio 2010
Csharp | VB.Net

Friday 15 March 2013

How to fix Error the designer


Error the designer cannot process unknown name. The code whithin the method 'InitializeComponent' is generate by the designer and should not be manually modified. please remove any changes and try opening the designer again.



Why we get message error like that? I really annoying when I design GUI form and then get that message. But when we read that message carefully, we can see It's happen because we inadvertent have been modifications to the code desiner form. The code which is used to organize and manage the GUI on Windows Form Application.

On my case it's happen because I inadvertent create an event button1_Click , and I delete that "event_Click" when I the event created.



If we click "Ignore and Continue"



This would be trouble, which may all projects that we have built from scratch will be gone, replaced with a blank form.



Bu if we click "Go to code" for the solution to know an missing event error

Or double click on error list




Or Go to Solution Explorer


End then delete the error event It's will fix that problem.








Thank You