Thursday 29 October 2009

All About Batch Files

I can't explain how much I love batch files. You can write your commands in a .bat file, then you can run them. It's great for automation which saves a lot of time.

Ok, what can you do with it?

Start Applications

SET fromFolder=C:\Projects\Beacon\v1.0\code

START %fromFolder%\BrokerService\bin\Debug\BeaconServer.BrokerService.exe

START http://localhost/BeaconClientService.WebUI/Default.aspx

Copy Files


SET fromFolder=C:\Projects\Beacon\v1.0\code

SET toFolder=D:\Projects\Beacon\v1.0\code

xcopy /E /Y %fromFolder% %toFolder%

Build Solutions

SET msBuildFolder= C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

CD %msBuildFolder%

SET rootFolder=C:\SharedFolder\Beacon\v1.0\code\

MSBUILD %rootFolder%BeaconClient\src\BeaconClient.sln

MSBUILD %rootFolder%BeaconServer\src\BeaconServer.sln

pause

Start IE with a Specific Url

SET iexplore=C:\"Program Files"\"Internet Explorer"\IEXPLORE.EXE

SET url=http://www.yahoo.com

START %iexplore% %url%

Kill All IE Instances

taskkill /f /im iexplore.exe

Open Chrome in a New Window

start "Chrome" chrome --new-window https://mail.google.com

Start Chrome with 2 Specific Urls


SET appPath=C:\Users\[Username]\AppData\Local\Google\Chrome\Application\chrome.exe

START %appPath% http://dictionary.reference.com/ http://translate.google.com/

Empty a File
To empty any file, such as .log, .txt, .cs, you can use the following command:


set filePath1=FolderName\filename.log
type NUL > %filePath1%

Reset IIS
iisreset

Kill Current Web Server Processes

Taskkill /IM WebDev.WebServer40.EXE /F

Kill Chrome

Taskkill /IM WebDev.WebServer40.EXE /F

Build and Publish a Solution

msbuild C:\\AppFolder\AppProject.csproj /p:DeployOnBuild=true /p:PublishProfile=C:\\AppFolder\Properties\PublishProfiles\localhost.pubxml /p:VisualStudioVersion=12.0

Delete a File

DEL c:\folder\filename.sql



SVN Get Latest

CD C:\Program Files\TortoiseSVN\bin\

START TortoiseProc.exe /command:update /path:"C:\Svn\mediacenter\" /closeonend:1



More:

Friday 9 October 2009

How to Know Which Ports of a Computer Is Open or Closed?

Code:

This is my PortScanner class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

public class PortScanner
{
public string Host { get; set; }

public PortScanner(string host)
{
this.Host = host;
}

public ScannerResult Scan(int fromPort, int toPort)
{
var result = new ScannerResult();

for (int portNumber = fromPort; portNumber <= toPort; portNumber++)
{
if (IsPortOpen(portNumber))
result.OpenPorts.Add(portNumber.ToString());

else result.ClosedPorts.Add(portNumber.ToString());
}

return result;
}

public int FindFirstOpenPort(int fromPort, int toPort)
{
for (int portNumber = fromPort; portNumber <= toPort; portNumber++)
{
if (IsPortOpen(portNumber))
return portNumber;
}
return 0;
}







private static int FindFreePort()
{
int port = 0;

IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(endPoint);
IPEndPoint local = (IPEndPoint)socket.LocalEndPoint;
port = local.Port;
}

if (port == 0)
throw new InvalidOperationException("Unable to find a free port.");

return port;
}

public bool IsPortOpen(int port)
{
Socket socket = null;
try
{
// Make a TCP-based socket
socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
// Connect
socket.Connect(host, port);
return true;
}
catch (SocketException se)
{
if (se.SocketErrorCode == SocketError.ConnectionRefused)
{
return false;
}
else
{
// An error occurred when attempting to access the socket
Debug.WriteLine(se.ToString());
Console.WriteLine(se.ToString());
}
}
finally
{
if (socket != null)
{
if (socket.Connected)
socket.Disconnect(false);
socket.Close();
}
}
return false;
}

}








This is my ScannerResult class:






using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class ScannerResult
{
public List<string> OpenPorts = new List<string>();
public List<string> ClosedPorts = new List<string>();
}




And this is how to use it:




var portScanner = new PortScanner("127.0.0.1");
var result = portScanner.Scan(1, 65535);

How to Ping a Website or Server Asynchronously

Why?

Sometimes, you need to know whether a Server is down.

Code:

private void btnPing_Click(object sender, RoutedEventArgs e)
{
PingAsync("www.google.com", "I send myself to the callback method");
}

private static void PingAsync(string hostName, object toBeSent)
{
var pinger = new Ping();

pinger.PingCompleted += pinger_PingCompleted;

pinger.SendAsync(hostName, toBeSent);
}
private static void pinger_PingCompleted(object sender, PingCompletedEventArgs e)
{
PingReply reply = e.Reply;

DisplayPingReplyInfo(reply);

if (e.Cancelled)
{
Console.WriteLine("Ping for " + e.UserState.ToString() + " was cancelled");
}
else if (e.Error != null)
{
Console.WriteLine("Exception thrown during ping: {0}", e.Error.ToString());
}
}
private static void DisplayPingReplyInfo(PingReply reply)
{
Console.WriteLine("Results from pinging " + reply.Address);
Console.WriteLine("\tFragmentation allowed?: {0}", !reply.Options.DontFragment);
Console.WriteLine("\tTime to live: {0}", reply.Options.Ttl);
Console.WriteLine("\tRoundtrip took: {0}", reply.RoundtripTime);
Console.WriteLine("\tStatus: {0}", reply.Status.ToString());
}

Unsuccessful Ping:

If a computer is not reached successfully by the ping request, it does not necessarily mean that the computer is unreachable. Many factors can prevent a ping from succeeding such as:

  • The machine being offline
  • Network topology
  • Firewalls
  • Packet filters
  • Proxy servers

More details:

Wednesday 7 October 2009

How to Check Whether a Socket Is Still Connected?

Socket class has a property called Connected. This Connected property doesn't specify whether the socket is now connected or not but it returns true if the Socket was connected to a remote resource as of the most recent operation; otherwise, false. What this means is that Microsoft is better to rename this property to "WasConnected" rather than "Connected".

The following method helps to determine whether a socket is now connected (Indeed, it pings the socket):

public static bool IsSocketStillConnected(Socket socket)
{
bool connected = true;
bool blockingState = socket.Blocking;
try
{
byte[] tmp = new byte[1];
// Setting Blocking to false makes the execution not to wait until it's complete
socket.Blocking = false;
socket.Send(tmp, 0, 0);
}
catch (SocketException e)
{
connected = false;
}
finally
{
socket.Blocking = blockingState;
}
return connected;
}

Even if you use this method, there is still a millisecond gap, you see?

if (IsSocketStillConnected(mySocket))
{
mySocket.Send(message);
}

What this means is that the best practice is:

Whenever you want to Send or Receive a message using a Socket whether synchronously or asynchronously, you should wrap it with a try/catch block.

Sunday 4 October 2009

C# Code Analysis Tools

StyleCop:
StyleCop is a free static code analysis tool from Microsoft that checks C# code for conformance to StyleCop's recommended coding styles and a subset of Microsoft's .NET Framework Design Guidelines such as casing, white space, indents, etc.

It can be run from inside of Visual Studio or integrated into an MSBuild project.

Links:
FxCop:
FxCop is a free static code analysis tool from Microsoft that checks .NET managed code assemblies for conformance to Microsoft's .NET Framework Design Guidelines.

It's main concerns are:
  • Correctness
  • Library design
  • Localization
  • Naming conventions
  • Performance
  • Security
Unlike StyleCop, you can't run FxCop from inside Visual Studio but it has a project for itself that needs to be opened.


Tip: Both FxCop and StyleCop have few overlapping features such as Naming Convention

Visual Studio Integration Code Analysis Tool:
FxCop is essentially a standalone version of Visual Studio Integration Code Analysis.

NArrange

Resharper: