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#.
Oct
Strip HTML Tags
Corey referred a very useful code snippet provided by John which helps you to strip HTML Tags.
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;
}
Sep
Checking Image Download Progress
This application demonstrated how we may check the download progress of an image. The progress is visualized with a Progress Bar.
// 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
}
}
Sep
Create Path in C# and XAML
Matthias Shapiro demonstrated how you create a geometry object using C# and XAML.
Sep
Create Gradient Background
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.
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;
<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>
Sep
Upload file using File Dialog
The coding below demonstrating how you might utilize your FileDialog to upload files from your local disk to server.
The code demonstrated the following:
- Limited the selection of JPG and PNG files only
- Only 1 file can be selected
- Upload the file with the corresponding file name
- How to get the file data inside PHP
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);
}
}
$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);
}
Sep
Loading external assembly
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.
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){}
}
Sep
Load & Save File from Isolated Storage
Mike Snow demonstrated how to read file and load file from local storage. Please read the C# for details.
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;
}
}
}
Sep
Clip/Mask To Actual Size
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.
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);
}
}
}
<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>
Sep
Hit Test (Get all objects in a specific point)
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.
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() > 0)
{
foreach (var selectedControl in selectedControls)
{
// do your opreation here
}
}
}
}
}







