Tag Archive for c

Drag & Drop with WPF in C#

// WPF Canvas Object
// Canvas LayoutCanvas;
//
// Events Required
//
// Canvas_PreviewMouseLeftButtonDown
// Canvas_PreviewMouseMove
// Canvas_PreviewMouseLeftButtonUp
// Parent_PreviewKeyDown
//
// LayoutCanvas.PreviewMouseLeftButtonDown += LayoutCanvas_PreviewMouseLeftButtonDown;
// LayoutCanvas.PreviewMouseMove += LayoutCanvas_PreviewMouseMove;
// LayoutCanvas.PreviewMouseLeftButtonUp += LayoutCanvas_PreviewMouseLeftButtonUp;
// WindowOrPage.PreviewKeyDown += WindowOrPage_PreviewKeyDown;
//
// Parameters Required
//
// For capturing the mouse position:
// Point ddStartPoint;
//
// The top left corner of the child object (left = x, top = y)
// double ddOriginalLeft;
// double ddOriginalTop;
//
// Properties for managing the state of the drag & drop process:
// bool ddIsMouseDown;
// bool ddIsBeingDragged;
//
// Our original UI element (in my case the children are all Image objects)
// UIElement ddOriginalElement;
//
// The container of the above element when we are in dragging mode
// System.Windows.Shapes.Rectangle ddOverlay;
//

//
// Canvas_PreviewMouseLeftButtonDown
//
// We assign this to our Canvas object as it will control
// catching whether or not we are clicking on the canvas itself
// or on one of its children
//
private void LayoutCanvas_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    // If the source of the click is our canvas object then we want
    // to exit because we are looking for it's children to drag 
    // and not the canvas itself.
    if(e.Source == LayoutCanvas)
    {
	return;
    }
    
    // Identifies that we have started dragging
    ddIsMouseDown = true;

    // Captures the mouse position in the layout canvas
    ddStartPoint = e.GetPosition(LayoutCanvas);

    // Sets up our element that we will be dragging
    ddOriginalElement = (UIElement)e.Source;

    // Tells the Window to give the mouse to the LayoutCanvas
    // object.
    LayoutCanvas.CaptureMouse();

    e.Handled = true;
}	

//
// Canvas_PreviewMouseMove
// 
// Our event handler for updating the position of our
// dragged element
//
// This introduces two helper methods DragStarted() and DragMoved()
// They will be covered later on in the code.
//
private void LayoutCanvas_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
    if(ddIsMouseDown)
    {
	if(!ddIsBeingDragged)
	{
	    // Capture our mouse position relative to the LayoutCanvas object
	    var mousePosition = e.GetPosition(LayoutCanvas);

	    // Creates a transparent rectangle around our current drag point and we want to 
	    // check here that we are within that rectangle
	    if(Math.Abs(mousePosition.X - ddStartPoint.X) > SystemParameters.MinimumHorizontalDragDistance &&
		    Math.Abs(mousePosition.Y - ddStartPoint.Y) > SystemParameters.MinimumVeritcalDragDistance)
	    {
		DragStarted();
	    }
	}
	else
	{
	    DragMoved();
	}
    }
}

//
// Canvas_PreviewMouseLeftButtonUp
//
// Controls the functionality for finishing our drag and drop process.
// This will also introduce the call to DragFinished(bool state);
//
private void LayoutCanvas_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    // This is a fairly simple check. If we are still dragging
    // or starting to drag which means ddIsMouseDown would be 'True'
    // then we don't stop the drag
    if(ddIsMouseDown)
    {
	DragFinished(false);
    }
}

//
// Page_PreviewKeydown
//
// In my code I have my canvas in a Page, you can do this with a Window object as well.
//
private void Page_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    if(e.Key == Key.Escape && ddIsBeingDragged)
    {
	DragFinished = true;
    }
}

// Helper Methods

//
// DragStarted()
//
//
private void DragStarted()
{
    // Capture our last remaining properties
    // needed to support our drag and drop
    // process
    ddIsBeingDragged = true;
    ddOriginalLeft = Canvas.GetLeft(ddOriginalElement);
    ddOriginalTop = Canvas.GetTop(ddOriginalElement);

    // What we are doing here is creating a semi-transparent
    // mirror image of the object we are dragging.
    //
    // This allows us to visually see that we have selected 
    // an object and are dragging it.
    var brush = new VisualBrush(ddOriginalElement);
    brush.Opacity = 0.5;

    ddOverlay = new System.Windows.Shapes.Rectangle();
    ddOverlay.Width = ddOriginalElement.RenderSize.Width;
    ddOverlay.Height = ddOriginalElement.RenderSize.Height;
    ddOverlay.Fill = brush;

    // Finally add the overlay to the LayoutCanvas for displaying
    LayoutCanvas.Children.Add(ddOverlay);
}


//
// DragMoved();
//
private void DragMoved()
{
    // Capture the current mouse position, this will be used
    // to redraw the overlay element we created in DragStarted()
    var currentPosition = System.Windows.Input.Mouse.GetPosition(LayoutCanvas);
    var elementLeft = (currentPosition.X - ddStartPoint.X) + ddOriginalLeft;
    var elementTop = (currentPosition.Y - ddStartPoint.Y) + ddOriginalTop;

    // We update the overlay's position on the LayoutCanvas
    // by setting it's top left corner position below
    Canvas.SetLeft(ddOverlay, elementLeft);
    Canvas.SetTop(ddOverlay, elementTop);
}

//
// DragFinished();
//
private void DragFinished(bool canceled)
{
    if(ddOverlay != null)
    {
	// capture our current position
	var topLeft = Canvas.GetLeft(ddOverlay);
	var top = Canvas.GetTop(ddOverlay);

	if(ddIsBeingDragged)
	{
	    LayoutCanvas.Children.Remove(ddOverlay);

	    // If it wasn't prematurely canceled, then
	    // move the element to the current mouse position
	    if(!canceled)
	    {
		Canvas.SetLeft(ddOriginalElement, topLeft);
		Canvas.SetTop(ddOriginalElement, top);
	    }

	    // Release the mouse from the layoutcanvas.
	    // This is very important. If you do not release the mouse
	    // you have to set the focus of the mouse to another application
	    // and then back again to regain mouse control
	    LayoutCanvas.ReleaseMouseCapture();

	    // Reset our drag & drop properties
	    ddOverlay = null;
	    ddIsMouseBeingDragged = false;
	    ddIsMouseDown = false;
	}
    }
}

source

Shorten text class

public class CropText
{
    public CropText()
    {
    }

    public string ShortenText(string input, int MaxLenght, bool DoDots)
    {
        string result = input;
        int InputLength = input.Length;

        string lastChar = result.Substring(result.Length - 1);

        if (MaxLenght < InputLength)
        {
            result = input.Substring(0, MaxLenght);

            if (lastChar == " ")
            {
                result = result.Substring(0, result.Length - 1);
            }

            if (DoDots)
            {
                result += "...";
            }
        }
        return result;
    }
}

source

Simple SQL Server Diff Tool

using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;

namespace Sdiff
{
    internal class Program
    {
        /// <param name = "args">arg[0] old schema connection string, arg[1] target schema connection string</param>
        /// <summary>
        ///   Tells you what to do with old schema to get it into the shape of the new
        /// </summary>
        private static void Main(string[] args)
        {
            var diffs = new List<Diff>();

            var oldContext = new IsDataContext(args[0]);
            var newContext = new IsDataContext(args[1]);

            var newTableNames = newContext.Tables.Select(x => x.Name).ToList();
            var oldTableNames = oldContext.Tables.Select(x => x.Name).ToList();

            AddDiffs(diffs, oldTableNames.Except(newTableNames), DiffKind.TableDelete);
            AddDiffs(diffs, newTableNames.Except(oldTableNames), DiffKind.TableCreate);

            var commonTableNames = newTableNames.Intersect(oldTableNames);
            foreach (var tableName in commonTableNames)
            {
                var newColumns = newContext.Columns.Where(x => x.TableName == tableName).ToList();
                var oldColumns = oldContext.Columns.Where(x => x.TableName == tableName).ToList();

                var newColumnNames = newColumns.Select(x => x.FullName);
                var oldColumnNames = oldColumns.Select(x => x.FullName);

                AddDiffs(diffs, oldColumnNames.Except(newColumnNames), DiffKind.ColumnDelete);
                AddDiffs(diffs, newColumnNames.Except(oldColumnNames), DiffKind.ColumnCreate);

                var commonColumnNames = newColumnNames.Intersect(oldColumnNames);
                foreach (var commonColumnName in commonColumnNames)
                {
                    var newDataType = newColumns.Where(x => x.FullName == commonColumnName).Select(x => x.DataType).Single();
                    var oldDataType = oldColumns.Where(x => x.FullName == commonColumnName).Select(x => x.DataType).Single();
                    if (oldDataType != newDataType) diffs.Add(new Diff(commonColumnName + " " + oldDataType + " -> " + newDataType, DiffKind.ColumnDataTypeChange));
                }
            }

            WriteSection(diffs.Where(x => x.Kind == DiffKind.TableDelete), "Tables to delete");
            WriteSection(diffs.Where(x => x.Kind == DiffKind.TableCreate), "Tables to create");
            WriteSection(diffs.Where(x => x.Kind == DiffKind.ColumnDelete), "Columns to delete");
            WriteSection(diffs.Where(x => x.Kind == DiffKind.ColumnCreate), "Columns to create");
            WriteSection(diffs.Where(x => x.Kind == DiffKind.ColumnDataTypeChange), "Columns to modify");

            Console.ReadKey();
        }

        private static void AddDiffs(List<Diff> diffs, IEnumerable<string> names, DiffKind diffKind)
        {
            diffs.AddRange(names.Select(name => new Diff(name, diffKind)));
        }


        private static void WriteSection(IEnumerable<Diff> diffs, string title)
        {
            if (!diffs.Any()) return;
            Console.WriteLine();
            Console.WriteLine(title);
            Console.WriteLine(string.Empty.PadLeft(title.Length, '-'));
            foreach (var name in diffs.Select(x => x.Name).OrderBy(x => x))
            {
                Console.WriteLine(name);
            }
        }

        private class Diff
        {
            public Diff(string name, DiffKind kind)
            {
                Name = name;
                Kind = kind;
            }

            public string Name { get; private set; }
            public DiffKind Kind { get; private set; }
        }

        internal enum DiffKind
        {
            TableDelete,
            TableCreate,
            ColumnDelete,
            ColumnCreate,
            ColumnDataTypeChange
        }
    }


    public class IsDataContext : DataContext
    {
        public Table<Column> Columns;
        public Table<Table> Tables;
        public IsDataContext(string connection) : base(connection) {}
    }

    [Table(Name = "INFORMATION_SCHEMA.TABLES")]
    public class Table
    {
        [Column(Name = "TABLE_NAME")] public string Name;
    }

    [Table(Name = "INFORMATION_SCHEMA.COLUMNS")]
    public class Column
    {
        [Column(Name = "CHARACTER_MAXIMUM_LENGTH")] public int? CharacterMaximumLength;
        [Column(Name = "DATA_TYPE")] public string DataTypeName;
        [Column(Name = "COLUMN_NAME")] public string Name;
        [Column(Name = "TABLE_NAME")] public string TableName;

        public string DataType
        {
            get
            {
                if (!CharacterMaximumLength.HasValue) return DataTypeName;
                if (CharacterMaximumLength.Value == -1) return DataTypeName + "(MAX)";
                return DataTypeName + "(" + CharacterMaximumLength.Value + ")";
            }
        }

        public string FullName { get { return TableName + "." + Name; } }
    }
}

source

Binding Visibility property (View) with Bool property (ViewModel)

<!-- XAML VisibilityConverter Usage -->


<Window.Resources>
    <vw:VisibilityConverter x:Key="VisibilityConverter" />
</Window.Resources>

<Grid Visibility="{Binding MyBoolean, Converter={StaticResource VisibilityConverter}}">
  ...
</Grid>


// C# VisibilityConverter implementation

public class VisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Visibility rv = Visibility.Visible;
            try
            {
                var x = bool.Parse(value.ToString());
                if (x)
                {
                    rv = Visibility.Visible;
                }
                else
                {
                    rv = Visibility.Collapsed;
                }
            }
            catch (Exception)
            {
            }
            return rv;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value;
        }
    }

source

Sorting Gridview Control ASP.NET

protected void grdVw_FileList_Sorting(object sender, GridViewSortEventArgs e)
        {

            GridSorting(e.SortExpression, grdVw_FileList);
         
        }

        private void GridSorting(string column, GridView grid)
        {
            // Session["column"] = ""; clear this after ever search/load
string column_ASC = column + " ASC";
            string column_DESC = column + " DESC";

            DataTable dt = (DataTable)Session["fileList"];

            if (Session["column"].ToString().ToUpper() == column_ASC.ToUpper())
            {
                DataView dv = new DataView(dt, "", column_DESC, DataViewRowState.CurrentRows);
                grid.DataSource = dv;
                grid.DataBind();
                Session["column"] = column_DESC;
            }
            else
            {
                DataView dv = new DataView(dt, "", column_ASC, DataViewRowState.CurrentRows);
                grid.DataSource = dv;
                grid.DataBind();
                Session["column"] = column_ASC;
            }

        }

source

GetRESTData

/// <summary>
        /// Parses REST data from a url.
        /// </summary>
        /// <param name="Request">he Request object</param>
        /// <param name="Match">A url pattern to match. Example: /{Department}/{ID}</param>
        /// <returns>A dictionary of values matched to the pattern position</returns>
        public static StringDictionary GetRESTData(this HttpRequest Request, string UrlPattern)
        {
            string query = Request.PathInfo;
            StringDictionary parms = new StringDictionary();

            if (UrlPattern.StartsWith("/")) UrlPattern = UrlPattern.Substring(1);
            string[] matchParms = UrlPattern.Split('/');

            if (query.StartsWith("/")) query = query.Substring(1);
            string[] urlPath = query.Split('/');

            for (int i = 0; i < matchParms.Length; i++)
            {
                string parm = matchParms[i];
                bool hasData = urlPath.Length > i;
                bool hasParm = parm.StartsWith("{") && parm.EndsWith("}");
                if (hasData && hasParm)
                {
                    var p = parm.Substring(1, parm.Length - 2);
                    parms[p] = urlPath[i];
                }
            }
            return parms;
        }

source

Hello World

void main ()
{
 printf ("Hello world
");
}

source

Convert special Turkish chars to international Latin chars

public static string ConvertTurkishChars(string text)
        {
            String[] olds = { "Ğ", "ğ", "Ü", "ü", "Ş", "ş", "İ", "ı", "Ö", "ö", "Ç", "ç" };
            String[] news = { "G", "g", "U", "u", "S", "s", "I", "i", "O", "o", "C", "c" };

            for (int i = 0; i < olds.Length; i++)
            {
                text = text.Replace(olds[i], news[i]);
            }

            text = text.ToUpper();

            return text;
        }

source

MBProgressHUD with an asynchronous NSURLConnection call

- (void)setSearchingModeEnabled:(BOOL)isSearching
{
	//when network action, toggle network indicator and activity indicator
	if (isSearching) {
		[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
		
		UIWindow *window = [UIApplication sharedApplication].keyWindow;
		HUD = [[MBProgressHUD alloc] initWithWindow:window];
		[window addSubview:HUD];
		HUD.labelText = @"Connecting";
		[HUD show:YES];
	} else {
		[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
		
		[HUD hide:YES];
		[HUD removeFromSuperview];
		[HUD release];
	}

}


- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
	[searchBar resignFirstResponder];
	
	NSString *searchType = [ConstantsConverter searchTypeTagToKey:self.selectedSearchType];
	
	NSString *searchString = [searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	NSString *searchURLString = [[NSString alloc] initWithFormat:@"%@?type=%@&search=%@", 
								 self.baseURL, searchType, searchString];
	
	NSLog(@"connecting to: %@", searchURLString);
	//retrieve the json data
	self.responseData = [[NSMutableData data] retain];
	NSURL *searchURL = [[NSURL alloc] initWithString:searchURLString];
	NSURLRequest *request = [NSURLRequest requestWithURL:searchURL];
	
	[self setSearchingModeEnabled:YES];
	[[NSURLConnection alloc] initWithRequest:request delegate:self];
	
	[searchURLString release];
	[searchURL release];
}


#pragma mark -
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
	[self.responseData setLength:0];
	self.searchResultFileSize = [NSNumber numberWithLongLong:[response expectedContentLength]];
	if ([self.searchResultFileSize intValue] != NSURLResponseUnknownLength) {
		HUD.mode = MBProgressHUDModeDeterminate;
		HUD.labelText = @"Getting Results";
	}
	
    NSLog(@"content-length: %@ bytes", self.searchResultFileSize);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
	[self.responseData appendData:data];
	
	NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[self.responseData length]];
    NSLog(@"resourceData length: %d", [resourceLength intValue]);
    NSLog(@"filesize: %d", self.searchResultFileSize);
    NSLog(@"float filesize: %f", [self.searchResultFileSize floatValue]);
    HUD.progress = [resourceLength floatValue] / [self.searchResultFileSize floatValue];
    NSLog(@"progress: %f", [resourceLength floatValue] / [self.searchResultFileSize floatValue]);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{
	[self setSearchingModeEnabled:NO];
	
	NSString *detailMessage = [[NSString alloc]
							   initWithFormat:@"Connection failed: %@",
							   [error description]];
	
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failure" message:detailMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	
	[alert show];
	[alert release];
	[detailMessage release];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
	[self setSearchingModeEnabled:NO];
	
	[connection release];
	
	NSString *jsonResponse = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
	[self.responseData release];
	
	NSString *searchType = [ConstantsConverter searchTypeTagToKey:self.selectedSearchType];
	
	//parse the result and remove outermost wrapper
	SBJSON *parser = [[SBJSON alloc] init];
	NSArray *tempResults = [[parser objectWithString:jsonResponse error:nil] objectForKey:searchType];
	NSMutableDictionary *searchResultsKeepers = [[NSMutableDictionary alloc] init];
	
	//evaluate the results, and keep only unique ones
	for (NSDictionary *entry in tempResults) {
		if (![[searchResultsKeepers allKeys] containsObject:[entry objectForKey:@"label"]]) {
			//insert the search type
			NSMutableDictionary *modifiedEntry = [[NSMutableDictionary alloc] initWithDictionary:entry];
			[modifiedEntry setObject:searchType forKey:@"type"];
			[searchResultsKeepers setObject:modifiedEntry forKey:[modifiedEntry objectForKey:@"label"]];
			[modifiedEntry release];
		}
	}	
	self.searchResults = searchResultsKeepers;
	
	[searchResultsKeepers release];
	[parser release];
	[jsonResponse release];
	[resultsView reloadData];
}

source

SQLDataReader Return reader

 public static SqlDataReader Title()
    {
        SqlConnection connection = ConnectionManager.GetConnection();

        var command = new SqlCommand("StoredProcedure", connection);

        command.CommandType = CommandType.StoredProcedure;

        SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);

        return reader;
    }

source