DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets

  • submit to reddit

Recent Snippets

                    using System;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
 
public class WebsiteThumbImage
{
    public int ThumbWidth { get; set; }
    public int ThumbHeight { get; set; }
    public int BrowserWidth { get; set; }
    public int BrowserHeight { get; set; }
 
    public string Url { get; set; }
    public Bitmap ThumbImage { get; set; }
 
    public Bitmap Generate()
    {
        if (ValidationControl())
            return null;
 
        Thread th = new Thread(new ThreadStart(_Execute));
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
        th.Join();
 
        return ThumbImage;
    }
 
    // just operational codes :D
    public void _Execute()
    {            
        WebBrowser browser = new WebBrowser();
        browser.ScrollBarsEnabled = false;
        browser.Navigate(this.Url);
        browser.DocumentCompleted += browser_DocumentCompleted;
 
        while (browser.ReadyState != WebBrowserReadyState.Complete)
            Application.DoEvents();
        browser.Dispose();
 
    }
 
    void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        WebBrowser WebBrowser = (WebBrowser)sender;
        WebBrowser.ClientSize = new Size(this.BrowserWidth, this.BrowserHeight);
        WebBrowser.ScrollBarsEnabled = false;
 
        this.ThumbImage = new Bitmap(WebBrowser.Bounds.Width, WebBrowser.Bounds.Height);
        WebBrowser.BringToFront();
        WebBrowser.DrawToBitmap(this.ThumbImage, WebBrowser.Bounds);
        this.ThumbImage = (Bitmap)this.ThumbImage.GetThumbnailImage(this.ThumbWidth, this.ThumbHeight, null, IntPtr.Zero);
    }
 
    private bool ValidationControl() 
    {
        if (String.IsNullOrEmpty(this.Url))
            throw new ArgumentNullException();
 
        // for url validation
        if (!Uri.IsWellFormedUriString(this.Url, UriKind.RelativeOrAbsolute))
            throw new Exception();
 
        // another validation method -- using optional
        if (!IsValidUrl(this.Url))
            throw new Exception();
 
        return true;
    }
 
    private bool IsValidUrl(string url)
    {
        return Regex.IsMatch(url, @"(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?");
    }
}
 
// Let's use
 string url = ((string.IsNullOrEmpty(Request.Params["site"])) ? "blog.yemrekeskin.com" : Request.Params["site"]);
 int width = ((string.IsNullOrEmpty(Request.Params["width"])) ? 1000 : int.Parse(Request.Params["width"]));
 int height = ((string.IsNullOrEmpty(Request.Params["height"])) ? 940 : int.Parse(Request.Params["height"]));
 int capWidth = ((string.IsNullOrEmpty(Request.Params["capWidth"])) ? 900 : int.Parse(Request.Params["capWidth"]));
 int capHeight = ((string.IsNullOrEmpty(Request.Params["capHeight"])) ? 800 : int.Parse(Request.Params["capHeight"]));
 
 string address = "http://" + url;
 Bitmap thumbnail = WebsiteThumbnailImageGenerator.GetWebSiteThumbnail(address, capWidth, capHeight, width, height);
 
 Response.ContentType = "image/jpeg";
 thumbnail.Save(Response.OutputStream, ImageFormat.Jpeg);                
                    // Object Structure
 
[Serializable]
public class BasePerson
{
    public string SerialNo { get; set; }
    public Guid IdNo { get; set; }
}
 
[Serializable]
public class Person
    :BasePerson
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public short Age { get; set; }
 
    public AddressInfo AddressInfo { get; set; }
}
 
[Serializable]
public class AddressInfo 
{
    public string Street { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}
 
// Helper class for other data formats
// for binary serilization
public static class BinarySerilizationHelper
{
    public static TObject Deserialize<TObject>(string binarydata)
    {
        byte[] b = Convert.FromBase64String(binarydata);
        using (var stream = new MemoryStream(b))
        {
            var formatter = new BinaryFormatter();
            stream.Seek(0, SeekOrigin.Begin);
            return (TObject)formatter.Deserialize(stream);
        }
    }
 
    public static string Serialize<TObject>(TObject obj)
    {
        using (var stream = new MemoryStream())
        {
            var formatter = new BinaryFormatter();
            formatter.Serialize(stream, obj);
            stream.Flush();
            stream.Position = 0;
            return Convert.ToBase64String(stream.ToArray());
        }
    }
}
// for XML Serilization
public static class XmlSerilizationHelper
{
    public static string ToXML(Object obj)
    {
        var stringwriter = new System.IO.StringWriter();
        var serializer = new XmlSerializer(obj.GetType());
        serializer.Serialize(stringwriter, obj);
        return stringwriter.ToString();
    }
 
    public static BasePerson ToObject(string xml)
    {
        var stringReader = new System.IO.StringReader(xml);
        var serializer = new XmlSerializer(typeof(Person));
        return serializer.Deserialize(stringReader) as Person;
    }
}
 
// Let's use our helper classes in console application :D
class Program
{
    static void Main(string[] args)
    {
        // JSON
        // Binary
        // XML
 
        AddressInfo address = new AddressInfo
        {
            Street = "Bülbül str.",
            City = "İstanbul",
            Country = "Turkey"
        };
 
        Person obj = new Person
        {
            AddressInfo = address,
            IdNo = System.Guid.NewGuid(),
            SerialNo = "SED23SU98",
            Age = 13,
            Name = "Yunus Emre",
            Surname = "KESKIN"
        };
 
 
        // JSON
        var json = new JavaScriptSerializer().Serialize(obj);
        Console.WriteLine(json);
 
        Console.WriteLine("---");
 
        // XML
        string xml = XmlSerilizationHelper.ToXML(obj);
        Console.WriteLine(xml);
 
        Console.WriteLine("---");
 
        Person person = XmlSerilizationHelper.ToObject(xml) as Person;
            
        // Binary Serilization
        string binary = BinarySerilizationHelper.Serialize(obj);
        Console.WriteLine(binary);
        Person dummy = BinarySerilizationHelper.Deserialize<Person>(binary);
            
        Console.WriteLine(dummy.IdNo);
            
 
        Console.ReadLine();
 
    }
}                
                    public static class WebServiceExtention
{
    public static bool isValidWebServiceUrl(this string url)
    {
        bool rv = true;
        if (String.IsNullOrEmpty(url))
            rv = false;
 
        string Http_URL = HttpUtility.UrlDecode(url);
 
        HttpWebRequest ObjReq = (HttpWebRequest)HttpWebRequest.Create(Http_URL);
        ObjReq.Timeout = 36000;
        ObjReq.UseDefaultCredentials = true;
 
        try
        {
            if (ObjReq.GetResponse().ContentLength < 0)
                rv = false;
        }
        catch (Exception)
        {
            rv = false;
        }
        return rv;
    }
}                
                    public interface IProcessor
{
    void Process();
}
 
public abstract class BaseProcessor
    : IProcessor
{
    public delegate void ProcessorStartingEventHandler(params Object[] param);
    public delegate void ProcessorStartedEventHandler(params Object[] param);
    public delegate void ProcessorCompletedEventHandler(params Object[] param);
    public delegate void ProcessorErrorEventHandler(params Object[] param);
 
    public ProcessorStartingEventHandler ProcessorStarting = null;
    public ProcessorStartedEventHandler ProcessorStarted = null;
    public ProcessorCompletedEventHandler ProcessorCompleted = null;
    public ProcessorErrorEventHandler ProcessorError = null;
 
    // you can set status in the processor class 
    public ProcessorStatus.Current Status { get; private set; }
 
    // parameter variables
    public Parameters _parameters = null;
    public Parameters Parameters
    {
        set { _parameters = value; }
    }
 
    // threading mechanism (Semaphore)
    private static Semaphore _semaphore = null;
    private static object _semaphoreLockObj = new object();
        
    // singleton pattern for semaphore
    private void InitializeSemaphore(int jobCountLimit)
    {
        if (_semaphore == null)
        {
            lock (_semaphoreLockObj)
            {
                if (_semaphore == null)
                {
                    _semaphore = new Semaphore(jobCountLimit, jobCountLimit);
                }
            }
        }
    }
 
    // ctor methods
    public BaseProcessor(Parameters param, int jobCountLimit)
    {
        this._parameters = param;
        InitializeSemaphore(jobCountLimit);
    }
 
    public BaseProcessor(Parameters param)
        : this(param, 3)
    { }
 
    // Real Job Method 
    protected abstract void RunJob(object param, out object[] output);
 
    public void Process()
    {
        // starting loging for real job's log table
        this.Status = ProcessorStatus.Current.Starting;
 
        if (ProcessorStarting != null)
            ProcessorStarting(this.GetType());
 
        ThreadPool.QueueUserWorkItem(new WaitCallback(Job), this._parameters);
    }
 
    private void Job(object param)
    {
        object[] output = null;
 
        // started loging
        this.Status = ProcessorStatus.Current.Started;
        if (ProcessorStarted != null)
            ProcessorStarted(this.GetType());
 
        try
        {
            _semaphore.WaitOne();
            RunJob(param, out output);
        }
        catch (Exception ex)
        {
            this.Status = ProcessorStatus.Current.Error;
            if (ProcessorError != null)
            {
                ProcessorError(this.GetType(), ex);
            }
            // error logging
        }
        finally
        {
            _semaphore.Release();
        }
 
        // completing loging
        this.Status = ProcessorStatus.Current.Completing;
 
        if (ProcessorCompleted != null)
        {
            ProcessorCompleted(this.GetType(), output);
        }
 
        // completed loging
        this.Status = ProcessorStatus.Current.Completed;
    }
}
 
// Customized Processor Class for custom jobs
public class MainProcessor
    : BaseProcessor
{
    public MainProcessor(Parameters param, int jobLimit)
        : base(param, jobLimit)
    { }
 
    public MainProcessor(Parameters param)
        : base(param)
    { }
 
    protected override void RunJob(object param, out object[] output)
    {
        MainJob mj = new MainJob();
        output = mj.Start(param as Parameters);
    }
}
 
public class ProcessorStatus
{
    public enum Current
    {
        Starting = 1,
        Started = 2,
        Completing = 3,
        Completed = 4,
        Error = 5
    }
}
 
public class Parameters
{
    public IDictionary<string, Object> _prms = null;
 
    public Parameters()
    {
        this._prms = new Dictionary<string, Object>();
    }
 
 
    public void Add(string key, object value)
    {
        this.Remove(key);
 
        if (!String.IsNullOrEmpty(key))
            this._prms.Add(key, value);
    }
 
    public void Remove(string key)
    {
        if (this._prms.ContainsKey(key) && !String.IsNullOrEmpty(key))
            this._prms.Remove(key);
    }
 
    public object TryGetValue(string key)
    {
        object obj;
        _prms.TryGetValue(key, out obj);
        return obj;
    }
 
    public void Clear()
    {
        this._prms.Clear();
    }
}

public interface IJob
{
    object[] Start(Parameters paramList = null);
}
 
public abstract class BaseJob
    : IJob
{
    public abstract object[] Start(Parameters paramList = null);
}
 
public class MainJob
    : BaseJob
{
    public override object[] Start(Parameters paramList = null)
    {
        try
        {
            // fact job operations
            Console.WriteLine("Real Operational Job...");
        }
        catch (Exception ex)
        {
            return new object[] { ex.Message };
        }
        return null;
    }
}                
                    /**
*
* @param mixed VARGS: any number of strings or arrays, each being a file path or a glob to watch.
* @return array The set of files matches the passed globs.
*/
function recursive_glob($requestedGlobs)
{
    // expoode vargs
    $requestedGlobs = array();
    foreach (func_get_args() as $arg) {
        if (!is_array($arg))
        {
            $arg = array($arg);
        }
        $requestedGlobs = array_merge($requestedGlobs, $arg);
    }
    $requestedGlobs = array_unique($requestedGlobs);

    // expand all a/b/**/c/*.foo into globs
    $globsToProcess = array();
    foreach ($requestedGlobs as $glob) {
        $hasRecursiveDirGlob = (strpos($glob, '**') !== false);
        if ($hasRecursiveDirGlob)
        {
            list($baseDir, $subGlob) = explode('**', $glob, 2);
            $baseDir = rtrim($baseDir, '/');
            $subGlob = ltrim($subGlob, '/');

            // root glob
            $globsToProcess[] = "{$baseDir}/{$subGlob}";

            $rDirIterator = new RecursiveDirectoryIterator($baseDir);
            $itIterator = new RecursiveIteratorIterator($rDirIterator, RecursiveIteratorIterator::CHILD_FIRST);
            foreach ($itIterator as $path => $fileInfo) {
                if ($itIterator->getInnerIterator()->isDot()) continue;
                if ($itIterator->getInnerIterator()->isFile()) continue;

                $globsToProcess[] = "{$path}/{$subGlob}";
            }
        }
        else
        {
            $globsToProcess[] = $glob;
        }
    }

    $matches = array();
    $globsToProcess = array_unique($globsToProcess);
    foreach ($globsToProcess as $glob) {
        $matches = array_merge($matches, glob($glob));
    }

    $matches = array_unique($matches);
    return $matches;
}

                
                    //[C#]

// Private members
private SPSite site = null;
private SPWeb web = null;

/// <summary>
/// This method is called through the delegate elevatedGetSite which is definend in button2_Click
/// </summary>
private void EstablishSharepoint()
{
    site = new SPSite("http://localhost/Site1");
    web = site.OpenWeb();
}

/// <summary>
/// Click the event of a Windows form button
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
    SPSecurity.CodeToRunElevated elevatedGetSite = new SPSecurity.CodeToRunElevated(EstablishSharepoint);
    SPSecurity.RunWithElevatedPrivileges(elevatedGetSite);

    // Path to the MSG file stored in Shared Documents folder
    SPFile msgFile = web.GetFile("Shared Documents/Test.msg");

    // Read the file into a memory stream.
    MemoryStream fileStream = new MemoryStream();
    byte[] currentFileContent = msgFile.OpenBinary();
    fileStream.Write(currentFileContent, 0, currentFileContent.Length);
    fileStream.Position = 0;

    // Create an instance of the MailMessage class
    // and pass the memory stream of the MSG file to it
    MailMessage msg = MailMessage.Load(fileStream, MessageFormat.Msg);
    fileStream.Close();
    fileStream.Dispose();

    // Access the MailMessage class' public properties
    Console.WriteLine("Subject: " + msg.Subject);
    Console.WriteLine("From: " + msg.From.ToString());
    Console.WriteLine("Text Body: " + msg.TextBody);
}
 
//[VB.NET]

' Private members
Private site As SPSite = Nothing
Private web As SPWeb = Nothing

''' <summary>
''' This method is called through the delegate elevatedGetSite which is definend in button2_Click
''' </summary>
Private Sub EstablishSharepoint()
    site = New SPSite("http://localhost/Site1")
    web = site.OpenWeb()
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim elevatedGetSite As New SPSecurity.CodeToRunElevated(AddressOf EstablishSharepoint)
    SPSecurity.RunWithElevatedPrivileges(elevatedGetSite)

    ' The path to the MSG file stored in the Shared Documents folder
    Dim msgFile As SPFile = web.GetFile("Shared Documents/Test.msg")

    ' Read the file into a memory stream.
    Dim fileStream As New MemoryStream()
    Dim currentFileContent As Byte() = msgFile.OpenBinary()
    fileStream.Write(currentFileContent, 0, currentFileContent.Length)
    fileStream.Position = 0

    ' Create an instance of the MailMessage class
    ' and pass the memory stream of the MSG file to it
    Dim msg As MailMessage = MailMessage.Load(fileStream, MessageFormat.Msg)
    fileStream.Close()
    fileStream.Dispose()

    ' Access the MailMessage class' public properties 
    Console.WriteLine("Subject: " & msg.Subject)
    Console.WriteLine("From: " & msg.From.ToString())
    Console.WriteLine("Text Body: " & msg.TextBody)
End Sub
                
                    public String getPath() throws UnsupportedEncodingException {
		String path = this.getClass().getClassLoader().getResource("").getPath();
		String fullPath = URLDecoder.decode(path, "UTF-8");
		String pathArr[] = fullPath.split("/WEB-INF/classes/");
		System.out.println(fullPath);
		System.out.println(pathArr[0]);
		fullPath = pathArr[0];
		
		String reponsePath = "";
// to read a file from webcontent
		reponsePath = new File(fullPath).getPath() + File.separatorChar + "newfile.txt";
		return reponsePath;
	}                
                    #!/bin/sh
# Empties current directory and extracts single file/folder from svn
# see complete description on http://jv-ration.com/2013/11/modify-single-file-in-svn-tree

die () {
    echo >&2 "$@"
    exit 1
}

usage=$"This scripts extract single file/folder from SVN repository into the current directory,\n\
allowing to modify it locally without extracting all other sibling files and directories\n\
\n\
$0 svn_uri\n\
"

[ "$#" -ge 1 ] || die "SVN URI is not provided. $usage"
fullUri=$1

# Testing is svn CLI is present
svnRun=`which svn 2> /dev/null`
if [ ! $svnRun ]
then
  die "svn CLI is not found on PATH"
fi  

# determine parent folder and file from the give URI
svnFile=${fullUri##*/}
svnParent=${fullUri%%/${svnFile}}

# remove .svn and the file if they exist
rm -rf .svn
rm -f $svnFile

# extract the file
svn checkout -q --depth=empty $svnParent .
svn update $svnFile

echo "\n\
After $svnFile is changed locally commit it using\n\
  svn commit -m \"your update description\""                
                    //Sample Code for Downloading Messages from the Public Folders of Exchange Server

//[C#]

class Program
{
    static string mailboxURI = "https://exchange/ews/exchange.asmx"; // EWS
    static string username = "administrator";
    static string password = "pwd";
    static string domain = "ex2013.local";


    static void Main(string[] args)
    {
        try
        {
            ReadPublicFolders();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    private static void ReadPublicFolders()
    {
        NetworkCredential credential = new NetworkCredential(username, password, domain);
        IEWSClient client = EWSClient.GetEWSClient(mailboxUri, credentials);

        ExchangeFolderInfoCollection folders = client.ListPublicFolders();
        foreach (ExchangeFolderInfo publicFolder in folders)
        {
            Console.WriteLine("Name: " + publicFolder.DisplayName);
            Console.WriteLine("Subfolders count: " + publicFolder.ChildFolderCount);
            ListMessagesFromSubFolder(publicFolder, client);

        }
    }

    private static void ListMessagesFromSubFolder(ExchangeFolderInfo publicFolder, ExchangeWebServiceClient client)
    {
        Console.WriteLine("Folder Name: " + publicFolder.DisplayName);
        ExchangeMessageInfoCollection msgInfoCollection = client.ListMessagesFromPublicFolder(publicFolder);
        foreach (ExchangeMessageInfo messageInfo in msgInfoCollection)
        {
            MailMessage msg = client.FetchMessage(messageInfo.UniqueUri);
            Console.WriteLine(msg.Subject);
            msg.Save(msg.Subject + ".msg", MailMessageSaveType.OutlookMessageFormat);
        }

        // Call this method recursively for any subfolders
        if (publicFolder.ChildFolderCount > 0)
        {
            ExchangeFolderInfoCollection subfolders = client.ListSubFolders(publicFolder);
            foreach (ExchangeFolderInfo subfolder in subfolders)
            {
                ListMessagesFromSubFolder(subfolder, client);
            }
        }
    }
}
 
//[VB.NET]

Class Program
	Private Shared mailboxURI As String = "https://ex2010/ews/exchange.asmx" ' EWS
	Private Shared username As String = "administrator"
	Private Shared password As String = "pwd"
	Private Shared domain As String = "ex2010.local"


	Shared Sub Main(ByVal args As String())
		Try
			ReadPublicFolders()
		Catch ex As Exception
			Console.WriteLine(ex.Message)
		End Try
	End Sub

	Private Shared Sub ReadPublicFolders()
		Dim credential As NetworkCredential = New NetworkCredential(username, password, domain)
		Dim client As ExchangeWebServiceClient = New ExchangeWebServiceClient(mailboxURI, credential)

		Dim folders As ExchangeFolderInfoCollection = client.ListPublicFolders()
		For Each publicFolder As ExchangeFolderInfo In folders
			Console.WriteLine("Name: " & publicFolder.DisplayName)
			Console.WriteLine("Subfolders count: " & publicFolder.ChildFolderCount)
			ListMessagesFromSubFolder(publicFolder, client)

		Next publicFolder
	End Sub

	Private Shared Sub ListMessagesFromSubFolder(ByVal publicFolder As ExchangeFolderInfo, ByVal client As ExchangeWebServiceClient)
		Console.WriteLine("Folder Name: " & publicFolder.DisplayName)
		Dim msgInfoCollection As ExchangeMessageInfoCollection = client.ListMessagesFromPublicFolder(publicFolder)
		For Each messageInfo As ExchangeMessageInfo In msgInfoCollection
			Dim msg As MailMessage = client.FetchMessage(messageInfo.UniqueUri)
			Console.WriteLine(msg.Subject)
			msg.Save(msg.Subject & ".msg", MailMessageSaveType.OutlookMessageFormat)
		Next messageInfo

		' Call this method recursively for any subfolders
		If publicFolder.ChildFolderCount > 0 Then
			Dim subfolders As ExchangeFolderInfoCollection = client.ListSubFolders(publicFolder)
			For Each subfolder As ExchangeFolderInfo In subfolders
				ListMessagesFromSubFolder(subfolder, client)
			Next subfolder
		End If
	End Sub
End Class
                
                    separator=':'
text_to_split=$PATH

paths=(`echo $PATH | tr $separator ' '`)

cant=${#paths[*]}
i=0
while [ $i -lt $cant ]; do
        echo ${paths[$i]}
	let i++
done