Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Archive for the ‘Silverlight’ Category

Detect browser F5 / refresh and X / Close in javascript

Posted by Viral Sarvaiya on May 8, 2012


Below javascript is use to detect wether browser is refereshed or closed.

window.onunload = function (e) {
// Firefox || IE
e = e || window.event;
var y = e.pageY || e.clientY;

if (y < 0) {
alert("close");
}
else {
alert("refresh");
}
}

Thanks.

Posted in ASP.NET, Javascript, Silverlight | Tagged: , , , , , | 2 Comments »

The “CreateRiaClientFilesTask” task failed unexpectedly

Posted by Viral Sarvaiya on February 14, 2012


Some day ago, when i build my project i get unexpected error.

Error 3 The “CreateRiaClientFilesTask” task failed unexpectedly.
System.Web.HttpException (0x80004005): Could not load file or assembly ‘FileHelpers.DataLink’ or one of its dependencies. Access is denied. —> System.Configuration.ConfigurationErrorsException: Could not load file or assembly ‘FileHelpers.DataLink’ or one of its dependencies. Access is denied. —> System.IO.FileLoadException: Could not load file or assembly ‘FileHelpers.DataLink’ or one of its dependencies. Access is denied……….

Sometime that happen when Visual studio cannot access files. so have to remove Temporary file.

I get simple solution from goggling, just close visual studio and reopen, and if Visual studio has no administrator rights then please right click to visual studio icon and choose “Run as a Administrator”.

Then re-build project and problem solved.

Thanks.

Posted in .Net, ASP.NET, RIA WCF, Silverlight, Visual Studio, WCF Services, WPF | Tagged: , , , , , | 4 Comments »

Prevent Silverlight XAP file from caching in your browser.

Posted by Viral Sarvaiya on January 19, 2012


Sometime when we deploy silverlight project, that happen often that when you run website it run older deploy project. because that comes from the cache,

so clear the cache of the Browser and some time that problem occur also after clearing cache.

so for that we have to force website to download new version of xap file every time when it run.

normally we have tag for XAP file, as like below

<param name="source" value="/ClientBin/SilverApp.xap" />

but we have to download our XAP file new at every run of site.

so there so many option for that.

1) changing the Assembly and File version numbers

2) GUID value for the project

but, here is the simple and best solution for that and then it worked like a charm everytime.

<param name="source" value="/ClientBin/SilverApp.xap?ignoreme=<%=System.DateTime.Now.ToUniversalTime()%>" />

Enjoy,

Posted in .Net, ASP.NET, Silverlight | Tagged: , , , , , , , , , | 1 Comment »

Get Silverlight XAP and Hosting Page URL

Posted by Viral Sarvaiya on December 5, 2011


Get the URL to the current xap file:
App.Current.Host.Source.AbsoluteUri

Sample:
http://www.WebsiteName.com/ClientBin/SilverlightApplicationName.xap

Get the full URL of the page hosting the xap (with QueryStrings):
HtmlPage.Document.DocumentUri.ToString()

Sample:
http://www.WebsiteName.com/SilverlightApplicationName.aspx?param=1

Posted in .Net, ASP.NET, Silverlight, Visual Studio | Tagged: , , , , , | Leave a Comment »

Bind Multiple Columns in Combobox in Silverlight

Posted by Viral Sarvaiya on October 15, 2011


Silverlight has simple combobox like below.

<Combobox x:Name="combo1"  Width="100" Height="30" />

we use ItemSource property for binding data to combobox.
we can set DisplayMemberPath property as like

<Combobox x:Name="combo1"  Width="100" Height="30"  DisplayMemberPath ="Name"  />

for the multiple property we can edit compbobox itemTemplate.
for that you have to remove DisplayMemberPath property from Combobox tag and use the below tag for binding multiple properties to Combobox.

<ComboBox x:Name="cboTest">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name, Mode=OneWay}" />
<TextBlock Text=" " />
<TextBlock Text="{Binding Surname, Mode=OneWay}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>

if you want to select an item and want Id of selected item then you can use SelectedValue or Selecteditem Property as like below

<ComboBox x:Name="cboTest" ItemSource="{Binding MyList, Mode=TwoWay}" SelectedValue={Binding Path=Name, Mode="TwoWay"}>
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name, Mode=OneWay}" />
<TextBlock Text=" " />
<TextBlock Text="{Binding Surname, Mode=OneWay}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>

hope this will help you.

Posted in .Net, ASP.NET, Silverlight | Tagged: , , , , , | 2 Comments »

Calling a WCF service from Javascript

Posted by Viral Sarvaiya on May 16, 2011


Hi

we know how to use WCF service in silverlight and asp.net that shows in my some previous posts

https://viralsarvaiya.wordpress.com/2010/09/17/bind-silverlight-grid-view-with-wcf-service/

https://viralsarvaiya.wordpress.com/2010/08/26/use-of-wcf-service-in-silverlight/

but i face another problem in it, it can possible to call WCF service from javascipt?

Answer is yes  and i find interesting post.

for more detail click here.

thanks and enjoy…

Posted in .Net, ASP.NET, RIA WCF, Silverlight, WCF Services | Tagged: , , , , , , , | Leave a Comment »

Multilanguage Application in WPF

Posted by Viral Sarvaiya on May 7, 2011


From this 2 link we can get batter idea of Globalization and Localization,

http://msdn.microsoft.com/en-us/library/ms752337.aspx

http://msdn.microsoft.com/en-us/library/ms788718.aspx

Here i demostrate very simple way for multiple language application in WPF.

here i make a simple login form in wpf with 2 language English and French Button.
Step 1:  Open Visual studion, Create New Project of WPF give name “WPFMultiLanguage”.

so now you have 2 .xaml file App.xaml and MainWindow.xaml,

Step 2: New we add new folder named “Resources” for Multiple Language.

Step 3: Add resource files

To add resource file named “StringResources.xaml”, right click to Resource folder => Add => Resource Directory (See Image below)

So your file is as like

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >

</ResourceDictionary>

I have added one namespace which points to mscorlib, and named it as system and now add resource string to StringResources.xaml

so StringResources.xaml as below

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib">

<system:String x:Key="Username">Username</system:String>
<system:String x:Key="Password">Password</system:String>
<system:String x:Key="close">close</system:String>
<system:String x:Key="login">login</system:String>
<system:String x:Key="French">French</system:String>
<system:String x:Key="English">English</system:String>

</ResourceDictionary>

Now add another resource directory for French language named “StringResource.fr-CA.xaml”

put there French string resuouce and give same key name as per above file,

so StringResource.fr-CA.xaml as below.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib">

<system:String x:Key="Username">Nom d'utilisateur</system:String>
<system:String x:Key="Password">Mot de passe</system:String>
<system:String x:Key="close">Fermer</system:String>
<system:String x:Key="login">connexion</system:String>
<system:String x:Key="French">Française</system:String>
<system:String x:Key="English">En anglais</system:String>

</ResourceDictionary>

Step 4: Add Resource file to window.

Now its time to add resource file to Mainwindow page.

for that in the MainWindow.xaml file design the login page and put 2 button for the language transfer.

For display content and text from resource file, use DynamicResource.

for that i have made 1 function that add dictionaries directly to window resources and in click event of the button for language transfer i set culture for that.

so MainWindow.xaml as below.

<Window x:Class="WPFMultiLanguage.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid Background="Beige" >
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>

<TextBlock Name="Username" Text="{DynamicResource Username}" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,24,18,38"></TextBlock>
<TextBox Name="txtuser" Width="100" Height="30" Grid.Column="1" Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Left"></TextBox>
<TextBlock Name="Password" Text="{DynamicResource Password}" Grid.Column="0" Margin="0,24,18,38" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Right"></TextBlock>
<PasswordBox Name="txtpass" Width="100" Height="30" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center" />

<Button x:Name="btnLogin" Width="100" Height="40" VerticalAlignment="Top" HorizontalAlignment="Right"
Click="btnLogin_Click" Content="{DynamicResource login}" Grid.Row="2" Grid.Column="0" Padding="10" />
<Button x:Name="btnClose" Width="100" Height="40" VerticalAlignment="Top" HorizontalAlignment="Left"
Click="btnClose_Click" Content="{DynamicResource close}" Grid.Row="2" Grid.Column="1" Padding="10" />

<Button x:Name="btnEnglish" Width="100" Height="40" VerticalAlignment="Bottom" HorizontalAlignment="Right"
Click="btnEnglish_Click" Content="{DynamicResource English}" Grid.Row="3" Grid.Column="0" Padding="10" />

<Button x:Name="btnFrench" Width="100" Height="40" VerticalAlignment="Bottom" HorizontalAlignment="Left"
Click="btnFrench_Click" Content="{DynamicResource French}" Grid.Row="3" Grid.Column="1" Padding="10" />
</Grid>
</Window>

and MainWindow.xaml.cs as below.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Threading;
namespace WPFMultiLanguage
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
SetLanguageDictionary();
}

private void SetLanguageDictionary()
{
ResourceDictionary dict = new ResourceDictionary();
switch (Thread.CurrentThread.CurrentCulture.ToString())
{
case "en-US":
dict.Source = new Uri("..\\Resources\\StringResources.xaml", UriKind.Relative);
break;
case "fr-CA":
dict.Source = new Uri("..\\Resources\\StringResource.fr-CA.xaml", UriKind.Relative);
break;
default:
dict.Source = new Uri("..\\Resources\\StringResources.xaml", UriKind.Relative);
break;
}
this.Resources.MergedDictionaries.Add(dict);
}

private void btnLogin_Click(object sender, RoutedEventArgs e)
{
if (txtuser.Text.Trim() == "")
{
MessageBox.Show("Please Enter Username");
//If u want to set resource from code behind then use below code
//FindResource("<Resource Key Name>").ToString()
return;
}
if (txtpass.Password.Trim() == "")
{
MessageBox.Show("Please Enter Password");
return;
}
if (txtuser.Text.Trim() == txtpass.Password.Trim())
{
MessageBox.Show("Sucess");
}

}

private void btnClose_Click(object sender, RoutedEventArgs e)
{
this.Close();
}

private void btnEnglish_Click(object sender, RoutedEventArgs e)
{
System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = cultureInfo;
SetLanguageDictionary();
}

private void btnFrench_Click(object sender, RoutedEventArgs e)
{
System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("fr-CA");
Thread.CurrentThread.CurrentCulture = cultureInfo;
SetLanguageDictionary();
}
}
}

Now run the solution

english is by default so first time when you run code it display in english language
and then click to French button it display in French.

Enjoy…..

Posted in .Net, Silverlight, Visual Studio, WPF | Tagged: , , , , , | 4 Comments »

Set Source on Image from code in Silverlight

Posted by Viral Sarvaiya on January 11, 2011


Hi

this is the first post of year 2o11

here I demonstrate how to set source of the image from code in silverlight

basically we define source of image from XAML file as below


<Image x:name="imgPhoto" Source="http://www.viralsarvaiya.wordpress.com/imgphoto.jpg" />

so how can we define this source from code file.


string imgurl = " http://www.viralsarvaiya.wordpress.com/imgphoto.jpg ";

ImageSourceConvertor convertor = new ImageSourceConvertor();

imgPhoto.Source = (ImageSource) convertor.ConvertFromString(imgurl);

here we use ImageSourceConvertor but u can also use BitmapImage with an Uri class as below,


Uri uri = new Uri("http://www.viralsarvaiya.wordpress.com/imgphoto.jpg", Urikind.Absolute);

ImageSource imgs = new ImageSource(uri);

imgPhoto.Source = imgs;

with this you can define source of the image from source.

Enjoy…

Posted in Silverlight | Tagged: , , , | Leave a Comment »

File Drag and Drop in Silverlight4

Posted by Viral Sarvaiya on November 2, 2010


Silverlight 4 have drag and drop functionality. here i demostrate that functionality.
first create new project named “DragAndDropImage”.
You have to add references “Microsoft.Expression.Interactions”, “system.windows.interactivity” and “system.windows.browser”

Silverlight is too fun, when coding gets this simple. So the image can now be dragged around. Now lets add the drop feature.

For making everything very simple, I will just now add AllowDrop=”True” and then add a drop handler to handle any file that is being dropped.

Now, lets move to the code behind. For demonstration purpose, I will use images from deviantArt gallery.

In DragAndDropImageTest.xaml file


<UserControl x:Class="SilverLightTest.DragAndDropImageTest"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 mc:Ignorable="d"
 xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
 xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
 d:DesignHeight="300" d:DesignWidth="400">

 <Grid x:Name="LayoutRoot" AllowDrop="True" Drop="LayoutRoot_Drop" Background="Black">
 <StackPanel x:Name="DropCollection" Height="100" Margin="10,30,10,10" VerticalAlignment="Top" HorizontalAlignment="Center" Orientation="Horizontal">
 </StackPanel>
 <Image x:Name="DropImage" Margin="0,100,0,0" Width="400" Cursor="Hand">
 <i:Interaction.Behaviors>
 <ei:MouseDragElementBehavior ConstrainToParentBounds="True"></ei:MouseDragElementBehavior>
 </i:Interaction.Behaviors>
 </Image>
 </Grid>
</UserControl>

In DragAndDropImageTest.xaml.cs file


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

using System.Windows.Media.Imaging;
using System.Collections.ObjectModel;
using System.Windows.Media;
using System.Windows.Browser;
using System.IO;

namespace SilverLightTest
{
 public partial class DragAndDropImageTest : UserControl
 {
 public DragAndDropImageTest()
 {
 InitializeComponent();
 }

 private void LayoutRoot_Drop(object sender, DragEventArgs e)
 {
 if (e.Data != null)
 {
 //reading the drop file
 FileInfo file = ((FileInfo[])e.Data.GetData(DataFormats.FileDrop)).FirstOrDefault();

 //creating a bitmapImage
 BitmapImage img = new BitmapImage();

 using (Stream s = file.OpenRead())
 {
 img.SetSource(s);
 }

 //setting the image in xaml
 DropImage.Source = img;

 Image newImage = new Image { Source = img };
 newImage.MouseLeftButtonDown += (a, b) =>
 {
 DropImage.Source = newImage.Source;
 };

 DropCollection.Children.Add(newImage);
 }
 }
 }
}

Run the application and check with dropping the image file in browser.

 

Enjoy Coding…..

Posted in ASP.NET, Silverlight | Tagged: , , , , , | 1 Comment »

New Data Binding Features in Silverlight 4

Posted by Viral Sarvaiya on October 11, 2010


Data Binding and String Formatting

In prior versions of Silverlight, in order to perform string formatting while data binding you would need to write a converter that would format the data during binding. In Silverlight 4 you are now able to format the data directly in XAML. This greatly simplifies the process of creating bindings that require some formatting of the data. Adding string formatting is as simple as adding a StringFormat extension in the XAML markup of the data binding. The StringFormat extension supports the same formatting options as the String’s Format method. Consider the following XAML. There are four text boxes displayed, all bound to the same property in code behind. The difference, however, is that each TextBox change displays the data differently based on the binding’s StringFormat extension. The first TextBox shows the raw data, the second formats the data to three decimal places, the third show the value in scientific notation, and the fourth shows the data as currency.


<Grid x:Name="LayoutRoot" Background="White">

<Grid.RowDefinitions>

<RowDefinition Height="*" />

<RowDefinition Height="*" />

<RowDefinition Height="*" />

<RowDefinition Height="*" />

</Grid.RowDefinitions>

<TextBox

Margin="5"

Grid.Row="0"

Text="{Binding DecimalValue}" />

<TextBox

Margin="5"

Grid.Row="1"

Text="{Binding DecimalValue, StringFormat='##.###'}" />

<TextBox

Margin="5"

Grid.Row="2"

Text="{Binding DateValue, StringFormat='MMM dd, yyyy'}" />

<TextBox

Margin="5"

Grid.Row="3"

Text="{Binding DecimalValue, StringFormat='c'}" />

</Grid>

As you can see from this example, you can easily change the format of data directly through the XAML.

TargetNullValue and FallBackValue Extensions

Two other extensions have been added to the base binding class in Silverlight 4: the TargetNullValue and FallBackValue extensions. These extensions allow you to specify data that will be displayed in the case when the data being bound to the control is not as expected. TargetNullValue provides a value for the binding that should be used if the data value being bound is null. An example of using this extension is shown here:


<TextBox Text="{Binding ValueName, TargetNullValue='Value is Null'}" />

FallBackValue provides a value to be used if the bound data is missing or if there was a mismatch that occurred. An example of using the FallBackValue extension is shown here:


<TextBox Text="{Binding ValueName, FallbackValue='Value Not Found'}" />

Thanks you.

Posted in ASP.NET, Silverlight | Tagged: , , , , , , , , | Leave a Comment »

 
%d bloggers like this: