Esempio n. 1
0
        private void ExchangeIconButton_Click(object sender, EventArgs e)
        {
            var viewModel = DataContext as MainViewModel;

            if (viewModel == null)
            {
                return;
            }

            Focus();

            Dispatcher.BeginInvoke(() =>
            {
                viewModel.Save();

                if (!NetworkInterface.GetIsNetworkAvailable())
                {
                    MessageBox.Show("No network connection found!", "Error", MessageBoxButton.OK);

                    return;
                }

                viewModel.ExchangeCurrency();
            });
        }
Esempio n. 2
0
        /// <summary>
        /// 获取本地IPv4地址
        /// </summary>
        public static string GetHostIPv4(string[] NetNames)
        {
            System.Net.NetworkInformation.NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
            int len = interfaces.Length;

            for (int i = 0; i < len; i++)
            {
                System.Net.NetworkInformation.NetworkInterface ni = interfaces[i];
                if (ni.NetworkInterfaceType == System.Net.NetworkInformation.NetworkInterfaceType.Ethernet)
                {
                    if (NetNames.Contains(ni.Name))
                    {
                        System.Net.NetworkInformation.IPInterfaceProperties property = ni.GetIPProperties();
                        foreach (System.Net.NetworkInformation.UnicastIPAddressInformation ip in property.UnicastAddresses)
                        {
                            if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                            {
                                return(ip.Address.ToString());
                            }
                        }
                    }
                }
            }

            return(string.Empty);
        }
        public static System.Net.IPAddress GetFirstMulticastIPAddress(System.Net.NetworkInformation.NetworkInterface networkInterface, System.Net.Sockets.AddressFamily addressFamily)
        {
            //Filter interfaces which are not usable.
            if (networkInterface == null ||
                false == networkInterface.SupportsMulticast ||
                networkInterface.OperationalStatus != System.Net.NetworkInformation.OperationalStatus.Up)// The interface is not up (should probably ignore...?)
            {
                return(System.Net.IPAddress.None);
            }

            //Get the IPInterfaceProperties for the NetworkInterface
            System.Net.NetworkInformation.IPInterfaceProperties interfaceProperties = networkInterface.GetIPProperties();

            //If there are no IPInterfaceProperties then try the next interface
            if (interfaceProperties == null)
            {
                return(null);
            }

            //Iterate for each Multicast IP bound to the interface
            foreach (System.Net.NetworkInformation.MulticastIPAddressInformation multicastIpInfo in interfaceProperties.MulticastAddresses)
            {
                //If the IP AddresFamily is the same as required then return it. (Maybe Broadcast...)
                if (multicastIpInfo.Address.AddressFamily == addressFamily)
                {
                    return(multicastIpInfo.Address);
                }
            }

            //Indicate no multicast IPAddress was found
            return(System.Net.IPAddress.None);
        }
Esempio n. 4
0
        private void FacebookLogOut(object sender, RoutedEventArgs e)
        {
            try
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    if (App.FacebookSessionClient != null && App.FacebookSessionClient.CurrentSession != null)
                    {
                        App.FacebookSessionClient.Logout();
                    }
                    App.IsAuthenticated = false;

                    LogOut.Visibility = Visibility.Collapsed;
                    LogIn.Visibility  = Visibility.Visible;
                }
                else
                {
                    MessageBox.Show(AppResources.WarnInternetMsg, AppResources.WarnNwTitle, MessageBoxButton.OK);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, AppResources.ErrFbLogout, MessageBoxButton.OK);
            }
        }
Esempio n. 5
0
        public virtual void Bind(System.Net.IPEndPoint localEndPoint, System.Net.NetworkInformation.NetworkInterface networkInterface)
        {
            //Check not already attached.
            if (NetworkConnectionFlags.HasFlag(NetworkConnectionState.Bound).Equals(false))
            {
                //Check for a null input
                if (object.ReferenceEquals(LocalEndPoint, null))
                {
                    throw new System.ArgumentNullException("localEndPoint");
                }

                //Ensure the latest details are availble.
                Refresh();

                //Double check not bound
                if (IsBound)
                {
                    throw new System.InvalidOperationException("Already Bound on: " + LocalEndPoint.ToString());
                }

                //Assign the end point
                LocalEndPoint = localEndPoint;

                //Assign the network interface
                NetworkInterface = networkInterface ?? Common.Extensions.NetworkInterface.NetworkInterfaceExtensions.GetNetworkInterface(localEndPoint);

                //Indicate Bound
                FlagBound();
            }
        }
Esempio n. 6
0
        public void Connect(int addressIndex, System.Net.NetworkInformation.NetworkInterface networkInterface, int port = 0)
        {
            if (ConnectionSocket == null)
            {
                throw new System.InvalidOperationException("There must be a ConnectionSocket assigned before calling Connect.");
            }

            if (addressIndex < 0)
            {
                throw new System.IndexOutOfRangeException("addressIndex must be > 0 and < HostEntry.AddressList.Length");
            }

            if (networkInterface == null)
            {
                throw new System.ArgumentNullException("networkInterface");
            }

            NetworkInterface = networkInterface;

            RemoteEndPoint = new System.Net.IPEndPoint(RemoteIPHostEntry.AddressList[addressIndex], port);

            Connect();

            LocalEndPoint = ConnectionSocket.LocalEndPoint;

            RemoteAddressInformation = new IPAddressInformation(RemoteIPEndPoint.Address, RemoteAddressInformation.IsDnsEligible, RemoteAddressInformation.IsTransient);
        }
Esempio n. 7
0
        /// <summary>
        /// Creates and adds a few Person objects into the Items collection.
        /// </summary>
        public async Task LoadData(bool forceRefresh = false)
        {
            if (Loading)
            {
                return;
            }

            var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();

            Loading = true;
            try
            {
                const string metadataUrl = "http://www.bloomberg.com/billionaires/db/metadata/js";

                var result = await DownloadString(new Uri(metadataUrl), forceRefresh);

                if (result == null)
                {
                    return;
                }

                result = result.Substring(7);

                var x2 = JsonConvert.DeserializeObject <JObject>(result);

                var d = x2["people"];
                foreach (Person person in ConsecutivePairs(d))
                {
                    People.Add(person);
                }

                NotifyPropertyChanged("People");
                NotifyPropertyChanged("GroupedPeople");
                NotifyPropertyChanged("GroupedByIndustryPeople");

                await Task.WhenAll(
                    LoadRanking(forceRefresh),
                    LoadImages(forceRefresh),
                    LoadDetails(forceRefresh))
                .ContinueWith(_ =>
                {
                    IsDataLoaded = true;
                    Loading      = false;
                }, uiScheduler);
            }
            catch (Exception)
            {
                if (!NetworkInterface.GetIsNetworkAvailable())
                {
                    MessageBox.Show(
                        "Network is not available. Local data will be used if available, but information might be missing or incorrect.",
                        "No network", MessageBoxButton.OK);
                }

                Loading      = false;
                IsDataLoaded = false;
            }
        }
Esempio n. 8
0
        //EnqueMessage

        //SendMessge

        #endregion

        #region Constructor / Destructor

        public TransportClient(System.Net.NetworkInformation.NetworkInterface networkInterface)
        {
            if (networkInterface == null)
            {
                throw new System.ArgumentNullException();
            }

            NetworkInterface = networkInterface;
        }
        /// <summary>
        /// The time in nanoseconds it takes to transmit 96 bits of raw data on the medium
        /// </summary>
        /// <param name="networkInterface"></param>
        /// <returns></returns>
        public static double GetInterframeGapNanoseconds(this System.Net.NetworkInformation.NetworkInterface networkInterface)
        {
            if (networkInterface == null)
            {
                return(0);
            }

            return(CaulculateInterframeGapNanoseconds(networkInterface.Speed));
        }
Esempio n. 10
0
        public TransportClient(System.Net.NetworkInformation.NetworkInterface networkInterface, bool shouldDispose = true)
            : base(shouldDispose)
        {
            if (object.ReferenceEquals(networkInterface, null))
            {
                throw new System.ArgumentNullException();
            }

            NetworkInterface = networkInterface;
        }
Esempio n. 11
0
        public static string sMAC;// = GetMAC();
        public static string GetMAC()
        {
            string sMAC = "";

            System.Net.NetworkInformation.NetworkInterface[] adapters = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
            if (adapters.Length > 0)
            {
                System.Net.NetworkInformation.NetworkInterface adapter = adapters[0];
                System.Net.NetworkInformation.PhysicalAddress  phadd   = adapter.GetPhysicalAddress();
                sMAC = phadd.ToString();
            }
            return(sMAC);
        }
Esempio n. 12
0
 private void SetSettings(AttackParams Params, System.Net.NetworkInformation.NetworkInterface Adapter, int altport, IPEndPoint NewMasterPoint)
 {
     LogBox.Text = "";
     Controller.InitInterface(Adapter, altport, NewMasterPoint);
     Controller.InitParams(Params);
     if (Controller.mode)
     {
         ChangeMode(true);
     }
     else
     {
         ChangeMode(false);
     }
 }
Esempio n. 13
0
        private IObservable <WebResponse> WebRequestAsync(Uri address, bool noCache)
        {
            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                return(Observable.Throw <WebResponse>(new WebException("Network is not available")));
            }

            return(Observable.Using(
                       () => this.CreateRequest(address, noCache),
                       r =>
            {
                Debug.WriteLine("GET " + address.OriginalString);
                return Observable.FromAsyncPattern <WebResponse>(r.BeginGetResponse, r.EndGetResponse)();
            }).Catch <WebResponse, WebException>(DownloadExtensions.HandleWebException <WebResponse>));
        }
Esempio n. 14
0
        public bool Run(bool withoutLogging = false)
        {
            if (!NetworkInterface.GetIsNetworkAvailable() || !withoutLogging && ApplicationState.Current.IsOffline)
            {
                return(false);
            }
            client = ApplicationState.CreateService();
            using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
            {
                ApplicationState.AddCustomHeaders();
                method(client, operationEvent);
            }

            return(true);
        }
Esempio n. 15
0
        public static bool Discover()
        {
            System.Net.NetworkInformation.NetworkInterface nic = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0];

            System.Net.NetworkInformation.GatewayIPAddressInformation gwInfo = nic.GetIPProperties().GatewayAddresses[0];
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
            string req = "M-SEARCH * HTTP/1.1\r\n" +
                         "HOST: " + gwInfo.Address.ToString() + ":1900\r\n" +
                         "ST:upnp:rootdevice\r\n" +
                         "MAN:\"ssdp:discover\"\r\n" +
                         "MX:3\r\n\r\n";
            Socket client = new Socket(AddressFamily.InterNetwork,
                                       SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint endPoint = new
                                  IPEndPoint(IPAddress.Parse(gwInfo.Address.ToString()), 1900);

            client.SetSocketOption(SocketOptionLevel.Socket,
                                   SocketOptionName.ReceiveTimeout, 5000);

            byte[] q = Encoding.ASCII.GetBytes(req);
            client.SendTo(q, q.Length, SocketFlags.None, endPoint);
            IPEndPoint sender   = new IPEndPoint(IPAddress.Any, 0);
            EndPoint   senderEP = (EndPoint)sender;

            byte[] data          = new byte[1024];
            int    recv          = client.ReceiveFrom(data, ref senderEP);
            string queryResponse = "";

            queryResponse = Encoding.ASCII.GetString(data);

            DateTime start = DateTime.Now;

            string resp = queryResponse;

            if (resp.Contains("upnp:rootdevice"))
            {
                resp = resp.Substring(resp.ToLower().IndexOf("location:") + 9);
                resp = resp.Substring(0, resp.IndexOf("\r")).Trim();
                if (!string.IsNullOrEmpty(_serviceUrl = GetServiceUrl(resp)))
                {
                    _descUrl = resp;
                    return(true);
                }
            }
            return(false);
        }
        public static double GetSpeedInMBytesPerSecond(this System.Net.NetworkInformation.NetworkInterface networkInterface)
        {
            if (object.ReferenceEquals(networkInterface, null))
            {
                return(0);
            }

            long speed = networkInterface.Speed;

            if (speed <= 0)
            {
                return(0);
            }

            return(networkInterface.Speed / Common.Extensions.TimeSpan.TimeSpanExtensions.NanosecondsPerMillisecond);
        }
Esempio n. 17
0
        public static Databases.RetrieverCore.Common.Models.NetworkInterface From(System.Net.NetworkInformation.NetworkInterface networkInterface,
                                                                                  Win32_NetworkAdapter win32NetworkAdapter)
        {
            var output = new Databases.RetrieverCore.Common.Models.NetworkInterface();

            output.AdapterType          = win32NetworkAdapter.AdapterType;
            output.Caption              = win32NetworkAdapter.Caption;
            output.GUID                 = string.IsNullOrWhiteSpace(networkInterface?.Id) ? null : Guid.Parse(networkInterface.Id);
            output.ProductName          = win32NetworkAdapter.ProductName;
            output.NetworkInterfaceType = networkInterface?.NetworkInterfaceType
                                          ?? System.Net.NetworkInformation.NetworkInterfaceType.Unknown;
            var mac = networkInterface?.GetPhysicalAddress().GetAddressBytes();

            output.MAC = mac == null || mac.Length == 0 ? null : Encoding.ASCII.GetString(mac);

            return(output);
        }
        public static System.Net.IPAddress GetFirstUnicastIPAddress(System.Net.NetworkInformation.NetworkInterface networkInterface, System.Net.Sockets.AddressFamily addressFamily)
        {
            //Filter interfaces which are not usable.
            if (networkInterface == null ||
                networkInterface.OperationalStatus != System.Net.NetworkInformation.OperationalStatus.Up)// The interface is not up
            {
                return(System.Net.IPAddress.None);
            }

            //Get the IPInterfaceProperties for the NetworkInterface
            System.Net.NetworkInformation.IPInterfaceProperties interfaceProperties = networkInterface.GetIPProperties();

            //If there are no IPInterfaceProperties then try the next interface
            if (interfaceProperties == null)
            {
                return(null);
            }

            //Iterate for each Unicast IP bound to the interface
            foreach (System.Net.NetworkInformation.UnicastIPAddressInformation unicastIpInfo in interfaceProperties.UnicastAddresses)
            {
                //Get the address
                System.Net.IPAddress address = unicastIpInfo.Address;

                //If the IP AddressFamily is not the same as required then return it.
                if (address.AddressFamily != addressFamily)
                {
                    continue;
                }

                //Don't use Any and don't use Broadcast.
                if (address.Equals(System.Net.IPAddress.Broadcast)
                    ||
                    (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6 ? address.Equals(System.Net.IPAddress.IPv6Any) : address.Equals(System.Net.IPAddress.Any)))
                {
                    continue;
                }

                //Return the compatible address.
                return(address);
            }

            //Indicate no unicast IPAddress was found
            return(System.Net.IPAddress.None);
        }
Esempio n. 19
0
 private void FacebookLogIn(object sender, RoutedEventArgs e)
 {
     try
     {
         if (!NetworkInterface.GetIsNetworkAvailable())
         {
             MessageBox.Show(AppResources.WarnInternetMsg, AppResources.WarnNwTitle, MessageBoxButton.OK);
         }
         else
         {
             NavigationService.Navigate(new Uri("/FacebookLogin.xaml?" + UriParameter.ReferrerPage + "=Settings.xaml", UriKind.Relative));
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, AppResources.ErrFbLogin, MessageBoxButton.OK);
     }
 }
Esempio n. 20
0
        static void Main(string[] args)
        {
            Int32 sessionId = (Int32)DateTime.Now.Ticks;

            using (Socket dhcpClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                dhcpClientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
                dhcpClientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
                dhcpClientSocket.Bind(new IPEndPoint(IPAddress.Parse("0.0.0.0"), 68));

                DhcpMessage discoverMessage = new DhcpMessage();

                discoverMessage.SessionId = sessionId;
                discoverMessage.Operation = DhcpOperation.BootRequest;
                discoverMessage.Hardware  = HardwareType.Ethernet;
                discoverMessage.Flags     = 128;

                Byte[] physicalAddr = NetworkInterface.GetAllNetworkInterfaces()[0].GetPhysicalAddress().GetAddressBytes();
                discoverMessage.ClientHardwareAddress = physicalAddr;

                discoverMessage.AddOption(DhcpOption.DhcpMessageType, (Byte)DhcpMessageType.Discover);

                Byte[] clientId = new Byte[physicalAddr.Length + 1];
                clientId[0] = (Byte)1;
                physicalAddr.CopyTo(clientId, 1);
                discoverMessage.AddOption(DhcpOption.AutoConfig, 1);
                discoverMessage.AddOption(DhcpOption.Hostname, Encoding.ASCII.GetBytes(Environment.MachineName));
                discoverMessage.AddOption(DhcpOption.ClassId, 77, 83, 70, 84, 32, 53, 46, 48);
                discoverMessage.AddOption(DhcpOption.ClientId, clientId);
                discoverMessage.AddOption(DhcpOption.ParameterList, 1, 15, 3, 6, 44, 46, 47, 31, 33, 121, 249, 43);

                dhcpClientSocket.SendTo(discoverMessage.ToArray(), new IPEndPoint(IPAddress.Broadcast, 67));

                Byte[] buffer      = new Byte[1024];
                Int32  len         = dhcpClientSocket.Receive(buffer);
                Byte[] messageData = new Byte[len];
                Array.Copy(buffer, messageData, Math.Min(len, buffer.Length));
                DhcpMessage responseMessage = new DhcpMessage(messageData);

                Console.ReadLine();
            }
        }
Esempio n. 21
0
        private void SyncNowClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (App.IsTrial)
                {
                    //messagebox to prompt to buy
                    var buyAppForSyncMessageBox = new CustomMessageBox
                    {
                        Height             = 300,
                        Caption            = AppResources.BuyFullVersion,
                        Message            = AppResources.BuyAppGenericMessage,
                        LeftButtonContent  = AppResources.BuyLabel,
                        RightButtonContent = AppResources.LaterLabel,
                        VerticalAlignment  = VerticalAlignment.Center
                    };

                    buyAppForSyncMessageBox.Dismissed += BuyAppForSyncBoxDismissed;
                    buyAppForSyncMessageBox.Show();

                    return;
                }

                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    var result = MessageBox.Show(AppResources.ContactSyncRedirectMsg, AppResources.SyncContactsLabel, MessageBoxButton.OKCancel);
                    if (result.Equals(MessageBoxResult.OK))
                    {
                        NavigationService.Navigate(new Uri("/FacebookLogin.xaml?" + UriParameter.IsSyncScneario + "=Yes", UriKind.Relative));
                    }
                }
                else
                {
                    MessageBox.Show(AppResources.WarnInternetMsg, AppResources.WarnNwTitle, MessageBoxButton.OK);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, AppResources.ErrLoadSyncScreen, MessageBoxButton.OK);
            }
        }
Esempio n. 22
0
        private async Task Authenticate()
        {
            try
            {
                if (!NetworkInterface.GetIsNetworkAvailable())
                {
                    NavigationService.Navigate(!string.IsNullOrEmpty(ReferrerPage)
                        ? new Uri("/" + ReferrerPage, UriKind.Relative)
                        : new Uri("/MainPage.xaml", UriKind.Relative));
                }
                else
                {
                    App.FacebookSessionClient = new FacebookSessionClient(Constants.AppId);
                    Session = await App.FacebookSessionClient.LoginAsync("friends_birthday,friends_photos,email,user_mobile_phone,user_friends,friends_about_me,friends_status,read_friendlists");

                    App.AccessToken = Session.AccessToken;
                    App.FacebookId  = Session.FacebookId;

                    if (!string.IsNullOrEmpty(ReferrerPage))
                    {
                        Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/" + ReferrerPage, UriKind.Relative)));
                    }
                    else
                    {
                        Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/FacebookConnect.xaml?" + UriParameter.IsSyncScneario + "=" + IsSync, UriKind.Relative)));
                    }
                }
            }
            catch (InvalidOperationException e)
            {
                AppLog.WriteToLog(DateTime.Now, "Login failed !  Error : " + e.Message + ". Stack : " + e.StackTrace, LogLevel.Error);
                MessageBox.Show(AppResources.FbLoginFailedText, AppResources.FbLoginFailedTitle, MessageBoxButton.OK);
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
            }
            catch (Exception ex)
            {
                AppLog.WriteToLog(DateTime.Now, "Login failed !  Error : " + ex.Message + ". Stack : " + ex.StackTrace, LogLevel.Error);
                MessageBox.Show(AppResources.FbLoginFailedText, AppResources.FbLoginFailedTitle, MessageBoxButton.OK);
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
            }
        }
Esempio n. 23
0
        void GetColectivosCercanos()
        {
            ResetUI();
            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                ConnectionError.Visibility = Visibility.Visible;
                Dispatcher.BeginInvoke(() => MessageBox.Show("Ha habido un error intentando acceder a los nuevos datos o no hay conexiones de red disponibles.\nPor favor asegúrese de contar con acceso de red y vuelva a intentarlo."));
                return;
            }

            GeoPosition <GeoCoordinate> currentLocation = PositionService.GetCurrentLocation();

            if (!App.Configuration.IsLocationEnabled)
            {
                Dispatcher.BeginInvoke(() => MessageBox.Show("Para buscar colectivos cercanos, por favor, active la función de localización en la configuración de la aplicación."));
                return;
            }
            if (currentLocation == null)
            {
                Dispatcher.BeginInvoke(() => MessageBox.Show("Para buscar colectivos cercanos, por favor, active la función de localización."));
                return;
            }

            ProgressBar.Show("Buscando más cercanos...");
            if (ViewModel.Items.Count == 0)
            {
                Refreshing.Visibility = Visibility.Visible;
            }
            SetApplicationBarEnabled(false);
            CancelarRequest();

            var client = new HttpClient();

            _httpReq = client.Get("/transporte/cercano".ToApiCallUri());
            _httpReq.BeginGetResponse(HTTPWebRequestCallBack, _httpReq);
        }
Esempio n. 24
0
 internal NetworkInterface(NetworkInterfaceInformation info)
 {
     Information = info;
 }
Esempio n. 25
0
 public BandwidthMeter(string id)
 {
     _networkInterface = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(x => x.Id == id);
 }
Esempio n. 26
0
        async static Task <T> exceptionHandling <T>(Func <IBodyArchitectAccessService, Task <T> > method, bool withoutLogging = false)
        {
            if (!NetworkInterface.GetIsNetworkAvailable() || !withoutLogging && ApplicationState.Current.IsOffline)
            {
                throw new NetworkException(NetworkError.SocketNotConnected);
            }
            try
            {
                bool      retry     = true;
                Exception exception = null;
                IBodyArchitectAccessService client = ApplicationState.CreateService();



                do
                {
                    OperationContextScope scope =
                        new OperationContextScope(((BodyArchitectAccessServiceClient)client).InnerChannel);
                    ApplicationState.AddCustomHeaders();
                    try
                    {
                        return(await method(client));
                    }
                    catch (FaultException <BAAuthenticationException> ex)
                    {
                        if (!retry)
                        {
                            throw ex;
                        }
                        retry     = false;
                        exception = ex;
                    }

                    scope = new OperationContextScope(((BodyArchitectAccessServiceClient)client).InnerChannel);
                    ApplicationState.AddCustomHeaders();
                    ClientInformation info = Settings.GetClientInformation();

                    var sessionData =
                        await
                        Task <SessionData> .Factory.FromAsync(client.BeginLogin, client.EndLogin, info,
                                                              ApplicationState.Current.TempUserName,
                                                              ApplicationState.Current.TempPassword, null);

                    if (sessionData == null)
                    {
                        throw exception;
                    }
                    ApplicationState.Current.SessionData = sessionData;
                    ApplicationState.Current.SessionData.Token.Language = ApplicationState.CurrentServiceLanguage;
                } while (true);
                return(default(T));
            }
            catch (FaultException <ValidationFault> ex)
            {
                throw new ValidationException(ex.Detail.ToValidationResults());
            }
            catch (FaultException <BAAuthenticationException> baEx)
            {
                throw new Portable.Exceptions.AuthenticationException(baEx.Detail.Message);
            }
            catch (FaultException <BAServiceException> baEx)
            {
                switch (baEx.Detail.ErrorCode)
                {
                case ErrorCode.ProfileRankException:
                    throw new ProfileRankException(baEx.Detail.Message);

                case ErrorCode.ProfileIsNotActivatedException:
                    throw new ProfileIsNotActivatedException(baEx.Detail.Message);

                case ErrorCode.UserDeletedException:
                    throw new UserDeletedException(baEx.Detail.Message);

                case ErrorCode.MaintenanceException:
                    throw new MaintenanceException(baEx.Detail.Message);

                case ErrorCode.ProfileDeletedException:
                    throw new ProfileDeletedException(baEx.Detail.Message);

                case ErrorCode.ConsistencyException:
                    throw new ConsistencyException(baEx.Detail.Message);

                case ErrorCode.SecurityException:
                    throw new SecurityException(baEx.Detail.Message);

                case ErrorCode.EMailSendException:
                    throw new EMailSendException(baEx.Detail.Message);

                case ErrorCode.DeleteConstraintException:
                    throw new DeleteConstraintException(baEx.Detail.Message);

                case ErrorCode.UniqueException:
                    throw new UniqueException(baEx.Detail.Message);

                case ErrorCode.CrossProfileOperation:
                    throw new CrossProfileOperationException(baEx.Detail.Message);

                case ErrorCode.ValidationException:
                    throw new ValidationException(baEx.Detail.Message);

                case ErrorCode.AuthenticationException:
                    throw new Portable.Exceptions.AuthenticationException(baEx.Detail.Message);

                case ErrorCode.InvalidOperationException:
                    throw new InvalidOperationException(baEx.Detail.Message);

                case ErrorCode.ArgumentNullException:
                    throw new ArgumentNullException(baEx.Detail.AdditionalData, baEx.Detail.Message);

                case ErrorCode.ArgumentOutOfRange:
                    throw new ArgumentOutOfRangeException(baEx.Detail.AdditionalData, baEx.Detail.Message);

                case ErrorCode.ProductAlreadyPaid:
                    throw new ProductAlreadyPaidException(baEx.Detail.Message);

                case ErrorCode.ArgumentException:
                    throw new ArgumentException(baEx.Detail.Message);

                case ErrorCode.DatabaseException:
                    throw new DatabaseException(baEx.Detail.Message);

                case ErrorCode.NullReferenceException:
                    throw new NullReferenceException(baEx.Detail.Message);

                case ErrorCode.DatabaseVersionException:
                    throw new DatabaseVersionException(baEx.Detail.Message);

                case ErrorCode.OldDataException:
                    throw new OldDataException(baEx.Detail.Message);

                case ErrorCode.CannotAcceptRejectInvitationDoesntExistException:
                    throw new CannotAcceptRejectInvitationDoesntExistException(baEx.Detail.Message);

                case ErrorCode.ProfileAlreadyFriendException:
                    throw new ProfileAlreadyFriendException(baEx.Detail.Message);

                case ErrorCode.ObjectIsFavoriteException:
                    throw new ObjectIsFavoriteException(baEx.Detail.Message);

                case ErrorCode.ObjectIsNotFavoriteException:
                    throw new ObjectIsNotFavoriteException(baEx.Detail.Message);

                case ErrorCode.ObjectNotFound:
                    throw new ObjectNotFoundException(baEx.Detail.Message);

                case ErrorCode.UnauthorizedAccessException:
                    throw new UnauthorizedAccessException(baEx.Detail.Message);

                case ErrorCode.TrainingIntegrityException:
                    throw new TrainingIntegrationException(baEx.Detail.Message);

                case ErrorCode.FileNotFoundException:
                    throw new FileNotFoundException(baEx.Detail.Message);

                case ErrorCode.AlreadyOccupied:
                    throw new AlreadyOccupiedException(baEx.Detail.Message);

                case ErrorCode.LicenceException:
                    throw new LicenceException(baEx.Detail.Message);
                }
                throw new Exception(baEx.Detail.Message);
            }
        }
        private void DeleteAppBarClick(object sender, EventArgs e)
        {
            try
            {
                if (App.IsTrial)
                {
                    //messagebox to prompt to buy
                    var buyAppForDeleteMessageBox = new CustomMessageBox
                    {
                        Height             = 300,
                        Caption            = AppResources.BuyFullVersion,
                        Message            = AppResources.BuyAppForDelete,
                        LeftButtonContent  = AppResources.BuyLabel,
                        RightButtonContent = AppResources.LaterLabel,
                        VerticalAlignment  = VerticalAlignment.Center
                    };

                    buyAppForDeleteMessageBox.Dismissed += BuyAppForDeleteMessageBoxDismissed;
                    buyAppForDeleteMessageBox.Show();

                    return;
                }
                //display warning for confirmation
                var result = MessageBox.Show(AppResources.DeleteConfirmMessage, AppResources.DeleteLabel, MessageBoxButton.OKCancel);

                if (!result.Equals(MessageBoxResult.OK))
                {
                    return;
                }

                //check which list is active
                if (MainPagePanorama.SelectedItem.Equals(MostRecentPanorama))
                {
                    if (RecentBirthdayList != null && RecentBirthdayList.SelectedItems != null && RecentBirthdayList.SelectedItems.Count > 0)
                    {
                        foreach (FriendBirthday friend in RecentBirthdayList.SelectedItems)
                        {
                            BirthdayUtility.DeleteFriend(friend.Id);
                        }
                    }
                    else
                    {
                        MessageBox.Show(AppResources.WarnSelectItem, AppResources.WarnTryAgain, MessageBoxButton.OK);
                    }

                    BindDataContext();
                }
                else if (MainPagePanorama.SelectedItem.Equals(AllItemPanorama))
                {
                    if (AllBirthdayList != null && AllBirthdayList.SelectedItems != null && AllBirthdayList.SelectedItems.Count > 0)
                    {
                        foreach (FriendBirthday friend in AllBirthdayList.SelectedItems)
                        {
                            BirthdayUtility.DeleteFriend(friend.Id);
                        }
                    }
                    else
                    {
                        MessageBox.Show(AppResources.WarnSelectItem, AppResources.WarnTryAgain, MessageBoxButton.OK);
                    }

                    BindDataContext();
                }
                else if (MainPagePanorama.SelectedItem.Equals(BirthdayCardPanorama))
                {
                    //if image upload/delete is complete
                    if (NetworkInterface.GetIsNetworkAvailable())
                    {
                        if (BirthdayCardList != null && BirthdayCardList.SelectedItems != null && BirthdayCardList.SelectedItems.Count > 0)
                        {
                            var service      = new AzureStorageService(Services.AzureConnectionString, App.UserPreferences.UserDetails.FacebookId);
                            var items        = BirthdayCardList.SelectedItems;
                            var deletedCards = new List <int>();

                            if (items != null)
                            {
                                foreach (var cardEntity in items.Cast <CardEntity>())
                                {
                                    service.DeleteBlob(Path.GetFileName(cardEntity.Url));
                                    deletedCards.Add(cardEntity.Id);
                                }
                            }

                            var birthdays = DataContext as Birthdays;

                            if (birthdays == null)
                            {
                                return;
                            }

                            var birthdayCards = birthdays.BirthdayCards;

                            foreach (var cardId in deletedCards)
                            {
                                birthdayCards.Remove(birthdayCards.Single(c => c.Id == cardId));
                            }

                            //remove entry fromm database
                            BirthdayUtility.DeleteCards(deletedCards);
                        }
                        else
                        {
                            MessageBox.Show(AppResources.WarnSelectItem, AppResources.WarnTryAgain, MessageBoxButton.OK);
                        }
                    }
                    else
                    {
                        MessageBox.Show(AppResources.WarnInternetMsg, AppResources.WarnNwTitle, MessageBoxButton.OK);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, AppResources.ErrDeleting, MessageBoxButton.OK);
            }
        }
        private void AddClick(object sender, EventArgs e)
        {
            try
            {
                //check which list is active
                if (MainPagePanorama.SelectedItem.Equals(MostRecentPanorama) || MainPagePanorama.SelectedItem.Equals(AllItemPanorama))
                {
                    NavigationService.Navigate(new Uri("/FriendDetails.xaml", UriKind.Relative));
                }
                else if (MainPagePanorama.SelectedItem.Equals(BirthdayCardPanorama))
                {
                    if (NetworkInterface.GetIsNetworkAvailable())
                    {
                        var bdayObj = DataContext as Birthdays;

                        if (bdayObj == null)
                        {
                            return;
                        }

                        if (App.IsTrial)
                        {
                            if (bdayObj.BirthdayCards == null || bdayObj.BirthdayCards.Count < 5)
                            {
                                UploadPhoto();
                            }
                            else
                            {
                                //messagebox to prompt to buy
                                var buyAppMessageBox = new CustomMessageBox
                                {
                                    Height             = 300,
                                    Caption            = AppResources.BuyFullVersion,
                                    Message            = AppResources.BuyAppForCard,
                                    LeftButtonContent  = AppResources.BuyLabel,
                                    RightButtonContent = AppResources.LaterLabel,
                                    VerticalAlignment  = VerticalAlignment.Center
                                };

                                buyAppMessageBox.Dismissed += BuyAppMessageBoxDismissed;
                                buyAppMessageBox.Show();
                            }
                        }
                        else
                        {
                            if (bdayObj.BirthdayCards == null || bdayObj.BirthdayCards.Count < 100)
                            {
                                UploadPhoto();
                            }
                            else
                            {
                                //message box to buy credits
                                MessageBox.Show(AppResources.CardLimitExceedCaption, AppResources.Only100CardsMessage, MessageBoxButton.OK);
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show(AppResources.WarnInternetMsg, AppResources.WarnNwTitle, MessageBoxButton.OK);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, AppResources.ErrAddFriend, MessageBoxButton.OK);
            }
        }
 /// <summary>
 /// The time in microseconds it takes to transmit 96 bits of raw data on the medium
 /// </summary>
 /// <param name="networkInterface"></param>
 /// <returns></returns>
 public static double GetInterframeGapMicroseconds(this System.Net.NetworkInformation.NetworkInterface networkInterface)
 {
     return(GetInterframeGapNanoseconds(networkInterface) * Media.Common.Extensions.TimeSpan.TimeSpanExtensions.NanosecondsPerMicrosecond);
 }
Esempio n. 30
0
 internal NetworkInterface(NetworkInterfaceInformation info)
 {
     Information = info;
 }
Esempio n. 31
0
        /// <summary>
        /// Download profile images of friends
        /// </summary>
        /// <param name="isSync">Is synchronization action getting performed</param>
        public static async void DownloadProfileImages(String isSync)
        {
            try
            {
                //crreate image directory if it does not exist
                var storage = IsolatedStorageFile.GetUserStoreForApplication();
                if (!storage.DirectoryExists(FileSystem.ProfilePictureDirectory))
                {
                    storage.CreateDirectory(FileSystem.ProfilePictureDirectory);
                }

                //get list of FB friends for pic download
                var friendList     = GetFriendList();
                var isSyncScenario = (!String.IsNullOrEmpty(isSync) && isSync.Equals("Yes", StringComparison.InvariantCultureIgnoreCase));

                if (friendList == null || friendList.Count <= 0)
                {
                    return;
                }

                foreach (var friend in friendList)
                {
                    try
                    {
                        if (!friend.TypeOfContact.Equals(ContactType.Facebook) || string.IsNullOrEmpty(friend.FacebookId) ||
                            (!String.IsNullOrEmpty(friend.ProfilePictureLocation) && !isSyncScenario) || !NetworkInterface.GetIsNetworkAvailable())
                        {
                            continue;
                        }

                        await friend.DownloadProfilePicture();

                        friend.ProfilePictureLocation = @"isostore:/" + FileSystem.ProfilePictureDirectory + friend.UniqueId + ".jpg";
                        UpdateFriendDetails(friend);
                    }
                    catch (Exception ex)
                    {
                        AppLog.WriteToLog(DateTime.Now, "Error downloading one or more photos. " + ex.Message, LogLevel.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteToLog(DateTime.Now, "Error downloading one or more photos. " + ex.Message, LogLevel.Error);
            }
        }