Posts Tagged ‘C#’
18
Nov

Simple File Upload Solution

Post a comment » Popularity: 8%

Gergely Orosz target to implement a simple solution in uploading file using Silverlight. The upload control contains a progress indicator where you can keep track of the upload progress. The sample also showed you how you can collect the uploaded file using PHP or C#.

Simple File Upload Solution

09
Oct

Strip HTML Tags

1 Comment » Popularity: 25%

Corey referred a very useful code snippet provided by John which helps you to strip HTML Tags.

Strip HTML Tags

View Demo: New Window
csharp title:
private string StripHtmlTags(string value){
    int length = 0;
    int.TryParse(value, out length);

    // Remove HTML tags and empty newlines and spaces and leading spaces
    string formattedValue = Regex.Replace(value as string, "<.*?>", "");
    formattedValue = Regex.Replace(formattedValue, @"\n+\s+", "\n\n");
    formattedValue = formattedValue.TrimStart(' ');
    formattedValue = HttpUtility.HtmlDecode(formattedValue);
    if(length > 0 && formattedValue.Length >= length)
        formattedValue = formattedValue.Substring(0, length - 1);
    return formattedValue;
}
28
Sep

Checking Image Download Progress

Post a comment » Popularity: 3%

This application demonstrated how we may check the download progress of an image. The progress is visualized with a Progress Bar.

Checking Image Download Progress

View Demo: New Window
Check the download progress:
// C#
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.DownloadProgress += new EventHandler<downloadprogresseventargs>(bitmapImage_DownloadProgress);
bitmapImage.UriSource = new Uri(URL, UriKind.Absolute);
Image newImage = new Image() { Source = _bitmapImage };  

void bitmapImage_DownloadProgress(object sender, DownloadProgressEventArgs e)
{
    int progress = e.Progress; // 0 = 100  

    if (e.Progress == 100)
    {
        // finish
    }
}
26
Sep

Create Path in C# and XAML

Post a comment » Popularity: 1%

Matthias Shapiro demonstrated how you create a geometry object using C# and XAML.

Create-Path-in-C#

26
Sep

Create Gradient Background

Post a comment » Popularity: 1%

Most of the time when you are using Visual Studio and you don’t’ want to open Blend for just setting a very Gradient Background! The below code can surely help you.

Create Gradient Background in XAML

Creat gradient background in c#:
LinearGradientBrush linear = new LinearGradientBrush();
linear.StartPoint = new Point(0.5, 0);
linear.EndPoint = new Point(0.5, 1);

GradientStop g1 = new GradientStop();
g1.Color = _backgroundColor1;
g1.Offset = 0;

GradientStop g2 = new GradientStop();
g2.Color = _backgroundColor2;
g1.Offset = 1;

linear.GradientStops.Add(g2);
linear.GradientStops.Add(g1);

Border border = new Border();
border.Background = linear;
Creating gradient background in xaml:
<UserControl x:Class="GradientBackground.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="600" Height="400">
    <Grid x:Name="LayoutRoot" Background="White">
        <Rectangle Stroke="Black" Height="180" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="285">
            <Rectangle.Fill>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="Black" Offset="0"/>
                    <GradientStop Color="White" Offset="1"/>
                </LinearGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
        <Rectangle Stroke="Black" Height="190" HorizontalAlignment="Left" Margin="10,0,0,10" VerticalAlignment="Bottom" Width="285">
            <Rectangle.Fill>
                <LinearGradientBrush EndPoint="0,0" StartPoint="0,1">
                    <GradientStop Color="Black" Offset="0"/>
                    <GradientStop Color="White" Offset="0.1"/>
                    <GradientStop Color="Black" Offset="0.2"/>
                    <GradientStop Color="White" Offset="0.3"/>
                    <GradientStop Color="Black" Offset="0.4"/>
                    <GradientStop Color="White" Offset="0.5"/>
                    <GradientStop Color="Black" Offset="0.6"/>
                    <GradientStop Color="White" Offset="0.7"/>
                    <GradientStop Color="Black" Offset="0.8"/>
                    <GradientStop Color="White" Offset="0.9"/>
                    <GradientStop Color="Black" Offset="1"/>
                </LinearGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
        <Rectangle Stroke="Black" Height="180" HorizontalAlignment="Right" Margin="0,10,10,0" VerticalAlignment="Top" Width="285">
            <Rectangle.Fill>
                <LinearGradientBrush EndPoint="0,0" StartPoint="1,1">
                    <GradientStop Color="Black" Offset="0"/>
                    <GradientStop Color="Red" Offset="1"/>
                </LinearGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
        <Rectangle Stroke="Black" Height="190" HorizontalAlignment="Right" Margin="0,0,10,10" VerticalAlignment="Bottom" Width="285">
            <Rectangle.Fill>
                <RadialGradientBrush>
                    <GradientStop Color="White" Offset="0"/>
                    <GradientStop Color="Black" Offset="1"/>
                </RadialGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
    </Grid>
</UserControl>
View Demo: New Window
25
Sep

Upload file using File Dialog

Post a comment » Popularity: 1%

The coding below demonstrating how you might utilize your FileDialog to upload files from your local disk to server.

The code demonstrated the following:

  1. Limited the selection of JPG and PNG files only
  2. Only 1 file can be selected
  3. Upload the file with the corresponding file name
  4. How to get the file data inside PHP

Upload file using File Dialog 

Select and upload file in c#:
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Image Files (.jpg,.png)|*.JPG;*.jpg;*.PNG;*.png";
dialog.FilterIndex = 1;
bool? userClickedOK = _imageDialog.ShowDialog();

// Process input if the user clicked OK.
if (userClickedOK == true)
{
    UploadFile(dialog.File.Name, dialog.File.OpenRead());
}

private void UploadFile(string filename, Stream data)
{
    UriBuilder ub = new UriBuilder(UPLOAD_PATH);
    ub.Query = string.Format("filename={0}", filename);

    WebClient c = new WebClient();
    c.OpenWriteCompleted += (sender, e) =>
    {
        PushData(data, e.Result);
        e.Result.Close();
        data.Close();
    };
    c.OpenWriteAsync(ub.Uri, "Post");
}

private void PushData(Stream input, Stream output)
{
    byte[] buffer = new byte[4096];
    int bytesRead;

    while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
    {
        output.Write(buffer, 0, bytesRead);
    }
}
Get and save file in PHP:
$filepath = $_REQUEST['filename'];
$handle = fopen("php://input", "r");
$file = fopen($filepath,"w");

if($file != null && $handle != null)
{
        while ($data = fread($handle, 8192)) fwrite($file, $data);
        fclose($handle);
        fclose($file);
}
24
Sep

Loading external assembly

Post a comment » Popularity: 1%

Terence Tsang demonstrated how to load an external assembly library (Usually a dll or xap file) into your own Silverlight application. This is a very effective method to minimize the application file size.

Loading external assembly

Loading external library in C#:
WebClient downloader = new WebClient();
downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(onDownloadCompleted);
downloader.OpenReadAsync(new Uri(DLL_PATH, UriKind.Absolute));  

// Once the assembly is downloaded
private void onDownloadCompleted(object o, OpenReadCompletedEventArgs args)
{
    try
    {
        AssemblyPart ap = new AssemblyPart();
        Assembly assembly = ap.Load(args.Result);
        Object control = assembly.CreateInstance(CLASS_NAME);
    }
    catch (Exception e){}
}
24
Sep

Load & Save File from Isolated Storage

Post a comment » Popularity: 1%

Mike Snow demonstrated how to read file and load file from local storage. Please read the C# for details.

Load & Save File from Isolated Storage

Save and read file from local storage:
using System;
using System.Windows.Controls;
using System.IO.IsolatedStorage;
using System.IO;

namespace SilverlightApplication10
{
    public class Page : UserControl
    {
        public Page()
        {
            SaveData("Hello There", "MyData.txt");
            if (HasFile("MyData.txt"))
            {
                string test = LoadData("MyData.txt");
            }
        }

        private void SaveData(string data, string fileName)
        {
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
            IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Create, isf);
            using (StreamWriter sw = new StreamWriter(isfs))
            {
                sw.Write(data);
                sw.Close();
            }
        }

        private bool HasFile(string fileName)
        {
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
            return isf.FileExists(fileName);
        }

        private string LoadData(string fileName)
        {
            string data = String.Empty;
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
            IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Open, isf);
            using (StreamReader sr = new StreamReader(isfs))
            {
                string lineOfData = String.Empty;
                while ((lineOfData = sr.ReadLine()) != null) data += lineOfData;
            }
            return data;
        }
    }
}
23
Sep

Clip/Mask To Actual Size

Post a comment » Popularity: 1%

Colin Eberhardt created a very useful Clipping behavior class which helps you do clipping easily. The behavior can detect the ActualHeight and ActualWidth at run time and create a RectangleGeometry() to Clip your Grid.

Clip To Bounds

c# implementation of the behavior:
using System;
using System.Windows;

namespace Namespace
{

    public class Clip
    {
        public static bool GetToBounds(DependencyObject depObj)
        {
            return (bool)depObj.GetValue(ToBoundsProperty);
        }

        public static void SetToBounds(DependencyObject depObj, bool clipToBounds)
        {
            depObj.SetValue(ToBoundsProperty, clipToBounds);
        }

        /// <summary>
        /// Identifies the ToBounds Dependency Property.
        /// <summary>
        public static readonly DependencyProperty ToBoundsProperty =
        DependencyProperty.RegisterAttached("ToBounds", typeof(bool),
        typeof(Clip), new PropertyMetadata(false, OnToBoundsPropertyChanged));

        private static void OnToBoundsPropertyChanged(DependencyObject d,
        DependencyPropertyChangedEventArgs e)
        {
        FrameworkElement fe = d as FrameworkElement;
        if (fe != null)
        {
            ClipToBounds(fe);

            // whenever the element which this property is attached to is loaded
            // or re-sizes, we need to update its clipping geometry
            fe.Loaded += new RoutedEventHandler(fe_Loaded);
            fe.SizeChanged += new SizeChangedEventHandler(fe_SizeChanged);

        }
        }

        /// <summary>
        /// Creates a rectangular clipping geometry which matches the geometry of the
        /// passed element
        /// </summary>
        private static void ClipToBounds(FrameworkElement fe)
        {
        if (GetToBounds(fe))
        {
            fe.Clip = new RectangleGeometry()
            {
            Rect = new Rect(0, 0, fe.ActualWidth, fe.ActualHeight)
            };
        }
        else
        {
            fe.Clip = null;
        }
        }

        static void fe_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            ClipToBounds(sender as FrameworkElement);
        }

        static void fe_Loaded(object sender, RoutedEventArgs e)
        {
            ClipToBounds(sender as FrameworkElement);
        }
    }
}
sample usage in XAML:
<UserControl x:Class="Namespace.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:this="clr-namespace:Namespace;assembly=Namespace"
    >
    <Grid x:Name="LayoutRoot"  this:Clip.ToBounds="True" >

    </Grid>
</UserControl>
21
Sep

Hit Test (Get all objects in a specific point)

Post a comment » Popularity: 1%

Most of the time, when you are creating games, you will have to find out all the UIElemetn in a specific coordinate. (Or we can this hittest). In such circumstance, you will need to use the method VisualTreeHelper.FindElementsInHostCoordinates. Please view the C# coding for more details.

Hit-Test

Get all the UIElement in a specific coordinate:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

namespace HitTest
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            App.Current.RootVisual.MouseLeftButtonDown += new MouseButtonEventHandler(RootVisual_MouseLeftButtonDown);
        }

        void RootVisual_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            List<uielement> list = VisualTreeHelper.FindElementsInHostCoordinates
            (e.GetPosition(null), LayoutRoot as UIElement) as List<uielement>;

            var selectedControls = from control in list
                                   where control is Rectangle
                                   select control as Rectangle;

            if (selectedControls.Count() &gt; 0)
            {
                foreach (var selectedControl in selectedControls)
                {
                    // do your opreation here
                }
            }
        }
    }
}