Tuesday, January 29, 2013

Windows Phone: OnManipulationStarted doesn't fire when touching ad control

Windows Phone: OnManipulationStarted doesn't fire when touching ad control

When I try to add Nokia Ad Exchange ad control in my page XAML, the overridden OnManipulationStarted event handler doesn't fire when I touch it. It is fired if I touch anything else, but if I touch it specifically, then it doesn't enter in the method code.

Is this a related issue to the control or should I add something else?

Answers & Comments...

Answer: 1

It's probably handled by the control, so it doesn't bubble up. You can use the alternative control.AddHandler method rather than += to add an event handler. It takes a boolean that specifies if you want the event handler called even if it was handled by a sub-element.

by : dotMortenhttp://stackoverflow.com/users/1702326




Modification of a report, mavariable is at null, what should I do to change that and to be able to display the report for changings

Modification of a report, mavariable is at null, what should I do to change that and to be able to display the report for changings

Here is an extract of the code. There I don't know what to add as code to make it funtion... For the moment I can create a report but I cannot modify it... That's the part concerning modifications...

 protected override void OnNavigatedTo(NavigationEventArgs e)         {             ReLoadListInDB();             if (NavigationContext.QueryString["action"].Equals("create"))             {                 act°IsCreate = true;                 lblRapportAdd.Text = "Création d'un rapport";                 textboxRapportT.Text = "Titre automatique à déterminer";                 dpRapDeb.SelectedDate = DateTime.Now;                 //cbboxRapportChoixPeriode.SelectedIndex = 1;             }            else             {                 actionIsCreate = false;                 lblRapportAdd.Text = "Modification d'un rapport";                   web_ReportingReportT mavariable = App.Rapport;                    textboxRapport.Text = mavariable.Title;                 dpRapDeb.SelectedDate = mavariable.DateStart;                 dpRapportFin.SelectedDate = mavariable.DateEnd;                 cbboxRapportChoixFrequence.SelectedItem = mavariable.web_RapportingFreq;             } 

The debugger stops on this part of the code: web_ReportingReport mavariable = App.Rapport; and it explains that the reference of the object is not defined at an instance of an object, mavariable is thus at the moment null. When I select a recordline in fact a specific report and I clic on the event modify, it bugs.

Here is another extract of the code which can help to the complete comprehension and where it's perhaps also necessary to add some code... If you need more explanations, don't hesitate to ask me

protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)     {         base.OnNavigatingFrom(e);         if (demandeModification)         {             if (radGridViewRapportAuto.SelectedItem != null)                 App.Rapport = radGridViewRapportAuto.SelectedItem as web_Reportg;             if (demandeModification == false || radGridViewRapportAuto.SelectedItem == null)             {                 //demandeModification = false;                 MessageBox.Show("Un rapport doit être sélectionné", "Erreur", MessageBoxButton.OK);                 e.Cancel = true;             }                      }          } 

Answers & Comments...




In Silverlight how do I set a buttons enabled state to be enabled based on items selected in a listbox?

In Silverlight how do I set a buttons enabled state to be enabled based on items selected in a listbox?

I have a dialog that contains a listbox and the customary ok, cancel buttons. I would like set the enabled state of the ok button to be enabled only if an item in the listbox has been select. I would like to do this with bindings rather than in the code behind.

I may have been going down the wrong route but I have being trying to do something like the following

IsEnabled="{Binding ElementName=ProjectList, Path=??? }"  

As you can probably see I have no idea what would go in the "Path"

Answers & Comments...

Answer: 1

If ProjectList is the name of the list box then you should be able to use SelectedItem.

You will need to bind through a converter that checks for the SelectedItem being null and returning false in that case.

So your XAML becomes:

IsEnabled="{Binding ElementName=ProjectList, Path=SelectedItem, Converter={StaticResource SelectedItemToBool}}"  

and the selector looks something like this:

public class SelectedItemToBool : IValueConverter {     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)     {         return value != null;     }      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)     {         throw new NotImplementedException();     } } 
by : ChrisFhttp://stackoverflow.com/users/59303




Where can I find Silverlight templates for Windows Phone 7 applications?

Where can I find Silverlight templates for Windows Phone 7 applications?

I need Silverlight in order to use IronRuby, as Silverlight provides the DRL. However, I can't find a template for creating Silverlight Windows Phone applications in Visual Studio 2012 for Windows Phone.

Can someone point me to such a template? Because all the tutorials for IronRuby on Windows Phone say to use Silverlight.

Answers & Comments...

Answer: 1

I just took a quick look in VS2012/Exp, all the C# Phone templates there are for SilverLight. They just don't say so (explicitly) any more. When you see a MainPage.xaml you're doing SL.

But do note that Project|Properties|Build also has a combobox for the target platform. If WP7 isn't in the list you'll have to install another/extra SDK.

by : Henk Holtermanhttp://stackoverflow.com/users/60761




Tips and/or suggestions to install Silverlight on Mac Computers

Tips and/or suggestions to install Silverlight on Mac Computers

All:

Our ASP.NET C# web application is used in the following environment

.NET Framework 4  Silverlight 4 ( with PivotViewer )  IIS 7  Windows 2008  Visual Studio 2010 

.NET IDE

C#  HTTPS ( SSL ) 

The Mac users of our application usually have trouble with installing Silverlight. For some Silverlight installs in the Mac with ease. However, most people have to install silverlight, and restart the machine a number of times.

It's so unpredictable how Silverlight installs on the Macs.

In a lot of the cases a mac user has to separately install Silverlight for the various browsers ( i.e. FireFox, Safari and Chrome ).

Moreover, Silverlight might only start working after the user restarts the Mac after a number of times.

-----For users who have Mac OS X 10.7 (Lion) or a higher version of Mac Operating Systems------ The Mac OS X 10.7 (Lion) and higher versions of Mac Operating Systems seem to have the feature called "Resume" which ensures that the Mac system will recall the state of applications and files just before you quit which would allow you to open them up again, and just pick up from where you left off.

However, the "Resume" feature may be a stumbling block when it comes to installing Silverlight.

Therefore, it might be a good idea if we turn off the "Resume" feature temporarily in order to install Silverlight.

If you have a Mac OS X 10.7 (Lion) or a higher version of Mac Operating Systems then go to the Mac OS's System Preference. Go to "General" Tab within System Preferences. Ensure that the checkbox for "Restore windows when quitting and re-opening apps." is unchecked.

After installing Silverlight, and ensuring that the Silverlight/Pivot Viewer in Perls Web Application shows up properly, you could check the checkbox for "Restore windows when quitting and re-opening apps." if you want the "Resume" feature for your Mac OS X 10.7 (Lion) or a higher version of Mac Operating Systems

------Some of my colleagues also gave the following steps but it only worked for some Mac Users therefore it's still unpredictable-------------------------------------------------- Mac User might have to install Silverlight, uninstall silverlight, and then install silverlight again.

Mac users usually had a problem with our Silverlight/Pivot Viewer component within our Web Application.

if the Mac User already has Silverlight installed on his Mac but has problems using the Silverlight/Pivot Viewer component within our Web Application then kindly take the following steps in Removing Silverlight plugins on Macintosh:

  • Access your hard drive

  • Double-click the hard drive icon on your desktop

  • Find the plugin by Navigating to your Internet Plug-Ins directory: /Library/Internet Plug-Ins/

  • Remove the plugin by Dragging any of the following into your trash bin: a) Silverlight.plugin b) WPFe.plugin

-Just quit all applications, and then shutdown your Mac, and then start up your Mac again.

-Open up Safari browser in Mac.

-In general, Safari on Macs place entities downloaded from the internet on to the following directory

/Users/blah blah your Mac LoginID folder blah blah/Downloads/

  1. However, if you want to configure where downloads by Safari on Macs should be placed then Click on the "Safari" menu on the Main Menu of the Mac computer.
  2. When the drop-down menu shows up, make sure that you select the "Preferences……" option.
  3. A new Window should show up with the title "General"
  4. There should be a drop-down box with the Label "Save downloaded files to:" within the Window
  5. Using drop-down box with the Label "Save downloaded files to:", we can configure where we want Safari to placed Downloaded entities.
  6. click the Save Downloaded Files To show the drop-down menu and choose Other.
  7. Navigate to and select the location where you want the files stored and click Select.
  8. Click the Close button to exit Preferences.
  9. The folder you chose will now be the default location for anything you download from the Internet.

-lets start off by entering the url called http://www.microsoft.com/ on the Safari browser.

-On the Microsoft Website, search for "download Silverlight for mac" -Click on the Relevant link associated with getting Silverlight -Try to download the Silverlight component

It is important to note that we found that for the Silverlight installation needed for the Silverlight/Pivot Viewer component within our Web Application, we needed to ensure that you quit all browsers on the Mac before the installation of Silverlight.

-Ensure that you quit out of all browsers.

-Just quit all applications, and then shutdown your Mac, and then start up your Mac again.

-Ensure that you quit out of all browsers.

-Navigate to the folder where Safari places Downloaded files: -Click on the Silverlight installation file ( should be a file with the extension pkg or it might be file with extension dmg which contains the file with extension pkg.) -Run the installation.

-Navigate to Web application Website

-Login, and try to see if the Silverlight/Pivot Viewer shows up properly.

Does anyone know straightforward steps, tips or suggestions taken to install Silverlight on Mac computers? If so, could you please list it out?

Thanks in advance.

Answers & Comments...




Using a custom WCF serializer in Silverlight

Using a custom WCF serializer in Silverlight

In "full" .NET it is pretty easy to swap out the serializer - either in configuration, or via custom attributes. However, I want to do something similar in Silverlight's WCF - i.e. provide a different serialization engine. I will provide the engine (protobuf-net) - I just need to get WCF to use it!

Last time I looked at this (some time ago) no good options were obvious. My best kludge was to expose the data as byte[] or Stream - but this loses all the "mex" goodness. Which is a shame, as it all pretty-much just works in full .NET.

Is this yet possible? Bonus points for WP7 too :)

Answers & Comments...

Answer: 1

It is possible, but it's quite hard to do. The class DataContractSerializerOperationBehavior (where you'd usually replace the serializer by overriding the CreateSerializer method) is internal in SL, so you can't really use it. What you'd need to do is to create an IOperationBehavior which did what the DCSOB does - namely, set the IClientMessageFormatter which the client will use to convert between the Message body (XML Infoset) and the operation parameters / return values. That would mean writing the code to wrap / unwrap the parameters from the operation into / from the Message object. Not completely impossible, but it should work.

As far as WP7, it doesn't have the extensibility points required for this solution (IOperationBehavior, IClientMessageFormatter) aren't there (they were added on SL4, and WP7 is roughly compatible with SL3), so I don't think it's possible there - or at least not in a generic way (you can have all your operations declared with Message objects - Message MyOperation(Message input) - and at that stage you can deal with the message Infoset (GetReaderAtBodyContents) directly, but that would need to be done in every operation call.

Updated: well, I tried and it is possible to do it in Windows Phone 7 (and Silverlight 3) as well, it's just a lot harder. I recreated the extensibility points using a pair of custom channels. The description of how this can be done can be found at http://blogs.msdn.com/b/carlosfigueira/archive/2011/06/21/wcf-extensibility-extensibility-in-windows-phone-and-silverlight-3.aspx.

by : carlosfigueirahttp://stackoverflow.com/users/751090

Answer: 2

Further to Carlos' answer, since WP7.1 (Mango) is SL4 compatible, it might have the extensibility points required.

by : Richard Szalayhttp://stackoverflow.com/users/3603




I'm trying to make a reddit app for windows phone 7, any starting point? [closed]

I'm trying to make a reddit app for windows phone 7, any starting point? [closed]

I'm new to WP7 and C#, I looked through reddit's APIs but didn't see any obvious C# working sample on how to display user info, or on how to list subreddits etc.

Edit: I found this cool little project at codeplex: redditwp.codeplex.com

No Answer and comments so far




Where can I find the "Silverlight Developer Runtime" for Silverlight 5?

Where can I find the "Silverlight Developer Runtime" for Silverlight 5?

I need to remote debug a Silverlight application that's running on a Mac. According to Microsoft's walkthrough I need to install the developer runtime on the Mac.

I've been Googling for a while now but I can't find an up to date version. This question has links to version 4 and a beta for version 5, but nothing for the current version.

Answers & Comments...

Answer: 1

Try this: Silverlight 5 Developer Runtime for Mac OSX (32 bit)

by : Memoizerhttp://stackoverflow.com/users/1937750




Silverlight "Ctrl + Enter" key handler compatibility

Silverlight "Ctrl + Enter" key handler compatibility

We are planning on using the key combination of "Ctrl + Enter" to generate new rows in grids throughout our application. This key combination doesn't appear to be reserved, but we were just wondering if anyone knows of any browsers that this would present a problem in before we go to production?

Thanks in advance. Ryan.

Answers & Comments...




Internet Explorer fails to run Silverlight Apps after BitDefender 2013 Install

Internet Explorer fails to run Silverlight Apps after BitDefender 2013 Install

I have no idea what's happening here. All I know is that my silverlight web apps ran perfectly after being deployed in December, and now when I open my project and run it it dies with the check manifest error:

Error: Unhandled Error in Silverlight Application Code: 2103
Category: InitializeError
Message: Invalid or malformed application: Check manifest

I know that silly error, and trust me, I didn't change anything (no names, no namespaces, nothing)

A bit of fiddling in fiddler shows that the following 2 files cannot be found each time the app is loading:

/B1D671CF-E532-4481-99AA-19F420D90332/netdefender/hui/ndhui.css

and

/B1D671CF-E532-4481-99AA-19F420D90332/netdefender/hui/ndhui.js?0=0&0=0&0=0

I am not familiar with those files, and in no area of my app am I reffering to them. I am now wondering if the recent installation of BitDefender 2013 has anything to do with it, or maybe it could be the recent windows update that updated the .NET framework 4.0. I tried editing the anti Phishing feature in fact I turned off all the features in BitDefender with nothing availing. If anyone knows what to do regarding this, I would be most thankful for a tip.

Answers & Comments...

Answer: 1

From error code 2103, it seems that there is an issue with manifest file. Most probably you have changed namespace. Here are 4 links that might be helpful.

MSDN Blog

One More MSDN Blog

Code Project

StackOverflow Thread

by : Manojhttp://stackoverflow.com/users/164811

Answer: 2

Well then, I was right after all; BitDefender was at fault. I finally made up my mind and decided to uninstall bitDefender 2013. So I ran the BitDefender Uninstall tool I used to uninstall bitDefender 2012. It seemed to have gone through the process ok, then as expected asked for a restart to complete uninstallation. I didn't realize that only the uninstall tool specifically made for bitDefender 2013 could uninstall it. So, after restart bitDefender 2013 was still present and running perfectly. However, the difference now was that visual studio had no problem debugging my applications neither my browsers any problem loading my Silverlight apps either locally or externally.

Weird? Believe it.

by : Houdini Sutherlandhttp://stackoverflow.com/users/1135128




BitmapImage to Bitmap

BitmapImage to Bitmap

Hy How can i convert a BitmapImage to a Bitmap in Silverlight 4?

Thanks!

Answers & Comments...

Answer: 1

BMP is not supported in Silverlight. BMP is a very old and not a very efficient format (compared with PNG & JPG) so they have not bothered to support it.

Silverlight only supports JPG & PNG format images

The best way to display them is to convert them on the web server so they can be served up as PNGs. The webserver will have access to enough .Net libraries that BMP=>PNG conversion will be easy. I would not bother to create a BMP loader client-side

by : Jignesh.Rajhttp://stackoverflow.com/users/1928157




Tab Navigation on Virtualized Items Panel

Tab Navigation on Virtualized Items Panel

How can you set the Tab Navigation on virtualized items? As example;

        <ListBox x:Name="Items">                     <ListBox.Template>                 <ControlTemplate>                     <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">                         <ItemsPresenter/>                                </ScrollViewer>                          </ControlTemplate>                   </ListBox.Template>             <ListBox.ItemsPanel>                 <ItemsPanelTemplate>                     <VirtualizingStackPanel VirtualizingStackPanel.VirtualizationMode="Recycling"/>                          </ItemsPanelTemplate>                    </ListBox.ItemsPanel>             <ListBox.ItemTemplate>                 <DataTemplate>              <Button />                 </DataTemplate>                      </ListBox.ItemTemplate>                    </ListBox> 

If I set TabNavigation=Once or Cycle on the Scrollviewer itself, or the Listbox parent etc, it only tabs through items available in the viewport since the others haven't been generated yet. Is there a trick someone might share for when tabbing through Item Objects it will allow Tab to proceed to the next not-yet-virtualized item while bringing it to view in the viewport and providing intuitive tabbing through the controls?

Answers & Comments...

Answer: 1

You Should Try This And Type To Help You For This Questen

MSDN

Link

by : Jignesh.Rajhttp://stackoverflow.com/users/1928157

Answer: 2

So basically what was came up (thanks to the extra eyes and help of another fine dev) with was to go ahead and render the other items but while remaining virtualized from onload with a custom behavior and at the same time exposing a dependency for continuous scrolling and bringing the current item into view in the viewport;

namespace The.Namespace {     using System;     using System.Linq;     using System.Windows;        using System.Windows.Controls;     using System.Windows.Input;     /// <summary>     /// Scroll selected item into view.     /// </summary>     public class ListBoxFocusBehavior : FocusBehavior<ListBox>     {         public static readonly DependencyProperty IsContinuousProperty = DependencyProperty.Register("IsContinuous",                                                                          typeof(bool),                                                                          typeof(ListBoxFocusBehavior),                                                                          new PropertyMetadata(                                                                              false,                                                                              (d, e) => ((ListBoxFocusBehavior)d).IsContinuousScroll = (bool)e.NewValue));         /// <summary>         /// Gets or sets a value indicating whether this instance is continuous.         /// </summary>         /// <value>         ///      <c>true</c> if this instance is continuous; otherwise, <c>false</c>.         /// </value>         public bool IsContinuous         {             get { return (bool)GetValue(IsContinuousProperty); }             set { SetValue(IsContinuousProperty, value); }         }         /// <summary>         /// Called after the behavior is attached to an AssociatedObject.         /// </summary>         protected override void OnAttached()         {             base.OnAttached();             AssociatedObject.SelectionChanged += SelectionChanged;             AssociatedObject.KeyDown += KeyDown;         }          /// <summary>         /// Keys down.         /// </summary>         /// <param name="sender">The sender.</param>         /// <param name="e">The <see cref="System.Windows.Input.KeyEventArgs"/> instance containing the event data.</param>         private void KeyDown(object sender, KeyEventArgs e)         {             e.Handled = false;             if (e.Key == Key.Tab && Keyboard.Modifiers == ModifierKeys.None)             {                //forward tab ...                 var idx = AssociatedObject.Items.IndexOf(AssociatedObject.SelectedItem);                 if (idx < AssociatedObject.Items.Count-1)                 {                     AssociatedObject.SelectedItem = AssociatedObject.Items[idx + 1];                     e.Handled = true;                 }             }             if (e.Key == Key.Tab && (Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift)             {                 //back tab.                 var idx = AssociatedObject.Items.IndexOf(AssociatedObject.SelectedItem);                 if (idx > 0)                 {                     AssociatedObject.SelectedItem = AssociatedObject.Items[idx - 1];                     e.Handled = true;                 }              }         }            /// <summary>         /// Called when the behavior is being detached from its AssociatedObject, but before it has actually occurred.         /// </summary>         protected override void OnDetaching()         {             base.OnDetaching();             AssociatedObject.SelectionChanged -= SelectionChanged;             AssociatedObject.KeyDown -= KeyDown;         }          /// <summary>         /// Gots the focus.         /// </summary>         /// <param name="sender">The sender.</param>         /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>         private void GotFocus(object sender, RoutedEventArgs e)         {             if (AssociatedObject.SelectedItem == null && AssociatedObject.Items.Any())             {                 AssociatedObject.SelectedItem = AssociatedObject.Items.First();             }         }          /// <summary>         /// Selections the changed.         /// </summary>         /// <param name="sender">The sender.</param>         /// <param name="e">The <see cref="System.Windows.Controls.SelectionChangedEventArgs"/> instance containing the event data.</param>         private void SelectionChanged(object sender, SelectionChangedEventArgs e)         {             if (AssociatedObject.SelectedItem == null) return;             AssociatedObject.UpdateLayout();              //have to, otherwise the listbox will probably not focus.             Action setFocus = () =>                                   {                                       AssociatedObject.UpdateLayout();                                                                            AssociatedObject.ScrollIntoView(AssociatedObject.SelectedItem);                                       //ensure that if the container did not exist yet (virtualized), it gets created.                                       AssociatedObject.UpdateLayout();                                          var container =                                          AssociatedObject.ItemContainerGenerator.ContainerFromItem(                                              AssociatedObject.SelectedItem) as Control;                                       if (container != null)                                       {                                           container.Focus();                                       }                                    };             AssociatedObject.Dispatcher.BeginInvoke(setFocus);         }     } } 
by : Chris W.http://stackoverflow.com/users/1090206




Silverlight with RIA WCF project can't add regular WCF service reference

Silverlight with RIA WCF project can't add regular WCF service reference

I don't know if this is a bug/feature but I need to find a way to make it work.

To recreate, use VS2012, open a new SL5 project with RIA services enabled. Create another project, add a simple WCF service (or a SL enabled WCF) and add a method that accepts or returns a simple object (I have an object with one string property in it). Try and add this as a service reference to your SL project. You'll receive this error, among others, in the warnings:

Custom tool warning: No endpoints compatible with Silverlight 5 were found. The generated client class will not be usable unless endpoint information is provided via the constructor.

and no generated code is actually generated.

I found that if I remove the object from the service method and use a simple string/int/bool instead, the reference is added just fine. Also, if I add the same service to a regular SL app without RIA, everything works like you would expect it to. Once I enable RIA on this app where the service is working, and update the service reference, the generated code is gone again.

I remember this used to work because I had projects that used both RIA and external WCF services. Is this a new VS2012 thing? Is there a way to solve this issue?

Thanks,

Eyal

Answers & Comments...

Answer: 1

I can duplicate the problem, and it only seems to happen if the Silverlight client has the 2 System.ServiceModel.DomainServices.Client and System.ServiceModel.DomainServices.Client.Web assemblies in its referenced assemblies. And only if it targets SL 5.

I have found 2 workarounds I recommend you try if your situation permits:

1) Change the Silverlight application to target Silverlight 4, not 5, or 2) Right-click the Service Reference and ask to Configure it. Click the checkbox to "Reuse types in specified referenced assemblies" and select all assembles except the 2 mentioned above.

This does appear to be a bug related to either SL 5 or VS2012. I will repost if I find a more satisfactory answer.

by : Ron Cainhttp://stackoverflow.com/users/1819246

Answer: 2

I have exactly the same problem, but the workarounds don't work...any other suggestion?

by : Georgeshttp://stackoverflow.com/users/1540107

Answer: 3

The problem is because of silverlight 5 and vs 2012 has some bug. [It can solve itself by restarting the vs2012]

If you look at your ServiceRefrences.ClientConfig will see it is empty. You need to enter your service refrences manually here. I have attached an example of my config page, you need to change the names accordingly

<configuration> <system.serviceModel>     <bindings>         <basicHttpBinding>             <binding name="BasicHttpBinding_IService2" maxBufferSize="2147483647"                 maxReceivedMessageSize="2147483647">                 <security mode="None" />             </binding>         </basicHttpBinding>     </bindings>     <client>         <endpoint address="../Service2.svc" binding="basicHttpBinding"             bindingConfiguration="BasicHttpBinding_IService2" contract="ServiceReference1.IService2"             name="BasicHttpBinding_IService2" />     </client> </system.serviceModel> 

by : user2020571http://stackoverflow.com/users/2020571




How to play swf file in silverlight?

How to play swf file in silverlight?

i am tring to play a .swf in silverlight5 page.i am using the ListBox control or Image Control Or Any Idea To Play swf File in Silvarlight

<Image Grid.Row="0" Name="bottom_video" Height="80" Source="{Binding VodeoUrl,Mode=OneWay}" Margin="0,20,0,0" />  

Answers & Comments...

Answer: 1

This is impossible. Silverlight does not play swf files. If it is just a video file without any interaction, you might be able to convert the video to something that Silverlight can play. Here is some information about the supported formats:
http://msdn.microsoft.com/en-us/library/cc189080%28v=vs.95%29.aspx

by : Henrik Söderlundhttp://stackoverflow.com/users/250605

Answer: 2

You might be able use the the Flash ActiveX control that is automatically installed with the flash player itself on every windows machine but if it works it'd still comes with a lot of limitations as stated here another problem will be the "Airspace" problem.

Another way is to convert the SWF to XAML using this. But I found quite a lot of swf files that couldn't be converted. Especially if there is a lot of ActionScript or dynamic loading of content involved.

by : bitbonkhttp://stackoverflow.com/users/4227




Add a tooltip to a textbox in a grid in silverlight

Add a tooltip to a textbox in a grid in silverlight

<Grid> <Canvas>  <TextBox Name="txt" IsReadOnly="True" Width="620" VerticalAlignment="Center" Canvas.Left="340" Canvas.Top="5" Text="{Binding RowTitle2,Mode=OneWay}"     ToolTipService.ToolTip="{Binding Path=Text, RelativeSource={RelativeSource Self}}" TextWrapping="NoWrap" HorizontalAlignment="Stretch"/>  </Canvas> </Grid> 

this way there is no tooltip, so how to add one ? here i create dynamically records(txtboxes in the grid)

but on a similar example everything works just fine(no dynamilcall creation of txtboxes)

<Grid> <Canvas>    <TextBox Name="txt" Margin="0,5,5,0" IsReadOnly="True" Width="620" VerticalAlignment="Center"   Canvas.Left="-200" Canvas.Top="-5"  ToolTipService.ToolTip="{Binding Path=Text, RelativeSource={RelativeSource Self}}" TextWrapping="NoWrap" HorizontalAlignment="Stretch"/>  </Canvas> </Grid> 

Answers & Comments...

Answer: 1

What's the point here ? Its a bit confusing to use ReadOnly text box in a canvas which is located in a grid. Instead use a TextBlock which also improves performance, prevents memory leak, and looks better.

    <Grid>   <TextBlock Margin="0,5,5,0"  VerticalAlignment="Center"  HorizontalAlignment="Stretch" TextWrapping="NoWrap" Text="{Binding RowTitle2}" ToolTipService.ToolTip="{Binding Path=Text, RelativeSource={RelativeSource Self}}"  /> </Grid> 
by : serifcetinerhttp://stackoverflow.com/users/1530871




SL media element won't play my wave file after the first time

SL media element won't play my wave file after the first time

I use WaveMediaStreamSource (WAVmss) library to play wave files on silverlight media element.
It plays the first time I load the file into the element, but when I try and play it a second time it doesn't play.
I used the sample from here.

Maybe I'm missing something, here is my code where I'm opening wave file and play it successfully for the first time, Here is the file reading and setting as source in my media element:

OpenFileDialog openFileDialog = new OpenFileDialog();     MemoryStream audioSource = new MemoryStream();  if (openFileDialog.ShowDialog() == true)     {        using (FileStream fileStream = openFileDialog.File.OpenRead())        {            audioSource.SetLength(fileStream.Length);            fileStream.Read(audioSource.GetBuffer(), 0, (int)fileStream.Length);        }     }  WaveMSS.WaveMediaStreamSource audioStreamSource =                   new WaveMSS.WaveMediaStreamSource(audioSource);  mediaElement1.SetSource(audioStreamSource); 

And when the first play over (I know it since I'm getting _MediaEnded event) I can't play this video again.

I tried to set the position of the MediaElement but failed to play it again:

mediaElement1.Position = TimeSpan.FromSeconds(0); mediaElement1.Play(); 

I debugged it and the Position property does get set to zero but when I'm trying to click play again position property moves to the end and the _MediaEnded event pops up again.

What can I do?

Answers & Comments...

Answer: 1

In the MediaEnded event, cast "sender" to a MediaElement and call Stop(). This resets the object so you can play it again.

by : LordTakkerahttp://stackoverflow.com/users/1783619

Answer: 2

Thanks to Gilles Khouzam quick response the problem has been solved.

Ok, I found the issue. The implementation of SeekAsync, the position in the stream was changed but the remaining count in the chunk was not. In WaveMediaStreamSource.cs, look for the SeekAsync method and change the code to this (add the MoveToChunkOffest line):

this.currentPosition = this.wavParser.WaveFormatEx.BufferSizeFromAudioDuration( seekToTime ) + this.startPosition; this.wavParser.MoveToChunkOffset( ( uint ) this.wavParser.WaveFormatEx.BufferSizeFromAudioDuration( seekToTime ) ); this.currentTimeStamp = seekToTime; ReportSeekCompleted( seekToTime ); 
by : Dor Cohenhttp://stackoverflow.com/users/871672




Print from Silverlight 5 / VB.Net

Print from Silverlight 5 / VB.Net

I'm really struggling to understand how to do this.

Does any one have any VB.Net code I can wire up to a 'Print' button in Silverlight that will print multiple pages, AND fit to print?

My output is made up of multiple grids, all 1020px wide and totalling approx 5000px in height.

Thanks.

Answers & Comments...

Answer: 1

You might think about the memory usage during print process. Debug your code and printer interface of computer and check the data sent to printer. In your case, Silverlight might send GB's of data to printer which blocks computer and printer both.

http://msdn.microsoft.com/en-us/library/system.windows.printing.printdocument(v=vs.95).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2

by : serifcetinerhttp://stackoverflow.com/users/1530871




C# difference between `==` and .Equals()

C# difference between `==` and .Equals()

I have a condition in a silverlight application that comapres 2 strings, for some reason when I use '==' it returns false while .Equals() returns true. Here is the code :

 if (((ListBoxItem)lstBaseMenu.SelectedItem).Content.Equals("Energy Attack"))  { // Execute code  }   if (((ListBoxItem)lstBaseMenu.SelectedItem).Content == "Energy Attack")  { // Execute code  } 

Any reason as to why this is happening?

Answers & Comments...

Answer: 1

When == is used on an object type, it'll resolve to System.Object.ReferenceEquals.

Equals is just a virtual method and behaves as such, so the overridden version will be used (which, for string type compares the contents).

by : Mehrdad Afsharihttp://stackoverflow.com/users/33708

Answer: 2

INACCURATE: String.Equals compares string content, but "==" compares object references. If the two strings you are comparing are referring to the same exact instance of a string, both will return true, but if one of the strings has the same content and came from a different source (is a separate instance of a string), only Equals will return true.

CORRECTION: The second comment associated with this post is correct. The following code illustrates the issue:

string s1 = "test"; string s2 = "test"; string s3 = "test1".Substring(0, 4); object s4 = s3; Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s2), s1 == s2, s1.Equals(s2)); Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s3), s1 == s3, s1.Equals(s3)); Console.WriteLine("{0} {1} {2}", object.ReferenceEquals(s1, s4), s1 == s4, s1.Equals(s4)); 

The output is:
True True True
False True True
False False True

by : BlueMonkMNhttp://stackoverflow.com/users/78162

Answer: 3

What == and .Equals does is both dependent upon the behavior defined in the actual type and the actual type at the call site. Both are just methods / operators which can be overridden on any type and given any behavior the author so desires. In my experience, I find it's common for people to implement .Equals on an object but neglect to implement operator ==. This means that .Equals will actually measure the equality of the values while == will measure whether or not they are the same reference.

When I'm working with a new type whose definition is in flux or writing generic algorithms, I find the best practice is the following

  • If I want to compare references in C#, I use Object.ReferenceEquals directly (not needed in the generic case)
  • If I want to compare values I use EqualityComparer<T>.Default

In some cases when I feel the usage of == is ambiguous I will explicitly use Object.Reference equals in the code to remove the ambiguity.

Eric Lippert recently did a blog post on the subject of why there are 2 methods of equality in the CLR. It's worth the read

by : JaredParhttp://stackoverflow.com/users/23283

Answer: 4

I am a bit confused here. If the runtime type of Content is of type string, then both == and Equals should return true. However, since this does not appear to be the case, then runtime type of Content is not string and calling Equals on it is doing a referential equality and this explains why Equals("Energy Attack") fails. However, in the second case, the decision as to which overloaded == static operator should be called is made at compile time and this decision appears to be ==(string,string). this suggests to me that Content provides an implicit conversion to string.

by : Mehmet Arashttp://stackoverflow.com/users/95437

Answer: 5

I would add that if you cast your object to a string then it will work correctly. This is why the compiler will give you a warning saying "Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'"

by : MikeKullshttp://stackoverflow.com/users/701485

Answer: 6

Adding one more point to the answer.

.EqualsTo method gives you provision to compare against culture and case sensitive.

by : Balahttp://stackoverflow.com/users/764963

Answer: 7

== Operator 1. If operands are Value Types and their values are equal, it returns true else false. 2. If operands are Reference Types with exception of string and both refer to same object, it returns true else false. 3. If operands are string type and their values are equal, it returns true else false.

.Equals 1. If operands are Reference Types, it performs Reference Equality that is if both refer to same object it returns true else false. 2. If Operands are Value Types then unlike == operator it checks for their type first. If their types are same it performs == value type equality else it returns false.

by : kashifhttp://stackoverflow.com/users/1290058




Save to XML from TreeView

Save to XML from TreeView

I have a problem with saving my data from TreeView. I've googled a lot of topics how to save data from TreeView to XML, and I saw i few methods how to make that. But all of them were using WindowsForms application, and nobody - WPF. I tried to convert those examples to WPF, but no one from them do not work correct. Is there any way to make it? One of the ways I tried to port:

    void SaveToXml(TreeView tw)     {         XmlDocument d = new XmlDocument();         XmlNode n = d.CreateNode(XmlNodeType.Element, "root", "");         foreach (TreeViewItem t in tw.Items)         {             n.AppendChild(getXmlNode(t, d));         }         d.AppendChild(n);         d.Save(AppDomain.CurrentDomain.BaseDirectory + "out.xml");     }     private XmlNode getXmlNode(TreeViewItem tnode, XmlDocument d)     {         XmlNode n = d.CreateNode(XmlNodeType.Element, tnode.Name, " ");          foreach (TreeViewItem t in tnode.Items)         {             n.AppendChild(getXmlNode(t, d));         }         return n;     } 

It throws ArgumentException "Local element's and attribute's names cannot be empty". I'm trying to save info about files on my D:\ drive using code:

  private void ListDirectory(TreeView treeView, string path)     {         var rootDirectoryInfo = new DirectoryInfo(path);         treeView.Items.Add(CreateDirectoryNode(rootDirectoryInfo));     }      private static TreeViewItem CreateDirectoryNode(DirectoryInfo directoryInfo)     {         var directoryNode = new TreeViewItem();         directoryNode.Header = directoryInfo.Name;         try         {             foreach (var directory in directoryInfo.GetDirectories())                 directoryNode.Items.Add(CreateDirectoryNode(directory));             foreach (var file in directoryInfo.GetFiles())                 directoryNode.Items.Add(new TreeViewItem { Header = file.Name });         }         catch (UnauthorizedAccessException e)         { }         return directoryNode;     } 

It works fine, and TreeView shows all the folders and files. Please, show me how to save data from TreeView to XML. Thanks.

Tried this:

  public void exportToXml(TreeView tv, string filename)     {         sr = new StreamWriter(filename, false, System.Text.Encoding.UTF8);         //Write the header         sr.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");         //Write our root node         sr.WriteLine("<ROOT>");         foreach (TreeViewItem node in tv.Items)         {             saveNode(node.Items);         }         //Close the root node         sr.WriteLine("</ROOT>");         sr.Close();     }      private void saveNode(TreeViewItem[] tnc)     {         foreach (TreeViewItem node in tnc)         {             //If we have child nodes, we'll write              //a parent node, then iterrate through             //the children             if (node.Items.Count > 0)             {                 sr.WriteLine("<" + node.Name + ">");                 saveNode(node.Items);                 sr.WriteLine("</" + node.Name + ">");             }             else //No child nodes, so we just write the text                 sr.WriteLine(node.Name);         }     } 

But saveNode(node.Items); says that there are different types between node.Items and TreeViewItem[], so I tried List<TreeViewItem>, but error is the same.

Answers & Comments...

Answer: 1

I'm afraid this is not a real answer, but you may try replacing this line :

saveNode(node.Items);  

with this one :

saveNode(node.Items.OfType<TreeViewItem>().ToArray());  

Hope this will help,


Example of getting an indented string from an xml doc :

public static String ToString(XmlDocument doc) {     StringBuilder sb = new StringBuilder();     XmlTextWriter mywriter = new XmlTextWriter(new StringWriter(sb));     mywriter.Formatting = Formatting.Indented;     doc.WriteTo( mywriter );     mywriter.Flush();     return(sb.ToString()); } 
by : jblhttp://stackoverflow.com/users/1236044




Does Silverlight 5 support Dolby Digital (AC-3) 5.1 surround sound playback?

Does Silverlight 5 support Dolby Digital (AC-3) 5.1 surround sound playback?

Does playing video with Silverlight 5 support the playback of Dolby Digital (AC-3) 5.1 surround sound, or will it always downmix the channels to stereo?

I'm streaming a Smooth Streaming video, but the Silverlight Smooth Streaming Sample Player doesn't seem to support Dolby audio playback.

Answers & Comments...

Answer: 1

No with default players.

Source: http://msdn.microsoft.com/en-us/library/cc189080%28v=vs.95%29.aspx#delivery_method_containers_and_codecs

Quote:

(For WMA audio, the only one mentioning surround sound) Multichannel (5.1 and 7.1 surround) audio content is automatically mixed down to stereo. 

And for Smooth Streaming:

http://www.iis.net/learn/media/smooth-streaming/smooth-streaming-client-readme

Not many details here, supported audio codec is AAC.


See also here:

http://www.iis.net/learn/media/smooth-streaming/smooth-streaming-primer#create_piff

Supported codecs are AAC and WMA/WMA Pro.

by : jv42http://stackoverflow.com/users/428381




"Unable to start program" error for web project

"Unable to start program" error for web project

I have a Silverlight project that we use internally that I wrote - and since we've not had any need to work on it, it's been a while since I've opened the project. I opened it up this morning and everything is fine in terms of building, but whenever I try to debug I get the following error:

Unable to start program "http://mymachinename/mywebsite/index.aspx"

Of course, running it in Firefox works fine but no symbols are loaded. Running without debugging still throws the same error but IE loads up anyway...

Navigating to the website in IE works fine - SL app opens up, loads data etc etc, all looks good

I've Googled this all morning (usually quite good at finding info) and been through all the questions on SO and I can't figure out what's going on - there doesn't seem to be any messages in the event log, there are no messages in any VS output window, the w3wp just terminates immediately after starting (probably due to there being an error trying to open IE). I've tried reinstalling IE, cleaning/rebuilding, using local dev server, creating a new web project, turning on/off settings in IE9 etc etc

Nothing seems to make a difference - anyone got any experiences of this and has fixed it without doing one of the things I've already done? Any other suggestions?

Thanks in advance!

UPDATE

Just to be clear in case anyone asks - I get this problem when creating a new web project - i.e. everything I said I'd tried (above) didn't change the behaviour. It showed the same error no matter what I'd done so far (that includes a NON SL web project)

I've also tried attaching the debugger to w3wp that is running (the standard IIS process) and I can't seem to get it to debug (no symbols are loading), but that might be another issue altogether. I'm going to look at that next and maybe if I figure that out it might lead to fixing this issue

UPDATE 2

Debugging in Firefox works - I attached to w3wp with no success, then realising my stupidity (SL being a client side app!) I attached to the plugin-container.exe that FF runs its plugins in. This works. I can probably do the same for IE and just attach to IE, but why won't it start up from VS?! hair pull

UPDATE 3

Just in case anyone asks, the default browser is set to IE in VS. Also I've managed to debug by attaching to IE, it just won't start IE from within VS - annoying but I can live with it for now. If anyone does have a suggestion though, feel free...

Answers & Comments...

Answer: 1

For anyone's information in case they have this same problem, it ended up being that the port I was running my site on was also running a SharePoint site!

I created a new site on port 81 and used that for dev - not sure what setting on the other site caused the issue but it ended up working on port 81.

by : Charlehhttp://stackoverflow.com/users/987509




Printing in Silverlight/Lightswitch using XAML and custom controls

Printing in Silverlight/Lightswitch using XAML and custom controls

I am programming a Silverlight application using Lightswitch. I want to print the data which is displayed on some screens.

I found this tutorial for printing in Silverlight/Lightswitch. It describes how to create a custom control using XAML which can be printed. The control looks like this:

Printing in Lightswitch

In the background you can see the control how it looks like in the Silverlight application. The control contrains both a button and a grid:

<StackPanel>     <Button Content="Print" Name="btnPrint" Click="btnPrint_Click" />         <Grid x:Name="LayoutRoot">             <!-- grid code goes here -->             <!-- some more code an closing tags --> 

Using Silverlight's printing API, printing is done like this in the custom control:

PrintDocument printInvoice = new PrintDocument(); private void btnPrint_Click(object sender, System.Windows.RoutedEventArgs e){        printInvoice.PrintPage +=         new EventHandler<PrintPageEventArgs>(printInvoice_PrintPage); }  void printInvoice_PrintPage(object sender, PrintPageEventArgs e){     e.PageVisual = LayoutRoot; } 

Since e.PageVisual = LayoutRoot is used, we only see the table in the printed output, and not the button. That's okay, but I would like to use a seperate XAML for the print layout. My goal is to just show a button Print on the Silverlight application, and define the print layout in a seperate XAML.

So, I just started to create a second XAML as SilverlightControl and tried to use it:

MyPrintLayout mpl = new MyPrintLayout(); void printArtikels_PrintPage(object sender, PrintPageEventArgs e){     e.PageVisual = mpl.LayoutRoot; } 

But I get the error "Das Element ist bereits das untergeordnete Element eines anderen Elements" (english: "The element is already the sub-element of another element"). This error was discussed in this question as well, but it does not solve my problem.

When I include MyPrintLayout in the silverlight application it is displayed without a problem (there is only some text in it to test the functionality).

It seems like I am doing this completely wrong. How can I achieve my goal?

Answers & Comments...

Answer: 1

mpl.LayoutRoot already sub-element of mpl. Try this:

void printArtikels_PrintPage(object sender, PrintPageEventArgs e){     MyPrintLayout mpl = new MyPrintLayout();     e.PageVisual = mpl; } 
by : Memoizerhttp://stackoverflow.com/users/1937750




Object is not destructing after removing it from the collection

Object is not destructing after removing it from the collection

In Silverlight, I have a collection of tab items. On clicking of a button, I am adding a new tab with a control as content in the collection and showing it to the screen. Now, I have a "Close" button in the screen, calling which, the current visible tab removes from the collection and thus no longer visible in the screen.

I noticed that, though the tab item has been removed from the collection from the tab item and collection, the destructor of the control part of the tab is not getting call all the time. And sometime, it is getting called after a long time (not always).

Though the item has been removed, why it is taking time to call the destructor of the object? How can I resolve this issue? Any pointers?

Answers & Comments...

Answer: 1

The destructor of the object called by Garbage Collector, when it seems necessary. Programmer should not rely on the immediate calling the destructor.

by : Memoizerhttp://stackoverflow.com/users/1937750




Load operation failed for query due to data limit

Load operation failed for query due to data limit

We have a silverlight application which interfaces with an RIA service to get a list of contacts to display in a grid, this normally works however we are getting the following error:

load operation failed for query x. the remote server returned an error: notfound 

Tracing this through we have determined it is due to the amount of data that is being passed as it will work if the we pass roughly 3,800 records or less. We need to load at least 15,000 records from the database.

I have searched all over the internet to find a solution and have changed the following settings but nothing seems to have worked.

Settings changed are:

  • In IIS7 changed the ASP setting 'Response Buffering Limit' to 67108864
  • In IIS7 changed the ASP setting 'Maximum Requesting Entity Body Limit' to 2000000
  • In IIS7 changed the ASP setting 'Client Connection Test Interval' to 00:00:10
  • In our application web.config changed 'maxItemsInObjectGraph' to 2147483647
  • In our application web.config binding attributes 'maxReceivedMessageSize', 'maxBufferSize' and 'maxBufferPoolSize' are all set to 200000000
  • In our application web.config readerQuotas attributes 'maxArrayLength', 'maxStringContentLength', 'maxBytesPerRead', 'maxNameTableCharCount' are all set to 200000000

This is setup on Server 2008 R2 with IIS7 and using .Net 4.

This error also occurs when running in the debugger using the ASP.NET Development Server.

Any help would be appreciated.

Answers & Comments...




Upgrading Silverlight application while in use on clients

Upgrading Silverlight application while in use on clients

I have a Silverlight 5 application which communicates with the server by a WCF service.

Most users that use the application are running it inside a browser (mostly Internet Explorer, but also other browsers are used) and a few install it OOB (Out Of Browser).

When the application starts, It checks for newer versions and upgrade if necessarily. Nothing out of the ordinary here.

Now and then, mostly in evenings and weekends, I do upgrades on the solution. That may be changes in the database, changes in the WCF service, changes in the Silverlight application itself, or a mix of all. And in most cases, that is absolutely no problem.

My problem is that some users never close their web browser. Some users even work via a Citrix window, and only close the Citrix window and goes home after work, letting the Silverlight application run and exist in the web browser. And some just don't close the browser at all. Or if they run OOB, they let the application stay open. Those are my problem. Because they will never check for new updates. The Silverlight application will never upgrade, and also not fit to the new WCF service which may be upgraded.

That all makes the Silverlight applications crash and throw strange exceptions because the world around has changed.

Has anyone had similar problems and actually found a good solution?

I have tried:

  • Creating a Timer that resets at any keyboard- or mouse clicks and exits the application after a given period of time with no activity. But it seems like this timer sometimes don't count, like when dosconnected from RDP or Citrix session.

  • Checking for updates every time a certain control or window is showing. But that is not a good solution because all users may not use the same. It may also interrupt the user if they are working with something.

But they all seem to me like a little tacky work-arounds.

Any suggestions, anyone?

Answers & Comments...




Unit Testing in Lightswitch

Unit Testing in Lightswitch

I'm thinking of running unit tests for the business logic in the Lightswitch application. I've added a Silverlight unit test project (from the Silverlight Toolkit), however I couldn't retrieve the code from Lightswitch to write tests on.

Or is there really no way and the best way is to move the code out to another Silverlight class library?

Answers & Comments...

Answer: 1

Ended up creating a separate test project, then adding the code to be tested through the "Add as Link" option. This way I was able to unit test the code even if the logic is inside the Lightswitch project.

by : Bryan Honghttp://stackoverflow.com/users/928978

Answer: 2

You can test custom LightSwitch code by using the GoF bridge pattern, see https://github.com/legg/UnitTestingLightSwitch2011

by : Legghttp://stackoverflow.com/users/1957882




How to printing a document in silverlight

How to printing a document in silverlight

I've written an application web in silverlight for view Tiff files. I send an absolut uri of Tiff files to silverlight app and it view /zooming or download a file.

I print the tiff with PrintDocument library, but the file sent to printer is very large (500Mb for 100kb of tiff file).

Now this is my code for printing:

 Protected Sub pd_PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)     Try         If (PrintPageCount = 0) Then             PrintPageCount = ImageTiff.NumberOfDirectories             PrintCurrPage = 0         End If         If (PrintCurrPage < PrintPageCount) Then             ImageTiff.SetDirectory(PrintCurrPage)             Dim cnv As New Canvas With                 {                     .Width = 840,                     .Height = 1180,                     .Background = New ImageBrush With {                              .ImageSource = GetWritableBmp(ImageTiff, larghezza, altezza),                              .Stretch = Stretch.Fill                      }                 }             ev.PageVisual = cnv             PrintCurrPage += 1             ev.HasMorePages = True         Else             ev.HasMorePages = False         End If     Catch ex As Exception         MessageBox.Show("Errore handler:" & ex.Message & vbCrLf & ex.StackTrace)     End Try End Sub 

And my event handler for print button

 Private Sub ButtonPrint_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonPrint.Click     Try         Dim pdoc As New PrintDocument()         AddHandler pdoc.PrintPage, AddressOf Me.pd_PrintPage         pdoc.Print(Uri.AbsoluteUri)     Catch ex As Exception         MessageBox.Show("Errore:" & ex.Message)     End Try End Sub 

I want to send print of "http://www.mysite.it/tifffiles/mytif.tif" directly to printer, this is possible?

Answers & Comments...




What MVVM framework are you using?

What MVVM framework are you using?

I am looking to write a WPF app and am trying to pick a MVVM framework to handle some of the complexity. What would you recommend and where can I find a good tutorial/getting started guide for said framework?

Answers & Comments...

Answer: 1

I have had success with the Composite Application Guidance for WPF and Silverlight framework, also known as "Prism". It is available, as open-source, at http://compositewpf.codeplex.com/.

I learned the basics by following along to the information in four videos describing the construction of a Prism-based application:

  1. Part 1
  2. Part 2
  3. Part 3
  4. Part 4

Good luck!

by : JeffFergusonhttp://stackoverflow.com/users/93991

Answer: 2

Here's a bunch of links to MVVM frameworks:

by : Cameron MacFarlandhttp://stackoverflow.com/users/3820

Answer: 3
  • PRISM - Developed by Microsoft, targeting WPF, Silverlight, Windows Phone 7.
  • MVVM light by Laurent Bugnion WPF, Silverlight, WP7
  • Simple MVVM WPF, Silverlight, WPF
  • Caliburn - Caliburn implements a variety of UI patterns for solving real-world problems. Patterns that are enabled by the framework include MVC, MVP, Presentation Model (MVVM), Commands and Application Controller.
  • Caliburn Micro - A smaller version of Caliburn.
  • Silverlight.FX - Silverlight.FX is a light-weight application framework for building Rich Internet Applications with Silverlight 2.
by : Aaron Fischerhttp://stackoverflow.com/users/5618

Answer: 4

Yet another framework with support for the Model-View-ViewModel (MVVM) pattern:

WPF Application Framework (WAF)

http://waf.codeplex.com

by : jbehttp://stackoverflow.com/users/103988

Answer: 5

I needed Extensibility (the ability to write add-ins for my application) in addition to WPF/MVVM, so I pieced together my own framework and released it as open source:

by : Scott Whitlockhttp://stackoverflow.com/users/17635

Answer: 6

Have not used any of them personally, but there is a roundup of a few frameworks here:

http://www.japf.fr/2009/10/a-quick-tour-of-existing-mvvm-frameworks/

by : Frep D-Orongehttp://stackoverflow.com/users/3024

Answer: 7

There is also Vidyano which uses MVVM as architecture.

by : XIUhttp://stackoverflow.com/users/295296

Answer: 8

A personal mix of others. I use some elements from Josh Smith's MVVM foundation (reflection helpers for type safe INotifyPropertyChanged implementation), Event Aggregator from Cinch, RelayCommand (from... I forgot :D) and many others.

Mix your own! Use only what you need, understand it all.

by : Andrei Rineahttp://stackoverflow.com/users/1796

Answer: 9

I'd recommend CinchV2 , I do think it is one of the best MVVM-frameworks currently available.

http://sachabarber.net/?page_id=523

by : Karaaiehttp://stackoverflow.com/users/678490

Answer: 10

I would recomend you MVVMCross framework.

It's free, open-source and well designed. It is developed by Stuart Lodge.

He implemented binding for Android and iPhone, so now MVVM is applicable to these platforms too.

For me it is one of the best MVVM frameworks - it really shows the power of MVVM. With it you can write one code (model and viewmodel layers) for different platforms (WP7, Android, iPhone, WinRT) and just change application UI (view layer).

by : gerichhomehttp://stackoverflow.com/users/1201963

Answer: 11

Well, I've been using CarbonMVVM for a few months and it showed as a large productivity boost. It took me some time to get used to the new model of thinking, but now i can't live without it :)

It is poorly documented for now, but has good examples.

Hope it helps someone.

by : jax2http://stackoverflow.com/users/1558918

Answer: 12

Try new open-source project.

It contains many interesting solutions and templates of different MVVM problems.

https://mvvmframework.codeplex.com

by : user2022448http://stackoverflow.com/users/2022448




Is it possible to launch a Silverlight 4 OOB application from a web page?

Is it possible to launch a Silverlight 4 OOB application from a web page?

I'm planning to build a download manager application and would like to be able to launch the application when a user clicks a button the site. The application would obviously already need to be installed on the client machine.

There are a few reasons why this needs to be written using Silverlight, but they're not really relevant to the question. I only mention it so that people don't suggest that I use another technology.

Answers & Comments...

Answer: 1

Yes. Here is an example: http://www.silverlight.net/content/samples/apps/facebookclient/sfcquickinstall.aspx

by : Michael S. Scherotterhttp://stackoverflow.com/users/27306

Answer: 2

I think that is not possible according to this post post 1 and to other post. But I don't know if MS will change that in the last version of SL 4

by : Sebastianhttp://stackoverflow.com/users/356609

Answer: 3

Doing a bit of a mash up from two other posts [1] and [2].

But of course this will only work for Windows not Mac. There you will have to fallback to the @michael-s-scherotter style solution.

private void Button_Click(object sender, RoutedEventArgs e) {     if (Application.Current.HasElevatedPermissions && System.Windows.Interop.ComAutomationFactory.IsAvailable)     {          string run = "\""%ProgramFiles%\\Microsoft Silverlight\\sllauncher.exe"\" /emulate:"Silverface.xap" /origin:\"http://www.silverlight.net/content/samples/apps/facebookclient/ClientBin/Silverface.xap\" /overwrite";         dynamic cmd = ComAutomationFactory.CreateObject("WScript.Shell");         cmd.Run(run, 1, true);      } } 
by : JProgrammerhttp://stackoverflow.com/users/1675

Answer: 4

I found a trick that launches the installed silverlight OOB from the silverlight app in-browser. Both applications should be singed and have the elevated trust.

  1. When a user installs the silverlight OOB App first time, retrive the path and argument values from the shortcut file of the OOB app on desktop. (ref: How I can use Shell32.dll in Silverlight OOB) If you know the the path and argument values, you can launch the OOB app using Com Object.

  2. Send the retrive the path and argument values to the silverlight App in-browser. (ref: http://msdn.microsoft.com/en-us/library/dd833063(v=vs.95).aspx)

  3. Store the path and argument values in a cookie.

  4. Now, the silverlight app in-browser is able to launch the silverlight OOB using the path and argument values in the cookie.

    using (dynamic shell = AutomationFactory.CreateObject("WScript.Shell")) { shell.Run(launchPath); }

I hope this trick is useful to you :)

by : user689072http://stackoverflow.com/users/689072




Making the Silverlight XAP file expire from browser cache programmatically

Making the Silverlight XAP file expire from browser cache programmatically

How to do I prevent a Silverlight XAP file being cached by the web browser?

The reason I want to do this is during development I don't want to manually clear the browser cache, I'm looking for a programmatic approach server side.

Cheers

AWC

Answers & Comments...

Answer: 1

Add a query parameter to the URL for the XAP in the element on the HTML Page:

  • clientBin/MyApp.xap?rev=1
  • clientBin/MyApp.xap?rev=2

It will be ignored and break the cache. In IE8, there are some cache management tools: Open the Developer tools:

  • Try Cache...Always Refresh from Server
  • Try Cache...Clear Browser Cache for this domain...
by : Michael S. Scherotterhttp://stackoverflow.com/users/27306

Answer: 2

Using IIS management add a custom header Cache-Control with the value no-cache. That'll cause the browser to check that any cached version of the XAP is the latest before using it.

by : AnthonyWJoneshttp://stackoverflow.com/users/17516

Answer: 3

Create a custom http handler for handling *.xap files and then set your caching options inside the handler.

Something like this...

using System; using System.IO; using System.Web;  public class FileCacheHandler : IHttpHandler {     public virtual void ProcessRequest(HttpContext context)     {         if (File.Exists(context.Request.PhysicalPath))         {             DateTime lastWriteTime = File.GetLastWriteTime(filePath);             DateTime? modifiedSinceHeader = GetModifiedSinceHeader(context.Request);              if (modifiedSinceHeader == null || lastWriteTime > modifiedSinceHeader)             {                 context.Response.AddFileDependency(filePath);                 context.Response.Cache.SetLastModifiedFromFileDependencies();                 context.Response.Cache.SetCacheability(HttpCacheability.Public);                 context.Response.TransmitFile(filePath);                 context.Response.StatusCode = 200;                 context.Response.ContentType = "application/x-silverlight-app";                 context.Response.OutputStream.Flush();             }             else             {                 context.Response.StatusCode = 304;             }         }     }      public DateTime? GetModifiedSinceHeader(HttpRequest request)     {         string modifiedSinceHeader = request.Headers["If-Modified-Since"];         DateTime modifiedSince;         if (string.IsNullOrEmpty(modifiedSinceHeader)           || modifiedSinceHeader.Length == 0           || !DateTime.TryParse(modifiedSinceHeader, out modifiedSince))             return null;          return modifiedSince;     } } 
by : David Cooperhttp://stackoverflow.com/users/616875

Answer: 4

The solution presented here is somewhat similar to Michael's but is automatic and guarantees the client will always get a new version. This may be inefficient depending on your situation.

Since Lars says in his comments that he is not on Stack Overflow, I'm copying the response here.

<object id="Xaml1" data="data:application/x-silverlight-2,     "type="application/x-silverlight-2" width="100%" height="100%">    <%––<param name="source" value="ClientBin/SilverlightApp.xap"/>––%>    <%          string orgSourceValue = @"ClientBin/SilverlightApp.xap";          string param;      if (System.Diagnostics.Debugger.IsAttached)          {         param = "<param name=\"source\" value=\"" + orgSourceValue + "\" />";     }     else          {            string xappath = HttpContext.Current.Server.MapPath(@"") + @"\" + orgSourceValue;        DateTime xapCreationDate = System.IO.File.GetLastWriteTime(xappath);              param = "<param name=\"source\" value=\"" + orgSourceValue + "?ignore=" +                 xapCreationDate.ToString() + "\" />";          }      Response.Write(param);        %>    ....  </object> 
by : Jedidjahttp://stackoverflow.com/users/9913

Answer: 5

Well all the above examples depend on the browser NOT caching the HTML that contains the new trick xap name.... so you just move the problem on to something else. And they are also fiendishly complicated....

However for the debugging case, at least, it's easy to write the <object> and <param> tags in javascript so that the name changes every time the html page is used, whether it's cached by the browser or not!

<script type="text/javascript">    document.write('<object blah blah >');    document.write('<param name="Source" value="myapp.xap?'                + new Date().getTime()+'">');    document.write('</object>');  </script> 

This sidesteps any hassle you may have controlling server settings and works just as well regardless of the server technology in use.

Note: you have to write the whole object group with the same method because putting a script tag inside the object tag means "only do this if the browser doesnt support the object.

by : Chris Harlowhttp://stackoverflow.com/users/813094

Answer: 6

I added a query parm to the path of the xap file, so that I can manage it through Versioning.

Default.aspx code:

<param    name="source"    value="ClientBin/MySilverLightApp.xap?xapid<%=XapID %>" /> 

Default.aspx.cs code:

protected string XapID {     get     {         Version v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;          if (System.Diagnostics.Debugger.IsAttached)             Response.Write(string.Format("Build: {0}.{1}.{2}.{3}", v.Major.ToString(), v.Minor.ToString(), v.Build.ToString(), v.Revision.ToString()));         return string.Format("{0}.{1}.{2}.{3}", v.Major.ToString(), v.Minor.ToString(), v.Build.ToString(), v.Revision.ToString()     } } 
by : Big Chickenhttp://stackoverflow.com/users/2022512




Wednesday, January 23, 2013

Take a screenshot with silverlight 5 / xna

Take a screenshot with silverlight 5 / xna

I'm trying to take a screenshot of a subclassed XNA DrawingSurface element from within a silverlight 5 application. This sl app will run inside an aspx page.

Here's what I've tried so far without success:

WriteableBitmap bmp = new WriteableBitmap(LayoutRoot, null);  testImage.Source = bmp;  

with LayoutRoot being the parent control on the silverlight page and testImage is just an Image control on the page to see if the screenshot is correct.

This will render all the silverlight controls on the page just fine, but the drawingsurface part remains empty. In other words the XNA content is not rendered into the image.

I've also tried to render the XNA content to a RenderTarget2D, but the silverlight version of the render target does not seem to have any methods to save the data. I saw some WP7 examples that used a method called SaveAsJpeg(), but that doesn't seem to be available in the SL5 version of the class.

I would appreciate any help with this.

Greets,

Floris

Answers & Comments...

Answer: 1

One possibility would be to draw your screen into a RenderTarget2D and then use the method SaveAsPng like:

using (Stream stream = File.OpenWrite("filename.png")) { renderTarget2D.SaveAsPng(stream, renderTarget2D.Width, renderTarget2D.Height); } 
by : pad_areshttp://stackoverflow.com/users/1955152




Tuesday, January 22, 2013

TimHeuer's FloatableWindow Issue - Setting Offset Has No Effect

TimHeuer's FloatableWindow Issue - Setting Offset Has No Effect

I have the following XAML inside a Grid named LayoutRoot.

<sdk:DataGrid x:Name="dgOrderContents" AutoGenerateColumns="False" HorizontalAlignment="Stretch" HorizontalContentAlignment="Left" AlternatingRowBackground="#FFFAEF">     <sdk:DataGrid.Columns>         <sdk:DataGridTemplateColumn Header="Thumb">             <sdk:DataGridTemplateColumn.CellTemplate>                 <DataTemplate>                     <ucp:PhotoComponentForDataGrid Source="{Binding PhotoUrl}" PopupTarget="{Binding ElementName='LayoutRoot' }" Width="60" />                 </DataTemplate>             </sdk:DataGridTemplateColumn.CellTemplate>         </sdk:DataGridTemplateColumn     </sdk:DataGrid.Columns> </sdk:DataGrid> 

PhotoComponentForDataGrid, is a UserControl, which is an image that when the user's mouse enters the image area, displays the same image, but larger using Tim Heuer's FloatableWindow, http://timheuer.com/blog/archive/2009/07/08/silverlight-floatablewindow-updated-with-resizing-capabilities.aspx

The problem I'm having is, when I try to set the position of the FloatableWindow so that the FloatableWindow is near my PhotoComponentForDataGrid control, no matter what values I use, the Window remains centered within my main Grid.

My PhotoComponentForDataGrid control has a Dependency Property named PopUpTarget which is a reference to LayoutRoot. That way when I create the FloatableWindow, I can specify the 'ParentLayoutRoot' property.

The code below is what I'm using to display my PopUp, except the X, and Y, refuse to change:

private void imgThumb_MouseEnter(object sender, MouseEventArgs e)         {             if (!this.displayingPopup)             {                 imgThumb.MouseEnter -= imgThumb_MouseEnter;                 imgThumb.MouseLeave += imgThumb_MouseLeave;                  GeneralTransform gt = imgThumb.TransformToVisual(Application.Current.RootVisual as UIElement);                 Point pt = gt.Transform(new Point(0, 0));                  try                 {                     this.popup.ParentLayoutRoot = this.PopupTarget;                     this.popup.Show(pt.X, pt.Y);                 }                 catch (Exception excep)                 {                      // Do nothing. Mouse was moved too fast.                 }                  this.displayingPopup = true;             }         } 

Thanks in advance for any help or suggestions.

Answers & Comments...




ColorAnimation doesn't do anything

ColorAnimation doesn't do anything

I'm trying to integrate a little colorApplication to a little "game" I did in silverlight.

I'm kinda noob with C# so I just searched on the net and I found something which explain how to do a colorApplication.

Here, I just want to change my background color from orange to blue and then use the autoreverse to come back to orange.

Here is my XAML

<Grid x:Name="LayoutRoot" Background="Orange">     <Grid.Resources>         <Storyboard x:Name="colorStoryboard">             <ColorAnimation BeginTime="00:00:00" AutoReverse="True"                             Storyboard.TargetName="LayoutRoot"                             Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)"                              Duration="00:00:02" From="Orange" To="Blue" />         </Storyboard>     </Grid.Resources>      <sdk:Label Height="16" HorizontalAlignment="Left" Margin="162,12,0,0"                 Name="label1" VerticalAlignment="Top" Width="84"                 Content="Vrai ou Faux ?" />     <Button Content="Vrai" Height="23" HorizontalAlignment="Left" Margin="59,61,0,0"             Name="buttonVrai" VerticalAlignment="Top" Width="75"               Click="buttonVrai_Click" />     <Button Content="Faux" Height="23" HorizontalAlignment="Left" Margin="267,61,0,0"             Name="buttonFaux" VerticalAlignment="Top" Width="75"              Click="buttonFaux_Click" />     <sdk:Label Height="20" HorizontalAlignment="Left" Margin="59,184,0,0"                 Name="label2" VerticalAlignment="Top" Width="60" Content="Score" />     <sdk:Label Height="20" HorizontalAlignment="Left" Margin="322,184,0,0"                 Name="labelScore" VerticalAlignment="Top" Width="20" Content="0" />     <Button Content="Redémarrer" Height="23" HorizontalAlignment="Left"              Margin="162,265,0,0" Name="buttonRedemarrer" VerticalAlignment="Top"              Width="84" Click="buttonRedemarrer_Click" /> </Grid> 

I just followed the tutorial but it doesn't work. My background color doesn't change. Did I forgot something ? Thanks for your help guys...

Answers & Comments...

Answer: 1

The problem is probably that nothing is triggering the animation. If I trigger the animation on, say, Window.Loaded, the animation works fine:

<Grid x:Name="LayoutRoot"       Background="Orange">   <Grid.Triggers>     <EventTrigger RoutedEvent="Window.Loaded">       <BeginStoryboard>         <Storyboard x:Name="colorStoryboard">           <ColorAnimation BeginTime="00:00:00"                           AutoReverse="True"                           Storyboard.TargetName="LayoutRoot"                           Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)"                           Duration="00:00:02"                           From="Orange"                           To="Blue" />         </Storyboard>       </BeginStoryboard>     </EventTrigger>   </Grid.Triggers>   <!-- ETC --> </Grid> 

You'll need to trigger the animation somehow -- perhaps on a button click or another routed event.

by : Dochttp://stackoverflow.com/users/84873

Answer: 2

I thought that I didn't have to write a method or something like that to start the animation. I thought that set the BeginTime = "00:00:00" will implicitly start the animation. I can compile and run this code.

So now, my "new question" is : How can I auto-start the animation ?

by : Hitohttp://stackoverflow.com/users/1840498