27 Commits

Author SHA1 Message Date
farcasclaudiu c4438c87b0 Create README.md 2015-03-18 08:39:09 +02:00
farcasclaudiu 62dd116449 - handle GpsLocations events with Reactive Extensions 2011-05-27 11:40:30 +03:00
farcasclaudiu 1f79fa6349 - App check if running on device or emulator
- LocationString on update
- web app markers icons
2011-05-09 13:20:44 +03:00
farcasclaudiu 72c1bbdcfc Improve images caching
Improve error reporting
Implemented IsolatedStorageExplorer feature
2011-04-13 06:52:25 +03:00
farcasclaudiu a297460f37 friends caching
small improvements
2011-04-09 01:47:50 +03:00
farcasclaudiu 9c59a73113 fix list pick issue
clear GPS location on tombstoning resume
2011-04-06 08:49:07 +03:00
farcasclaudiu bf599907dc offline images
friends list / select
friend distance
2011-04-05 00:40:21 +03:00
farcasclaudiu f79ee0adc2 refactor LocationService 2011-04-04 18:22:03 +03:00
farcasclaudiu 2de2c2485e imrpovements 2011-04-04 09:47:17 +03:00
farcasclaudiu d70777bfec gps location and publish improvements 2011-04-04 05:09:50 +03:00
farcasclaudiu a9533b651c map issue fixed 2011-04-04 03:04:43 +03:00
farcasclaudiu fd9061e6c5 cleanup 2011-04-03 11:24:16 +03:00
farcasclaudiu c0d31a8652 map improvement
user picture
image crop
2011-03-31 06:24:59 +03:00
farcasclaudiu 833083ca0e Settings Page (in work)
Fixing Web hosting in Azure
2011-03-30 02:25:27 +03:00
farcasclaudiu 84642c37ad Up into the azure cloud 2011-03-29 05:43:32 +03:00
farcasclaudiu 7de756e3f0 Error reporting (via email)
fix Hammock rest error handling
2011-03-29 02:17:13 +03:00
farcasclaudiu 00f97e41d6 push notification helper library
http://windowsteamblog.com/windows_phone/b/wpdev/archive/2011/01/14/windows-push-notification-server-side-helper-library.aspx
http://create.msdn.com/en-us/education/catalog/article/pnhelp-wp7
2011-03-28 21:22:11 +03:00
farcasclaudiu a4c09735f0 textbox binding
refresh command
2011-03-28 09:34:32 +03:00
farcasclaudiu a25a7fb3fd tombstoning - saving and loadign from IsolateStorage 2011-03-25 13:47:13 +02:00
farcasclaudiu f069ee7010 IoC and NavigationService implementation 2011-03-25 11:22:57 +02:00
farcasclaudiu 98c8cf3f94 rule update 2011-03-24 22:47:31 +02:00
farcasclaudiu b566cae92d rules update 2011-03-24 22:46:20 +02:00
farcasclaudiu 8565c16206 Merge revisions 2011-03-24 22:41:24 +02:00
farcasclaudiu 6ff88738da update for excluding tests when not in testing mode 2011-03-24 22:34:22 +02:00
farcasclaudiu fd94eb6f05 merge 2011-03-24 10:41:14 +02:00
farcasclaudiu 8c674337c3 Added tag home for changeset 73eaf77c4d76 2011-03-24 10:24:14 +02:00
farcasclaudiu 3c434a0d06 Added tag tag1 for changeset 4c285537b335 2011-03-24 10:15:27 +02:00
324 changed files with 23525 additions and 1066 deletions
-1
View File
@@ -5,5 +5,4 @@ syntax: glob
*/obj/* */obj/*
*_ReSharper* *_ReSharper*
*/Bin/* */Bin/*
*/sql/debug/*
*.dbmdl *.dbmdl
+10
View File
@@ -0,0 +1,10 @@
# myfriendsaround
Application used on Windows Phone 7 presentation
within CodeCamp.Ro spring 2011 event.
http://codecamp.ro/post/2011/04/12/CodeCamp-Iasi-7-mai-2011.aspx
# myfriendsaround
Automatically exported from code.google.com/p/myfriendsaround
@@ -52,6 +52,23 @@
<CodeAnalysisRuleSetDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets</CodeAnalysisRuleSetDirectories> <CodeAnalysisRuleSetDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets</CodeAnalysisRuleSetDirectories>
<CodeAnalysisRuleDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules</CodeAnalysisRuleDirectories> <CodeAnalysisRuleDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules</CodeAnalysisRuleDirectories>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'GPS_EMULATOR|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\GPS_EMULATOR\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<CodeAnalysisLogFile>bin\Debug\GpsEmulator.exe.CodeAnalysisLog.xml</CodeAnalysisLogFile>
<CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>
<CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRuleSetDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets</CodeAnalysisRuleSetDirectories>
<CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisRuleDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules</CodeAnalysisRuleDirectories>
<CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>
<CodeAnalysisFailOnMissingRules>false</CodeAnalysisFailOnMissingRules>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.configuration" /> <Reference Include="System.configuration" />
@@ -43,7 +43,7 @@ namespace GpsEmulator
try try
{ {
// setup the GPS host service // setup the GPS host service
host = new ServiceHost(this, new Uri("http://localhost:8192/")); host = new ServiceHost(this, new Uri("http://localhost:9192/"));
host.AddServiceEndpoint(typeof(IGpsEmulatorService), new BasicHttpBinding(BasicHttpSecurityMode.None), "GpsEmulator"); host.AddServiceEndpoint(typeof(IGpsEmulatorService), new BasicHttpBinding(BasicHttpSecurityMode.None), "GpsEmulator");
host.Open(); host.Open();
} }
@@ -167,7 +167,7 @@ namespace GpsEmulatorClient
status = GeoPositionStatus.Initializing; status = GeoPositionStatus.Initializing;
client = new GpsEmulatorServiceClient( client = new GpsEmulatorServiceClient(
new BasicHttpBinding(BasicHttpSecurityMode.None), new BasicHttpBinding(BasicHttpSecurityMode.None),
new EndpointAddress("http://localhost:8192/GpsEmulator")); // change end point to real IP when testing on a real device new EndpointAddress("http://localhost:9192/GpsEmulator")); // change end point to real IP when testing on a real device
client.OpenCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_OpenCompleted); client.OpenCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_OpenCompleted);
client.GetCurrentPositionCompleted +=new EventHandler<GetCurrentPositionCompletedEventArgs>(client_GetCurrentPositionCompleted); client.GetCurrentPositionCompleted +=new EventHandler<GetCurrentPositionCompletedEventArgs>(client_GetCurrentPositionCompleted);
ICommunicationObject commObject = client as ICommunicationObject; ICommunicationObject commObject = client as ICommunicationObject;
@@ -55,6 +55,22 @@
<CodeAnalysisRuleSetDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets</CodeAnalysisRuleSetDirectories> <CodeAnalysisRuleSetDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets</CodeAnalysisRuleSetDirectories>
<CodeAnalysisRuleDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules</CodeAnalysisRuleDirectories> <CodeAnalysisRuleDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules</CodeAnalysisRuleDirectories>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'GPS_EMULATOR|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\GPS_EMULATOR\</OutputPath>
<DefineConstants>DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE</DefineConstants>
<NoStdLib>true</NoStdLib>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<CodeAnalysisLogFile>Bin\Debug\GpsEmulatorClient.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>
<CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>
<CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRuleSetDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets</CodeAnalysisRuleSetDirectories>
<CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisRuleDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules</CodeAnalysisRuleDirectories>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System.Device" /> <Reference Include="System.Device" />
<Reference Include="System.Runtime.Serialization" /> <Reference Include="System.Runtime.Serialization" />
@@ -9,7 +9,7 @@
</basicHttpBinding> </basicHttpBinding>
</bindings> </bindings>
<client> <client>
<endpoint address="http://localhost:8192/GpsEmulator" binding="basicHttpBinding" <endpoint address="http://localhost:9192/GpsEmulator" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IGpsEmulatorService" bindingConfiguration="BasicHttpBinding_IGpsEmulatorService"
contract="ServiceReference1.IGpsEmulatorService" name="BasicHttpBinding_IGpsEmulatorService" /> contract="ServiceReference1.IGpsEmulatorService" name="BasicHttpBinding_IGpsEmulatorService" />
</client> </client>
@@ -62,6 +62,23 @@
<CodeAnalysisRuleSetDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets</CodeAnalysisRuleSetDirectories> <CodeAnalysisRuleSetDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets</CodeAnalysisRuleSetDirectories>
<CodeAnalysisRuleDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules</CodeAnalysisRuleDirectories> <CodeAnalysisRuleDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules</CodeAnalysisRuleDirectories>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'GPS_EMULATOR|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\GPS_EMULATOR\</OutputPath>
<DefineConstants>DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE</DefineConstants>
<NoStdLib>true</NoStdLib>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<CodeAnalysisLogFile>Bin\Debug\GpsEmulatorPhoneTestClient.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>
<CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>
<CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRuleSetDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets</CodeAnalysisRuleSetDirectories>
<CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisRuleDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules</CodeAnalysisRuleDirectories>
<CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Microsoft.Phone" /> <Reference Include="Microsoft.Phone" />
<Reference Include="Microsoft.Phone.Interop" /> <Reference Include="Microsoft.Phone.Interop" />
@@ -1,9 +1,4 @@
///////////////////////////////////////////////////////////////////////////////////////// using System;
// define GPS EMULATOR when working with Windows Phone GPS Emulator to simulate location
#define GPS_EMULATOR
////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
@@ -14,6 +9,7 @@ using System.Windows.Input;
using System.Windows.Media; using System.Windows.Media;
using System.Windows.Media.Animation; using System.Windows.Media.Animation;
using System.Windows.Shapes; using System.Windows.Shapes;
using Microsoft.Devices;
using Microsoft.Phone.Controls; using Microsoft.Phone.Controls;
using GpsEmulatorClient; using GpsEmulatorClient;
using System.Device.Location; using System.Device.Location;
@@ -34,11 +30,14 @@ namespace GpsEmulatorPhoneTestClient
{ {
InitializeComponent(); InitializeComponent();
#if GPS_EMULATOR if (Microsoft.Devices.Environment.DeviceType == DeviceType.Emulator)
{
_Watcher = new GpsEmulatorClient.GeoCoordinateWatcher(); _Watcher = new GpsEmulatorClient.GeoCoordinateWatcher();
#else }
else
{
_Watcher = new System.Device.Location.GeoCoordinateWatcher(); _Watcher = new System.Device.Location.GeoCoordinateWatcher();
#endif }
_Watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged); _Watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
_Watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged); _Watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,8 @@
using System;
namespace MicroIoc
{
public class InjectAttribute : Attribute
{
}
}
@@ -0,0 +1,24 @@
using System;
namespace MicroIoc
{
public class ContainerConfiguration : IConfiguration
{
private readonly IMicroIocContainer _container;
public ContainerConfiguration(IMicroIocContainer container)
{
if (container == null)
throw new ArgumentNullException("container");
_container = container;
}
public IConfiguration Configure<T>(InjectedMemberBase injection)
{
var fullName = injection.DeriveFullName<T>();
_container.RegisterInstance(injection.MemberValue.GetType(), injection.MemberValue, fullName);
return this;
}
}
}
@@ -0,0 +1,7 @@
namespace MicroIoc
{
public interface IConfiguration
{
IConfiguration Configure<T>(InjectedMemberBase injection);
}
}
@@ -0,0 +1,16 @@
namespace MicroIoc
{
public class InjectedConstructorParam<T> : InjectedMemberBase
{
public InjectedConstructorParam(string name, T value)
{
MemberName = name;
MemberValue = value;
}
public override string DeriveFullName<TClass>()
{
return typeof (TClass).ConstructorParamPattern(MemberName);
}
}
}
@@ -0,0 +1,10 @@
namespace MicroIoc
{
public abstract class InjectedMemberBase
{
public string MemberName { get; set; }
public object MemberValue { get; set; }
public abstract string DeriveFullName<T>();
}
}
@@ -0,0 +1,16 @@
namespace MicroIoc
{
public class InjectedProperty<T> : InjectedMemberBase
{
public InjectedProperty(string name, T value)
{
MemberName = name;
MemberValue = value;
}
public override string DeriveFullName<TClass>()
{
return typeof(TClass).PropertyPattern(MemberName);
}
}
}
@@ -0,0 +1,104 @@
using System;
using System.Collections.Generic;
namespace MicroIoc
{
public interface IMicroIocContainer
{
/// <summary>
/// Register a type within the container. Useful when registering a type by key, so calls to Resolve(null, key) will work
/// </summary>
/// <typeparam name="T">The type of class being registered</typeparam>
/// <param name="key">If specified, will associate a specific instance for this type</param>
/// <param name="isSingleton">Indicates if the registration should yield a singleton object when resolved</param>
/// <returns>The container, complete with new registration</returns>
IMicroIocContainer Register<T>(string key = null, bool isSingleton = false);
/// <summary>
/// Register an implementation type against an interface or class
/// </summary>
/// <typeparam name="TFrom">The type of interface or class to be registered</typeparam>
/// <typeparam name="TTo">The type of concrete class to be instantiated when <see cref="TFrom" /> is resolved from the container.</typeparam>
/// <param name="key">If specified, will associate a specific instance for this type</param>
/// <param name="isSingleton">Indicates if the registration should yield a singleton object when resolved</param>
/// <returns>The container, complete with new registration</returns>
IMicroIocContainer Register<TFrom, TTo>(string key = null, bool isSingleton = false) where TTo : TFrom;
/// <summary>
/// Register a specific instance of a concrete implementation for an interface or class
/// </summary>
/// <typeparam name="TInterface">The type of interface or class to be registered</typeparam>
/// <param name="instance">The instance to register in the container</param>
/// <param name="key">(Optional) a key to specify the instance within the container</param>
/// <returns>The container, complete with new registration</returns>
IMicroIocContainer RegisterInstance<TInterface>(TInterface instance, string key = null);
/// <summary>
/// Register a specific instance of a concrete implementation for an interface or class
/// </summary>
/// <param name="type">The type of interface or class to be registered</param>
/// <param name="instance">The instance to register in the container</param>
/// <param name="key">(Optional) a key to specify the instance within the container</param>
/// <returns>The container, complete with new registration</returns>
IMicroIocContainer RegisterInstance(Type type, object instance, string key = null);
/// <summary>
/// Resolve an instance of the specified interface (or class) Type
/// </summary>
/// <typeparam name="T">The type of interface or class to be resolved</typeparam>
/// <param name="key">(Optional) a key to specify the instance within the container</param>
/// <returns>The registered instance if key is specified, or a dynamically instantiated instance, if not</returns>
T Resolve<T>(string key = null);
/// <summary>
/// Try to resolve an instance of the specified interface (or class) Type
/// </summary>
/// <typeparam name="T">The type of interface or class to be resolved</typeparam>
/// <param name="key">(Optional) a key to specify the instance within the container</param>
/// <returns>An instance of <typeparamref name="T"/> if registered, or null</returns>
T TryResolve<T>(string key = null) where T : class;
/// <summary>
/// Resolve an instance of the specified interface (or class) Type
/// </summary>
/// <param name="type">The type of interface or class to be resolved</param>
/// <param name="key">(Optional) a key to specify the instance within the container</param>
/// <returns>The registered instance if key is specified, or a dynamically instantiated instance, if not</returns>
object Resolve(Type type, string key = null);
/// <summary>
/// Try to resolve an instance of the specified interface (or class) Type
/// </summary>
/// <param name="type">The type of interface or class to be resolved</param>
/// <param name="key">(Optional) a key to specify the instance within the container</param>
/// <returns>An instance of if registered, or null</returns>
object TryResolve(Type type, string key = null);
/// <summary>
/// Resolve all registered instances of a specified type
/// </summary>
/// <typeparam name="T">The type of interface or class to be resolved</typeparam>
/// <returns>A collection of registered instances. If no instances are registered, returns empty collection, not null</returns>
IEnumerable<T> ResolveAll<T>();
/// <summary>
/// Resolve all registered instances of a specified type
/// </summary>
/// <param name="type">The type of interface or class to be resolved</param>
/// <returns>A collection of registered instances. If no instances are registered, returns empty collection, not null</returns>
IEnumerable<object> ResolveAll(Type type);
/// <summary>
///
/// </summary>
/// <returns></returns>
IConfiguration GetConfiguration();
/// <summary>
/// Create an instance with properties from the container.
/// Only properties attributed [Inject] will be set.
/// </summary>
/// <param name="instance"></param>
void BuildUp(object instance);
}
}
@@ -0,0 +1,299 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using MicroIoc;
namespace MicroIoc
{
public class MicroIocContainer : IMicroIocContainer
{
private readonly Dictionary<Tuple<Type, string>, Func<object>> _resolverDictionary
= new Dictionary<Tuple<Type, string>, Func<object>>();
private readonly IList<Type> _registeredSingletons
= new List<Type>();
private readonly Dictionary<Type, object> _singletonInstances
= new Dictionary<Type, object>();
private static readonly string CollectionDefaultKey = Guid.NewGuid().ToString();
#region Register
/// <summary>
/// Register a type within the container. Useful when registering a type by key, so calls to Resolve(null, key) will work
/// </summary>
/// <typeparam name="T">The type of class being registered</typeparam>
/// <param name="key">If specified, will associate a specific instance for this type</param>
/// <param name="isSingleton">Indicates if the registration should yield a singleton object when resolved</param>
/// <returns>The container, complete with new registration</returns>
public IMicroIocContainer Register<T>(string key = null, bool isSingleton = false)
{
return Register<T, T>(key, isSingleton);
}
/// <summary>
/// Register an implementation type against an interface or class
/// </summary>
/// <typeparam name="TFrom">The type of interface or class to be registered</typeparam>
/// <typeparam name="TTo">The type of concrete class to be instantiated when <see cref="TFrom" /> is resolved from the container.</typeparam>
/// <returns>The container, complete with new registration</returns>
public IMicroIocContainer Register<TFrom, TTo>(string key = null, bool isSingleton = false) where TTo : TFrom
{
key = ValueOrDefault(key);
var fromType = typeof(TFrom);
var toType = typeof(TTo);
if (isSingleton)
_registeredSingletons.Add(toType);
_resolverDictionary[new Tuple<Type, string>(fromType, key)] = () => BuildFromType(toType);
return this;
}
/// <summary>
/// Register a specific instance of a concrete implementation for an interface or class
/// </summary>
/// <typeparam name="TInterface">The type of interface or class to be registered</typeparam>
/// <param name="instance">The instance to register in the container</param>
/// <param name="key">(Optional) a key to specify the instance within the container</param>
/// <returns>The container, complete with new registration</returns>
public IMicroIocContainer RegisterInstance<TInterface>(TInterface instance, string key = null)
{
return RegisterInstance(typeof (TInterface), instance, key);
}
public IMicroIocContainer RegisterInstance(Type type, object instance, string key=null)
{
key = ValueOrDefault(key);
_resolverDictionary[new Tuple<Type, string>(type, key)] = () => instance;
return this;
}
#endregion
#region Resolve
/// <summary>
/// Resolve an instance of the specified interface (or class) Type
/// </summary>
/// <typeparam name="T">The type of interface or class to be resolved</typeparam>
/// <param name="key">(Optional) a key to specify the instance within the container</param>
/// <returns>The registered instance if key is specified, or a dynamically instantiated instance, if not</returns>
public T Resolve<T>(string key = null)
{
return (T) Resolve(typeof (T), key);
}
/// <summary>
/// Try to resolve an instance of the specified interface (or class) Type
/// </summary>
/// <typeparam name="T">The type of interface or class to be resolved</typeparam>
/// <param name="key">(Optional) a key to specify the instance within the container</param>
/// <returns>An instance of <typeparamref name="T"/> if registered, or null</returns>
public T TryResolve<T>(string key) where T : class
{
return (T) TryResolve(typeof (T), key);
}
/// <summary>
/// Resolve an instance of the specified interface (or class) Type
/// </summary>
/// <param name="type">The type of interface or class to be resolved</param>
/// <param name="key">(Optional) a key to specify the instance within the container</param>
/// <returns>The registered instance if key is specified, or a dynamically instantiated instance, if not</returns>
public object Resolve(Type type, string key = null)
{
var result = ResolveCore(type, key);
BuildUp(result);
return result;
}
/// <summary>
/// Try to resolve an instance of the specified interface (or class) Type
/// </summary>
/// <param name="type">The type of interface or class to be resolved</param>
/// <param name="key">(Optional) a key to specify the instance within the container</param>
/// <returns>An instance of if registered, or null</returns>
public object TryResolve(Type type, string key)
{
try
{
return Resolve(type, key);
}
catch
{
return null;
}
}
/// <summary>
/// Resolve all registered instances of a specified type
/// </summary>
/// <typeparam name="T">The type of interface or class to be resolved</typeparam>
/// <returns>A collection of registered instances. If no instances are registered, returns empty collection, not null</returns>
public IEnumerable<T> ResolveAll<T>()
{
var allObjects = ResolveAll(typeof (T));
return allObjects.Select(obj => (T) obj);
}
/// <summary>
/// Resolve all registered instances of a specified type
/// </summary>
/// <param name="type">The type of interface or class to be resolved</param>
/// <returns>A collection of registered instances. If no instances are registered, returns empty collection, not null</returns>
public IEnumerable<object> ResolveAll(Type type)
{
return _resolverDictionary.Keys
.Where(key => key.Item1 == type)
.Select(t => _resolverDictionary[t]());
}
#endregion
/// <summary>
/// Create an instance with properties from the container.
/// Only properties attributed [Inject] will be set.
/// </summary>
/// <param name="instance"></param>
public void BuildUp(object instance)
{
var propertyInfoCollection = instance.GetType().GetProperties();
foreach (var propertyInfo in propertyInfoCollection)
{
var info = propertyInfo;
if (!info.GetCustomAttributes(typeof(InjectAttribute), false).Any()) continue;
object property = null;
try
{
var fullPropertyName = string.Format("{0}.{1}", instance.GetType().FullName, info.Name);
property = Resolve(null, fullPropertyName);
}
catch (Exception)
{
property = Resolve(info.PropertyType);
}
finally
{
info.SetValue(instance, property, null);
}
}
}
public IConfiguration GetConfiguration()
{
return new ContainerConfiguration(this);
}
#region Private helper methods
private object ResolveCore(Type type, string key)
{
if (type == null)
{
type = DeriveType(key);
if (type == null)
throw new ResolutionException("Failed to Derive type for " + key);
}
key = ValueOrDefault(key);
return _resolverDictionary.ContainsKey(new Tuple<Type, string>(type, key))
? _resolverDictionary[new Tuple<Type, string>(type, key)]()
: BuildFromType(type);
}
private Type DeriveType(string key)
{
var result = GetTypeFromContainer(key);
if (result != null) return result;
// Not in the container? Try the Assembly
return Assembly.GetExecutingAssembly()
.GetTypes()
.SingleOrDefault(t => t.Name == key);
}
private Type GetTypeFromContainer(string key)
{
var tuple = _resolverDictionary
.Keys
.FirstOrDefault(t => t.Item2 == key);
return (tuple == null)
? null
: tuple.Item1;
}
private object BuildFromType(Type type)
{
if (_registeredSingletons.Contains(type))
{
object instance;
if (_singletonInstances.TryGetValue(type, out instance))
return instance;
instance = InstantiateInstance(type);
_singletonInstances[type] = instance;
return instance;
}
return InstantiateInstance(type);
}
private object InstantiateInstance(Type type)
{
var constructor = type.GetConstructors()
.OrderByDescending(c => c.GetParameters().Length)
.FirstOrDefault();
if (constructor == null)
throw new ResolutionException("Could not locate a constructor for " + type.FullName);
var constructorParams = new List<object>(constructor.GetParameters().Length);
foreach (var parameterInfo in constructor.GetParameters())
{
object parameter=null;
try
{
string key = type.ConstructorParamPattern(parameterInfo.Name);
parameter = Resolve(null, key);
}
catch (Exception)
{
parameter = Resolve(parameterInfo.ParameterType);
}
finally
{
constructorParams.Add(parameter);
}
}
try
{
return constructor.Invoke(constructorParams.ToArray());
}
catch (Exception exception)
{
throw new ResolutionException("Failed to resolve " + type.Name, exception);
}
}
private static string ValueOrDefault(string key)
{
if (key != null) key = key.Trim();
return string.IsNullOrEmpty(key)
? CollectionDefaultKey
: key;
}
#endregion
}
}
@@ -0,0 +1,13 @@
using System;
namespace MicroIoc
{
public class ResolutionException : Exception
{
public ResolutionException(string message)
: base(message) { }
public ResolutionException(string message, Exception innerException)
: base(message, innerException) { }
}
}
@@ -0,0 +1,37 @@
using System;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using MicroIoc;
using System.Linq.Expressions;
namespace MicroIoc
{
public static class ConfigurationExtensions
{
public static IConfiguration Property<T, TProp>(this IConfiguration configuration, Expression<Func<T, TProp>> propertyExpression, TProp value)
{
var memberExpression = propertyExpression.Body as MemberExpression;
if (memberExpression == null)
throw new ArgumentException("propertyExpression is not a valid member expression");
var propertyInfo = memberExpression.Member as PropertyInfo;
if (propertyInfo == null)
throw new ArgumentException("propertyExpression is not a valid property on the class");
return configuration.Configure<T>(new InjectedProperty<TProp>(propertyInfo.Name, value));
}
public static IConfiguration ConstructorParam<T, TParam>(this IConfiguration configuration, string name, TParam value)
{
return configuration.Configure<T>(new InjectedConstructorParam<TParam>(name, value));
}
}
}
@@ -0,0 +1,17 @@
using System;
namespace MicroIoc
{
public static class PatternExtensions
{
public static string PropertyPattern(this Type type, string memberName)
{
return type.FullName + "." + memberName;
}
public static string ConstructorParamPattern(this Type type, string memberName)
{
return type.FullName + "#" + memberName;
}
}
}
@@ -0,0 +1,91 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.20506</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{23F63AE9-A436-4B27-9113-4142C09ADD08}</ProjectGuid>
<ProjectTypeGuids>{C089C8C0-30E0-4E22-80C0-CE093F111A43};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MicroIoc</RootNamespace>
<AssemblyName>MicroIoc</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<SilverlightVersion>$(TargetFrameworkVersion)</SilverlightVersion>
<TargetFrameworkProfile>WindowsPhone</TargetFrameworkProfile>
<TargetFrameworkIdentifier>Silverlight</TargetFrameworkIdentifier>
<SilverlightApplication>false</SilverlightApplication>
<ValidateXaml>true</ValidateXaml>
<ThrowErrorsInValidation>true</ThrowErrorsInValidation>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>Bin\Debug</OutputPath>
<DefineConstants>DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE</DefineConstants>
<NoStdLib>true</NoStdLib>
<NoConfig>true</NoConfig>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>Bin\Release</OutputPath>
<DefineConstants>TRACE;SILVERLIGHT;WINDOWS_PHONE</DefineConstants>
<NoStdLib>true</NoStdLib>
<NoConfig>true</NoConfig>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'GPS_EMULATOR|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\GPS_EMULATOR\</OutputPath>
<DefineConstants>DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE</DefineConstants>
<NoStdLib>true</NoStdLib>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<CodeAnalysisLogFile>Bin\Debug\MicroIoc.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>
<CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>
<CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRuleSetDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets</CodeAnalysisRuleSetDirectories>
<CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisRuleDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules</CodeAnalysisRuleDirectories>
</PropertyGroup>
<ItemGroup>
<Reference Include="System.Windows" />
<Reference Include="system" />
<Reference Include="System.Core" />
<Reference Include="System.Xml" />
<Reference Include="System.Net" />
</ItemGroup>
<ItemGroup>
<Compile Include="Configuration\ContainerConfiguration.cs" />
<Compile Include="Configuration\IConfiguration.cs" />
<Compile Include="Configuration\InjectedConstructorParam.cs" />
<Compile Include="Configuration\InjectedMemberBase.cs" />
<Compile Include="Configuration\InjectedProperty.cs" />
<Compile Include="Container\IMicroIocContainer.cs" />
<Compile Include="Attributes\InjectAttribute.cs" />
<Compile Include="Container\MicroIocContainer.cs" />
<Compile Include="Extensions\ConfigurationExtensions.cs" />
<Compile Include="Extensions\PatternExtensions.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Exceptions\ResolutionException.cs" />
<Compile Include="Tuple.cs" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.$(TargetFrameworkProfile).Overrides.targets" />
<Import Project="$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.CSharp.targets" />
<ProjectExtensions />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
@@ -0,0 +1,35 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MicroIoc")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("MicroIoc")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("dafbba88-e0f6-4b77-94de-a70fdf20bf46")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
+52
View File
@@ -0,0 +1,52 @@
namespace MicroIoc
{
public class Tuple<T1, T2>
{
public Tuple(T1 item1, T2 item2)
{
Item1 = item1;
Item2 = item2;
}
public T1 Item1 { get; private set; }
public T2 Item2 { get; private set; }
public bool Equals(Tuple<T1, T2> other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Equals(other.Item1, Item1) && Equals(other.Item2, Item2);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != typeof(Tuple<T1, T2>))
{
return false;
}
return Equals((Tuple<T1, T2>)obj);
}
public override int GetHashCode()
{
unchecked
{
return (Item1.GetHashCode() * 397) ^ Item2.GetHashCode();
}
}
}
}
@@ -0,0 +1,38 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetworkAwarenessTest", "NetworkAwarenessTest\NetworkAwarenessTest.csproj", "{27C10B97-20D1-46F7-92BF-FC07037F900E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetworkDetection", "NetworkDetection\NetworkDetection.csproj", "{794D79F0-E898-460D-BDB5-49FED553E0D5}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetworkNamespaces", "NetworkNamespaces\NetworkNamespaces.csproj", "{41A5C85F-7E30-418B-BAD2-AB2F40FF22CF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{27C10B97-20D1-46F7-92BF-FC07037F900E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{27C10B97-20D1-46F7-92BF-FC07037F900E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{27C10B97-20D1-46F7-92BF-FC07037F900E}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
{27C10B97-20D1-46F7-92BF-FC07037F900E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{27C10B97-20D1-46F7-92BF-FC07037F900E}.Release|Any CPU.Build.0 = Release|Any CPU
{27C10B97-20D1-46F7-92BF-FC07037F900E}.Release|Any CPU.Deploy.0 = Release|Any CPU
{794D79F0-E898-460D-BDB5-49FED553E0D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{794D79F0-E898-460D-BDB5-49FED553E0D5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{794D79F0-E898-460D-BDB5-49FED553E0D5}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
{794D79F0-E898-460D-BDB5-49FED553E0D5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{794D79F0-E898-460D-BDB5-49FED553E0D5}.Release|Any CPU.Build.0 = Release|Any CPU
{794D79F0-E898-460D-BDB5-49FED553E0D5}.Release|Any CPU.Deploy.0 = Release|Any CPU
{41A5C85F-7E30-418B-BAD2-AB2F40FF22CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{41A5C85F-7E30-418B-BAD2-AB2F40FF22CF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{41A5C85F-7E30-418B-BAD2-AB2F40FF22CF}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
{41A5C85F-7E30-418B-BAD2-AB2F40FF22CF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{41A5C85F-7E30-418B-BAD2-AB2F40FF22CF}.Release|Any CPU.Build.0 = Release|Any CPU
{41A5C85F-7E30-418B-BAD2-AB2F40FF22CF}.Release|Any CPU.Deploy.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
@@ -0,0 +1,19 @@
<Application
x:Class="NetworkAwarenessTest.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone">
<!--Application Resources-->
<Application.Resources>
</Application.Resources>
<Application.ApplicationLifetimeObjects>
<!--Required object that handles lifetime events for the application-->
<shell:PhoneApplicationService
Launching="Application_Launching" Closing="Application_Closing"
Activated="Application_Activated" Deactivated="Application_Deactivated"/>
</Application.ApplicationLifetimeObjects>
</Application>
@@ -0,0 +1,136 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
namespace NetworkAwarenessTest
{
public partial class App : Application
{
/// <summary>
/// Provides easy access to the root frame of the Phone Application.
/// </summary>
/// <returns>The root frame of the Phone Application.</returns>
public PhoneApplicationFrame RootFrame { get; private set; }
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Show graphics profiling information while debugging.
if (System.Diagnostics.Debugger.IsAttached)
{
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are being GPU accelerated with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
}
// Standard Silverlight initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
}
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
#region Phone application initialization
// Avoid double-initialization
private bool phoneApplicationInitialized = false;
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
// Do not add any additional code to this method
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
#endregion
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

@@ -0,0 +1,50 @@
<phone:PhoneApplicationPage
x:Class="NetworkAwarenessTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="NETWORK AWARENESS AND ZUNE DETECTION" Style="{StaticResource PhoneTextNormalStyle}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox Height="556" HorizontalAlignment="Left" Margin="6,134,0,0" Name="listBox1" VerticalAlignment="Top" Width="444" />
<Button Content="Refresh" Height="72" HorizontalAlignment="Left" Name="buttonRefresh" VerticalAlignment="Top" Width="220" Click="buttonRefresh_Click" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="6,78,0,0" Name="textBlock1" Text="UI Responsiveness Progressbar" VerticalAlignment="Top" />
<Button Content="Add Time" Height="72" HorizontalAlignment="Left" Margin="226,0,0,0" Name="buttonTime" VerticalAlignment="Top" Width="230" Click="buttonTime_Click" />
</Grid>
<ProgressBar IsIndeterminate="True" Height="27" HorizontalAlignment="Left" Margin="18,101,0,0" Name="progressBar1" VerticalAlignment="Top" Width="444" Grid.Row="1" />
</Grid>
<!--Sample code showing usage of ApplicationBar-->
<!--<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
<shell:ApplicationBar.MenuItems>
<shell:ApplicationBarMenuItem Text="MenuItem 1"/>
<shell:ApplicationBarMenuItem Text="MenuItem 2"/>
</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>-->
</phone:PhoneApplicationPage>
@@ -0,0 +1,112 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
namespace NetworkAwarenessTest
{
public partial class MainPage : PhoneApplicationPage
{
string NetType = "";
bool online = false;
// Constructor
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
Unloaded += new RoutedEventHandler(MainPage_Unloaded);
}
void MainPage_Unloaded(object sender, RoutedEventArgs e)
{
System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged -= new System.Net.NetworkInformation.NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
listBox1.Items.Insert(0, ">>> Refresh Started " + System.DateTime.Now.ToString("T") + " >>>>>>>>");
Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType net = Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType;
NetType = net.ToString();
listBox1.Items.Insert(1," Refresh Ended " + System.DateTime.Now.ToString("T"));
listBox1.Items.Insert(2, " stored at Changed event: " + NetType);
listBox1.Items.Insert(3, " Current status: " + net.ToString());
if (net == Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Ethernet) listBox1.Items.Insert(4, "!!!!! Zune is Connected");
SetupNetworkChange();
}
void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
{
listBox1.Items.Insert(0, "+++++ Changed started " + System.DateTime.Now.ToString("T") + " +++++");
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
if (!online)
{
online = true;
// do what is needed to GoOnline();
}
}
else
{
if (online)
{
online = false;
listBox1.Items.Insert(0, "----- No network available. -----");
// do what is needed to GoOffline();
}
}
listBox1.Items.Insert(1, " Changed GetNetType " + System.DateTime.Now.ToString("T"));
Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType net = Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType;
NetType = net.ToString();
listBox1.Items.Insert(2, " Changed Ended " + System.DateTime.Now.ToString("T"));
listBox1.Items.Insert(3, " IsOnline : " + online.ToString());
listBox1.Items.Insert(4, " Current status: " + net.ToString());
if (net == Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Ethernet) listBox1.Items.Insert(5,"!!!!! Zune is Connected");
}
private void SetupNetworkChange()
{
// Get current network availalability and store the
// initial value of the online variable
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
online = true;
// do what is needed to GoOnline();
}
else
{
online = false;
// do what is needed to GoOffline();
}
// Now add a network change event handler to indicate
// network availability
System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged += new System.Net.NetworkInformation.NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
}
private void buttonRefresh_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Insert(0, ">>> Refresh Started " + System.DateTime.Now.ToString("T") + " >>>>>>>>");
Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType net = Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType;
//MessageBox.Show("Current status: "+net.ToString(), "stored nettype:" + App.NetType, MessageBoxButton.OK);
listBox1.Items.Insert(1, " Refresh Ended " + System.DateTime.Now.ToString("T"));
listBox1.Items.Insert(2," stored at Changed event: " + NetType);
listBox1.Items.Insert(3, " Current status: " + net.ToString());
}
private void buttonTime_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Insert(0, "<<<<< Current Time " + System.DateTime.Now.ToString("T") + " <<<<<<<<<");
}
}
}
@@ -0,0 +1,101 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.20506</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{27C10B97-20D1-46F7-92BF-FC07037F900E}</ProjectGuid>
<ProjectTypeGuids>{C089C8C0-30E0-4E22-80C0-CE093F111A43};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>NetworkAwarenessTest</RootNamespace>
<AssemblyName>NetworkAwarenessTest</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<SilverlightVersion>$(TargetFrameworkVersion)</SilverlightVersion>
<TargetFrameworkProfile>WindowsPhone</TargetFrameworkProfile>
<TargetFrameworkIdentifier>Silverlight</TargetFrameworkIdentifier>
<SilverlightApplication>true</SilverlightApplication>
<SupportedCultures>
</SupportedCultures>
<XapOutputs>true</XapOutputs>
<GenerateSilverlightManifest>true</GenerateSilverlightManifest>
<XapFilename>NetworkAwarenessTest.xap</XapFilename>
<SilverlightManifestTemplate>Properties\AppManifest.xml</SilverlightManifestTemplate>
<SilverlightAppEntry>NetworkAwarenessTest.App</SilverlightAppEntry>
<ValidateXaml>true</ValidateXaml>
<ThrowErrorsInValidation>true</ThrowErrorsInValidation>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>Bin\Debug</OutputPath>
<DefineConstants>DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE</DefineConstants>
<NoStdLib>true</NoStdLib>
<NoConfig>true</NoConfig>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>Bin\Release</OutputPath>
<DefineConstants>TRACE;SILVERLIGHT;WINDOWS_PHONE</DefineConstants>
<NoStdLib>true</NoStdLib>
<NoConfig>true</NoConfig>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Phone" />
<Reference Include="Microsoft.Phone.Interop" />
<Reference Include="System.Windows" />
<Reference Include="system" />
<Reference Include="System.Core" />
<Reference Include="System.Net" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
</Compile>
<Compile Include="MainPage.xaml.cs">
<DependentUpon>MainPage.xaml</DependentUpon>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="App.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</ApplicationDefinition>
<Page Include="MainPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
</ItemGroup>
<ItemGroup>
<None Include="Properties\AppManifest.xml" />
<None Include="Properties\WMAppManifest.xml" />
</ItemGroup>
<ItemGroup>
<Content Include="ApplicationIcon.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="Background.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="SplashScreenImage.jpg" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.$(TargetFrameworkProfile).Overrides.targets" />
<Import Project="$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
<ProjectExtensions />
</Project>
@@ -0,0 +1,6 @@
<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<Deployment.Parts>
</Deployment.Parts>
</Deployment>
@@ -5,12 +5,12 @@ using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information // set of attributes. Change these attribute values to modify the information
// associated with an assembly. // associated with an assembly.
[assembly: AssemblyTitle("MyFriendsAround.Web.Tests")] [assembly: AssemblyTitle("NetworkAwarenessTest")]
[assembly: AssemblyDescription("")] [assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")] [assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("MyFriendsAround.Web.Tests")] [assembly: AssemblyProduct("NetworkAwarenessTest")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] [assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")] [assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")] [assembly: AssemblyCulture("")]
@@ -20,7 +20,7 @@ using System.Runtime.InteropServices;
[assembly: ComVisible(false)] [assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM // The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f496bfd5-1473-4070-bbed-57cd23844621")] [assembly: Guid("59705a9b-da65-482a-8c30-552b5622a972")]
// Version information for an assembly consists of the following four values: // Version information for an assembly consists of the following four values:
// //
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2009/deployment" AppPlatformVersion="7.0">
<App xmlns="" ProductID="{357f9fb2-82b9-4758-a63a-af9dcda19dc0}" Title="NetworkAwarenessTest" RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal" Author="NetworkAwarenessTest author" Description="Sample description" Publisher="NetworkAwarenessTest">
<IconPath IsRelative="true" IsResource="false">ApplicationIcon.png</IconPath>
<Capabilities>
<Capability Name="ID_CAP_GAMERSERVICES"/>
<Capability Name="ID_CAP_IDENTITY_DEVICE"/>
<Capability Name="ID_CAP_IDENTITY_USER"/>
<Capability Name="ID_CAP_LOCATION"/>
<Capability Name="ID_CAP_MEDIALIB"/>
<Capability Name="ID_CAP_MICROPHONE"/>
<Capability Name="ID_CAP_NETWORKING"/>
<Capability Name="ID_CAP_PHONEDIALER"/>
<Capability Name="ID_CAP_PUSH_NOTIFICATION"/>
<Capability Name="ID_CAP_SENSORS"/>
<Capability Name="ID_CAP_WEBBROWSERCOMPONENT"/>
</Capabilities>
<Tasks>
<DefaultTask Name ="_default" NavigationPage="MainPage.xaml"/>
</Tasks>
<Tokens>
<PrimaryToken TokenID="NetworkAwarenessTestToken" TaskName="_default">
<TemplateType5>
<BackgroundImageURI IsRelative="true" IsResource="false">Background.png</BackgroundImageURI>
<Count>0</Count>
<Title>NetworkAwarenessTest</Title>
</TemplateType5>
</PrimaryToken>
</Tokens>
</App>
</Deployment>
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

@@ -0,0 +1,19 @@
<Application
x:Class="NetworkDetection.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone">
<!--Application Resources-->
<Application.Resources>
</Application.Resources>
<Application.ApplicationLifetimeObjects>
<!--Required object that handles lifetime events for the application-->
<shell:PhoneApplicationService
Launching="Application_Launching" Closing="Application_Closing"
Activated="Application_Activated" Deactivated="Application_Deactivated"/>
</Application.ApplicationLifetimeObjects>
</Application>
@@ -0,0 +1,139 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
namespace NetworkDetection
{
public partial class App : Application
{
/// <summary>
/// Provides easy access to the root frame of the Phone Application.
/// </summary>
/// <returns>The root frame of the Phone Application.</returns>
public PhoneApplicationFrame RootFrame { get; private set; }
//NetworkDetector nd;
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Show graphics profiling information while debugging.
if (System.Diagnostics.Debugger.IsAttached)
{
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are being GPU accelerated with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
}
// Standard Silverlight initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
}
NetworkDetector nd;
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
nd = NetworkDetector.Instance;
}
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
nd = NetworkDetector.Instance;
}
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
#region Phone application initialization
// Avoid double-initialization
private bool phoneApplicationInitialized = false;
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
// Do not add any additional code to this method
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
#endregion
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

@@ -0,0 +1,56 @@
<phone:PhoneApplicationPage
x:Class="NetworkDetection.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="44"/>
<RowDefinition Height="724*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Margin="12,17,0,0">
<TextBlock x:Name="ApplicationTitle" Text="NETWORK AWARENESS AND ZUNE DETECTION" Style="{StaticResource PhoneTextNormalStyle}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox Height="532" HorizontalAlignment="Left" Margin="6,186,0,0" Name="listBox1" VerticalAlignment="Top" Width="444" />
<Button Content="DF" Height="72" HorizontalAlignment="Left" Name="buttonMode" VerticalAlignment="Top" Width="102" Margin="290,64,0,0" Click="buttonMode_Click" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="6,130,0,0" Name="textBlock1" Text="UI Responsiveness Progressbar" VerticalAlignment="Top" />
<Button Content="T" Height="72" HorizontalAlignment="Left" Margin="374,0,0,0" Name="buttonTime" VerticalAlignment="Top" Width="82" Click="buttonTime_Click" />
<Button Content="Stop Poll" Height="72" HorizontalAlignment="Left" Margin="142,0,0,0" Name="buttonStoppPoll" VerticalAlignment="Top" Width="163" Click="buttonStoppPoll_Click" />
<Button Content="Start Poll" Height="72" HorizontalAlignment="Left" Name="buttonStartPoll" VerticalAlignment="Top" Width="161" Click="buttonStartPoll_Click" />
<Button Content="Clr" Height="72" HorizontalAlignment="Left" Margin="290,0,0,0" Name="buttonClear" VerticalAlignment="Top" Width="102" Click="buttonClear_Click" />
<Button Content="+ 100 mS" Height="72" HorizontalAlignment="Left" Margin="0,64,0,0" Name="buttonIncrease" VerticalAlignment="Top" Width="161" Click="buttonIncrease_Click" />
<Button Content="- 100 mS" Height="72" HorizontalAlignment="Left" Margin="142,64,0,0" Name="buttonDecrease" VerticalAlignment="Top" Width="163" Click="buttonDecrease_Click" />
<ProgressBar IsIndeterminate="True" Height="27" HorizontalAlignment="Left" Margin="6,153,0,0" Name="progressBar1" VerticalAlignment="Top" Width="444" />
<Button Content="R" Height="72" HorizontalAlignment="Left" Margin="374,64,0,0" Name="buttonRefresh" VerticalAlignment="Top" Width="81" Click="buttonRefresh_Click" />
</Grid>
</Grid>
<!--Sample code showing usage of ApplicationBar-->
<!--<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
<shell:ApplicationBar.MenuItems>
<shell:ApplicationBarMenuItem Text="MenuItem 1"/>
<shell:ApplicationBarMenuItem Text="MenuItem 2"/>
</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>-->
</phone:PhoneApplicationPage>
@@ -0,0 +1,165 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
namespace NetworkDetection
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
NetworkDetector nd = NetworkDetector.Instance;
int interval = 500;
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
nd.OnAsyncGetNetworkTypeCompleted += new EventHandler<NetworkDetectorEventArgs>(nd_OnAsyncGetNetworkTypeCompleted);
nd.OnConnectedBroadbandCdma += new EventHandler<NetworkDetectorEventArgs>(nd_OnConnectedBroadbandCdma);
nd.OnConnectedBroadbandGsm += new EventHandler<NetworkDetectorEventArgs>(nd_OnConnectedBroadbandGsm);
nd.OnConnectedEthernet += new EventHandler<NetworkDetectorEventArgs>(nd_OnConnectedEthernet);
nd.OnConnectedNone += new EventHandler<NetworkDetectorEventArgs>(nd_OnConnectedNone);
nd.OnConnectedOther += new EventHandler<NetworkDetectorEventArgs>(nd_OnConnectedOther);
nd.OnConnectedWifi += new EventHandler<NetworkDetectorEventArgs>(nd_OnConnectedWifi);
nd.OnNetworkChanged += new EventHandler<NetworkAvailableEventArgs>(nd_OnNetworkChanged);
nd.OnNetworkOFF += new EventHandler<NetworkAvailableEventArgs>(nd_OnNetworkOFF);
nd.OnNetworkON += new EventHandler<NetworkAvailableEventArgs>(nd_OnNetworkON);
nd.OnZuneConnected += new EventHandler<NetworkDetectorEventArgs>(nd_OnZuneConnected);
nd.OnZuneDisconnected += new EventHandler<NetworkDetectorEventArgs>(nd_OnZuneDisconnected);
nd.OnLostNetworkType += new EventHandler<NetworkDetectorEventArgs>(nd_OnLostNetworkType);
nd.SetNetworkPolling(0,0,interval);
}
void nd_OnLostNetworkType(object sender, NetworkDetectorEventArgs e)
{
listBox1.Items.Insert(0, "OnLostNetworkType ->previous Nettype:" + e.NetType.ToString());
}
void nd_OnZuneDisconnected(object sender, NetworkDetectorEventArgs e)
{
listBox1.Items.Insert(0, "OnZuneDisconnected ->Nettype:" + e.NetType.ToString());
}
void nd_OnZuneConnected(object sender, NetworkDetectorEventArgs e)
{
listBox1.Items.Insert(0, "OnZuneConnected ->Nettype:" + e.NetType.ToString());
}
void nd_OnNetworkON(object sender, NetworkAvailableEventArgs e)
{
listBox1.Items.Insert(0, "OnNetworkON ->Online:" + e.IsOnline.ToString());
}
void nd_OnNetworkOFF(object sender, NetworkAvailableEventArgs e)
{
listBox1.Items.Insert(0, "OnNetworkOFF ->Online:" + e.IsOnline.ToString());
}
void nd_OnNetworkChanged(object sender, NetworkAvailableEventArgs e)
{
listBox1.Items.Insert(0, "OnNetworkChanged ->Online:" + e.IsOnline.ToString());
}
void nd_OnConnectedWifi(object sender, NetworkDetectorEventArgs e)
{
listBox1.Items.Insert(0, "OnConnectedWifi " + System.DateTime.Now.ToString("T") + " >>>>>>>>");
}
void nd_OnConnectedOther(object sender, NetworkDetectorEventArgs e)
{
listBox1.Items.Insert(0, "OnConnectedOther " + System.DateTime.Now.ToString("T") + " >>>>>>>>");
}
void nd_OnConnectedNone(object sender, NetworkDetectorEventArgs e)
{
listBox1.Items.Insert(0, "OnConnectedNone " + System.DateTime.Now.ToString("T") + " >>>>>>>>");
}
void nd_OnConnectedEthernet(object sender, NetworkDetectorEventArgs e)
{
listBox1.Items.Insert(0, "OnConnectedEthernet " + System.DateTime.Now.ToString("T") + " >>>>>>>>");
}
void nd_OnConnectedBroadbandGsm(object sender, NetworkDetectorEventArgs e)
{
listBox1.Items.Insert(0, "OnConnectedBroadbandGsm " + System.DateTime.Now.ToString("T") + " >>>>>>>>");
}
void nd_OnConnectedBroadbandCdma(object sender, NetworkDetectorEventArgs e)
{
listBox1.Items.Insert(0, "OnConnectedBroadbandCdma " + System.DateTime.Now.ToString("T") + " >>>>>>>>");
}
void nd_OnAsyncGetNetworkTypeCompleted(object sender, NetworkDetectorEventArgs e)
{
listBox1.Items.Insert(0, "OnAsyncGetNetworkTypeCompleted " + System.DateTime.Now.ToString("T") + " >>>>>>>>");
}
private void buttonMode_Click(object sender, RoutedEventArgs e)
{
nd.DetailedMode = !nd.DetailedMode;
if (nd.DetailedMode) buttonMode.Content = "DT";
else buttonMode.Content = "DF";
listBox1.Items.Insert(0, " DetailedMode : " + nd.DetailedMode.ToString() + " <<<<<<<<<");
}
private void buttonTime_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Insert(0, "<<<<< Current Time " + System.DateTime.Now.ToString("T") + " <<<<<<<<<");
}
private void buttonStoppPoll_Click(object sender, RoutedEventArgs e)
{
nd.DisableNetworkPolling();
}
private void buttonStartPoll_Click(object sender, RoutedEventArgs e)
{
nd.SetNetworkPolling(0, 0, interval);
}
private void buttonIncrease_Click(object sender, RoutedEventArgs e)
{
interval += 100;
//if (interval > 1000) interval = 1000;
nd.SetNetworkPolling(0, 0, interval);
listBox1.Items.Insert(0, " Current polling Time " + interval.ToString() + " <<<<<<<<<");
}
private void buttonClear_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Clear();
}
private void buttonDecrease_Click(object sender, RoutedEventArgs e)
{
interval -= 100;
if (interval < 100) interval = 100;
nd.SetNetworkPolling(0, 0, interval);
listBox1.Items.Insert(0, " Current polling Time " + interval.ToString() + " <<<<<<<<<");
}
private void buttonRefresh_Click(object sender, RoutedEventArgs e)
{
listBox1.Items.Insert(0, ">>> Refresh Started " + System.DateTime.Now.ToString("T") + " >>>>>>>>");
listBox1.Items.Insert(1, " Current status: " + nd.GetCurrentNetworkType().ToString());
nd.AsyncGetNetworkType();
listBox1.Items.Insert(2, " Refresh Ended " + System.DateTime.Now.ToString("T"));
}
}
}
@@ -0,0 +1,102 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.20506</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{794D79F0-E898-460D-BDB5-49FED553E0D5}</ProjectGuid>
<ProjectTypeGuids>{C089C8C0-30E0-4E22-80C0-CE093F111A43};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>NetworkDetection</RootNamespace>
<AssemblyName>NetworkDetection</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<SilverlightVersion>$(TargetFrameworkVersion)</SilverlightVersion>
<TargetFrameworkProfile>WindowsPhone</TargetFrameworkProfile>
<TargetFrameworkIdentifier>Silverlight</TargetFrameworkIdentifier>
<SilverlightApplication>true</SilverlightApplication>
<SupportedCultures>
</SupportedCultures>
<XapOutputs>true</XapOutputs>
<GenerateSilverlightManifest>true</GenerateSilverlightManifest>
<XapFilename>NetworkDetection.xap</XapFilename>
<SilverlightManifestTemplate>Properties\AppManifest.xml</SilverlightManifestTemplate>
<SilverlightAppEntry>NetworkDetection.App</SilverlightAppEntry>
<ValidateXaml>true</ValidateXaml>
<ThrowErrorsInValidation>true</ThrowErrorsInValidation>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>Bin\Debug</OutputPath>
<DefineConstants>DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE</DefineConstants>
<NoStdLib>true</NoStdLib>
<NoConfig>true</NoConfig>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>Bin\Release</OutputPath>
<DefineConstants>TRACE;SILVERLIGHT;WINDOWS_PHONE</DefineConstants>
<NoStdLib>true</NoStdLib>
<NoConfig>true</NoConfig>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Phone" />
<Reference Include="Microsoft.Phone.Interop" />
<Reference Include="System.Windows" />
<Reference Include="system" />
<Reference Include="System.Core" />
<Reference Include="System.Net" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
</Compile>
<Compile Include="MainPage.xaml.cs">
<DependentUpon>MainPage.xaml</DependentUpon>
</Compile>
<Compile Include="NetworkDetector.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="App.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</ApplicationDefinition>
<Page Include="MainPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
</ItemGroup>
<ItemGroup>
<None Include="Properties\AppManifest.xml" />
<None Include="Properties\WMAppManifest.xml" />
</ItemGroup>
<ItemGroup>
<Content Include="ApplicationIcon.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="Background.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="SplashScreenImage.jpg" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.$(TargetFrameworkProfile).Overrides.targets" />
<Import Project="$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
<ProjectExtensions />
</Project>
@@ -0,0 +1,387 @@
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
/**********************************************/
/* Copyright of Gabor Dolhai @ 2010 */
/* under MS-Pl license */
/* can be used freely for anybody */
/* If you use this code please send me an */
/*email about your project to dolhaig at gmail*/
/*******************Thanks*********************/
namespace NetworkDetection
{
#region Custom Enums and EventArgs
public enum NetworkTypeRequestStatus
{
Default = 0,
Started,//represents BackgroundWorker started
Ended//BackgroundWorker Finished
}
public class NetworkAvailableEventArgs : System.EventArgs
{
public NetworkAvailableEventArgs(bool isOnline)
{
IsOnline = isOnline;
}
public bool IsOnline { get; private set; }
}
public class NetworkDetectorEventArgs : System.EventArgs
{
public NetworkDetectorEventArgs(bool isOnline, Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType netType)
{
IsOnline = isOnline;
NetType = netType;
}
public bool IsOnline { get; private set; }
public Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType NetType { get; private set; }
}
#endregion
public class NetworkDetector
{
private static readonly NetworkDetector _instance = new NetworkDetector();
#region Events
public event EventHandler<NetworkAvailableEventArgs> OnNetworkON;
public event EventHandler<NetworkAvailableEventArgs> OnNetworkOFF;
public event EventHandler<NetworkAvailableEventArgs> OnNetworkChanged;
public event EventHandler<NetworkDetectorEventArgs> OnZuneConnected;
public event EventHandler<NetworkDetectorEventArgs> OnZuneDisconnected;
public event EventHandler<NetworkDetectorEventArgs> OnConnectedEthernet;
public event EventHandler<NetworkDetectorEventArgs> OnConnectedWifi;
public event EventHandler<NetworkDetectorEventArgs> OnConnectedNone;
public event EventHandler<NetworkDetectorEventArgs> OnConnectedBroadbandGsm;
public event EventHandler<NetworkDetectorEventArgs> OnConnectedBroadbandCdma;
public event EventHandler<NetworkDetectorEventArgs> OnConnectedOther;
public event EventHandler<NetworkDetectorEventArgs> OnLostNetworkType;
public event EventHandler<NetworkDetectorEventArgs> OnAsyncGetNetworkTypeCompleted;
#endregion
private System.Windows.Threading.DispatcherTimer updateTimer, pollTimer;
private Queue<long> requestQueue; //queue to store the requests timestemps
private BackgroundWorker networkWorker;
private bool online = false;
private Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType net;
private NetworkTypeRequestStatus requestStatus; //current status of the BackgroundWorker
private bool IsInstantRequestPresent;
private bool detailedMode;
private bool isZuneConnected;
private NetworkDetector()
{
requestQueue = new Queue<long>();
requestQueue.Clear();
requestStatus = NetworkTypeRequestStatus.Default;
updateTimer = new System.Windows.Threading.DispatcherTimer();
updateTimer.Tick += new EventHandler(updateTimer_Tick);
updateTimer.Interval = new TimeSpan(0, 0, 0, 0, 300);//there is no need to restart the BGWorker sooner then 300 millisec because the ~3request/sec requestlimit
//updateTimer.Start();
pollTimer = new System.Windows.Threading.DispatcherTimer();
pollTimer.Tick += new EventHandler(pollTimer_Tick);
networkWorker = new BackgroundWorker();
networkWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(networkWorker_RunWorkerCompleted);
networkWorker.DoWork += new DoWorkEventHandler(networkWorker_DoWork);
IsInstantRequestPresent = false;
detailedMode = false; //by default I hide the framework events for better Developer experience
isZuneConnected = false;
SetupNetworkChange(); //signing on the framework event
}
public static NetworkDetector Instance
{
get
{
return _instance;
}
}
#region BackgroundWorker
void networkWorker_DoWork(object sender, DoWorkEventArgs e)
{
Debug.WriteLine(">>>>> GetNetType started " + System.DateTime.Now.ToString("T") + " >>>>>");
e.Result = Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType;
}
//no need to lock the variables if We do everithing in the completed event handler
void networkWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
DetectOnlineStatus();
if ((detailedMode) || (net != (Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType)e.Result))
{
//there is no need to get events all the time, just when really changing something or the DetailedMode is true
if (net != (Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType)e.Result)
RaiseNotify(OnLostNetworkType, new NetworkDetectorEventArgs(online, net));
net = (Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType)e.Result;
Debug.WriteLine(" New NetType: " + net.ToString());
if (net == Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Ethernet) Debug.WriteLine("!!!!! Zune is Connected");
switch (net)
{
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Ethernet:
if (!isZuneConnected)
{
isZuneConnected = true;
RaiseNotify(OnZuneConnected, new NetworkDetectorEventArgs(online, net));
}
RaiseNotify(OnConnectedEthernet, new NetworkDetectorEventArgs(online, net));
break;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Wireless80211:
if (isZuneConnected)
{
isZuneConnected = false;
RaiseNotify(OnZuneDisconnected, new NetworkDetectorEventArgs(online, net));
}
RaiseNotify(OnConnectedWifi, new NetworkDetectorEventArgs(online, net));
break;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.MobileBroadbandCdma:
if (isZuneConnected)
{
isZuneConnected = false;
RaiseNotify(OnZuneDisconnected, new NetworkDetectorEventArgs(online, net));
}
RaiseNotify(OnConnectedBroadbandCdma, new NetworkDetectorEventArgs(online, net));
break;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.MobileBroadbandGsm:
if (isZuneConnected)
{
isZuneConnected = false;
RaiseNotify(OnZuneDisconnected, new NetworkDetectorEventArgs(online, net));
}
RaiseNotify(OnConnectedBroadbandGsm, new NetworkDetectorEventArgs(online, net));
break;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.None:
if (!online)
{
if (isZuneConnected)
{
/*if we lost all network connection and the Zune was present before,
then we lost the Zune too. Normally when Zune is present and then we got
a None NetType, the PC just lost the internet connection but not the Zune sync*/
isZuneConnected = false;
RaiseNotify(OnZuneDisconnected, new NetworkDetectorEventArgs(online, net));
}
}
RaiseNotify(OnConnectedNone, new NetworkDetectorEventArgs(online, net));
break;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.AsymmetricDsl:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Atm:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.BasicIsdn:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Ethernet3Megabit:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.FastEthernetFx:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.FastEthernetT:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Fddi:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.GenericModem:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.GigabitEthernet:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.HighPerformanceSerialBus:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.IPOverAtm:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Isdn:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Loopback:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.MultiRateSymmetricDsl:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Ppp:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.PrimaryIsdn:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.RateAdaptDsl:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Slip:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.SymmetricDsl:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.TokenRing:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Tunnel:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Unknown:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.VeryHighSpeedDsl:
default://theoretically we can't get here but better be prepared
RaiseNotify(OnConnectedOther, new NetworkDetectorEventArgs(online, net));
break;
}
}
for (int i = 0; i < requestQueue.Count; i++)
{
if (requestQueue.Peek() < System.DateTime.Now.Ticks) requestQueue.Dequeue();
//the requests before this moment just got answered
//if other requests are coming right after this, they will be served inside the next networkWorker_RunWorkerCompleted
}
if (requestQueue.Count == 0) updateTimer.Stop();
if (IsInstantRequestPresent) //the user requested a single poll
{
RaiseNotify(OnAsyncGetNetworkTypeCompleted, new NetworkDetectorEventArgs(online, net));
IsInstantRequestPresent = false;
}
requestStatus = NetworkTypeRequestStatus.Ended;
Debug.WriteLine("<<<<< GetNetType ended " + System.DateTime.Now.ToString("T") + " <<<<<");
}
#endregion
#region Private Functions
private void EnqueueRequest()
{
requestQueue.Enqueue(System.DateTime.Now.Ticks);
if (!updateTimer.IsEnabled) updateTimer.Start();
}
private void DetectOnlineStatus() //are we connected to any network or not
{
if (Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
if (!online)
{
online = true; //the network just came back
RaiseNotify(OnNetworkON, new NetworkAvailableEventArgs(online));
// do what is needed to GoOnline();
}
}
else
{
if (online)
{
online = false; //we just lost all network connectivity
RaiseNotify(OnNetworkOFF, new NetworkAvailableEventArgs(online));
Debug.WriteLine("----- No network available. -----");
// do what is needed to GoOffline();
}
}
}
void pollTimer_Tick(object sender, EventArgs e)
{
EnqueueRequest();
}
void updateTimer_Tick(object sender, EventArgs e)
{
if (requestQueue.Count > 0)
{
if (!networkWorker.IsBusy)
{
requestStatus = NetworkTypeRequestStatus.Started;
networkWorker.RunWorkerAsync();
}
}
}
#region Event Handling
private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
{
Debug.WriteLine("+++++ Changed started " + System.DateTime.Now.ToString("T") + " +++++");
DetectOnlineStatus();
if (detailedMode) RaiseNotify(OnNetworkChanged, new NetworkAvailableEventArgs(online));
Debug.WriteLine(" IsOnline : " + online.ToString());
Debug.WriteLine(" Current NetType: " + net.ToString());
Debug.WriteLine("+++++ Changed Ended " + System.DateTime.Now.ToString("T"));
Debug.WriteLine(" Changed GetNetType Launch" + System.DateTime.Now.ToString("T"));
EnqueueRequest();
}
private void SetupNetworkChange()
{
// Get current network availalability and store the
// initial value of the online variable
if (Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
online = true;
// do what is needed to GoOnline();
}
else
{
online = false;
// do what is needed to GoOffline();
}
// Now add a network change event handler to indicate network availability
EnqueueRequest();
System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged += new System.Net.NetworkInformation.NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
}
protected void RaiseNotify(EventHandler<NetworkDetectorEventArgs> handler, NetworkDetectorEventArgs e)
{
if (handler != null)
{
handler(this, e);
}
}
protected void RaiseNotify(EventHandler<NetworkAvailableEventArgs> handler, NetworkAvailableEventArgs e)
{
if (handler != null)
{
handler(this, e);
}
}
#endregion
#endregion
#region Public Functions and Properties
public void AsyncGetNetworkType()
{
//requestQueue.Enqueue(System.DateTime.Now.Ticks);
IsInstantRequestPresent = true;
if (!networkWorker.IsBusy)
{
requestStatus = NetworkTypeRequestStatus.Started;
networkWorker.RunWorkerAsync();
}
if (!updateTimer.IsEnabled) updateTimer.Start();
}
public void SetNetworkPolling(int Minutes, int Seconds, int Milliseconds)
{
pollTimer.Interval = new TimeSpan(0, 0, Minutes, Seconds, Milliseconds);
if (!pollTimer.IsEnabled) pollTimer.Start();
}
public void DisableNetworkPolling()
{
if (pollTimer.IsEnabled) pollTimer.Stop();
}
public Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType GetCurrentNetworkType()
{
return net;
}
public NetworkTypeRequestStatus GetRequestStatus()
{
//NetworkTypeRequestStatus temp = requestStatus;
//if (requestStatus == NetworkTypeRequestStatus.Ended) requestStatus = NetworkTypeRequestStatus.Default;
//return temp;
return requestStatus;
}
public bool DetailedMode
{
get
{
return detailedMode;
}
set
{
detailedMode = value;
}
}
public bool GetZuneStatus()
{
return isZuneConnected;
}
#endregion
}
}
@@ -0,0 +1,6 @@
<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<Deployment.Parts>
</Deployment.Parts>
</Deployment>
@@ -0,0 +1,35 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NetworkDetection")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("NetworkDetection")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2d90f1d3-7fb9-47d0-98c2-18ee1a63a5f5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2009/deployment" AppPlatformVersion="7.0">
<App xmlns="" ProductID="{794d79f0-e898-460d-bdb5-49fed553e0d5}" Title="NetworkDetection" RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal" Author="NetworkDetection author" Description="Sample description" Publisher="NetworkDetection">
<IconPath IsRelative="true" IsResource="false">ApplicationIcon.png</IconPath>
<Capabilities>
<Capability Name="ID_CAP_GAMERSERVICES"/>
<Capability Name="ID_CAP_IDENTITY_DEVICE"/>
<Capability Name="ID_CAP_IDENTITY_USER"/>
<Capability Name="ID_CAP_LOCATION"/>
<Capability Name="ID_CAP_MEDIALIB"/>
<Capability Name="ID_CAP_MICROPHONE"/>
<Capability Name="ID_CAP_NETWORKING"/>
<Capability Name="ID_CAP_PHONEDIALER"/>
<Capability Name="ID_CAP_PUSH_NOTIFICATION"/>
<Capability Name="ID_CAP_SENSORS"/>
<Capability Name="ID_CAP_WEBBROWSERCOMPONENT"/>
</Capabilities>
<Tasks>
<DefaultTask Name ="_default" NavigationPage="MainPage.xaml"/>
</Tasks>
<Tokens>
<PrimaryToken TokenID="NetworkDetectionToken" TaskName="_default">
<TemplateType5>
<BackgroundImageURI IsRelative="true" IsResource="false">Background.png</BackgroundImageURI>
<Count>0</Count>
<Title>NetworkDetection</Title>
</TemplateType5>
</PrimaryToken>
</Tokens>
</App>
</Deployment>
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

@@ -0,0 +1,19 @@
<Application
x:Class="NetworkNamespaces.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone">
<!--Application Resources-->
<Application.Resources>
</Application.Resources>
<Application.ApplicationLifetimeObjects>
<!--Required object that handles lifetime events for the application-->
<shell:PhoneApplicationService
Launching="Application_Launching" Closing="Application_Closing"
Activated="Application_Activated" Deactivated="Application_Deactivated"/>
</Application.ApplicationLifetimeObjects>
</Application>
@@ -0,0 +1,135 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
namespace NetworkNamespaces
{
public partial class App : Application
{
/// <summary>
/// Provides easy access to the root frame of the Phone Application.
/// </summary>
/// <returns>The root frame of the Phone Application.</returns>
public PhoneApplicationFrame RootFrame { get; private set; }
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Show graphics profiling information while debugging.
if (System.Diagnostics.Debugger.IsAttached)
{
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are being GPU accelerated with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
}
// Standard Silverlight initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
}
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
#region Phone application initialization
// Avoid double-initialization
private bool phoneApplicationInitialized = false;
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
// Do not add any additional code to this method
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
#endregion
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

@@ -0,0 +1,53 @@
<phone:PhoneApplicationPage
x:Class="NetworkNamespaces.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="144"/>
<RowDefinition Height="624*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="NETWORK NAMESPACE DIFFERENCES" Style="{StaticResource PhoneTextNormalStyle}"/>
<Button Content="Refresh" Height="71" Name="buttonRefresh" Width="160" Click="buttonRefresh_Click" />
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.5*" />
<ColumnDefinition Width="0.5*" />
</Grid.ColumnDefinitions>
<ListBox Height="576" HorizontalAlignment="Stretch" Margin="0,42,0,0" Name="listBoxSilverlight" VerticalAlignment="Top" Width="211" VerticalContentAlignment="Stretch" />
<ListBox Grid.Column="1" Height="576" HorizontalAlignment="Left" Name="listBoxPhone" VerticalAlignment="Top" Width="240" Margin="0,42,0,0" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="6,0,0,0" Name="textBlock1" Text="Silverlight" VerticalAlignment="Top" />
<TextBlock Grid.Column="1" Height="30" HorizontalAlignment="Left" Name="textBlock2" Text="Phone" VerticalAlignment="Top" />
</Grid>
</Grid>
<!--Sample code showing usage of ApplicationBar-->
<!--<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
<shell:ApplicationBar.MenuItems>
<shell:ApplicationBarMenuItem Text="MenuItem 1"/>
<shell:ApplicationBarMenuItem Text="MenuItem 2"/>
</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>-->
</phone:PhoneApplicationPage>
@@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
namespace NetworkNamespaces
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged += new System.Net.NetworkInformation.NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
}
void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
{
listBoxPhone.Items.Insert(0,Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable().ToString());
listBoxSilverlight.Items.Insert(0,System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable().ToString());
if (listBoxSilverlight.Items.Count > 21) listBoxSilverlight.Items.RemoveAt(listBoxSilverlight.Items.Count-1);
if (listBoxPhone.Items.Count > 21) listBoxPhone.Items.RemoveAt(listBoxPhone.Items.Count - 1);
}
private void buttonRefresh_Click(object sender, RoutedEventArgs e)
{
listBoxPhone.Items.Insert(0,Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable().ToString());
listBoxSilverlight.Items.Insert(0,System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable().ToString());
if (listBoxSilverlight.Items.Count > 21) listBoxSilverlight.Items.RemoveAt(listBoxSilverlight.Items.Count - 1);
if (listBoxPhone.Items.Count > 21) listBoxPhone.Items.RemoveAt(listBoxPhone.Items.Count - 1);
}
}
}
@@ -0,0 +1,101 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.20506</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{41A5C85F-7E30-418B-BAD2-AB2F40FF22CF}</ProjectGuid>
<ProjectTypeGuids>{C089C8C0-30E0-4E22-80C0-CE093F111A43};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>NetworkNamespaces</RootNamespace>
<AssemblyName>NetworkNamespaces</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<SilverlightVersion>$(TargetFrameworkVersion)</SilverlightVersion>
<TargetFrameworkProfile>WindowsPhone</TargetFrameworkProfile>
<TargetFrameworkIdentifier>Silverlight</TargetFrameworkIdentifier>
<SilverlightApplication>true</SilverlightApplication>
<SupportedCultures>
</SupportedCultures>
<XapOutputs>true</XapOutputs>
<GenerateSilverlightManifest>true</GenerateSilverlightManifest>
<XapFilename>NetworkNamespaces.xap</XapFilename>
<SilverlightManifestTemplate>Properties\AppManifest.xml</SilverlightManifestTemplate>
<SilverlightAppEntry>NetworkNamespaces.App</SilverlightAppEntry>
<ValidateXaml>true</ValidateXaml>
<ThrowErrorsInValidation>true</ThrowErrorsInValidation>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>Bin\Debug</OutputPath>
<DefineConstants>DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE</DefineConstants>
<NoStdLib>true</NoStdLib>
<NoConfig>true</NoConfig>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>Bin\Release</OutputPath>
<DefineConstants>TRACE;SILVERLIGHT;WINDOWS_PHONE</DefineConstants>
<NoStdLib>true</NoStdLib>
<NoConfig>true</NoConfig>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Phone" />
<Reference Include="Microsoft.Phone.Interop" />
<Reference Include="System.Windows" />
<Reference Include="system" />
<Reference Include="System.Core" />
<Reference Include="System.Net" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
</Compile>
<Compile Include="MainPage.xaml.cs">
<DependentUpon>MainPage.xaml</DependentUpon>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="App.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</ApplicationDefinition>
<Page Include="MainPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
</ItemGroup>
<ItemGroup>
<None Include="Properties\AppManifest.xml" />
<None Include="Properties\WMAppManifest.xml" />
</ItemGroup>
<ItemGroup>
<Content Include="ApplicationIcon.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="Background.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="SplashScreenImage.jpg" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.$(TargetFrameworkProfile).Overrides.targets" />
<Import Project="$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
<ProjectExtensions />
</Project>
@@ -0,0 +1,6 @@
<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<Deployment.Parts>
</Deployment.Parts>
</Deployment>
@@ -0,0 +1,35 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NetworkNamespaces")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("NetworkNamespaces")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e86f4db7-5169-481a-88c2-7afd0f470c2e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2009/deployment" AppPlatformVersion="7.0">
<App xmlns="" ProductID="{8a7d2a0b-f2ff-417f-aae7-56e8cf14a061}" Title="NetworkNamespaces" RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal" Author="NetworkNamespaces author" Description="Sample description" Publisher="NetworkNamespaces">
<IconPath IsRelative="true" IsResource="false">ApplicationIcon.png</IconPath>
<Capabilities>
<Capability Name="ID_CAP_GAMERSERVICES"/>
<Capability Name="ID_CAP_IDENTITY_DEVICE"/>
<Capability Name="ID_CAP_IDENTITY_USER"/>
<Capability Name="ID_CAP_LOCATION"/>
<Capability Name="ID_CAP_MEDIALIB"/>
<Capability Name="ID_CAP_MICROPHONE"/>
<Capability Name="ID_CAP_NETWORKING"/>
<Capability Name="ID_CAP_PHONEDIALER"/>
<Capability Name="ID_CAP_PUSH_NOTIFICATION"/>
<Capability Name="ID_CAP_SENSORS"/>
<Capability Name="ID_CAP_WEBBROWSERCOMPONENT"/>
</Capabilities>
<Tasks>
<DefaultTask Name ="_default" NavigationPage="MainPage.xaml"/>
</Tasks>
<Tokens>
<PrimaryToken TokenID="NetworkNamespacesToken" TaskName="_default">
<TemplateType5>
<BackgroundImageURI IsRelative="true" IsResource="false">Background.png</BackgroundImageURI>
<Count>0</Count>
<Title>NetworkNamespaces</Title>
</TemplateType5>
</PrimaryToken>
</Tokens>
</App>
</Deployment>
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

@@ -40,6 +40,23 @@
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'GPS_EMULATOR|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\GPS_EMULATOR\</OutputPath>
<DefineConstants>DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE</DefineConstants>
<NoStdLib>true</NoStdLib>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<CodeAnalysisLogFile>Bin\Debug\Phone7.Fx.Preview.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>
<CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>
<CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRuleSetDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets</CodeAnalysisRuleSetDirectories>
<CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisRuleDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules</CodeAnalysisRuleDirectories>
<CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Microsoft.Phone" /> <Reference Include="Microsoft.Phone" />
<Reference Include="mscorlib" /> <Reference Include="mscorlib" />
Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{33915750-A749-4D9D-A5E9-E1B01773D724}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Libraries</RootNamespace>
<AssemblyName>Libraries</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
<SccProjectName>SAK</SccProjectName>
<SccLocalPath>SAK</SccLocalPath>
<SccAuxPath>SAK</SccAuxPath>
<SccProvider>SAK</SccProvider>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Content Include="WP7_Toolkit\Microsoft.Phone.Controls.Toolkit.Design.dll" />
<Content Include="WP7_Toolkit\Microsoft.Phone.Controls.Toolkit.dll" />
<Content Include="WP7_Toolkit\Microsoft.Phone.Controls.Toolkit.pdb" />
<Content Include="WP7_Toolkit\Microsoft.Phone.Controls.Toolkit.xml" />
<Content Include="WPF_Interactivity\System.Windows.Interactivity.dll" />
<Content Include="WPF_Interactivity\System.Windows.Interactivity.xml" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
@@ -0,0 +1,69 @@
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit" xmlns:toolkitPrimitives="clr-namespace:Microsoft.Phone.Controls.Primitives;assembly=Microsoft.Phone.Controls.Toolkit" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
x:Class="WindowsPhone.Recipes.Push.Client.App"
>
<!--Application Resources-->
<Application.Resources>
<ItemsPanelTemplate x:Key="ItemsPanelTemplate">
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
<Style x:Key="PatternListBoxItemStyle" TargetType="ListBoxItem">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="BorderBrush" Value="Transparent"/>
<Setter Property="Padding" Value="2"/>
<Setter Property="Margin" Value="2"/>
<Setter Property="Width" Value="85"/>
<Setter Property="Height" Value="60"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border x:Name="LayoutRoot" HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}" Background="Transparent">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver"/>
<VisualState x:Name="Disabled">
<Storyboard>
<DoubleAnimation Duration="0" To=".5" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="ContentContainer"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
<VisualStateGroup x:Name="SelectionStates">
<VisualStateGroup.Transitions>
<VisualTransition GeneratedDuration="0:0:0.4" To="Selected"/>
</VisualStateGroup.Transitions>
<VisualState x:Name="Unselected"/>
<VisualState x:Name="Selected">
<Storyboard>
<ColorAnimation Duration="0" To="#FF1BA1E2" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" Storyboard.TargetName="LayoutRoot" d:IsOptimized="True"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<ContentControl x:Name="ContentContainer"
ContentTemplate="{TemplateBinding ContentTemplate}"
Content="{TemplateBinding Content}"
Foreground="{StaticResource PhoneForegroundBrush}"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
Margin="{TemplateBinding Padding}"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
<Application.ApplicationLifetimeObjects>
<!--Required object that handles lifetime events for the application-->
<shell:PhoneApplicationService
Launching="Application_Launching" Closing="Application_Closing"
Activated="Application_Activated" Deactivated="Application_Deactivated"/>
</Application.ApplicationLifetimeObjects>
</Application>
@@ -0,0 +1,137 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
namespace WindowsPhone.Recipes.Push.Client
{
public partial class App : Application
{
internal const string ServerAddress = "http://localhost:8000";
/// <summary>
/// Provides easy access to the root frame of the Phone Application.
/// </summary>
/// <returns>The root frame of the Phone Application.</returns>
public PhoneApplicationFrame RootFrame { get; private set; }
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Show graphics profiling information while debugging.
if (System.Diagnostics.Debugger.IsAttached)
{
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are being GPU accelerated with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
}
// Standard Silverlight initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
}
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
#region Phone application initialization
// Avoid double-initialization
private bool phoneApplicationInitialized = false;
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
// Do not add any additional code to this method
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
#endregion
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Some files were not shown because too many files have changed in this diff Show More