Want to get a space here? Contact us!
cghersi
cghersi
Reputation Top 1%
Cristiano Ghersi
163 Snippets  (1st place)
Published
13 Channels
Created
45 Channels
Following
yesterday at 11:34:29 AM
Last Visit
on May 5, 2012
Registered
4592 points  (1st place)
Reputation
Top 5% Publisher
Junior Code Generator
Serious Code Generator
Senior Code Generator
Master Code Generator
Guru Code Generator
Junior Publisher
Serious Publisher
Senior Publisher
Master Publisher
Guru Publisher
Master Topic Creator
Guru Topic Creator
Junior Topic Hub
Serious Topic Hub
Senior Topic Hub
Master Topic Hub
Junior Trend Maker
Serious Trend Maker
Senior Trend Maker
Serious Team Manager
Senior Team Manager
Junior Influencer
Serious Influencer
Senior Influencer
Junior Commenter
Serious Commenter
Senior Commenter
Master Commenter
Junior Judge
Serious Judge
Senior Judge
Master Judge
Junior Popular Coder
Serious Popular Coder
Senior Popular Coder
Master Popular Coder
Guru Popular Coder
Junior Autobiographer
Serious Autobiographer
Senior Autobiographer
Master Autobiographer
Junior Snip2Coder
Junior Geek Aggregator
Serious Geek Aggregator
Senior Geek Aggregator
Junior Famous Coder

Recent Snippets See all snippets by cghersi

public by cghersi modified on Apr 30, 2013  3684  8

Java: read from USB using RXTX library

This is a well-tested class to read from USB device using RXTX library. First of all place rxtxSerial.so (or rxtxSerial.dll) in the classpath. The received bytes are stored in a queue called "receivedBytes". This queue is filled by the serialEvent() callback called by RXTX framework. Users of this class should retrieve the ready data from "receiv
usb
import gnu.io.*;
import java.io.*;

import java.util.Enumeration;
import java.io.IOException;

/**
 * This class provides the utilities to read the data exchanged via USB port.
 */
public class USBComm implements SerialPortEventListener {

	/**
	 * Stream for the storage of incoming data
	 */
	private InputStream inputStream;
	/**
	 * Stream for the dispatching of data
	 */
	private OutputStream outputStream;
	/**
	 * Timeout of the USB port
	 */
	private final int PORT_TIMEOUT = 2000;
	/**
	 * Representation of the serial port used for the communication
	 */
	private SerialPort serialPort;
	/**
	 * Buffer that stores the received bytes from the media
	 */
	protected LinkedBlockingQueue<Byte> receivedBytes;

	/**
	 * Builds a new manager for the communication via USB port.
	 * @exception IOException if an error occurred during the opening of the USB port
	 */
	public USBComm() throws IOException {
		String port = "COM1"; //place the right COM port here, OS dependent
	
		//Check that the USB port exists and is recognized:
		Enumeration<?> portList = CommPortIdentifier.getPortIdentifiers();
		boolean portFound = false;
		CommPortIdentifier portId = null;
		while (portList.hasMoreElements()) {
			portId = (CommPortIdentifier) portList.nextElement();
		    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
		    	log.info(portId.getName());
				if (portId.getName().equals(port)) {
					System.out.println("Found port: " + port);
				    portFound = true;
				    break;
				} 
		    } 
		} 
	
		if (!portFound) 
		    throw new IOException("port " + port + " not found.");
	
		try {
			System.out.println("USB port opening...");
		    serialPort = (SerialPort) portId.open("USBCommunicator", PORT_TIMEOUT);
		    System.out.println("USB port opened");
		    inputStream = serialPort.getInputStream();
		    outputStream = serialPort.getOutputStream();
		    serialPort.addEventListener(this);
			    	serialPort.notifyOnDataAvailable(true);
			//#==================================================================#
			// WARNING! - DO NOT SET THE FOLLOWING PROPERTY WITH RXTX LIBRARY, IT
			// 			  CAUSES A PROGRAM LOCK:
			// 	serialPort.notifyOnOutputEmpty(true);
			//#==================================================================#
			    	
		    //wait for a while to leave the time to javax.comm to
		    //correctly configure the port:
		    Thread.sleep(1000);
		    
			int baudRate = 115200; //set propertly
	    	serialPort.setSerialPortParams(baudRate, 
	    		SerialPort.DATABITS_8, 
	    		SerialPort.STOPBITS_1, 
				SerialPort.PARITY_NONE);
		    
	    	serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
	    		
		    System.out.println("setted SerialPortParams");
		} catch (Exception e) {
			System.err.println(e.getMessage());
			throw new IOException(e.getMessage());
		}
	}

	
	public void closeUSB(){
		//close the streams for serial port:
		try {
			inputStream.close();
			outputStream.close();
		} catch (IOException e) {
			System.err.println("Cannot close streams:" + e.getMessage(), e);
		}
	}

	/**
	 * Listener for USB events
	 * 
	 * @param event new event occurred on the USB port
	 */
	public void serialEvent(SerialPortEvent event){
		switch (event.getEventType()) {
	
			case SerialPortEvent.BI:
			case SerialPortEvent.OE:
			case SerialPortEvent.FE:
			case SerialPortEvent.PE:
			case SerialPortEvent.CD:
			case SerialPortEvent.CTS:
			case SerialPortEvent.DSR:
			case SerialPortEvent.RI:
			case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
				//nothing to do...
			    break;
	
			case SerialPortEvent.DATA_AVAILABLE:
				byte received = -1;
				do {
					try {
						received = (byte)inputStream.read();
					} catch (IOException e) {
						System.err.println("Error reading USB:" + e.getMessage());
					}
				
					synchronized (receivedBytes) {
						try {
							receivedBytes.add(received);
						} catch (IllegalStateException ew) {
							System.err.println(ew.getMessage());
							receivedBytes.poll();
							receivedBytes.add(received);
						}
					}
				} while(received != -1);

			    break;
		}
	}

	protected void write(byte[] buffer){
	    try {
	    	outputStream.write(buffer);
	    	outputStream.flush();
	    } catch (IOException e) {
	    	System.err.println("Cannot write:" + e.getMessage());
	    }
	}
}

public by cghersi modified on Jan 31, 2014  646  7

How to encrypt and decrypt strings in C#

This class can be used to encrypt and decrypt the given string. In the current implementation the passwrod is directly saved inside the code; depending on the infrastructure and architecture of the code sometimes it can be passed as parameter
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

public static class Encryptor
{
    static private string _key = "myVeryStrongPsw";

    /// <summary>
    /// Encrypt the given string using the default key.
    /// </summary>
    /// <param name="strToEncrypt">The string to be encrypted.</param>
    /// <returns>The encrypted string.</returns>
    public static string Encrypt(string strToEncrypt)
    {
        try
        {
            return Encrypt(strToEncrypt, _key);
        }

        catch (Exception ex)
        {
            return "Wrong Input. " + ex.Message;
        }
    }

    /// <summary>
    /// Decrypt the given string using the default key.
    /// </summary>
    /// <param name="strEncrypted">The string to be decrypted.</param>
    /// <returns>The decrypted string.</returns>
    public static string Decrypt(string strEncrypted)
    {
        try
        {
            return Decrypt(strEncrypted, _key);
        }
        catch (Exception ex)
        {
            return "Wrong Input. " + ex.Message;
        }
    }

    /// <summary>
    /// Encrypt the given string using the specified key.
    /// </summary>
    /// <param name="strToEncrypt">The string to be encrypted.</param>
    /// <param name="strKey">The encryption key.</param>
    /// <returns>The encrypted string.</returns>
    public static string Encrypt(string strToEncrypt, string strKey)
    {
        try
        {
            TripleDESCryptoServiceProvider objDESCrypto =
                new TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();
            byte[] byteHash, byteBuff;
            string strTempKey = strKey;
            byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
            objHashMD5 = null;
            objDESCrypto.Key = byteHash;
            objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB
            byteBuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);
            return Convert.ToBase64String(objDESCrypto.CreateEncryptor().
                TransformFinalBlock(byteBuff, 0, byteBuff.Length));
        }
        catch (Exception ex)
        {
            return "Wrong Input. " + ex.Message;
        }
    }

    /// <summary>
    /// Decrypt the given string using the specified key.
    /// </summary>
    /// <param name="strEncrypted">The string to be decrypted.</param>
    /// <param name="strKey">The decryption key.</param>
    /// <returns>The decrypted string.</returns>
    public static string Decrypt(string strEncrypted, string strKey)
    {
        try
        {
            TripleDESCryptoServiceProvider objDESCrypto =
                new TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();
            byte[] byteHash, byteBuff;
            string strTempKey = strKey;
            byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
            objHashMD5 = null;
            objDESCrypto.Key = byteHash;
            objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB
            byteBuff = Convert.FromBase64String(strEncrypted);
            string strDecrypted = ASCIIEncoding.ASCII.GetString
            (objDESCrypto.CreateDecryptor().TransformFinalBlock
            (byteBuff, 0, byteBuff.Length));
            objDESCrypto = null;
            return strDecrypted;
        }
        catch (Exception ex)
        {
            return "Wrong Input. " + ex.Message;
        }
    }
}

public by cghersi modified on May 23, 2014  324  6

How to run unit tests created with MS Visual Studio without installing Visual Studio

Do you want to run your unit tests on your staging server? Surely you don't want to make your staging environment "dirty" by installing Visual Studio. I'm also not comfortable with installing the Test Agent. And perhaps you don't have the resources to use Visual Studio Online Continuous Integration stuff... It's not a problem of licenses. We don
1) From C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow (copy all content of the folder):
Extensions (folder)
ActivateApplication.exe
EntityFramework.dll
extension.vsixmanifest
Microsoft.TeamFoundation.TestPlatform.Client.dll
Microsoft.TestTools.Cpp.targets
Microsoft.VisualStudio.MSTest.TestWindow.dll
Microsoft.VisualStudio.TestPlatform.BuildTasks.dll
Microsoft.VisualStudio.TestPlatform.Client.dll
Microsoft.VisualStudio.TestPlatform.Common.dll
Microsoft.VisualStudio.TestPlatform.Core.dll
Microsoft.VisualStudio.TestPlatform.Fakes.dll
Microsoft.VisualStudio.TestPlatform.ObjectModel.dll
Microsoft.VisualStudio.TestPlatform.TestExecutor.Core.dll
Microsoft.VisualStudio.TestPlatform.Utilities.AppContainer.dll
Microsoft.VisualStudio.TestPlatform.Utilities.dll
Microsoft.VisualStudio.TestPlatform.Utilities.PhoneAppContainer.dll
Microsoft.VisualStudio.TestWindow.Core.dll
Microsoft.VisualStudio.TestWindow.CppUnitTestExtension.dll
Microsoft.VisualStudio.TestWindow.dll
Microsoft.VisualStudio.TestWindow.Interfaces.dll
Microsoft.VisualStudio.TestWindow.pkgdef
Microsoft.VisualStudio.TestWindow.VSTest.dll
msdia120typelib_clr0200.dll
TestWindowProvideCodeBase.pkgdef
vstest.console.exe
vstest.console.exe.config
vstest.discoveryengine.exe
vstest.discoveryengine.exe.config
vstest.discoveryengine.x86.exe
vstest.discoveryengine.x86.exe.config
vstest.executionengine.clr20.exe
vstest.executionengine.clr20.exe.config
vstest.executionengine.exe
vstest.executionengine.exe.config
vstest.executionengine.x86.clr20.exe
vstest.executionengine.x86.clr20.exe.config
vstest.executionengine.x86.exe
vstest.executionengine.x86.exe.config

2) From C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC:
vcvarsall.bat (put this file into a sufolder named "vc")

3) From C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\PrivateAssemblies:
Microsoft.VisualStudio.QualityTools.Sqm.dll

4) From C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ReferenceAssemblies\v2.0:
Microsoft.VisualStudio.QualityTools.ExecutionCommon.dll

5) For these files you need to use copy command from a DOS prompt, and then copy from c:/tmp to your staging folder: 
copy C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.QualityTools.Resource\12.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.QualityTools.Resource.dll c:\tmp
copy C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.QualityTools.Common\12.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.QualityTools.Common.dll c:\tmp
copy C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.QualityTools.Tips.UnitTest.ObjectModel\12.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.QualityTools.Tips.UnitTest.ObjectModel.dll c:\tmp
copy C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.QualityTools.UnitTestFramework\10.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll c:\tmp

public by cghersi modified on Apr 10, 2014  235  6

How to open a dockable window in Notepad++ in C#

This code has been refined thanks to the hints given in the Plugin Tutorial Demo that can be found here: https://sourceforge.net/projects/sourcecookifier/files/other%20plugins/NppPlugin.NET.v0.5.zip/download
public static void OpenForm(Form form, string title, int dialogID)
{
    NppTbData _nppTbData = new NppTbData();
    _nppTbData.hClient = form.Handle;
    _nppTbData.pszName = title;

    // the dlgDlg should be the index of funcItem where the current function pointer is in
    _nppTbData.dlgID = dialogID;

    // define the default docking behaviour
    _nppTbData.uMask = NppTbMsg.DWS_DF_CONT_RIGHT | NppTbMsg.DWS_ICONTAB | NppTbMsg.DWS_ICONBAR;
    //_nppTbData.hIconTab = (uint)tbIcon.Handle;
    _nppTbData.pszModuleName = PluginName;
    IntPtr _ptrNppTbData = Marshal.AllocHGlobal(Marshal.SizeOf(_nppTbData));
    Marshal.StructureToPtr(_nppTbData, _ptrNppTbData, false);

    try
    {
        SendMessage(nppData._nppHandle, NppMsg.NPPM_DMMREGASDCKDLG, 0, _ptrNppTbData);
    }
    catch (Exception exc)
    {
        if (log != null)
            log.ErrorFormat("Cannot open form due to {0}", exc.Message);
    }
}


[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct NppTbData
{
    public IntPtr hClient;            // HWND: client Window Handle
    public string pszName;            // TCHAR*: name of plugin (shown in window)
    public int dlgID;                // int: a funcItem provides the function pointer to start a dialog. Please parse here these ID
    // user modifications
    public NppTbMsg uMask;                // UINT: mask params: look to above defines
    public uint hIconTab;            // HICON: icon for tabs
    public string pszAddInfo;        // TCHAR*: for plugin to display additional informations
    // internal data, do not use !!!
    public RECT rcFloat;            // RECT: floating position
    public int iPrevCont;           // int: stores the privious container (toggling between float and dock)
    public string pszModuleName;    // const TCHAR*: it's the plugin file name. It's used to identify the plugin
}


[DllImport("user32")]
public static extern IntPtr SendMessage(IntPtr hWnd, NppMsg Msg, int wParam, IntPtr lParam);

public by cghersi modified on May 9, 2014  428  7

C#: How to Convert a generic Url to absolute Uri

This method provides an Uri object from the given URL, splitted as baseURl and extracted url, e.g. baseURL='http://www.snip2code.com', extractedUrl='./Snippet/25652'
/// <summary>
/// Converts a generic Url to absolute Uri
/// </summary>
/// <param name="baseUrl">The main url of the website</param>
/// <param name="extractedUrl">The url to be converted</param>
/// <returns>An absolute Uri | null</returns>
/// -----------------------------------------------------------------------------------------------------
static public Uri UriAbsoluteFromUrl(string baseUrl, string extractedUrl)
{
    // The URI is in a HTTP page and could have encoded HTML char ...
    string link = HttpUtility.HtmlDecode(extractedUrl.Replace("\n", ""));
    Uri baseUri = new Uri(baseUrl);
    string siteRoot = string.Empty;

    // create absolute link
    if (link.StartsWith("/"))
    {
        //absolute replace
        int firstSlashPos = baseUrl.IndexOf("://");
        string protocol = baseUrl.Substring(0, firstSlashPos + 3);
        Uri siteRef = new Uri(baseUrl.Trim());
        link = string.Concat(protocol, siteRef.Host, link.Trim());
    }
    else if (link.StartsWith("./"))
    {
        //relative replace - same level
        siteRoot = baseUrl.Trim();
        siteRoot = siteRoot.TrimEnd('/');
        link = string.Format("{0}/{1}", siteRoot, link.TrimStart('.', '/'));
    }
    else if (link.StartsWith("../"))
    {
        //relative replace - multi level                                
        siteRoot = baseUrl.Trim();
        string clean = link;

        while (clean.StartsWith("../"))
        {
            clean = clean.Remove(0, 3);
            siteRoot = siteRoot.TrimEnd('/');
            siteRoot = siteRoot.Substring(0, siteRoot.LastIndexOf('/'));
        }

        link = string.Format("{0}/{1}", siteRoot, clean.TrimStart('/'));
    }
    else if (!link.Contains("://"))
    {
        //relative replace - same level
        baseUrl += "/";
        int lastSlash = baseUrl.LastIndexOf('/');
        if (lastSlash > 0 && lastSlash < baseUrl.Length)
            siteRoot = baseUrl.Substring(0, lastSlash);
        siteRoot = siteRoot.TrimEnd('/');
        link = string.Format("{0}/{1}", siteRoot, link.TrimStart('.', '/'));
    }

    // escape the link
    if (!Uri.IsWellFormedUriString(link, UriKind.Absolute))
        link = Uri.EscapeUriString(link);

    if (Uri.IsWellFormedUriString(link, UriKind.Absolute))
        return new Uri(link);
    else
        return null;
}