I have a simple benchmark that I have been running on Windows Mobile devices for years. I don't have a Windows Phone 7 device myself, so I'm wondering if someone has a few minutes to run a test. I think the results may be interesting.
Here's the snippit: (in VB.NET, but C++ equivalent is fine):
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim limit, counter
limit = DateAdd("S", 10, Now)
counter = 0
Do Until Now > limit
counter = counter + 1
Loop
MsgBox(counter / 10, 0, "iterations")
End Sub
As benchmarks goes, it's as simple as it gets.
Post your results here - and I'll add them to the table and give a link.
I'm too lazy to convert it to C#, and windows phone 7 only runs C#. If you convert it to C# I will run it on two different phones.
athompson said:
I'm too lazy to convert it to C#, and windows phone 7 only runs C#. If you convert it to C# I will run it on two different phones.
Click to expand...
Click to collapse
Code:
private void Button1_Click(System.Object sender, System.EventArgs e)
{
dynamic limit = null;
dynamic counter = null;
limit = DateAndTime.DateAdd("S", 10, DateAndTime.Now);
counter = 0;
while (!(DateAndTime.Now > limit)) {
counter = counter + 1;
}
Interaction.MsgBox(counter / 10, 0, "iterations");
}
Developer Fusion has a converter. I can't link to it because I don't have good enough reputation yet.
Cheers!
DateAndTime doesn't seem to be available on windows phone 7 (Interation isn't either but I can work around that easily enough. Not sure what you'd want me to do with the DateAndTime problem).
Hmm, just posted it into a windows phone project. There are quite a few errors. I'll see if I can get it working
Code:
private void button1_Click(object sender, RoutedEventArgs e)
{
double counter;
DateTime limit = DateTime.Now.AddSeconds(10.0);
counter = 0;
while (!(DateTime.Now > limit))
{
counter = counter + 1;
}
MessageBox.Show(counter / 10 + " iterations");
}
I think this is what he was trying to accomplish, but in C#?
In the Samsung SGH-i917 I got 31702.2. Sorry, I forgot my other phone has something messed up and I can't load apps on it right now.
FWIW the emulator gets 55272.4 on my 64 bit 3.2GHZ computer.
Great progress! If you get a chance to post your project somewhere so other can run it to see if there is much variation between devices.
Meanwhile, try this out on your device:
nsbasic.com/speedtest.htm
It's the same test in JavaScript. I managed to run it on some sort of Samsung Windows Phone 7 device: it scored 40,000. Hmmm... JavaScript is faster than C#?
The same test on an Android device gets 400,000. The clock speed of the devices is the same.
We can't run C++ on these devices. If we could, I expect the result would be in the 2,000,000 range.
Wow, you're right. On my SGH-i917 I got 35,903 on the nsbasic.com/speedtest.htm . The IE team must feel proud of themselves.
But the times are fairly close, so it probably has more to do with the precise functions we are using than with the speed of javascript or C# in general applications.
Checking the DateTime each and every loop is a killer for performance. I'm not able to test a WP7 solution right now, but simply dropping the DateTime system and replacing it with an Async Timer running in it's own thread in a .NET 4.0 Console app running on my netbook made it jump from 720287 loops/sec, to a huge 241633375 loops/sec. A performance increase of 33546%.
In JS, the date functions are more optimised than in .NET, mainly because date and date manipulation functions make up a reasonable portion of Sunspider, which developers use, among other benchmarks, to track performance improvements in JS. In .NET, besides not really being tracked in the same way, DateTime's rarely used in performance-critical situations, particularly to track the passage of time, which is where MS recommend the usage of timers where suitable.
Code of C# implementation with Timers:
Code:
class Program
{
static bool loop = true;
static void Main(string[] args)
{
int count = 0;
DateTime finish = DateTime.Now.AddSeconds(10);
System.Timers.Timer time = new System.Timers.Timer(1000);
time.Elapsed += new System.Timers.ElapsedEventHandler(time_Elapsed);
time.Start();
while (loop)
count++;
Console.WriteLine("{0} Iterations", count);
}
static void time_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
loop = false;
}
}
athompson said:
Wow, you're right. On my SGH-i917 I got 35,903 on the nsbasic.com/speedtest.htm .
Click to expand...
Click to collapse
I got 40,995 on my HD7
Hounsell makes a good point, one which exposes the weakness of any benchmark: they really do not tell you how your own app will perform.
I urge everyone reading this to treat it as just for fun. If you need a benchmark that applies to your app, you should construct something that is relevant to your situation.
ghenne said:
Meanwhile, try this out on your device:
nsbasic.com/speedtest.htm
It's the same test in JavaScript. I managed to run it on some sort of Samsung Windows Phone 7 device: it scored 40,000. Hmmm... JavaScript is faster than C#?
The same test on an Android device gets 400,000. The clock speed of the devices is the same.
Click to expand...
Click to collapse
my HD2 running an mdeejay build of android sense with the s6.1 kernel just scored 385000 in the regular windows mobile it ranked only 98317.
I got a 40,995 on my Samsung SGH-i917 Focus.
Here is a WP7 Benchmark tool
Related
This is an Advanced UI SDK for developing finger-friendly Application UIs.
The reason for developing this SDK was mainly to learn about programming for Windows Mobile and the Compact Framework 3.5. I also developed this SDK because I could not find good UI controls that gave total display control to the programmer while taking care of all of the Physics, windowing, and frame buffering AND was open source.
Finally, this SDK was originally developed as part of the XDAFacebook application that I am currently developing.
I am releasing this SDK and its source so that people can have a good foundation to build finger-friendly Windows Mobile applications, and so that programmers starting off in the Windows Mobile world won't have to start from scratch when creating useful UI Controls.
Here are some of the features and uses of this SDK.
Features:
Fully customizable
Easily create custom UI Controls
Resolution independent
Full physics for rendering smooth scrolling
Uses:
Quickly create UI controls
Develop full UI SDKs
Learn basic UI programming for .net CF 3.5
I ask that if you use these controls, please provide feedback so that everyone can benefit!
Thank you and I hope you find these controls useful!
SDK Documentation
Even though the controls are easy to implement, they can seem intimidating at first. Here is an over-view of the core pieces to the SDK:
The IXFItem Interface:
Here are Properties of the interface
PHP:
XFPanelBase Parent { get; set; } // The item's List container
XFItemState State { get; set; } /* An Enum to describe the current item's state
This could include things like [B]Selected[/B] or [B]Normal[/B]*/
Bitmap Buffer { get; set; } // This is the item's cache buffer. Allows for speedy rendering
XFItemStyle Style { get; set; } // CSS like style object. Allows for easy customization
XFItemType ItemType { get; set; } /* Enum to label the type of the current object.
For example, [B]Clickable[/B] or [B]Display[/B] meaning the item won't change*/
The following are the methods that need to be implemented
PHP:
int GetHeight(); /* This returns the height of the item. This value is usually calulated
but in some instances is static. The value should be cached because this method
is called several times during the rendering process.*/
void ResetHeight(); // What ever needs to be done to reset the height cache
void ItemPaint(Graphics g, int x, int y); // Where the magic happens. More on this later
XFItemClickResult GetClickResult(); // An enum is return with what the action of clicking this item was.
The main part of the interface is the ItemPaint method. This method is called from the XFPanelList and passes a Graphics object created from the Buffer Bitmap of the Item. In this method, you do all of your graphics logic, drawing it with the supplied graphics object. The x and y are any offset numbers that should influence when the objects are based. Most of the time, these numbers will be 0, 0.
Because the programmer has total control over how the item is rendered, special care must be used when creating the items, to draw all the features with respect to the XFItemStyle object. This object usually is created in CTOR. An example of the XFItemStyle object being created in one of the SenseUI XFItem's CTORs:
PHP:
public SenseItem()
{
ItemType = XFItemType.Clickable;
Style = new XFItemStyle()
{
BoarderBottomColor = Color.FromArgb(189, 182, 189),
DashStyleBottom = System.Drawing.Drawing2D.DashStyle.Dash,
TextColor = Color.Black,
TextFont = new Font(FontFamily.GenericSansSerif, 8, FontStyle.Regular),
SelectedTextFont = new Font(FontFamily.GenericSansSerif, 8, FontStyle.Regular),
SecondaryTextFont = new Font(FontFamily.GenericSansSerif, 7, FontStyle.Regular),
SelectedSecondaryTextFont = new Font(FontFamily.GenericSansSerif, 7, FontStyle.Regular),
SecondaryTextColor = Color.FromArgb(57, 52, 57),
SelectedTextColor = Color.White,
SelectedBackgroundColor = Color.FromArgb(43, 36, 43),
SelectedSecondaryTextColor = Color.FromArgb(182, 178, 182),
Padding = 11,
PaddingBottom = 12,
PaddingLeft = 10,
PaddingRight = 16
};
}
You will also notice that the ItemType is also set here.
How you use the Style is a little more involved. In the ItemPaint, the programmer should base all of the features off of what is in the Style object. Here is an example of how the above Style object was used in the ItemPaint method:
PHP:
public void ItemPaint(Graphics g, int x, int y)
{
int width = Parent == null ? Screen.PrimaryScreen.WorkingArea.Width : Parent.Width;
XFControlUtils.DrawBoarders(Style, g, 0, 0, width, GetHeight());
int currX = Style.PaddingLeft;
int currY = Style.PaddingTop;
int mHeight = 0;
int sHeight = 0;
if (Icon != null)
currX += _iconSize + Style.PaddingLeft;
SizeF mText = new SizeF();
if (!string.IsNullOrEmpty(MainText))
{
mText = XFControlUtils.GetEllipsisStringMeasure(width - currX - Style.PaddingRight, MainText, Style.TextFont);
MainText = XFControlUtils.EllipsisWord(width - currX - Style.PaddingRight, MainText, Style.TextFont);
}
SizeF sText = new SizeF();
if (!string.IsNullOrEmpty(SecondaryText))
{
sText = XFControlUtils.GetEllipsisStringMeasure(width - currX - Style.PaddingRight, SecondaryText, Style.SecondaryTextFont);
SecondaryText = XFControlUtils.EllipsisWord(width - currX - Style.PaddingRight, SecondaryText, Style.SecondaryTextFont);
}
mHeight = (GetHeight() / 2) - ((int)mText.Height / 2);
if (!string.IsNullOrEmpty(SecondaryText))
{
mHeight = (GetHeight() / 2) - _textSpace - (int)mText.Height;
sHeight = (GetHeight() / 2) + _textSpace;
}
if (State == XFItemState.Selected)
{
XFControlUtils.DrawBackgroundSelected(Style, g, x, y, width, GetHeight());
if (!string.IsNullOrEmpty(MainText))
using (SolidBrush b = new SolidBrush(Style.SelectedTextColor))
g.DrawString(MainText, Style.SelectedTextFont, b, currX, mHeight);
if (!string.IsNullOrEmpty(SecondaryText))
using (SolidBrush b = new SolidBrush(Style.SelectedSecondaryTextColor))
g.DrawString(SecondaryText, Style.SelectedSecondaryTextFont, b, currX, sHeight);
}
else
{
if (!string.IsNullOrEmpty(MainText))
using (SolidBrush b = new SolidBrush(Style.TextColor))
g.DrawString(MainText, Style.TextFont, b, currX, mHeight);
if (!string.IsNullOrEmpty(SecondaryText))
using (SolidBrush b = new SolidBrush(Style.SecondaryTextColor))
g.DrawString(SecondaryText, Style.SecondaryTextFont, b, currX, sHeight);
}
if (Icon != null)
XFControlUtils.DrawAlphaFirstPix(g, Icon, Style.PaddingLeft, Style.PaddingTop);
}
That is as complex as it gets. Other than doing normal Event Handling for ClickReturns, this is all that is required to create beautiful UI Controls for your application.
I hope that this helps! Feel free to PM me or post a reply if you need further clarification.
Class List
Form Controls:
XFPanelContainer - The main control that interacts with the Form.
XFPanels:
XFPanelBase - Basic building block. Handles most of the generic functionality
XFPanelList - Can add IXFItem items.
XFPanelHeader - The top header bar for an XFPanelContainer
XFItems
IXFItem - Interface that all XFItems inherate
XFItemSimpleText - Simple item that displays text
XFItemBack - Special item that allows a panel to slide back
XFItemLoading - Item that allows for work to be down in the background.
XFControlUtils: Library of static, useful utilities for this SDK
DrawAlpha - Draws an image with a supplied Graphics object with a specific level of opacity
DrawAlphaFirstPix - Draws an image and renders all pixels that are the same color as pixel (1,1) are 100% transparent
DrawJustifiedString - draws a justified string
GetEllipsisStringMeasure - Takes a string and if it is more than the supplied width, clips the string and adds a trailing "..." at the end
EllipsisWord - same as the GetEllipsisStringMeasure, except it ellipsis at the words and not at the char level.
GetSizedString - Takes a string and adds "\n" so that the string wraps according to the supplied width
Many Others!
Sense UI Example
Here is a working example. I made this Sense UI example in about 3 hours 15 hours. It isn't complete but gives a good example of how to/why use this SDK. There are 3 screenshots of what this demo looks like.
I'll explain some of the pieces of code when I get some time later today.
The other great example of how to use this SDK is the XFAFacebook Application.
The source for this project is located @ http://code.google.com/p/xda-winmo-facebook/source/browse/#svn/trunk/XFSenseUI
There are a few screenshots of the XDAFacebook application included.
Finally, a quick start tutorial.
Start a new Smart Device project.
Add a reference to the XFControls.dll
Place the following lines of code in the Form1 constructor (after the InitializeComponent()
Code:
XFPanelContainer container = new XFPanelContainer();
container.Dock = DockStyle.Fill;
Controls.Add(container);
XFPanelList list = new XFPanelList();
container.SetMainPanel(list);
list.ShowScrollbar(true);
for (int i = 0; i < 50; i++)
{
list.Add("This is item " + i);
}
Run the project and you will get an output like the "SimpleText.png"
It's that easy!
UPDATE: I've added the XFSense to the Google Code page and have made some pretty extensive updates to it. I've added a few controls including sliders, toggles, checkboxes and radio buttons. It still isn't complete but I will be working to make it a full fledge Sense SDK.
Stay tuned!
Releases:
Initial Release - 9/1/10
When major updates occur, the DLLs will be posted here. The best thing to do is pull the source from the Google Code page and use that.
This will guarantee the freshes code will be used for your projects
Instructions:
Download and unzip the latest XFControls.zip from below.
Add the .dll as a reference.
Program!
The source can be found at: http://code.google.com/p/xda-winmo-facebook/source/browse/#svn/trunk/XDAFacebook/XFControls
List of downloads:
10/6/10 - Updated for speed and better scrolling! - XFControls 0.2.zip
9/1/10 - Initial upload - XFControls 0.1.zip
Other things I might have missed
Reserved Other
Sounds interesting! Definitely looking forward to some screenshots.
kliptik said:
Sounds interesting! Definitely looking forward to some screenshots.
Click to expand...
Click to collapse
Screenshots are up!
Only 3 downloads?! Hmmm.... I figured more people would be interested in a finger-friendly and open source UI SDK...
Is there something wrong with my posts? Are they too confusing?
Let me know what I can do to help! This has taken me a good deal of time to write and I would hope that it would be of use to someone else...
joe_coolish said:
Only 3 downloads?! Hmmm.... I figured more people would be interested in a finger-friendly and open source UI SDK...
Is there something wrong with my posts? Are they too confusing?
Let me know what I can do to help! This has taken me a good deal of time to write and I would hope that it would be of use to someone else...
Click to expand...
Click to collapse
Just DL'd a copy. I'm super swamped at the moment trying to get the next release of KD-Font out, but I'll try and check this out when I get a chance.
Thank you for your contribution!
I will definitely give this a test run at some point. Good work!
you have to add you own graphics to this sdk?
janneman22 said:
you have to add you own graphics to this sdk?
Click to expand...
Click to collapse
yes, this is a UI SDK. it is used to create user controls. The core code handles all the caching and physics, but the programmer must create the actual controls. including the graphics. look at the sense UI example to see how you can implement your own custom UI controls. like i said in the post, it only took about 3 hours to create those controls. most of which was spent creating graphics.
joe_coolish said:
yes, this is a UI SDK. it is used to create user controls. The core code handles all the caching and physics, but the programmer must create the actual controls. including the graphics. look at the sense UI example to see how you can implement your own custom UI controls. like i said in the post, it only took about 3 hours to create those controls. most of which was spent creating graphics.
Click to expand...
Click to collapse
oh right. but does it place controls in the toolbox, or have you to create the controls hard coded?
i could help you to make some grapics packages for this sdk
Ok, I've updated the binaries to be the latest and greatest. The scrolling is super smooth and things are starting to look pretty good!
I also will be updating the XFSense and I'll probably be extending it a little more because I plan on bringing it into the XDA Facebook app.
As always, let me know what you think!
EDIT: Oh, and to answer the question about adding objects to the toolbox, I have not added the OCX files (or whatever they are) so that they can be added to the tool box. But, after you've added the container and the panels, everything is logic after that, so adding the items to the toolbox really doesn't benefit too much.
As far as graphics, I would love help with graphics! Send me a PM and we'll talk!
joe_coolish said:
Here is a working example. I made this Sense UI example in about 3 hours. It isn't complete but gives a good example of how to/why use this SDK. There are 3 screenshots of what this demo looks like.
I'll explain some of the pieces of code when I get some time later today.
The other great example of how to use this SDK is the XFAFacebook Application.
The source for this project is located @ http://code.google.com/p/xda-winmo-facebook/source/browse/
There are a few screenshots of the XDAFacebook application included.
Finally, a quick start tutorial.
Start a new Smart Device project.
Add a reference to the XFControls.dll
Place the following lines of code in the Form1 constructor (after the InitializeComponent()
Code:
XFPanelContainer container = new XFPanelContainer();
container.Dock = DockStyle.Fill;
Controls.Add(container);
XFPanelList list = new XFPanelList();
container.SetMainPanel(list);
list.ShowScrollbar(true);
for (int i = 0; i < 50; i++)
{
list.Add("This is item " + i);
}
Run the project and you will get an output like the "SimpleText.png"
It's that easy!
Click to expand...
Click to collapse
Very nice control. I downloaded the sample (had problem with missing XFControl project but downloaded it from code.google).
Have a couple questions, how would i go about adding image to a child panel?
What I'm trying to so is have about 75 items on the main screen and each item will have sub-panel, when clicking on sub-panel I need to have label x2 and image.
Also when compiling the project I get error:
"Error 1 'XFControls.XFPanels.XFPanelHeader' does not contain a definition for 'BackgroundImage' and no extension method 'BackgroundImage' accepting a first argument of type 'XFControls.XFPanels.XFPanelHeader' could be found (are you missing a using directive or an assembly reference?) C:\downloads\C#\XFSenseUI\XFSenseUIDemo\Form1.cs 39 24 XFSenseUIDemo"
Alright, I'll post an example if I get some time in a bit. But as for the error, it is because the Core XFControls has been modified since the last time I updated this thread. You can download the freshes code from the google code page or use the attached DLL. I'd suggest the Google Code page, since it gets updated more frequently. But then you get all the XDAFacebook with it, so it can also be negative.
Basically to add an image to an XFItem to be added to the XFPanelList, you can either create your own item by inheriting from the IXFItem and doing all the image manipulation in the ItemDraw() method.
For an example of how to do that, look at the XFItemImageDisplay item in the XFControls.XFPanels.XFPanelItems namespace.
If you need something specific, let me know and I'll see if I can whip up an example
I'm new to C# and the compact framework so sample would be good...
Thanks
JarekG said:
I'm new to C# and the compact framework so sample would be good...
Thanks
Click to expand...
Click to collapse
Ok, could you describe how you want the control to look? Also, what you want to supply to the constructor? IE a path for an image, upper text, lower text, maybe even some style things. ETC
Newbie here. Maybe someone can give me some direction. I am writing an app for both standard and professional. I have 2 projects in my solution. One is for standard the othe is for professional. I am not sure if this is the right way or not but what I want to do is when the app opens it checks to see what platform is running and then runs the correct project. Any help would be greatly appreciated.
It is possible to create a single project that is capable of running on both platforms but there is quite a bit of groundwork you will have to do first.
Firstly, the main differences.
Standard : No touch screen i.e. No Mouse events. All user input is via the keyboard, buttons, D-PAD and ENTER. No Open/Save dialogboxes, you have to present the files to the user yourself. Message dialogs appear full screen.
Professional : None of the above limitations.
The are a few pointers here:
http://msdn.microsoft.com/en-us/library/bb985500.aspx
The following code will detect the platform and set the variable 'SmartPhone' to 1 (true) if the version is 'Standard'
Code:
#define MAX_LOADSTRING 100
int SmartPhone;
TCHAR szReturn[MAX_LOADSTRING];
SystemParametersInfo(SPI_GETPLATFORMTYPE,MAX_LOADSTRING,szReturn,false);
SmartPhone=wcscmp(TEXT("SmartPhone"),szReturn)^1;
Your processing code may have code such as:
Code:
if(SmartPhone)
{
........ Standard Stuff.......
}
else
{
......... Professional Stuff........
}
Note also that code dealing with a WM_LBUTTONDOWN message will never be executed on a smartphone, as WinMo Standard never generates this message.
It may seem a pain, but you only have one executable to deliver for both platforms.
As an example, here's one I prepared earlier.
http://forum.xda-developers.com/showthread.php?t=509413
more info
I am coding with VB. What I was thinking was creating a class project and making that the startup project. Within the class the VB would check the platform and then run the correct project.
Should work:
To get the Platform type in .NET CF have a look at:
http://msdn.microsoft.com/en-us/library/ms229660(VS.90).aspx
It's also listed in the VS Help.
I am using VS2008 TS and cf3.5. I have tried several methods and still can't get any to work. I must be missing a reference or something. Here is some code I can't get to work.
If SystemSettings.Platform = WinCEPlatform.PocketPC Then
txtDeviceType.Text = "Windows Mobile Professional"
ElseIf SystemSettings.Platform = WinCEPlatform.Smartphone Then
txtDeviceType.Text = "Windows Mobile Standard"
Else
txtDeviceType.Text = "Not Windows Mobile"
End If
Also tried this.
Public Enumeration WinCEPlatform
Dim instance As WinCEPlatform
I also tried getversionex but couldn't get it to work either.
I only code .NET in C# but there is virtually no difference.
Try this: You will have to add the reference to Microsoft.WindowsCE.Forms;
Right click on References in the Solution Explorer, click on Add Reference, in the .NET Tab, pick it out of the list.
Code:
using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.WindowsCE.Forms;
namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
WinCEPlatform Platform = new WinCEPlatform();
Platform = SystemSettings.Platform;
label1.Text = Platform.ToString();
}
}
}
Works a treat!
Let's let Red Gate's Reflector translate the IL into VB.
It also reveals that the compiler rips outs the middle variables and goes straight for :
Code:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
Me.label1.Text = SystemSettings.Platform.ToString
End Sub
I am getting an error on this InitializeComponent. Another question. Can I add a class project and use this code to point to the correct project?
Drop the InitialiseComponent function, that is only used used in C#
In VB in Form1 the only code you need is
Code:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Label1.Text = Microsoft.WindowsCE.Forms.SystemSettings.Platform.ToString
End Sub
End Class
This code works and puts "YES" in the box if run on a PPC
Code:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Microsoft.WindowsCE.Forms.SystemSettings.Platform = Microsoft.WindowsCE.Forms.WinCEPlatform.PocketPC Then
Label1.Text = "YES"
End If
End Sub
End Class
Ok. I got it to work with the following code. But I have another problem. My app is a very simple app. I want it to work on PPC2003 and smartphones. I have 2 different forms for standard and professional. Now the problem is that if I use .net compact framework 3.5 then the device has to have that installed. So if I want to the app to work on older devices it won't work without the .net compact framework. If I use .net compact framework 2.0 then I lose the ability to use the code to determine if its standard or professional. I was hoping there was a way to include the 3.5 CF into my app cab but I haven't seen it. I am currently using VS2008 whcih only allows you 2.0 CF and 3.5 CF. I was thinking about using VS2005 and use 1.0 CF so it would work on all Windows mobile devices. But then I would again lose the ability to use the code. Any ideas would be appreciated.
Shared Sub Main()
Dim Platform As New WinCEPlatform()
Platform = SystemSettings.Platform
If Platform = "1" Then
Application.Run(
New Pro())
ElseIf Platform = "2" Then
Application.Run(
New Standard())
End If
End Sub
Using VS2005 I started a new project and selected SmartDevice 1.0. Now I have some issues.
1. Trying to determine either standard or professional. I am trying to use the Pinvoke to do this. No luck so far. I get an error on ByVal nFolder As ceFolders.
2. The code I was using to play a .wav file no longer works.
Dim myplayer As New System.Media.SoundPlayer(New IO.MemoryStream(My.Resources.Dice))
myplayer.Play()
3. I had resource files for images and a wav file so my code to use these no longer work.
Me.PictureBox1.Image = My.Resources.red_die_1_th
1. I'll have a look at it. Watch this space.
2. The SoundPlayer object is only available from .net CF 3.5 onwards. To play sounds you my have to PInvoke PlaySound()
http://msdn.microsoft.com/en-us/library/ms229685(v=VS.80).aspx
3. Should work, but maybe there's a difference in the frameworks. Microsoft's catch-all is that not all methods, properties etc. are supported in all .NET or .NET CF. versions. You may end up doing it in two stages, create a bitmap image from the resource, then pass that to the picturebox.
The answer to 1 is below. This works in C# under VS2003 .NET CF 1.0 but it is only in C#, I do not have VB installed on this machine. You will have to reverse engineer it into VB yourself, not too difficult. The important code is the DLLImport definition, the SPI_GETPLATFORMTYPE definition, and the call of the function in Form1_Load().
On program start "PocketPC" appears in the label on screen.
Code:
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
namespace PInvTest
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.MainMenu mainMenu1;
[DllImport("coredll.dll", EntryPoint="SystemParametersInfo", SetLastError=true)]
private static extern int SystemParametersInfo(
int uiAction, int uiParam, string pvParam, int fWinIni);
private const int SPI_GETPLATFORMTYPE = 257;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
base.Dispose( disposing );
}
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
Application.Run(new Form1());
}
private void Form1_Load(object sender, System.EventArgs e)
{
string Platform = new string(' ',20);
SystemParametersInfo(SPI_GETPLATFORMTYPE,Platform.Length,Platform,0);
label1.Text=Platform;
}
}
}
The DllImport Project
This project is part "Real DllImport" and also not the same time. It has limited DllImport to only types "void();" (well isn't that DllImport )
Other CORE functions that require multiple [IN] or/and [OUT] are to complex for the code right now (there are so many possibilities).
Terms of use, using the code (free to use, under my name "fiinix00 @ XDA"~ in app)
As posted to JaxBot
Well thanks for asking, this project is free for everyone, the one purpose it was made for.
The only thing i needed back is my name (fiinix @ XDA) included in whose projects (external) that take use of my code base. There is no licence or something (GNU e.g.), it just make people mad and confused.
So feel free to take advantage of the code whenever you want, just remember, i want my name on it. =D
Click to expand...
Click to collapse
UPDATE @ (2011y-03m-26d - 23:08)
Ohyeah, i can control zune from my application (Resume, Stop, Pause, NextSong, PrevSong, ShutdownZune, StartZune, ... to come)
Turn on/off radio remote from code. (DAMN, the radio begins to play without "No antenna" but no sound, plugin again and it sounds :/)
UPDATE @ (2011-03-27 - 14:35)
- Set clipboard (lol, doesent even have NODO): DllImportCaller.lib.Clipboard_SET("Hello");
- Get clipboard: DllImportCaller.lib.Clipboard_GET(ref [string]);
- Enchanted: Phone.Clipboard.Value { get { ... } set { ... } }
- Basic calls against void without arguments: DllImportCaller.lib.VoidCall( [DLL] , [Method] );
- API for verifying method existence: DllImportCaller.NativeMethodExists( [DLL] , [Method] );
- Raw API for controlling vibrator (unlimited "on", also continues to vibrate on exit, dont forget to turn off ): Phone.Vibrator. { Vibrate(), Stop() }
Source code + test XAP updated (2011-03-27-17:38) (Clipboard GET; is corrupt)
HELLO THERE TASKMANAGER!!
(I can now enumerate the running processes on the phone )
Proof: http://moitox.com/WP7tskMngr.png
Hook to keyboard, for some reason it only show interest in the "Search" button.
Documentation of proc:
[WP7Process].{ CreationTime, ExitTime, KernelTime, UserTime, <-UpdateTimes(), Kill(exitCode), { PROCESSENTRY32 RAW } }
^ for "currentProcess.Kill()" use "Phone.TaskManager.GentlyExitCurrentProcess();" the Kill(exitCode) KILLS
WP7Process[] = Phone.TaskManager.Named("taskhost");
WP7Process = Phone.TaskManager.CurrentProcess();
Documentation of network
- ConnectionType { Unk0, Unk1, Unk2, Connected, Unk3 ... }
- ConnectionType = Phone.Network.GetWirlessState;
Phone.KeyboardHook.IsKeyDown(int key)
> Search = 124 (lol)
Misc finds
DllImportCaller.NativeMethodExists("urlmon", "IsIntranetAvailable");
DllImportCaller.NativeMethodExists("urlmon", "ObtainUserAgentString");
- Code updated! (2011-03-28-22:12)
Added "Phone.DEP", dep is a wrapper against info stored in "Microsoft.Phone.Info.DeviceExtendedProperties"
Full "TaskHost.exe" support
HostInformation = Phone.TaskHost.GetCurrenHostInfo();
HostInformation {
fDehydrating = 0,
fRehydrated = 0,
hHostWnd = -25821178 /* This silverlight managed window (host window) */
szAppDataFolder = "\\Applications\\Data\\8DC5214E-88FA-4C2D-A379-2CD74FE24B72\\Data"
szAppInstallFolder = "\\Applications\\Install\\8DC5214E-88FA-4C2D-A379-2CD74FE24B72\\Install"
szAppIsolatedStorePath = "\\Applications\\Data\\8DC5214E-88FA-4C2D-A379-2CD74FE24B72\\Data\\IsolatedStore"
szProductId = "{8DC5214E-88FA-4C2D-A379-2CD74FE24B72}"
szTaskPage = "MainPage.xaml" /* Current page? */
szUri = "app://8DC5214E-88FA-4C2D-A379-2CD74FE24B72/_default"
ullLastInstanceId = 39 /* fully retarded property? */
}
Code updated! (2011-03-29-23:25)
new Phone functionality
Phone.OS.{ Shutdown(ewxCode) } /* 1.0.2 can still call it with "DllImportCaller.lib.ShutdownOS" (failed tho on mine in 1.0.2) */
Added "GetLastError7" (C++ ::GetLastError()) for better C# side error handling.
Code updated! (2011-04-03-12:37)
Code updated! (2011-04-04-21:48)
- App launcher code!!
- Enchanted IO support
- 1.0.6!
Code updated! (2011-04-05-22:08)
- Enchanted task support
- Console7.Title { get; set; } etc.
Code updated! (2011-04-08-00:03)
- Stable%: 97 :/
- Battery support (see battery info (CORE only))
- Phone.Sound { MasterVolume!! { get; set; }, etc } (controlling phone master volume over all processes)
- Phone.OS.Kernel.ResetDevice(); (instant stops kernel, instant shutdown, not recommended!)
Code updated! (2011-04-09-22:39)
- Enchanted "Phone.Battery" class
- Phone.TaskManager.+GetCurrentProcessId
- WiFi Controll! (On/Off) (from code!)
- Bluetooth Controll! (On/Off) (from code here toe!)
- Phone.OS.+GetSystemStartupItems(),+GetDesktopWindowHandle()
- New class "Phone.Search."+SearchFor,+OpenSearch,+BindSearchButtonToPage (FAILS)
- New class "Phone.XboxLive"+GetIsXboxLiveEnable,+GetIsSignedIn
- Yep: 1.0.9!
Code updated! (2011-04-17-22:01) //damn, not update in 8 days~
- Phone.OS.OSLanguage { SubLanguageID, PrimaryLanguageID }
- Phone.WP7Process.+ CurrentProcessID (int),+GetCurrentProcess() returns guaranteed the right taskhost @class_WP7Process
- Improved Phone.OS.Memory
- + Extra i don't remember (8 days)
Code updated! (2011-05-22-21:25)
- 1.2.1 (because 1.2 methods was commented out to set things right (less crash))
- HUGE improvements
- Removed unneeded **** to speed things up
- Screenshot 161 ms per capture (non-save-to-gallery) =D
- =D
Mango support added(2011-10-26-19:30)
- yep, "ATL" Mango compiled. I have not yet tested to run it on a NoDo.
- Trying to implement a ASM virtual machine; example:
Code:
[ASMMethod(Dll = "coredll", EntryPoint = "GetLastError")]
public delegate int GetLastError();
var last = ASMGenerator.GenerateDelegateFor<GetLastError>();
int code = last();
Custom tile support added(2011-11-07-23:08)
- Custom core tiles ftw!
[/CODE]
Source: Attatchment
-Compile VS2008 folder with C++ compiler from WM6 SDK
-Windows Mobile SDK 6 PRO
-Visual Studio 2010 (+ WP7 Silverlight SDK)
Test-app: Attatchment
-Deploy
-No need anymore to do a initialize button call, automatic called on first use in code "DllImportcaller.lib.cctor" by JIT (Net Framework just in time).
-Do some tests from the scrolling list. (due there are more CORE back-code API's than buttons, all tests can not be tested).
OLDER VERSIONS WILL BE DEPRECATED AND WILL BE REPLACED BY NEWER, MAX ATTACHMENTS IS 8.
fiinix said:
Searched for dllimport but did not found what i was searching for; so i need to ask about if it is possible to do a dllimport with interop in meta?
Because if not, i think i have found something quite the same without dllimport.
Click to expand...
Click to collapse
We can't p/invoke, but only use COM interfaces to interop with native code. What did you find?
Im trying the method, of c++ calling the calls for me.
In c++ i call "HMODULE dll = LoadLibrary("MyDLL.dll");" to get the native kerner32.dll e.g.
Then call "Dword addr = GetProcAddress(dll, "MyMethod");"
Code:
typedef HRESULT (STDAPICALLTYPE * LPFNBOX) (void);
C# -> COM (LoadLibrary e.g.) ->
return dll addr -> return to C#
C# -> COM -> LPFNBOX * val = (LPFNBOX)GetProcAddress(addr, "method"); ->
return val(); ->
return to C#
May work with some privileges bypass, not tested. (^ Not programmer, skip it)
Step 1 of 2 "LoadLibrary7" S_OK (success!)
int result;
var hr = lib.MessageBox7("lpText", "lpCaption", MB.MB_OK, out result);
And: It shows a native msg box
It ** worked!
var t = DllImportCaller.Call<string, string>("coredll.dll", "CeRunAppAtEvent", "emptyArgs");
LoadLibrary7( .. "coredll.dll" .. ) @ -1304248592
GetProcAddress7( .. CeRunAppAtEvent" .. ) @ 1105512120
Now just "box" and call it
Sounds sweet. Any code to share?
kuerbis2 said:
Sounds sweet. Any code to share?
Click to expand...
Click to collapse
Well, last step now is to box it. Due "Compact Framework 3.7" there is no "Marshal.GetDelegateForFunctionPointer". But iw found something quite common.
Code, yes. (if i succeed)
Well, there we go. I did just shut down the phone with code (phone sided code)!
DllImportCaller.lib.ShutdownOS();
nevermind.
So you wrapped LoadLibrary/GetProcAddress via C++/COM, how is this any different than what we have now? It's easier to simply write C++ code and provide a calling mechanism. (Which is what we're doing.)
WithinRafael said:
So you wrapped LoadLibrary/GetProcAddress via C++/COM, how is this any different than what we have now? It's easier to simply write C++ code and provide a calling mechanism. (Which is what we're doing.)
Click to expand...
Click to collapse
The use of dllimports (gdiplus.dll located in "\Windows\" for example) in C# code. And you dont need to know c++/programmer to call c++ methods anymore.
The last annoying, to get that IntPtr (native) to become a managed method... (it is possible). Anyways its going great, i'll continue tomorrow
Hey any code on this?
Flow WP7 said:
Hey any code on this?
Click to expand...
Click to collapse
Very soon (today @ Central European Time, dinner). Due im currently at work. The preview will not do all the way down to dllimport because the last thing for me is to figure out how to call the native IntPtr from c# with c# arguments.
Glad you guys are asking
Yeah, would be really cool if thats possible, then it would be possible todo everything over mscoree.dll, i guess?!
I found something intresting myself yesterday, the mscorlib.dll and System.dll on the phone are different from the ones in the sdk. (They contain a lot more stuff) Also the the mscorlib contains DllImports for almost everything.
If there is some way to get an internal class that would be also a great alternative...
Flow WP7 said:
Yeah, would be really cool if thats possible, then it would be possible todo everything over mscoree.dll, i guess?!
I found something intresting myself yesterday, the mscorlib.dll and System.dll on the phone are different from the ones in the sdk. (They contain a lot more stuff) Also the the mscorlib contains DllImports for almost everything.
If there is some way to get an internal class that would be also a great alternative...
Click to expand...
Click to collapse
Internal's -> typeof(CLASS).GetMethod( ... ).Invoke( ... ). Works perfect with </Interop> in manifest. Else "MethodAccessException".
And all those dllimports in mscore, plenty of them, most doing calls to mscoree
Goad is to do "DllImportCaller.Call( DLL, METHOD, ARGS )"~
I just tried this:
Type type = Type.GetType("System.PInvoke.PAL");
Type type1 = Type.GetType("System.Host.HostNative+FIND_DATA");
object createInstance = Activator.CreateInstance(type1);
And this results into MethodAccessException
I have a WPInteropManifest.xml, so what do you mean by:
Works perfect with </Interop> in manifest. Else "MethodAccessException".
Click to expand...
Click to collapse
regards,
Flow
Flow WP7 said:
I just tried this:
Type type = Type.GetType("System.PInvoke.PAL");
Type type1 = Type.GetType("System.Host.HostNative+FIND_DATA");
object createInstance = Activator.CreateInstance(type1);
And this results into MethodAccessException
I have a WPInteropManifest.xml, so what do you mean by:
regards,
Flow
Click to expand...
Click to collapse
This is going kind of off topic. Stay to topic.
Anyways, Activaror.CreateInstance cannot create internal constructots, you need TYPE.GetConstructor( ... ).Invoke. Check visibility of ctor.
fiinix said:
The last annoying, to get that IntPtr (native) to become a managed method... (it is possible). Anyways its going great, i'll continue tomorrow
Click to expand...
Click to collapse
Having some difficulties (its killing itself on call) :/ Ill publish as fast as possible.
So during my break today I added a few more registry paths to check on my HTC Radar and I found HKCU\Software\Microsoft\ConMan\HostLauncher\HostData\. There I found a few Service entries:
Code:
7ABBE0D5-B437-42CA-B57B-CEED61680E4F
11EE50CA-6CD3-45BA-9D65-46E133CFF009
B2FC26AB-D6EC-4426-91FA-9E039F92A639
The first entry did not take me any where but the other two did.
Running those in my test application sent back:
Code:
Int32Type: 0
Int32Type: -2147024809
I know it isnt much and I am not sure what to send to the ConMan so if someone does please tell me:
Code:
private static void ExecutionTest()
{
#region Create Objects
ObjectId DeviceID = new ObjectId("30F105C9-681E-420b-A277-7C086EAD8A4E");
Platform platform = datastoremanager.GetPlatform(PlatformObjectID);
Device device = platform.GetDevice(DeviceID);
#endregion
try
{
//Connect to the device.
device.Connect();
if (device.IsConnected())
{
RemoteAgent ra = device.GetRemoteAgent(new ObjectId("910DCB1B-487B-452b-87FC-73852B5A239C"));
DevicePacketStream ps = ra.CreatePacketStream(new ObjectId(new Guid("11EE50CA-6CD3-45BA-9D65-46E133CFF009")));
// Create and write a packet of data.
Packet packet;
packet = new Packet();
for (int i = 0; i < 4; i++) packet.WriteInt32(i);
packet.WriteString("Hello Smart Device");
ps.Write(packet);
#region While stream is connected, try to read a packet.
while (ps.IsConnected())
{
if (ps.IsPacketAvailable())
{
packet = ps.Read();
while (!packet.IsEndOfPacket())
{
switch (packet.ReadDataType())
{
case DataType.BoolType: bool boolValue = packet.ReadBool(); break;
case DataType.ByteArrayType: byte[] buffer = packet.ReadBytes(); break;
case DataType.ByteType: byte byteValue = packet.ReadByte(); break;
case DataType.CharType: char charValue = packet.ReadChar(); break;
case DataType.Int32Type: Console.WriteLine("Int32Type: " + packet.ReadInt32().ToString()); break;
case DataType.StringType: Console.WriteLine("String: " + packet.ReadString()); break;
default: break;
}
}
break;
}
System.Threading.Thread.Sleep(1000);
}
#endregion
}
}
catch (Exception ex)
{
throw ex;
}
finally { device.Disconnect(); }
}
Huh, you got the remote "GetRemoteAgent" working. Right?
I think i might know how to resolve what to call in to the packet. VS2010 talks to wp7, and uses one of those GUID's; meaning one should be able do binary search all files (in a rom) to see who owns the GUID (what dll handler), disassemble that dll (to ASM/c), and extract "what it wants".
Or if MS has a hidden caller class somewhere
Ill look further into this, thanks
fiinix said:
Huh, you got the remote "GetRemoteAgent" working. Right?
I think i might know how to resolve what to call in to the packet. VS2010 talks to wp7, and uses one of those GUID's; meaning one should be able do binary search all files (in a rom) to see who owns the GUID (what dll handler), disassemble that dll (to ASM/c), and extract "what it wants".
Or if MS has a hidden caller class somewhere
Ill look further into this, thanks
Click to expand...
Click to collapse
Yes I did . Yeah I just need to know what to actually send to to the device. I know Visual Studio communicates this way.
MJCS said:
Yes I did . Yeah I just need to know what to actually send to to the device. I know Visual Studio communicates this way.
Click to expand...
Click to collapse
Great
I, myself tried 20+ GUID's once (from wp7 that _could_ be); all threw exceptions (aka not a remote agent handler).
It feels better now knowing what GUID's i can use.
Well the reg path was quite obvious; why did i not stumble upon that one earlier..
fiinix said:
Great
I, myself tried 20+ GUID's once (from wp7 that _could_ be); all threw exceptions (aka not a remote agent handler).
It feels better now knowing what GUID's i can use.
Well the reg path was quite obvious; why did i not stumble upon that one earlier..
Click to expand...
Click to collapse
Well I only found it since I know have an HTC Radar. My Dell venue pro requires you to manually enter in registry paths to see if they exist or not. I was able to decompile an older HTC registry viewer and then fix it so it didnt require interop unlock.
It should be possible to do registry browsing (but not editing) just fine on a DVP using the standard tools, unless there's a check that specifically blocks them. The browsing uses a native homebrew DLL that doesn't require ID_CAP_INTEROPSERVICES and has no device-specific dependencies. It's the editing that requires interop-unlock and device-specific DLLs.
GoodDayToDie said:
It should be possible to do registry browsing (but not editing) just fine on a DVP using the standard tools, unless there's a check that specifically blocks them. The browsing uses a native homebrew DLL that doesn't require ID_CAP_INTEROPSERVICES and has no device-specific dependencies. It's the editing that requires interop-unlock and device-specific DLLs.
Click to expand...
Click to collapse
There is no GetSubKeys method...anyways lets get back on topic.
I've been trying for weeks to get anything out of this. Nothing so far. I did find out that the Developer unlock is just a byte array of a cookie taken from Microsoft's auth server.
Has anyone had any success with this socket method yet? I really don't know enough about sockets to try.
BTW you have to have a core con connection to the device already open either from app debugging or some other method
I'm developing a WP7 app, working alongside a Windows (server) application. They are talking with each other using sockets.
As soon as the WP7 app opens, I wish to perform a network scan to find the server application.
I already found out how to get the IP address of the WP7. So let's say I know the server should be somewhere at 192.168.0.*. How do I go about scanning this network?
I tried many things, the last of which is the code below. The problem here is that somehow the TIMEOUT_MILLISECONDS parameter seems to be like playing roulette (tried everything in the range of 100-2000 with different success). In addition, if I sweep the whole subnet like in the code below the phone cannot seem to handle the work. I only get it to work if I set the timeout to 2000 (which is way to long) and by scanning up to 5 IP's in the for-loop, instead of the whole subnet.
Is there anyone that knows a better and much more efficient(!) way to do this?
Code:
string thisIP = "192.168.0.101"; // I normally get this from some other function
string[] arrIP = thisIP.ToString().Split('.');
string IPBase = arrIP[0] + "." + arrIP[1] + "." + arrIP[2] + ".";
//MessageBox.Show(address.ToString());
for (int i = 2; i < 254; i++) {
string IP = IPBase + i;
CheckConnection CheckConn = new CheckConnection();
string resultConnect = CheckConn.Connect(IP, int.Parse(Resource1.port));
if (resultConnect == "Success") {
CheckConn.Send("isAlive");
string result = CheckConn.Receive();
if (result.Contains("yes")) {
// We have found the server
break;
}
}
CheckConn.Close();
}
Code:
public class CheckConnection
{
// Cached Socket object that will be used by each call for the lifetime of this class
Socket _socket = null;
static ManualResetEvent _clientDone = new ManualResetEvent(false);
const int TIMEOUT_MILLISECONDS = 100;
const int MAX_BUFFER_SIZE = 2048;
public string Connect(string hostName, int portNumber) {
string result = string.Empty;
DnsEndPoint hostEntry = new DnsEndPoint(hostName, portNumber);
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = hostEntry;
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e) {
result = e.SocketError.ToString();
_clientDone.Set();
});
_clientDone.Reset();
_socket.ConnectAsync(socketEventArg);
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
return result;
}
public string Send(string data) {
string response = "Operation Timeout";
if (_socket != null) {
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
socketEventArg.UserToken = null;
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e) {
response = e.SocketError.ToString();
_clientDone.Set();
});
byte[] payload = Encoding.UTF8.GetBytes(data);
socketEventArg.SetBuffer(payload, 0, payload.Length);
_clientDone.Reset();
_socket.SendAsync(socketEventArg);
// Block the UI thread for a maximum of TIMEOUT_MILLISECONDS seconds.
// If no response comes back within this time then proceed
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
}
else {
response = "Socket is not initialized";
}
return response;
}
public string Receive() {
string response = "Operation Timeout";
if (_socket != null) {
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e) {
if (e.SocketError == SocketError.Success) {
response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
response = response.Trim('\0');
}
else {
response = e.SocketError.ToString();
}
_clientDone.Set();
});
_clientDone.Reset();
_socket.ReceiveAsync(socketEventArg);
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
}
else {
response = "Socket is not initialized";
}
return response;
}
public void Close() {
if (_socket != null) {
_socket.Close();
}
}
}
Why you don't know the server IP?
I can't help you with your subnet scanning problem, don't have experience with that corner of WP7 programming.
But I do wonder what kind of arrangement leads to the problem that your app does not know the server address and therefore has to scan for it. Is neither a fixed IP available for your server nor some kind of DNS service up to tell you the current IP?
Even if there are multiple servers running and the phone has the job to somehow decide which one of those is responsible for it, you still could set up some kind of super-server that the phones could ask first which server they should address.
In any way, phones scanning subnets to find servers as some routine app startup action is a bad idea, if you ask me.
Please note that by 'server' I'm just revering to a software that accepts socket connections. This software is installed into a Windows computer that most likely has it's IP from DHCP.
The server software itself could present it's IP address so the end-user can type this address into the client on their WP7. Nice for tech-savvy folks, but that's not how software should be designed in my opinion. People don't need to know what an IP address is and shouldn't be force into typing 'weird numbers'. Properly designed software just have to work instantly and developers (again in my opinion) need to take care of a good design and that includes making things plug-and-play where they can.
Take a look at 'PC Remote' and you will see the kind of easy plug-and-play experience I'm looking for.
Did you check broadcast?
I'm really not network guy, but from Googling I got the impression that people use broadcast instead of IP range scanning for such IP number discovery tasks, and there seems to be a way to do broadcast on WP7 (albeit only using some tricks / hardly documented functionalilty):
E.g. see this thread:
http://stackoverflow.com/questions/8533471/udp-broadcasting-in-windows-phone-7
Which links to this:
http://forums.create.msdn.com/forums/t/88975.aspx
This makes sense to me after reading that broadcast is also the method how a client finds its DHCP server - isn't that the exact same scenario like yours?
Did you already check this way of looking at the problem, or maybe rule it out already for some reason?
It's better if you use a multicast group to send/receive packages. I had way better experience with it than using the Broadcast IP.
You need to join the multicast group with the phone and with the server app. I know there are multicast classes but I found it easier and mor convient to implement it with a socket...
And after you found the server, I'd use a persistent tcp connection which should improve your network performance (udp and wp7 is sometimes really strange...)
Thanks rbrunner7 and chabun for your comments, I appreciate your input!
rbrunner7 said:
Did you already check this way of looking at the problem, or maybe rule it out already for some reason?
Click to expand...
Click to collapse
I did, briefly, but abandoned this path after reading about the physical network equipment (switches etc.) having the need to support broadcasting which might not always be the case.
Anyway, your mentioned post describes 'limited broadcasting', which might be exactly what I should be looking for. Hopefully hardware limitations will not be applicable; I will look into this method further and will let you know how it works out!
roady001 said:
the physical network equipment (switches etc.) having the need to support broadcasting which might not always be the case.
Click to expand...
Click to collapse
I had the same doubts about that as it's also the case for multicasting. Most modern equipement supports it though and you can always provide the possibility to manually enter the server ip if you can't discover one via multicast/broadcast