Tabindex in Tabcontrol in Silverlight
I have a tabcontrol and a simple buttoun in my usercontrol in silverlight.
In tabcontrol I have 2 tab items and and each tabitem conatin other 3 textbox and a button.
I have set tabindex property to all textbox and button in tabitems.
I have set tebindx property of btncancel to 5 which is outside tabcontrol. But it is not working.
My question is how can I access btncancel after btnsumit uysing tab?
<sdk:TabControl Height="250" HorizontalAlignment="Left" Margin="0,10,0,0" Name="tabControl1" VerticalAlignment="Top" Width="500">
<sdk:TabItem Header="tabItem1" Name="tabItem1" IsTabStop="True" TabNavigation="Once">
<Grid >
<TextBox Height="23" TabIndex="3" Margin="121,90,267,50" Name="txtname" Width="100" />
<TextBox Height="23" TabIndex="2" Margin="121,47,267,92" Name="txtmail" Width="100" />
<TextBox Height="23" TabIndex="1" Margin="121,6,267,133" Name="txtph" Width="100" />
<Button Height="23" TabIndex="4" Content="Submit" Width="50" Margin="150,118,288,20" Click="Btnsubmit_Click" />
</Grid>
</sdk:TabItem>
<sdk:TabItem Header="tabItem2" Name="tabItem2">
<Grid >
<TextBox Height="23" TabIndex="8" Margin="121,90,267,50" Name="txtcompny" Width="100" />
<TextBox Height="23" TabIndex="7" Margin="121,47,267,92" Name="txtroll" Width="100" />
<TextBox Height="23" TabIndex="6" Margin="121,6,267,133" Name="txtpost" Width="100" />
<Button Height="23" TabIndex="9" Content="Submit" Width="50" Margin="150,118,288,20" Click="Btnsubmit_Click" />
</Grid>
</sdk:TabItem>
</sdk:TabControl>
<Button Height="23" Content="Cancel" Width="70" TabIndex="5" Margin="576,260,67,70" Click="Btncancel_Click" />
No Answer and comments so far
WP7 , Silverlight Media Framework | Volume Control
Can any one point out as to how to use the SMF VOLUME CONTROL in Windows Phone 7 ?
No Answer and comments so far
Working with Lightswitch, Silverlight & costum controls
I am very new to Silverlight & Lightswitch.
I have a screen with some data. Inside the screen i have two custom
controls (on the left and right side). What I need to do is the following:
Bind some data from a database to some Controls in the first Custom control.
(fill a list, combobox etc, not so much the problem) The user then can select an entry in the list, press
a button -> the second CustomControl should now be set to visible; request some
data from the DB, based on the selection and dynamicly create and show a Chart.
So I now how to build the chart, build the Controls. But how can I access the Data
from the screen through Code and access another CustomControl from within the first CustomControl?
Program language is C#.
Thank you.
Answers & Comments...
Does this link help?
by: Answer by Yann Duran for Working with Lightswitch, Silverlight & costum controls
Custom control using WCF breaks VS2010 designer view
I've designed a custom control for a Silverlight website. When I run the debugger, or release it and pull it up over http, the control works perfectly. In the designer view for the control itself, it displays fine as well.
The problem comes when I add the control to the MainPage.xaml app as a control. The designer breaks saying: And Unhandled exception has occurred. System.NullReferenceException
Object reference not set to an instance of an object.
The control pulls its data from a WCF service while it runs its Loaded() event. The WCF service is located on the remote IIS server, not localhost.
I imagine the control is breaking because it can't pull data from the service in designer-view. Is there any way around this problem? Thanks in advance.
Answers & Comments...
You can use the DesignerProperties.IsInDesignTool property. This property has the value true
if your code is running in a designer tool such as the VS designer or Expression Blend, and false
otherwise.
In your Loaded
event handler, you can read the value of this property and only call your WCF service if the value of this property is false
.
by: Answer by Luke Woodward for Custom control using WCF breaks VS2010 designer view
Aside from what @Luke has said, you should actually fix the core of the problem: your data-loading code THROWS when it fails to load. Maybe just handle the error gracefully and CATCH the error and return empty data? Usually this is better for user experience to show nothing (or show a message) than to show a crash.. Your contorl will now crash also in the real release mode - i.e. if the data connection fails.
The IsInDesignTool property is stil very handy: once you fail to load the data, before you return empty set of data, check if the IsInDesignTool is true (as Luke said) - if it is, return an hardcoded example set of data. This way, when the contorl is unable to load and when it detects VisualStudio or Blend it will show some testing data and it will show up as filled with contents in the design view.
by: Answer by quetzalcoatl for Custom control using WCF breaks VS2010 designer view
Windows Phone 7 and WCF Video Service
I'm trying to implement a service that will allow users to watch and upload videos to a WCF service from a windows phone 7 client (something like youtube). Now, I have the basic implementation of the service which sends video files (.wmv) to a client which has a MediaElement implementation of the Silverlight framework (has some differences from .NET implementation of the same class). Now, whenever I try to play the video locally on the client I get a SecurityException was unhandled error. When I try to encapsulate the service call in a try/catch block the application just hangs there.
Here's the code:
Server-side:
class TransferService: ITransferService
{
public FileStream DownloadFile(string filename)
{
//string FilePath = Path.Combine(@"c:\Uploads", filename);
FileStream result = File.Open(@"C:\Uploads\test.wmv", FileMode.Open, FileAccess.Read, FileShare.Read);
return result;
}
public void UploadFile(FileStream request)
{
//Not yet implemented
}
}
Server-side(web.config):
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime maxRequestLength="100240" />
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="basicHttp" allowCookies="true"
maxReceivedMessageSize="20000000"
maxBufferSize="20000000"
maxBufferPoolSize="20000000" transferMode="Buffered">
<readerQuotas maxDepth="200000000"
maxArrayLength="200000000"
maxStringContentLength="200000000"
maxBytesPerRead="200000000"
maxNameTableCharCount="200000000"/>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="VideoService.TransferService" behaviorConfiguration="VideoServiceTypeBehaviors" >
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
<endpoint contract="VideoService.ITransferService" binding="basicHttpBinding" address="basic" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="VideoServiceTypeBehaviors" >
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Client-side:
public partial class Page1 : PhoneApplicationPage
{
TransferServiceClient sc;
public Page1()
{
InitializeComponent();
sc = new TransferServiceClient();
this.Loaded += new RoutedEventHandler(Page_Loaded);
}
void Page_Loaded(object sender, RoutedEventArgs e)
{
sc.DownloadFileCompleted += new EventHandler<DownloadFileCompletedEventArgs>(sc_DownloadFileCompleted); //I think the problem is here
sc.DownloadFileAsync("test.wmv");
}
void sc_DownloadFileCompleted(object sender, DownloadFileCompletedEventArgs e)
{
myMediaElement.SetSource(e.Result);
myMediaElement.Play();
}
Client-side(ServiceReference.clientconfig):
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ITransferService" closeTimeout="00:02:00"
openTimeout="00:02:00" receiveTimeout="00:10:00" sendTimeout="00:02:00"
maxBufferSize="210005536" maxReceivedMessageSize="210005536"
textEncoding="utf-8">
<security mode="None" />
</binding>
<binding name="BasicHttpBinding_ITransferService1" maxBufferSize="2147483647"
maxReceivedMessageSize="2147483647">
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:53163/TransferService.svc/basic"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ITransferService1"
contract="TransferService.ITransferService" name="BasicHttpBinding_ITransferService" />
</client>
</system.serviceModel>
</configuration>
Any help or insight would be much appreciated. Thanks
Answers & Comments...
first i would try to use this code block correctly:
sc.DownloadFileCompleted += new EventHandler(sc_DownloadFileCompleted); //I think the problem is here
sc.DownloadFileAsync("test.wmv");
myMediaElement.Play();
you fire up an asynchronous download-process and you are attaching a "download complete"-callback to it...
why do you call "myMediaElement.Play" synchronously AFTER the asynchronous invoke?
at this time, the file isn't downloaded yet and maybe the mediaelement fires the exception, because the file is locked (because of the download).
you have to call "myMediaElement" in the "sc_DownloadFileCompleted"-Handler AFTER the asynchronous download process finished....
please check if this was the prob...
by: Answer by TheHe for Windows Phone 7 and WCF Video Service
Silverlight - Highlighting a specific cell during drag and drop in telerik radgridview
I have the following scenario.
On my UI, I have ListBox and RadGridView. User can drag from listbox and drop onto RadGridView
Listbox has both Accounts and Indexes in it and my RadGridView has columns as below
<telerik:RadGridView.Columns>
<telerik:GridViewColumn UniqueName="Account"
Background="Transparent"
Header="">
<telerik:GridViewColumn.CellTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding CurrentUniverse1.UniverseID}"/>
<TextBlock x:Name="UniverseName1Text" TextTrimming="WordEllipsis"
Text="{Binding CurrentUniverse1.UniverseName, Mode=TwoWay}"
Grid.Column="1"/>
</Grid>
</DataTemplate>
</telerik:GridViewColumn.CellTemplate>
</telerik:GridViewColumn>
<telerik:GridViewColumn UniqueName="Index"
Header=""
HeaderTextAlignment="Left"
Width=".399*"
MinWidth="129">
<telerik:GridViewColumn.CellTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock TextTrimming="WordEllipsis" Text="Index Not Supported"
Foreground="Orange"
Grid.ColumnSpan="2"
Visibility="{Binding CurrentIndexNotSupported, Converter={StaticResource VisibilityConverter}}" />
<TextBlock Text="{Binding CurrentUniverse2.UniverseID}"
Visibility="{Binding CurrentUniverse2.IsValid, Converter={StaticResource VisibilityConverter}}" />
<TextBlock x:Name="UniverseName2Text" TextTrimming="WordEllipsis" Text="{Binding CurrentUniverse2.UniverseName, Mode=TwoWay}"
Grid.Column="1"
Visibility="{Binding CurrentUniverse2.IsValid, Converter={StaticResource VisibilityConverter}}" />
</Grid>
</DataTemplate>
</telerik:GridViewColumn.CellTemplate>
</telerik:GridViewColumn>
</telerik:RadGridView.Columns>
I am able to now detect that an object is being dropped into a specific cell and whether drop is possible or not in a particular cell.
This is what I need to do
If drop is possible I need to highlight only the valid cell ( name textblock) and all other remaining cells including cells previously mouse overed above and below current cell must be unhighlighted.
Any help is greatly appreciated.
No Answer and comments so far
Silverlight: converting a byte[] to a BitmapImage ends in "catastrophic failure"
I am trying to modify a BitmapImage in Silverlight, but happen to run into a "catastrophic failure"!
First I load an image and add it to the LayoutRoot.
BitmapImage source = new BitmapImage(new Uri("image.jpg", UriKind.Relative));
Image imageElement = new Image();
imageElement.Name = "imageElement";
imageElement.Source = source;
imageElement.Stretch = Stretch.None;
LayoutRoot.Children.Add(imageElement);
This works fine and the image is shown on the screen correctly.
Next I want to modify the image (for example: after a button click).
In the button click method, first, I get the image out of the LayoutRoot and then modify it by using a WriteableBitmap class:
Image imageElement = (Image) LayoutRoot.Children[1];
WriteableBitmap writeableBitmap = new WriteableBitmap(imageElement, null);
writeableBitmap.ForEach((x,y,color) => Color.FromArgb((byte)(color.A / 2), color.R, color.G, color.B));
Next i save it into a byte array buffer using the given method:
byte[] buffer = writeableBitmap.ToByteArray();
This also looks good. The buffer shows all ARGB values and even the alpha values are half the usual value with 127, just as it should be!
In the next step I want to load the modified data back into BitmapImage and finally into an Image and add it again into the LayoutRoot:
BitmapImage modifiedSource = null;
try
{
using (MemoryStream stream = new MemoryStream(buffer))
{
stream.Seek(0, SeekOrigin.Begin);
BitmapImage b = new BitmapImage();
b.SetSource(stream);
modifiedSource = b;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I found this code piece here: byte[] to BitmapImage in silverlight
As a last step I would simply create an Image again and add it to the LayoutRoot (just as I did it in the beginning:
Image modifiedImageElement = new Image();
modifiedImageElement.Name = "newImageElement";
modifiedImageElement.Source = modifiedSource;
modifiedImageElement.Stretch = Stretch.None;
LayoutRoot.Children.Add(modifiedImageElement);
But the final part is never reached because there occurs a "catastrophic failure" on the
b.SetSource(stream);
line, saying:
{System.Exception: Catastrophic failure (Ausnahme von HRESULT: 0x8000FFFF (E_UNEXPECTED))
at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
at MS.Internal.XcpImports.BitmapSource_SetSource(BitmapSource bitmapSource, CValue& byteStream)
at System.Windows.Media.Imaging.BitmapSource.SetSourceInternal(Stream streamSource)
at System.Windows.Media.Imaging.BitmapImage.SetSourceInternal(Stream streamSource)
at System.Windows.Media.Imaging.BitmapSource.SetSource(Stream streamSource)
at SilverlightApplication1.MainPage.button1_Click(Object sender, RoutedEventArgs e)}
I don't know what went wrong. I found an article here
Silverlight: BitmapImage from stream throws exception (Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))), which happens to have the same exception, but as I read it, it seemed that he had this problem only when he was uploading a lot of images, and it worked fine for him for a little amount of images. So I am still clueless on how to solve this issue?
Do you guys maybe have any advice? Thanks!
Answers & Comments...
I ran into this exception before:
- When passing an unsupported image type to silverlight: BMP, ... Only JPG and PNG are supported. See the MSDN
- When passing incorrect data (not all of the stream or incorrectly formatted)
by: Answer by Erno for Silverlight: converting a byte[] to a BitmapImage ends in "catastrophic failure"
I think that you are getting an crash because the byte array that you reconstruct your image from is a 'raw' array of ARGB values, whereas the Source
property is expecting a byte-stream that makes up a valid PNG or JPG file. Raw ARGB data is highly unlikely to be a valid PNG or JPG file as it will almost certainly not contain the valid header required by each of these formats.
I couldn't reproduce a crash; instead, the BitmapImage
s that were being created when I ran your code had PixelWidth
and PixelHeight
both zero. That could well be because I'm using a different image to the one you're using. Either way, crash or no crash, it's not desired behaviour.
If you want to load the modified data back into an Image
, you don't need to create a byte
array. Just create an Image
from the WriteableBitmap
object:
Image modifiedImage = new Image()
{
Source = writeableBitmap,
Stretch = Stretch.None
};
I used this to add a copy of the image below the original one. The modified image had a 'washed-out' look compared to the original, which is exactly what I would expect if I halve all of the alpha-channel values.
If you really do need to convert a byte array back to an image, you can use the FromByteArray
extension method within WriteableBitmapEx. You can then create an Image
as described above.
by: Answer by Luke Woodward for Silverlight: converting a byte[] to a BitmapImage ends in "catastrophic failure"
silverlight 5 and webservices
I have a Silverlight 5 app that runs in a browser. It's been working for over a year. When I look at the service referrence, it shows the address, access level is public, Data Type collection type is system.collections.generic.list and dictionary collection type is system.collections.generic.dictionary.
The Silverlight app runs and will use the webservice.. that is until I modify the _DoWorkCompleted private sub that is called for the webservice call. As soon as I modify that sub (something as simple as Dim x as string=string.empty), the webservice doesn't work anymore. I get an error about it not being the same doc type. When I go back to the webservice, all the information looks the same. I tried to delete the service reference and recreate it and again it tells me that the doc types are different. The webservice that I'm trying to connect to is on a public webserver.. nothing has changed on that end.. only thing changes is any code in the _DoWorkerCompleted.
What is going on and what am I doing wrong?
Edited
I need to modify the code in the _DoWorkCompleted event arg that takes place when the webservice call is complete. This is the sub that if i modify it, it no longer wants to connect to the webservice.
Here is the code that creates the call...
Dim client As New wsTypingTest.TypingTestClient
AddHandler client.DoWorkCompleted, AddressOf client_DoWorkCompleted
Then i have the
Private Sub client_DoWorkCompleted(ByVal sender As Object, e As wsTypingTest.DoWorkCompletedEventArgs)
It is here.. on the DoWorkComplete that i need to update code. So i'm not modifying the webservice referrence, i'm modifying some code but this modification seems to be what makes the webservice referrence no longer work.
Does that help at all
No Answer and comments so far
How to generate web service reference without INotifyPropertyChanged?
I am using Fody in a SilverLight project to auto-generate property dependencies. However, it doesn't work if setters already contain a RaisePropertyChanged
method call.
A workaround could be to generate web service reference code without INotifyPropertyChanged
and instead implement it in a partial method.
How can I generate web service reference code without INotifyPropertyChanged
?
I have a WCF service, let's call it MaterialService.svc. It looks something like this:
[ServiceContract]
public interface IMaterialService
{
[OperationContract]
Material GetMaterial(int id);
}
[DataContract]
public class Material
{
[DataMember]
public int ID { get; set; }
[DataMember]
public string Name { get; set; }
}
When I add the service as a Service Reference and generate client code, every class is set to implement INotifyPropertyChanged
:
public partial class Material : object, System.ComponentModel.INotifyPropertyChanged {
private int IDField;
private string NameField;
[System.Runtime.Serialization.DataMemberAttribute()]
public int ID {
get {
return this.IDField;
}
set {
if ((this.IDField.Equals(value) != true)) {
this.IDField = value;
this.RaisePropertyChanged("ID");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public System.Nullable<string> Name {
get {
return this.NameField;
}
set {
if ((this.NameField.Equals(value) != true)) {
this.NameField = value;
this.RaisePropertyChanged("Name");
}
}
}
}
How can I generate client code that doesn't implement INotifyPropertyChanged
?
Answers & Comments...
After you add the service reference, open the file Reference.svcmap
under the service reference (you may need to enable the "show all files" option in the "Project" menu). There find the <EnableDataBinding>
element, and change the value to false. That will remove the INotifyPropertyChanged
from the generated data contracts.
by: Answer by carlosfigueira for How to generate web service reference without INotifyPropertyChanged?
URI Relative Resource in Silverlight
I have a file within my Silverlight project, within a folder.
My project is called Display
Solution Explorer structure:
/Resources
cube.obj
My code is:
Uri u = new Uri(@"Display;component/Resources/cube.obj", UriKind.Relative);
Stream stream = Application.GetResourceStream(u).Stream;
StreamReader reader = new StreamReader(stream);
cube.obj has the build action set to Content if that's relevant.
I'm getting a NullReferenceException that comes up in the JavaScript and doesn't give me much help in determining the issue.
Any ideas?
Thanks!
Answers & Comments...
You can try enabling Silverlight debugging on your project, that way you'll be able to step through the SL code, Go to your project properties then on Debug go all the way down and enable the Silverlight debugger, then run your project and your SL breakpoints will be hit.
by: Answer by Xtian Macedo for URI Relative Resource in Silverlight
Set the file's build action to "Resource", not "Content".
The NullReferenceException
is coming from the Application.GetResourceStream(u).Stream
. GetResourceStream
returns null
because the file isn't available because it's the wrong build action. Accessing Stream
on the null reference then fires the exception.
EDIT: Also make sure that your Uri "Display;" portion is the proper name for your assembly that is housing the obj file.
Just to clarify. Use Content
when you want the file to be placed in the XAP file alongside the various assemblies. You can then access the file without the prefix "Display;component" path. (NOTE: off the top of my head, I don't think I've loaded a "Content" resource in this way with Application.GetResourceStream
specifically so I don't know for sure if it will work, but I suspect it would). I also suspect this could cause issues if you have the same file name located in different paths/projects. This method is especially useful if you want to share the same resource/file with multiple projects/assemblies.
Using Resource
will keep the file embedded within the assembly DLL. With this, you need to specify the assembly to look in (hence the "Display;component" prefix). But this is necessary if you're packaging pre-compiled assemblies for use in your Silverlight project or want to manage the files differently.
by: Answer by Chris Sinclair for URI Relative Resource in Silverlight
Sharing classes between Server and Client projects in Silverlight
Problem: Class B is a subclass of Class A. RIA service returns a list of object Bs. Class A and B are both necessarily defined on the server-side. They serialize fine, and I can use them in the primary client project.
I have two other libraries, organized as client libraries. One is for custom controls, and the other is for classes that are shared between custom controls and the actual client project.
I need Class A to be accessible from the Classes library clientside (so that the custom controls can get to it). How can I do this?
I've done this:
http://msdn.microsoft.com/en-us/library/ee707369%28v=vs.91%29.aspx
but the *.shared.cs convention doesn't give libraries other than the actual Client library access to Class A. The second method (Add as Link) does do what I want it to do, except that updating ClassA.cs in the server project doesn't cause the Client version to update, making it necessary to update both class files each time they're changed, which is unacceptable.
edit: Add as Link worked great after trying again several times.
Answers & Comments...
In Visual Studio (2010, at least — dunno exactly whe the feature was added), you can add an existing item to a project as a 'link', meaning the source file is shared between projects. Only one version of the source file exists.
- Right-click on your project.
- Click on 'Add..Existing Item'.
- Find the source file of choice and select it.
- The 'Add' Button is a drop-down. Click the drop-down icon in the button.
- Click on 'Add As Link'.
Easy!
Now any change to the share source file is reflected on both places. The drawback, of course, is that the developer gets no indication that changes to the shared source file might have wider ramifications than she might realize.
Another option would be to create a hard link
so two file names reference the same file ('inode' in Unix terms). On the command line, just chant the magic incantation:
fsutil hardlink create <new-filename> <existing-filename>
something like:
fsutil hardlink create c:\foo\bar\some-project\bazbat.cs c:\foo\bar\another-project\bazbat.cs
The restriction is that both names have to be on the same volume.
This has the possibility, of course, confusing your source control system. I'm willing to bet that TFS hasn't consider the possibility that a filesystem isn't necessarily a tree structure and that the same file might exist in multiple directories.
Hard-linked files may be deleted in any order: the file ceases to exist when the last link to gets removed.
The 3rd option, of course, and likely the "best-practice" — hate that term! — is to factor out the shard classes into an independent assembly that gets deployed to both the client and server. If want to limit the number of assemblies floating around, post-build, you can use ilmerge
to merge assemblies:
- http://www.codeproject.com/Articles/9364/Merging-NET-assemblies-using-ILMerge
- Merge two assemblies at runtime - C#
- How to: Merge multiple assemblies into one
Come to think of it, there's also no reason you can't embed the shared assemblies as embedded resources that get loaded on demand (or even at startup). This might even be cleaner than using ilmerge
. Here's how to do that:
by: Answer by Nicholas Carey for Sharing classes between Server and Client projects in Silverlight
What is the downside of using Monocross for WPF and Silverlight?
I am thinking...
Is Monocross a good option to use so
we could port to the IPad if we were
forced to?
Answers & Comments...
Monocross very nicely follows the kind of pattern enforced by monotouch and monodroid, with a separate presentation layer and application code
According to MonoCross' own wiki, their intent seems to be to fully support these platforms, and windows mobile in the future.
At the time of this writing however, (monoCross 0.3.2) all CRUD related operations are either in development, or not yet started, so there is a good chance you will still run into trouble during your own application development.
The biggest hamper (in my opinion) in porting applications to monotouch, is the lack of databinding support, and monocross has most of those implemented at its current release, but not all of them.
by: Answer by Timothy Groote for What is the downside of using Monocross for WPF and Silverlight?
You are correct that we intend to support the platforms mentioned above, but we will support Windows Phone 7 moving forward, and have depricated earlier versions of Windows Mobile.
Since the last post on this thread, we have added the concept of view perspectives to help with CRUD operations. View perspectives are used to enable multiple views for each of your model types, and are represented as a string passed from your controller to the view container to indicate the perspective you wish to provide the user. This makes it easier to construct and render views for CRUD, or any other, operations.
We are also currently writing a book for Wrox Press that will cover cross-platform development with MonoCross in much more detail. The book will be available in early 2012.
Scott Olson
MonoCross Project
by: Answer by Scott Olson for What is the downside of using Monocross for WPF and Silverlight?
Windows Phone 7 dialog input box
I have been surfing the web and MSDN for the equivalent java method JOptionPane.showInputDialog() for Windows Phone 7 but cannot find one. I simply want an input dialog box to appear if the user has achieved a high score, so that the user may enter their name.
Thanks!
CodeKingPlusPlus
Answers & Comments...
Hey you might want to check out the Coding4Fun toolkit for Windows Phone 7. Included in the toolkit is a InputPrompt control, which is exactly what you need in this case. It's also free.
If you need help getting started check out this article which contains an overview on all the controls included in the toolkit.
by: Answer by loyalpenguin for Windows Phone 7 dialog input box
I need help converting a c# anonymous method to vb.net
provider.OptionsSet += delegate
{
provider.FinishedLoading();
};
Answers & Comments...
provider.OptionsSet += Function() Do
provider.FinishedLoading()
End Function
This is taken from http://www.developerfusion.com/tools/convert/csharp-to-vb/, so I haven't tested it. It might be more helpful if you were able to provide more context. What is this being used for?
by: Answer by user656137 for I need help converting a c# anonymous method to vb.net
Nice demonstration how converters get this dramatically wrong, they have for a long time. The += operator isn't VB.NET syntax, AddHandler is required to subscribe events. Where the Do comes from is anybody's guess. The lambda can't be a Function, except for the very rare cases where the delegate type returns a value. Three bugs in one line, you don't stand a chance. You need VS2010 to write a Sub lambda. Like this:
Module Module1
Sub Main()
Dim obj As New Test
AddHandler obj.example, Sub(sender As Object, e As EventArgs)
'' etc...
End Sub
End Sub
End Module
Class Test
Public Event example As EventHandler
End Class
For earlier versions, you'll need a little non-anonymous helper method. Like this:
AddHandler obj.example, AddressOf helper
...
Sub helper(ByVal sender As Object, ByVal e As EventArgs)
'' etc..
End Sub
Human 1, machine 0.
by: Answer by Hans Passant for I need help converting a c# anonymous method to vb.net
Pete Brown has also has an example with inline sub:
http://10rem.net/blog/2010/04/16/tip-anonymous-event-handlers-in-vbnet
by: Answer by user656733 for I need help converting a c# anonymous method to vb.net
Is silverlight better or wpf for graphics, 3d?
I learning wpf/silverlight currently. I want to ask which one of them is better for graphics, 3d, ... ?
Answers & Comments...
i would sugest wpf in WPF you have all the Viewport sutff where you can do real 3d, In Silverlight you have PlaneTransformation but it is not close to real 3d
WPF 3d tutorial
by: Answer by kalvis for Is silverlight better or wpf for graphics, 3d?
People say "Silverlight is a subset of WPF" -- what they mean is that the programming model is the same (code + XAML), but Silverlight generally has a smaller API / less features than WPF.
I think a good example would be creating a reflection. In WPF you could use a VisualBrush, but Silverlight doesn't support it. Still you can create the same effect by creating a 2nd transformed element. You can pretty much acomplish the same task in both, although for Silverlight you may have to do some processing tasks on the server.
The choice of platform depends more on whether you want to target web deployment or not and possibly performance.
3D isn't implemented in Silverlight 4 (though there are 3D libraries out there). 3D will be part of Silverlight 5. (Beta coming soon, probably at MIX, and to be released this year.)
by: Answer by foson for Is silverlight better or wpf for graphics, 3d?
The deal is more deeper as I understand.
We will speak about WPF and Silverlight 5. There are two mechanisms of 3D Graphics. Before WPF it was a single one - so named pipeline graphics. It includes DirectX, OpenGL and multiple derivative and independent realizations (XNA from DirectX, for example). Although WPF is based internally on DirectX it realizes absolutely different conception of smart graphics. What is the difference for a pipeline and smart mechanism? The pipeline mechanism consists of infinity loop of drawing objects - typically primitives like vertex, triangles. It works by initialization of so named infinity loop by calling something like OnDraw/ReDraw method.
WPF does not use ReDraw and does not draw anything until we directly detect it. It is single correct way to use it. Therefore WPF allows to draw UI Elements with internal support of hundreds events, methods and full freedom of management (like usual WPF control - textbox, for example). (Helix 3D is good library for easy way to WPF 3D) And vice versa, Silverlight 5 has some API of XNA graphics - pipeline way without UIElement support for 3D objects.
There is Kit3D library http://kit3d.codeplex.com/ as very good idea for smart graphic realization for Silverlight and there are many other realizations (Balder, Babylon) on pipeline mechanism. If you are interesting to code an application like web 3D Game - choose pipeline Silverlight 3D graphics, if you are interesting about smart 3D applications - choose WPF 3D.
Author of WPF 3D CAE system TIMO Structural.
by: Answer by Siarhei Arlou for Is silverlight better or wpf for graphics, 3d?
Timer isn't stoping then restarting after executing method?
I have been working on this project for the past 3 days till 3-4 am and I believe I know where its messing up (My comments are marking the calculation that I believe is the issue) but as for solving the calculation and if that would even fix the timer I am not sure. I have marked in the code where I believe is the problem but I would accept any opinion on what they believe may fix it or where it is messing up. If it is the one calculation in the (Check) Method then I am not sure what calculation would fix it. If it is something else that someone else see's that I do not please tell me. I have looked at several different options and none seem to work.
This project is meant to test a product, it is to send a message every (x) (sec, mins, hours, days) for (y) (sec, mins, hours, days). () being the users input. After the (x) is elapsed then its time to, stop timer, send method, then restart timer. (ex. (user enters) Send 1 message every (30) sec. for (2) min.) There should be 4 rounds of messages sent but it is ending early due to the timer not stopping. I have an idea of where it is messing up but a little guidance and other opinions would be helpful.
<code>
private void TimeKeeperTimerElapsed(object sender, ElapsedEventArgs e)
{
if (flag == true && EndTime > DateTime.Now)
{
_timeKeeper.Stop();
Check();
_timeKeeper.Start();
}
if (flag == true && EndTime < DateTime.Now)
{
TestCompleted();
}
}
bool flag = true;
/// <summary>
/// Method "Check" checks to see it it is time to send a message, time elapsed and time left
/// </summary>
private void Check()
{
if (SelectedPerfTest != null && flag == true)
{
//Est. Date Time Now
var ct = DateTime.Now;
//Time Elapsed Output form now (counts up)
var te = ct.Subtract(StartTime);
TimeElapsed = string.Format("{0} days, {1} hours, {2} minutes, {3} seconds", te.Days, te.Hours,
te.Minutes,
te.Seconds);
// Time Left from now output (counts down)
var tl = EndTime.Subtract(ct);
TimeLeft = string.Format("{0} days, {1} hours, {2} minutes, {3} seconds", tl.Days, tl.Hours,
tl.Minutes,
tl.Seconds);
//Calculate the time til the next message (counting down)
var nnm = CalculateNextMessage(DateTime.Now);
NextNewMessage = string.Format("{0} days, {1} hours, {2} minutes, {3} seconds", nnm.Days, nnm.Hours,
nnm.Minutes,
nnm.Seconds);
//I feel like the Problem is here this equation will call the method to send message but the timer continues to tick... I
//need it to stop when the time elapsed that the user put in ex. user enter (send 1 message every (20 seconds)
//for (2 hours)) it needs to stop in 20 sec. to send message then check if its time to end (if 2 hours are up).
//If not send message in another 20 sec.
if (DateTime.Now.Add(CalculateNextMessage(DateTime.Now)) < DateTime.Now && EndTime > DateTime.Now )
if (ct.Subtract(StartTime) == LastExecuted.AddMilliseconds(ts).Subtract(ct))
{
if (CurrentProduct == ("Babyware"))
{
if (SelectedPerfTest == ("Short Test"))
{
ExecuteShortTest();
}
if (SelectedPerfTest == ("Long Test"))
{
ExecuteLongTest();
}
if (SelectedPerfTest == ("UCN"))
{
ExecuteUCNTest();
}
}
else
if (CurrentProduct == ("Antware"))
{
if (SelectedPerfTest == ("Short Test"))
{
ExecuteGAShortTest();
}
if (SelectedPerfTest == ("Long Test"))
{
ExecuteGALongTest();
}
}
}
}
}
#endregion
</code>
Answers & Comments...
Before subtracting StartTime and ct make sure it is it the same fortmat as
string.Format("{0} days, {1} hours, {2} minutes, {3} seconds", te.Days, te.Hours,
te.Minutes,
te.Seconds);
by: Answer by Clinton Ward for Timer isn't stoping then restarting after executing method?
Why not do something like this in the Timer_Tick?
If ticks = userTimeInterval Then
SendMessage()
Check()
ticks = 0
Else
ticks += 1
End If
Check the ticks (seconds) against what the user puts in to see if it is time to send the message, if it is then send it. Then check to see if it is time to stop sending the messages.
by: Answer by Barry Franklin for Timer isn't stoping then restarting after executing method?
Databound listbox - wrong datacontext present in item's "Loaded" event?
I'm writing what should have been a simple WP75 app.
Main page contains a Pivot, within which is a single ListBox and ItemTemplate. The ItemTemplate contains a Grid, which contains a variety of TextBlock and Rectangle objects.
This is all declared in XAML, and the ListBox itemsource is bound to an ObservableCollection e.g. {Binding SomeList}
At runtime I need to change the state (visibility, fill color) of some of the elements in each item's Grid, based on the data in some of the bound object fields.
To do this I'm catching the loaded event for the Grid within the listboxitem, and changing the visual state of the elements based on the DataContext values.
(See below for a summary of the XAML definitions)
The problem only occurs when I have a list long enough to cause some unloading/reloading of items (?) during scrolling.
The problem is that randomly it seems like the grid_loaded() event is called with either the wrong sender value, or the wrong DataContext value in the sending Grid.
The symptom is that elements in the listboxitem's Grid that are bound directly to a field of the list objects (like the textblock at end of XAML below) will always display the correct data.
However in the grid_loaded() callback (see below), the DataContext is the wrong Item ?!!
Assume I must be doing something stupid here, but I'm stumped. Again, it only happens when scrolling up and down in a longer list. It can affect one or many items.
Any help appreciated.
<controls:Pivot.ItemTemplate>
<DataTemplate>
<ListBox
x:Name="ItemListBox"
ItemsSource="{Binding ItemList}"
....
<ListBox.ItemTemplate>
<DataTemplate>
<Grid
Loaded="grid_Loaded"
....
<Rectangle> ...
<TextBlock Text="{Binding Name}" />
....
private void grid_Loaded(object sender, RoutedEventArgs e)
{
Grid grid = (Grid)sender;
Item item = (Item)grid.DataContext;
... item here is WRONG sometimes, and does not match the values in directly databound fields of the grid! ....
No Answer and comments so far
Unable to access new database fields after rebuilding RiaService
I have a solution that uses a RiaService project. I have been using it successfully for quite some time. On my last database change though, I came across a problem where any new fields are giving an error when I access them in my Silverlight project.
After a load operation I set my property to the first record returned:
Rights = loadOp.Entities.First();
At this point I am able to access all the old fields:
int _id = Rights.Id
string _name = Rights.Name
But when I try to access a newly added database field:
string _description = Right.Description
I get the following error:
- RIAServices.Web.Models.Rights' does not contain a definition for
'Description' and no extension method 'Description' accepting a first
argument of type 'RIAServices.Web.Models.Rights' could be
found (are you missing a using directive or an assembly reference?)
I don't get an error on the build, so it is seeing the correct metadata and recognizing that the DESCRIPTION field is valid. And it builds the RiaService just fine with the DESCRIPTION in the metadata. So I am at a loss as to why this happening. I have done this same thing hundreds of times as I build a project adding new tables and fields and I have never seen this before.
Answers & Comments...
I ended up just using a backup from about 3 weeks ago that was working correctly and manually updated the code up to the present. That seems to have done the trick, but without determining the actual cause of the problem.
by: Answer by user1588818 for Unable to access new database fields after rebuilding RiaService
How to call a methode asynchronous in Silverlight 4?
I'm developing a Silverlight app for SharePoint and want to get ListItems from a list. I know I need to query async to avoid blocking the ui thread. Normaly I use ExecuteQueryAsync but that won't work since i like to set the result as DataGrid source.
How can I call the GetItemsFromList methode async and set the result as DataGrid source without creating much code overhead? (lambda?)
SharePointHelper Class:
public static ListItemCollection GetItemsFromList(string name)
{
var context = ClientContext.Current;
var targetList = context.Web.Lists.GetByTitle("ListName");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>{0}</Value></Eq></Where></Query>RowLimit>4</RowLimit></View>",
name);
ListItemCollection collListItems = targetList.GetItems(camlQuery);
context.ExecuteQuery();
return collListItems;
}
UI Class:
private void SetDataGridItemSource()
{
dataGrid.Source = GetItemsFromList("name");
}
Answers & Comments...
Something like this?
public delegate void ItemsLoadedCallback(IEnumerable<object> Entities);
public static void GetItemsFromList(string name, ItemsLoadedCallback Callback)
{
// codesnip
// Do async thing, on return call:
if (Callback != null)
{
Callback(collListItems);
}
}
private void SetDataGridItemSource()
{
GetItemsFromList("name", (items) => dataGrid.Source = items);
}
by: Answer by Dan Wray for How to call a methode asynchronous in Silverlight 4?
I'm not familiar with the ClientContext class for SharePoint (or even SharePoint for that matter), but I do not see any async methods in the docs. If this call is going to be expensive, you can wrap the call in a BackgroundWorker. The BackgroundWorker would execute the query and you can return the results. You would not be able to assign the Source as you have described, but instead would need to set the Source when the worker completes.
private void SetDataGridItemSource()
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += WorkerOnDoWork;
worker.RunWorkerCompleted += WorkerOnRunWorkerCompleted;
worker.RunWorkerAsync("name");
}
private void WorkerOnDoWork(object sender, DoWorkEventArgs args)
{
if(args.Argument != null)
{
string name = args.Argument.ToString();
var context = ClientContext.Current;
var targetList = context.Web.Lists.GetByTitle("ListName");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>{0}</Value></Eq></Where></Query>RowLimit>4</RowLimit></View>",
name);
ListItemCollection collListItems = targetList.GetItems(camlQuery);
context.ExecuteQuery();
args.Result = collListItems;
}
}
private void WorkerOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs args)
{
dataGrid.Source = args.Result as ListItemCollection;
}
by: Answer by Shawn Kendrot for How to call a methode asynchronous in Silverlight 4?
Play an encrypted mp3 file
I am currently trying to play a encrypted .mp3 file. The way I am currently using is:
loading the encrypted file -> decrypting it -> save it to ISO -> play it with the backgroundaudioplayer
.
But this can take up to 10-15 seconds to start one .mp3 file. Is there any other way to do this faster ?
For example is there a way to play from a stream and somehow decrypt it while playing ?
And is there actually the need for encrypting the files on the IsolatedStorage ? Since nobody should be able to touch them anyways ?!
Answers & Comments...
Ok well since its been so long I would recommend "Buffering" its really easy, have your decrypt stream give you a decent sized buffer from the first 20 or so seconds of the file, that should take a few seconds max much faster than waiting for the whole file, then just simply feed the backgroundplayer using the decrypted buffer whilst the rest is still decrypting.
by: Answer by John Antony Daniel Nolan for Play an encrypted mp3 file
Setting the width of a Silverlight application based on screen size
On a silverlight 4.0 application I need to set the width of the main window to be the maximum possible width based on the size of the screen of user.
How can this be achieved?
No Answer and comments so far
Tiny WCF query times out for one SL client but not another
I have a WCF service which my SL app speaks to. I have an older version of the app and a newer version - I've deployed the new version onto the live server and it won't work (just sits there and eventually throws a timeout error)
I've put the original app back in place and put the new app along side it. I've run both and one works, the other doesn't. The debugger for the new app shows that the app is making a call to a few very simple web methods that query the backend DB and return a set of lookup values (in fact I've skipped over all but one of the calls out of curiosity and a single call that returns 3 rows from the DB still times out). I've queried the DB myself and the other app is also querying the same tables so I don't think the problem lies there as I get an immediate response. I've got no idea where to look now...
The strange thing is: occasionally the callback fires and I get a response, but most of the time it times out. This still takes a while though (10-15 seconds)
I've no idea why this has started happening, or why there is a difference between the two applications - both apps are using the same service references and the same app config settings. One works, one doesn't...
I'm starting to pull hair out!
Anyone had a similar issue?
No Answer and comments so far
Silverlight with AJAX
I'm wondering if any one tell me that if I want to use Silverlight with AJAX how will it be possible for me but remember that I'm a begginer so send me such document or code that will be helpful for me to understand.
Answers & Comments...
Assuming you are using Silverlight 2, the preferred way is to not use AJAX.
You use services with code-behind files that run on the client. Your services are asynchronous, and will likely return XML in some way or another, but you won't be doing much in the browser directly...
Might we call it ACAX? (Asynchronous C# And XML) ... I kid, I Kid...
Take a look at Scott Gu's tutorial for using Silverlight with services. It is really useful:
http://weblogs.asp.net/scottgu/pages/silverlight-2-end-to-end-tutorial-building-a-digg-search-client.aspx
by: Answer by Brian Genisio for Silverlight with AJAX
The idea of AJAX is that you can make server requests using Javascript and XML without having to reload the entire page. Silverlight 1 uses the same method of Javascript to get data from server based on user interactions. However, Silverlight 2 also allows you to make server calls using .NET code so it is no longer just AJAX. You write Silverlight code much like a desktop application that uses a web service so you really don't need to fully understand AJAX in order to work with Silverlight.
Here are a few links that discuss this distinction:
by: Answer by Bryant for Silverlight with AJAX
Programatically create Hyperlink Column in Silverlight DataGrid
I need to create a data grid which has various columns. One of the columns needs to be a hyperlink to a URL. For example i may have records of people in the grid and there name will link to a URL ging to the users file.
Is this done in silverlight using a programatically created hyperlink.
I did this in asp by doing a RowDataBind method, I need to do this in Silverlight-
protected void gvOrderData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Setup links
string OrderLink = "'http://crm1:5555/sfa/salesorder/edit.aspx?id={";
e.Row.Cells[0].Attributes.Add("onclick", "window.open(" + OrderLink + DataBinder.Eval(e.Row.DataItem, "SalesOrderID").ToString() + "}','tester','scrollbars=yes,resizable=yes');");
e.Row.Cells[0].Attributes.Add("onmouseover", "this.style.cursor='pointer'");
}
}
Answers & Comments...
Unfortunately you can't create a DataTemplate in code... But you can create a DataTemplate in XAML as a resource, and assign it to a column in code:
((DataGridTemplateColumn)dg.Columns[0]).CellTemplate = (DataTemplate)this.Resources["dt"];
from: http://forums.silverlight.net/forums/p/12912/41962.aspx
by: Answer by Vladimir Dorokhov for Programatically create Hyperlink Column in Silverlight DataGrid
Why do you need to do it in code? It could be done in XAML using a DataGridTemplateColumn with an appropriate template e.g:
<sdk:DataGridTemplateColumn Header="View" CellTemplate="{StaticResource MyDataTemplate}">
</sdk:DataGridTemplateColumn>
..and define the template in the page resources
<DataTemplate x:Key="MyDataTemplate">
<HyperlinkButton x:Name="ViewLink"
Style="{StaticResource ViewButton}"
Click="ViewLink_Click">
</HyperlinkButton>
</DataTemplate>
You could add some logic to open a child window in the code behind, or following a purist MVVM path, add a command to handle the Hyperlink click event.
by: Answer by Myles J for Programatically create Hyperlink Column in Silverlight DataGrid
WP7: Dynamically adding UIElements to a LongListSelector item
I'm trying to add UIElements to a LongListSelector item programmatically. I've created templates for the header, footer, items etc.
Right now I'm doing something like this (the list item template):
<DataTemplate x:Key="listItemTemplate">
<ContentPresenter Content="{Binding ItemContent}"></ContentPresenter>
</DataTemplate>
Inside the model, I assisgn the ItemContent to a Grid, on which I'm adding different UI elements. I don't really know if this is the way to do it or if this is even possible on the LongListSelector but when scrolling the list I get a "The parameter is incorrect." exception (at first, everything seems ok and all the elements added look fine). I tried different approaches but none worked and I feel that I'm just randomly trying solutions without a certain idea. Has anyone managed to do this by using a LongListSelector (any suggestions would be greatly appreciated)?
The call stack:
LongListSelectorPOC.dll!LongListSelectorPOC.App.Application_UnhandledException(object sender, System.Windows.ApplicationUnhandledExceptionEventArgs e) Line 102 + 0x5 bytes C#
System.Windows.dll!MS.Internal.Error.CallApplicationUEHandler(System.Exception e) + 0x30 bytes
System.Windows.dll!MS.Internal.Error.GetXresultForUserException(System.Exception ex) + 0x4d bytes
System.Windows.dll!MS.Internal.FrameworkCallbacks.ManagedPeerTreeUpdate(System.IntPtr oldParentElement, System.IntPtr parentElement, System.IntPtr childElement, byte bIsParentAlive, byte bKeepReferenceToParent, byte bCanCreateParent) + 0x6b bytes
[External Code]
System.Windows.dll!MS.Internal.XcpImports.MeasureOverrideNative(System.IntPtr element, float inWidth, float inHeight, out float outWidth, out float outHeight)
System.Windows.dll!MS.Internal.XcpImports.FrameworkElement_MeasureOverride(System.Windows.FrameworkElement element, System.Windows.Size availableSize) + 0x26 bytes
System.Windows.dll!System.Windows.FrameworkElement.MeasureOverride(System.Windows.Size availableSize) + 0x7 bytes
System.Windows.dll!System.Windows.FrameworkElement.MeasureOverride(System.IntPtr nativeTarget, double inWidth, double inHeight, out double outWidth, out double outHeight) + 0x43 bytes
[External Code]
System.Windows.dll!MS.Internal.XcpImports.Measure_WithDesiredSizeNative(System.IntPtr element, float inWidth, float inHeight, out float outWidth, out float outHeight)
System.Windows.dll!MS.Internal.XcpImports.UIElement_Measure_WithDesiredSize(System.Windows.UIElement element, System.Windows.Size availableSize) + 0x26 bytes
System.Windows.dll!System.Windows.UIElement.Measure_WithDesiredSize(System.Windows.Size availableSize) + 0x39 bytes
System.Windows.dll!System.Windows.Controls.VirtualizingStackPanel.MeasureChild(System.Windows.UIElement child, System.Windows.Size layoutSlotSize) + 0x42 bytes
System.Windows.dll!System.Windows.Controls.VirtualizingStackPanel.GeneratePreviousChild(int childIndex, System.Windows.Size layoutSlotSize) + 0x6f bytes
System.Windows.dll!System.Windows.Controls.VirtualizingStackPanel.GeneratePreviousItems(ref double logicalVisibleSpace, ref System.Windows.Size stackDesiredSize, System.Windows.Size layoutSlotSize, bool isHorizontal, bool adjustPositions) + 0x138 bytes
System.Windows.dll!System.Windows.Controls.VirtualizingStackPanel.MeasureOverride(System.Windows.Size constraint) + 0x4e1 bytes
System.Windows.dll!System.Windows.FrameworkElement.MeasureOverride(System.IntPtr nativeTarget, double inWidth, double inHeight, out double outWidth, out double outHeight) + 0x43 bytes
[External Code]
No Answer and comments so far
How to convert type 'system.windows.media.imagesource' to 'system.drawing.image' or byte[] in C#?
I am doing a project in which a built in class for DICOM giving me the ImageSource
,I want to use that ImageSource
in My silverlight Image
control. This conversion I am doing through WCF services. I found WCF does not support ImageSource
, so I need to convert the output of built in class into Image or else in byte[]. So that I can send that output to Silverlight and in Silverlight client I'll reconvert it to ImageSource and can assign it to Image Control easily.
I googled for this but I did not find any help in there. Can anybody help me to fix this problem or provide me any alternate solution for this. Any help will be appreciated, Thanks in advance.
Note:- I do not have any permission for code modification on the built in class. As its a third party library.
UPDATE:-
Brief Description:
I have a class let say GetImageSource
and in that I have a method say giveImgSource()
. Now my questions is:
In WCF I have to call this method and after getting ImageSource
from this method I need to pass it to my silverlight Client. As WCF doesn't know about ImageSource
, so I need to convert the output of this method to some one out of the following or any alternate if you knows:
byte[]
Image
FileStream
MemoryStream etc
Answers & Comments...
Is it a png image? Then use this to convert to byte[]:
var image = (BitmapSource)value;
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
using (var ms = new MemoryStream())
{
encoder.Save(ms);
return ms.ToArray();
}
UPDATE:
Decoding:
var bytes = (byte[])value;
var image = new BitmapImage();
image.BeginInit();
if (bytes == null)
{
// Processing null case
}
else
{
using (var ms = new MemoryStream(bytes))
{
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = ms;
image.EndInit();
}
}
return image;
by: Answer by dvvrd for How to convert type 'system.windows.media.imagesource' to 'system.drawing.image' or byte[] in C#?
Please refer to the below links for converting ImageSource to byte[]. They use the BitmapSource and WriteableBitmap classes which are available under PresentationCore library.
(1) How to Convert ImageSource to byte[]?
(2) How to Convert ImageSource to byte[] and back to ImageSource?
Hope that it will solve your problem.
by: Answer by DareToExplore for How to convert type 'system.windows.media.imagesource' to 'system.drawing.image' or byte[] in C#?
The following two helper methods should be able to do the trick:
public BitmapImage ImageFromBuffer(Byte[] bytes)
{
MemoryStream stream = new MemoryStream(bytes);
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = stream;
image.EndInit();
return image;
}
public Byte[] BufferFromImage(BitmapImage imageSource)
{
Stream stream = imageSource.StreamSource;
Byte[] buffer = null;
if (stream != null && stream.Length > 0)
{
using (BinaryReader br = new BinaryReader(stream))
{
buffer = br.ReadBytes((Int32)stream.Length);
}
}
return buffer;
}
by: Answer by Jodha for How to convert type 'system.windows.media.imagesource' to 'system.drawing.image' or byte[] in C#?
Definitive source(s) for the difference between Silverlight and WPF
Does anyone know of a definitive guide or guides that tells us the differences between WPF and Silverlight. I know that Silverlight, for example, doesn’t have all the controls and all the namespaces that WPF has. Is there a source which tells me exactly what controls and namespaces are absent in Silverlight?
There are other things that I know off the top of my head, like only allowing asynchronous communications using basic http binding. Also, Silverlgiht doesn’t have all of the type converters out of the box.
Anyone else have interesting experiences with the nuances or know of sources that explain them?
Answers & Comments...
XAML Processing Differences Between Silverlight and WPF
by: Answer by AnthonyWJones for Definitive source(s) for the difference between Silverlight and WPF
Two more useful resources -
Guidance on Differences Between WPF
and Silverlight:
http://wpfslguidance.codeplex.com/
Contrasting Silverlight and WPF:
http://msdn.microsoft.com/en-us/library/ff921107(v=pandp.20).aspx
by: Answer by akjoshi for Definitive source(s) for the difference between Silverlight and WPF
Silverlight 4 OOB + Browser HTTP Stack + Client Certificates = FAIL?
I'm having an issue where IIS 7.5 (on Windows 7 64-bit) is failing when I call it from an out-of-browser Silverlight 4 app using SSL and a client certificate, with the message "The I/O operation has been aborted because of either a thread exit or an application request. (0x800703e3)". The request does make it to IIS. here is a sample from the failed request trace:
I am using the browser HTTP stack, because the client HTTP stack does not support client certificates. The client code attempting to hit the server is the Prism module loader. If I run the app out-of-browser but ignore client certs, or if I run the application in-browser but require client certs, it works fine. It seems to be the combination of the two that is causing the problem.
I tried the following to gather more info:
- Used Fiddler to view the failing request. It works if Fiddler is running (presumably because Fiddler is handling the client certificate differently?);
- Created an .aspx web form to serve up the module .xaps;
- Created an HTTPModule to see if I could intercept the request before it failed;
- Used a packet sniffer to see if I could tell if the client certificate was being sent correctly.
None of the above gave me much useful information beyond what I could see in the trace file, although the Fiddler thing is interesting.
Any ideas? Thanks in advance!
Mike
Answers & Comments...
I beat my head against the wall for weeks on this problem. Here's what I learned and how I finally worked around it.
Prism's FileDownloader class uses System.Net.WebClient to load modules. In OOB mode, WebClient seems to use the same stack as IE, but it apparently either doesn't send the client certificate, or (more likely) doesn't correctly negotiate the SSL/client cert handshake with the server. I say this because:
- I was able to successfully request .xap files using Firefox and Chrome;
- I was not able to successfully request .xap files using IE;
- IIS would fail with a 500, not a 403.
I couldn't get good visibility into what was actually happening over the wire; if I used Fiddler, it would work, because Fiddler intercepts communications with the server and handles the client certificate handshake itself. And trying to use a packet sniffer obviously wouldn't tell me anything because of SSL.
So - I first spent a lot of time on the server side trying to eliminate things (unneeded handlers, modules, features, etc.) that might be causing the problem.
When that didn't work, I tried modifying the Prism source code to use the browser's HTTP stack instead of WebClient. To do this, I created a new class similar in design to FileDownloader, implementing IFileDownloader, that used the browser stack. I then made some changes to XapModuleTypeLoader (which instantiates the downloader) to make it use the new class. This approach failed with the same error I was originally experiencing.
Then I started researching whether a commercial third-party HTTP stack might be available. I found one that supported the features I needed and that supported the Silverlight 4 runtime. I created another implementation of IFileDownloader that used that stack, and BOOM - it worked.
The good news with this approach is that not only can I use this to load modules, I can also use it to protect communications between the client and our REST API (a benefit we were going to give up, before).
I plan to submit a patch to Prism to allow the downloader to be registered or bound externally, as it's currently hard-coded to use its own FileDownloader. If anyone is interested in that or in the commercial HTTP stack I'm using, contact me (msimpson -at- abelsolutions -dot- com) for links and code samples.
And I must say this - I still don't know for sure whether the root problem is in the HTTP stack on the client side or the server side, but it's a FAIL on Microsoft's part nonetheless.
by: Answer by slipjig for Silverlight 4 OOB + Browser HTTP Stack + Client Certificates = FAIL?
What we (Slipjig and I) found out this week is that there does appear to be a way around these issues, or at least, we're on the trail to determining whether there is a reliable, repeatable way. We're still not positive on that, but here's what we know so far:
At first pass, if you have code like this you can start making requests with either the Browser or Client stack:
First, place a "WebBrowser" control in your Silverlight XAML, and make it send a request to your HTTPS site.
This may pop up the certificate dialog box for the user. Big deal. Accept it. If you have only one cert, then you can turn an option in IE off to suppress that message.
private void Command_Click(object sender, RoutedEventArgs e) {
// This does not pop up the cert dialog if the option to take the first is turned on in IE settings:
BrowserInstance.Navigate(new Uri("https://www.SiteThatRequiresClientCertificates.com/"));
}
Then, in a separate handler invoke by the user, create an instance of your stack, either Client or Browser:
private void CallServer_Click(object sender, RoutedEventArgs e) {
// Works with BrowserHttp factory also:
var req = WebRequestCreator.ClientHttp.Create(new Uri("https://www.SiteThatRequiresClientCertificates.com/"));
req.Method = "GET";
req.BeginGetResponse(new AsyncCallback(Callback), req);
}
Finally, the Callback:
private void Callback(IAsyncResult result)
{
var req = result.AsyncState as System.Net.WebRequest;
var resp = req.EndGetResponse(result);
var content = string.Empty;
using (var reader = new StreamReader(resp.GetResponseStream())) {
content = reader.ReadToEnd();
}
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
Results.Text = content;
});
}
by: Answer by JoshGough for Silverlight 4 OOB + Browser HTTP Stack + Client Certificates = FAIL?
In fact the solution of the problem might be as simple as the one here:
http://forums.silverlight.net/forums/p/196906/458328.aspx
The only thing required is to place the certificate to the trusted root store. But unfortunately, this did not work in my case, and I am still struggling with this issue.
by: Answer by Chandresh Makwana for Silverlight 4 OOB + Browser HTTP Stack + Client Certificates = FAIL?
I had the same issue and I fixed it by creating the certificate using makecert. Follow the steps from this article http://www.codeproject.com/Articles/24027/SSL-with-Self-hosted-WCF-Service and replace CN with your ip/domain. In my case I have tested the service on the local machine and run the commands as follows:
1) makecert -sv SignRoot.pvk -cy authority -r signroot.cer -a sha1 -n "CN=Dev Certification Authority" -ss my -sr localmachine
after running the first command drag the certificate from "Personal" directory to "Trusted Root Certification Authority"
2) makecert -iv SignRoot.pvk -ic signroot.cer -cy end -pe -n
CN="localhost" -eku 1.3.6.1.5.5.7.3.1 -ss my -sr
localmachine -sky exchange -sp
"Microsoft RSA SChannel Cryptographic Provider" -sy 12
In case you want to run the silverlight application on another machine, export the certificate created at step1 and then import it on any machine where you want your application to run.
by: Answer by alex for Silverlight 4 OOB + Browser HTTP Stack + Client Certificates = FAIL?
WCF RIA standard error message don't get localized
I have a WCF RIA application. Some of the entities have required fields. When attempting to save an entity the required fields are checked for nullability. An error message is shown in English. I would like to have the standard WCF RIA error messages show in the local language. Here is what I have done
- CurrentCulture and CurrentUiCulture in CurrentThread are set to the
local language - XAML Property Language in the View is set to the local language
- Section SupportedCultures in the csproj file includes the local
language - System.ComponentModel.DataAnnotations.resources is being copied to
the right folder (Bin/[locallanguage] - The browser has the local language at the top of the language list
What else do I need to do? I would really appreciate any suggestions to investigate this issue.
No Answer and comments so far
Binding toggle button to two commands
I have a toggle button in my silverlight application as follows:
<ToggleButton Content="ToggleButton" Margin="0,30,0,0" Style="{StaticResource ChkToggleButton}" />
The toggle currently is changing visual states on toggle and nothing more.
However, I need to bind each of the toggle with a different command. For eg: On button press1, run command1
and on button press again, run command2
.
How can this be done?
Answers & Comments...
use a single command and also keep track of the toggle state.
Have a viewmodel (preferably, or some codebehind) and let it use these two inputs to decide what actually needs to be done.
by: Answer by Pete for Binding toggle button to two commands
Use Triggers
for such purposes:
<ToggleButton Content="ToggleButton" Margin="0,30,0,0" Style="{StaticResource ChkToggleButton}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Checked">
<i:InvokeCommandAction Command="{Binding FirstCommand}"
CommandParameter="{Binding SomeParameter}" />
</i:EventTrigger>
<i:EventTrigger EventName="Unchecked">
<i:InvokeCommandAction Command="{Binding SecondCommand}"
CommandParameter="{Binding AnotherParameter}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ToggleButton>
by: Answer by AnatoliiG for Binding toggle button to two commands
1 comment:
Psihotim Timisoara va recomanda: - Examinare psihologica
la angajare / periodica pentru toate profesiile,Examinare
psihologica pentru concurs post cadru didactic, asistente medicale, admitere facultate,Evaluare,
recrutare si selectie profesionala Analiza psihologica a muncii si prevenirea accidentelor de munca, Examinare
obtinere permis conducere auto,Examinare siguranta circulatiei.
Examinare obtinere/prelungire permis port-arma letala/neletala (autorizare, angajare)
in Timisoara. www.psihotim.ro
Also visit my webpage ... Testare Psihologica
Post a Comment
Send us your comment related to the topic mentioned on the blog