예제 #1
0
        /// <summary>
        /// The string to long.
        /// </summary>
        /// <param name="value">
        /// The value.
        /// </param>
        /// <param name="conversionMethod">
        /// The conversion type.
        /// </param>
        /// <returns>
        /// The <see cref="long"/>.
        /// </returns>
        public static long StringToLong(string value, ConversionMethods conversionMethod)
        {
            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentNullException("value");
            }

            switch (conversionMethod)
            {
            case ConversionMethods.IndividualIntegers:
            {
                return(IndividualIntegers(value));
            }

            case ConversionMethods.Rounded:
            {
                return(Rounded(value));
            }

            default:
            {
                throw new NotImplementedException(
                          string.Format("{0} Conversion Method is Not Supported.", conversionMethod));
            }
            }
        }
예제 #2
0
        public void toGramTest()
        {
            ConversionMethods conversionTest = new ConversionMethods();
            double            result         = conversionTest.toGrams(15);

            Assert.AreEqual(425.2428, result, 0.001);
        }
예제 #3
0
        public void ToEmail_Internal_CheckFormatExceptions()
        {
            // Arrange
            var inputMail = new ecn.communicator.mvc.Models.Email();

            inputMail.Birthdate      = SampleDummy;
            inputMail.UserEvent1Date = SampleDummy;
            inputMail.UserEvent2Date = SampleDummy;
            var inputUser = new KMPlatform.Entity.User();

            ShimEmail.GetByEmailIDInt32User = (p1, p2) => new Email();

            // Act
            try
            {
                var internalEmail = ConversionMethods.ToEmail_Internal(inputMail, inputUser);

                // Assert
                internalEmail.ShouldBeNull();
            }
            catch (ECNException ex)
            {
                ex.ErrorList.ShouldNotBeNull();
                ex.ErrorList.Count.ShouldBe(4);
                ex.ErrorList[0].ErrorMessage.ShouldBe(ExceptionMessageFormatBirthdate);
                ex.ErrorList[1].ErrorMessage.ShouldBe(ExceptionMessageFormatUserEvent1Date);
                ex.ErrorList[2].ErrorMessage.ShouldBe(ExceptionMessageFormatUserEvent2Date);
                ex.ErrorList[3].ErrorMessage.ShouldBe(ExceptionMessageEmailRequired);
            }
        }
        private void InitialiseWindow()
        {
            try
            {
                ThemeManager.PropagateThemeSelector(kcbTheme);

                knumDarkValue.Value = ConversionMethods.ConvertFloatToDecimal(_colourIntensitySettingsManager.GetDarkestColourIntensity());

                knumMediumValue.Value = ConversionMethods.ConvertFloatToDecimal(_colourIntensitySettingsManager.GetMediumColourIntensity());

                knumLightValue.Value = ConversionMethods.ConvertFloatToDecimal(_colourIntensitySettingsManager.GetLightColourIntensity());

                knumLightestValue.Value = ConversionMethods.ConvertFloatToDecimal(_colourIntensitySettingsManager.GetLightestColourIntensity());

                klblDarkColourFloatValue.Text = ColourHelpers.ReturnFloatAsString(_colourIntensitySettingsManager.GetDarkestColourIntensity());

                klblMediumColourFloatValue.Text = ColourHelpers.ReturnFloatAsString(_colourIntensitySettingsManager.GetMediumColourIntensity());

                klblLightColourFloatValue.Text = ColourHelpers.ReturnFloatAsString(_colourIntensitySettingsManager.GetLightColourIntensity());

                klblLightestColourFloatValue.Text = ColourHelpers.ReturnFloatAsString(_colourIntensitySettingsManager.GetLightestColourIntensity());
            }
            catch (Exception exc)
            {
                ExceptionHandler.CaptureException(exc, icon: MessageBoxIcon.Error, methodSignature: Helpers.GetCurrentMethod());
            }
        }
예제 #5
0
        public void toOunceTest()
        {
            ConversionMethods conversionTest = new ConversionMethods();
            double            result         = conversionTest.toOunces(15);

            Assert.AreEqual(0.52910942924, result, 0.001);
        }
예제 #6
0
        private static async Task UpdateElements(IElement element)
        {
            Ensure.ArgumentNotNull(nameof(element), element);

            var orderedPropertiesArray = await GetOrderedFilteredPropertyInfos(element);

            var models = await ConversionMethods.ConvertPropertyInfosToValidationModels(element, orderedPropertiesArray);

            await ProcessModels(element, models);
        }
예제 #7
0
        private void EmitConversionCode(Type fromType, Type toType)
        {
            MethodInfo parseMethod      = null;
            MethodInfo conversionMethod = null;

            // si los tipos son iguales no hay que emitir ningún código
            if (fromType == toType)
            {
                return;
            }
            if (fromType.IsEnum)
            {
                fromType = fromType.GetField("value__").FieldType;
            }
            if (toType.IsEnum)
            {
                toType = toType.GetField("value__").FieldType;
            }
            if (fromType.IsPrimitive && toType.IsPrimitive)
            {
                OpCode opCode;
                if (!nativeConversionOpcodes.TryGetValue(toType, out opCode))
                {
                    throw new InvalidCastException(string.Format(CultureInfo.InvariantCulture, "Cannot convert from {0} to {1}", fromType.FullName, toType.FullName));
                }
                cil.Emit(opCode);
            }
            else if (fromType == typeof(string) && (parseMethod = toType.GetMethod("Parse", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(string) }, null)) != null)
            {
                cil.Emit(OpCodes.Call, parseMethod);
            }
            else if (toType == typeof(string))
            {
                MethodInfo toStringMethod = fromType.GetMethod("ToString", Type.EmptyTypes);
                if (toStringMethod == null)
                {
                    throw new InvalidCastException(string.Format(CultureInfo.InvariantCulture, "Cannot convert from {0} to {1}", fromType.FullName, toType.FullName));
                }
                if (fromType.IsValueType)
                {
                    LocalBuilder localVar = cil.DeclareLocal(fromType);
                    cil.Emit(OpCodes.Stloc, localVar);
                    cil.Emit(OpCodes.Ldloca, localVar.LocalIndex);
                }
                cil.Emit(OpCodes.Call, toStringMethod);
            }
            else if ((conversionMethod = ConversionMethods.GetConversionMethod(fromType, toType)) != null)
            {
                cil.Emit(OpCodes.Call, conversionMethod);
            }
            else
            {
                throw new InvalidCastException(string.Format(CultureInfo.InvariantCulture, "Cannot convert from {0} to {1}", fromType.FullName, toType.FullName));
            }
        }
예제 #8
0
        private static void UpdateRepeatedItemList(IList list, Type subtype, IGenericRootItem genericRootItem)
        {
            var constructedType = ConversionMethods.GetConcreteClassFromInterface(subtype);
            var element         = constructedType as IElement;

            if (element == null)
            {
                return;
            }
            UpdateReferences(element, genericRootItem);
            list.Add(element);
        }
        private void kbtnConvert_Click(object sender, EventArgs e)
        {
            try
            {
                int[] rgb = ConversionMethods.ConvertHexadecimalToRGBTest(ktxtHexColourValue.Text);

                pnlPreview.BackColor = Color.FromArgb(rgb[0], rgb[1], rgb[2]);
            }
            catch (Exception)
            {
            }

            //UpdateUI();
        }
예제 #10
0
        public void ToEmail_Internal_CheckOneToOne_NoException()
        {
            // Arrange
            var inputMail = CreateSampleEmail();
            var inputUser = new KMPlatform.Entity.User();

            ShimEmail.GetByEmailIDInt32User = (p1, p2) => new Email();

            // Act
            var internalEmail = ConversionMethods.ToEmail_Internal(inputMail, inputUser);

            // Assert
            internalEmail.ShouldNotBeNull();
            CheckInternalEmail(internalEmail);
        }
예제 #11
0
        public void ToEmail_Internal_CheckEmptyMail_NoException()
        {
            // Arrange
            var inputMail = new ecn.communicator.mvc.Models.Email();

            inputMail.EmailAddress = SampleEmailAddress;
            inputMail.EmailID      = SampleEmailId;
            var inputUser = new KMPlatform.Entity.User();

            ShimEmail.GetByEmailIDInt32User = (p1, p2) => new Email();

            // Act
            var internalEmail = ConversionMethods.ToEmail_Internal(inputMail, inputUser);

            // Assert
            internalEmail.ShouldNotBeNull();
        }
예제 #12
0
        private static void UpdateInterfacePropertyValue(object instance, IPropertyValidation propertyValidationModel)
        {
            if (!propertyValidationModel.PropertyInfo.PropertyType.IsInterface)
            {
                return;
            }
            var anyClassImplementingInterface = ConversionMethods.GetConcreteClassFromInterface(propertyValidationModel.PropertyInfo);

            var anyClassAsElement = anyClassImplementingInterface as BaseElement;

            if (anyClassAsElement == null)
            {
                return;
            }

            UpdateReferences(anyClassAsElement, propertyValidationModel.GenericReferenceElement);
            propertyValidationModel.PropertyInfo.SetValue(instance, anyClassImplementingInterface);
        }
예제 #13
0
        private static void DoIt(TcpClient clientConnection)
        {
            NetworkStream stream = clientConnection.GetStream();
            StreamReader  reader = new StreamReader(stream);
            StreamWriter  writer = new StreamWriter(stream);

            while (true)
            {
                string request = reader.ReadLine();
                if (string.IsNullOrEmpty(request))
                {
                    break;
                }
                Console.WriteLine("Request: " + request);
                string response     = request;
                var    splitRequest = request.Split();

                double conversionNumber = double.Parse(splitRequest[1]);
                Console.WriteLine($"Converting {conversionNumber} to ounces:");

                switch (splitRequest[0])
                {
                case ("toounces"):
                    ConversionMethods toOuncesObject = new ConversionMethods();
                    double            OunceResult    = toOuncesObject.toOunces(conversionNumber);
                    Console.WriteLine($"Result: {OunceResult} oz");
                    break;

                case ("tograms"):
                    ConversionMethods toGramsObject = new ConversionMethods();
                    double            GramResult    = toGramsObject.toGrams(conversionNumber);
                    Console.WriteLine($"Result: {GramResult} g");
                    break;
                }

                writer.WriteLine(response);
                writer.Flush();
            }

            clientConnection.Close();
            Console.WriteLine("Socket closed");
        }
        private async Task <bool> UpdateLocation()
        {
            bool locationChanged = false;

            if (Settings.FollowGPS)
            {
                Geoposition newGeoPos = null;
                Geolocator  geolocal  = new Geolocator()
                {
                    DesiredAccuracyInMeters = 5000, ReportInterval = 900000, MovementThreshold = 1600
                };

                try
                {
                    cts.Token.ThrowIfCancellationRequested();
                    newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10)).AsTask(cts.Token);
                }
                catch (OperationCanceledException)
                {
                    return(locationChanged);
                }
                catch (Exception)
                {
                    var geoStatus = GeolocationAccessStatus.Unspecified;

                    try
                    {
                        cts.Token.ThrowIfCancellationRequested();
                        geoStatus = await Geolocator.RequestAccessAsync().AsTask(cts.Token);
                    }
                    catch (OperationCanceledException)
                    {
                        return(locationChanged);
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteLine(LoggerLevel.Error, ex, "{0}: error requesting location permission", taskName);
                    }
                    finally
                    {
                        if (!cts.IsCancellationRequested && geoStatus == GeolocationAccessStatus.Allowed)
                        {
                            try
                            {
                                newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10)).AsTask(cts.Token);
                            }
                            catch (Exception ex)
                            {
                                Logger.WriteLine(LoggerLevel.Error, ex, "{0}: GetWeather error", taskName);
                            }
                        }
                    }
                }

                // Access to location granted
                if (newGeoPos != null)
                {
                    var lastGPSLocData = await Settings.GetLastGPSLocData();

                    if (cts.IsCancellationRequested)
                    {
                        return(locationChanged);
                    }

                    // Check previous location difference
                    if (lastGPSLocData.query != null &&
                        Math.Abs(ConversionMethods.CalculateHaversine(lastGPSLocData.latitude, lastGPSLocData.longitude,
                                                                      newGeoPos.Coordinate.Point.Position.Latitude, newGeoPos.Coordinate.Point.Position.Longitude)) < geolocal.MovementThreshold)
                    {
                        return(false);
                    }

                    LocationQueryViewModel view = null;

                    await Task.Run(async() =>
                    {
                        view = await wm.GetLocation(newGeoPos);

                        if (String.IsNullOrEmpty(view.LocationQuery))
                        {
                            view = new LocationQueryViewModel();
                        }
                    }, cts.Token);

                    if (String.IsNullOrWhiteSpace(view.LocationQuery))
                    {
                        // Stop since there is no valid query
                        return(false);
                    }

                    if (cts.IsCancellationRequested)
                    {
                        return(locationChanged);
                    }

                    // Save oldkey
                    string oldkey = lastGPSLocData.query;

                    // Save location as last known
                    lastGPSLocData.SetData(view, newGeoPos);
                    Settings.SaveLastGPSLocData(lastGPSLocData);

                    // Update tile id for location
                    if (oldkey != null && SecondaryTileUtils.Exists(oldkey))
                    {
                        await SecondaryTileUtils.UpdateTileId(oldkey, lastGPSLocData.query);
                    }

                    locationChanged = true;
                }
            }

            return(locationChanged);
        }
예제 #15
0
        private async Task <bool> UpdateLocation()
        {
            bool locationChanged = false;

            if (Settings.DataSync == WearableDataSync.Off &&
                Settings.FollowGPS && (location == null || location.locationType == LocationType.GPS))
            {
                if (Activity != null && ContextCompat.CheckSelfPermission(Activity, Manifest.Permission.AccessFineLocation) != Permission.Granted)
                {
                    RequestPermissions(new String[] { Manifest.Permission.AccessFineLocation },
                                       PERMISSION_LOCATION_REQUEST_CODE);
                    return(false);
                }

                Android.Locations.Location location = null;

                if (WearableHelper.IsGooglePlayServicesInstalled && !WearableHelper.HasGPS)
                {
                    location = await mFusedLocationClient.GetLastLocationAsync();

                    if (location == null)
                    {
                        var mLocationRequest = new LocationRequest();
                        mLocationRequest.SetInterval(10000);
                        mLocationRequest.SetFastestInterval(1000);
                        mLocationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
                        await mFusedLocationClient.RequestLocationUpdatesAsync(mLocationRequest, mLocCallback, null);

                        await mFusedLocationClient.FlushLocationsAsync();
                    }
                }
                else
                {
                    LocationManager locMan       = Activity?.GetSystemService(Context.LocationService) as LocationManager;
                    bool            isGPSEnabled = (bool)locMan?.IsProviderEnabled(LocationManager.GpsProvider);
                    bool            isNetEnabled = (bool)locMan?.IsProviderEnabled(LocationManager.NetworkProvider);

                    if (isGPSEnabled || isNetEnabled)
                    {
                        Criteria locCriteria = new Criteria()
                        {
                            Accuracy = Accuracy.Coarse, CostAllowed = false, PowerRequirement = Power.Low
                        };
                        string provider = locMan.GetBestProvider(locCriteria, true);
                        location = locMan.GetLastKnownLocation(provider);

                        if (location == null)
                        {
                            locMan.RequestSingleUpdate(provider, mLocListnr, null);
                        }
                    }
                    else
                    {
                        Toast.MakeText(Activity, Resource.String.error_retrieve_location, ToastLength.Short).Show();
                    }
                }

                if (location != null)
                {
                    LocationData lastGPSLocData = await Settings.GetLastGPSLocData();

                    // Check previous location difference
                    if (lastGPSLocData.query != null &&
                        mLocation != null && ConversionMethods.CalculateGeopositionDistance(mLocation, location) < 1600)
                    {
                        return(false);
                    }

                    if (lastGPSLocData.query != null &&
                        Math.Abs(ConversionMethods.CalculateHaversine(lastGPSLocData.latitude, lastGPSLocData.longitude,
                                                                      location.Latitude, location.Longitude)) < 1600)
                    {
                        return(false);
                    }

                    LocationQueryViewModel view = null;

                    await Task.Run(async() =>
                    {
                        view = await wm.GetLocation(location);

                        if (String.IsNullOrEmpty(view.LocationQuery))
                        {
                            view = new LocationQueryViewModel();
                        }
                    });

                    if (String.IsNullOrWhiteSpace(view.LocationQuery))
                    {
                        // Stop since there is no valid query
                        return(false);
                    }

                    // Save location as last known
                    lastGPSLocData.SetData(view, location);
                    Settings.SaveHomeData(lastGPSLocData);

                    this.location   = lastGPSLocData;
                    mLocation       = location;
                    locationChanged = true;
                }
            }

            return(locationChanged);
        }
예제 #16
0
        internal void UpdateExtraParams()
        {
            lock (m_ExtraParamsLock)
            {
                int  i                = 0;
                int  limitedi         = 0;
                uint totalBytesLength = 1;
                uint extraParamsNum   = 0;

                uint limitedTotalBytesLength = 1;
                uint limitedExtraParamsNum   = 0;

                var             flexi          = m_Part.Flexible;
                var             light          = m_Part.PointLight;
                var             proj           = Projection;
                var             shape          = m_Part.Shape;
                var             emesh          = m_Part.ExtendedMesh;
                bool            isFlexible     = flexi.IsFlexible;
                bool            isSculpt       = shape.Type == PrimitiveShapeType.Sculpt;
                ObjectGroup     objectGroup    = m_Part.ObjectGroup;
                bool            isFullLight    = light.IsLight;
                AttachmentPoint attachPoint    = objectGroup?.AttachPoint ?? AttachmentPoint.NotAttached;
                bool            isLimitedLight = isFullLight &&
                                                 (!m_Part.IsAttachmentLightsDisabled || !IsPrivateAttachmentOrNone(attachPoint)) &&
                                                 (!m_Part.IsFacelightDisabled || (attachPoint != AttachmentPoint.LeftHand && attachPoint != AttachmentPoint.RightHand)) &&
                                                 (!m_Part.IsUnattachedLightsDisabled || attachPoint != AttachmentPoint.NotAttached);
                bool isProjecting = proj.IsProjecting;
                ExtendedMeshParams.MeshFlags emeshFlags = emesh.Flags;
                if (isFlexible)
                {
                    ++extraParamsNum;
                    totalBytesLength += 16;
                    totalBytesLength += 2 + 4;
                }

                if (isSculpt)
                {
                    ++extraParamsNum;
                    totalBytesLength += 17;
                    totalBytesLength += 2 + 4;
                }

                if (isProjecting)
                {
                    ++extraParamsNum;
                    totalBytesLength += 28;
                    totalBytesLength += 2 + 4;
                }

                if (emeshFlags != ExtendedMeshParams.MeshFlags.None)
                {
                    ++extraParamsNum;
                    totalBytesLength += 4;
                    totalBytesLength += 2 + 4;
                }

                limitedExtraParamsNum   = extraParamsNum;
                limitedTotalBytesLength = totalBytesLength;

                if (isLimitedLight)
                {
                    ++limitedExtraParamsNum;
                    limitedTotalBytesLength += 16;
                    limitedTotalBytesLength += 2 + 4;
                }

                if (isFullLight)
                {
                    ++extraParamsNum;
                    totalBytesLength += 16;
                    totalBytesLength += 2 + 4;
                }

                var updatebytes        = new byte[totalBytesLength];
                var updatebyteslimited = new byte[limitedTotalBytesLength];
                updatebyteslimited[limitedi++] = (byte)limitedExtraParamsNum;
                updatebytes[i++] = (byte)extraParamsNum;

                if (isFlexible)
                {
                    updatebytes[i++] = FlexiEP % 256;
                    updatebytes[i++] = FlexiEP / 256;

                    updatebytes[i++] = 16;
                    updatebytes[i++] = 0;
                    updatebytes[i++] = 0;
                    updatebytes[i++] = 0;

                    updatebytes[i++] = (byte)((byte)((byte)(flexi.Tension * 10.01f) & 0x7F) | (byte)((flexi.Softness & 2) << 6));
                    updatebytes[i++] = (byte)((byte)((byte)(flexi.Friction * 10.01f) & 0x7F) | (byte)((flexi.Softness & 1) << 7));
                    updatebytes[i++] = (byte)((flexi.Gravity + 10.0f) * 10.01f);
                    updatebytes[i++] = (byte)(flexi.Wind * 10.01f);
                    flexi.Force.ToBytes(updatebytes, i);
                    i += 12;
                }

                if (isSculpt)
                {
                    updatebytes[i++] = SculptEP % 256;
                    updatebytes[i++] = SculptEP / 256;
                    updatebytes[i++] = 17;
                    updatebytes[i++] = 0;
                    updatebytes[i++] = 0;
                    updatebytes[i++] = 0;
                    shape.SculptMap.ToBytes(updatebytes, i);
                    i += 16;
                    updatebytes[i++] = (byte)shape.SculptType;
                }

                Buffer.BlockCopy(updatebytes, 1, updatebyteslimited, 1, i - 1);
                limitedi = i;

                if (isFullLight)
                {
                    updatebytes[i++] = LightEP % 256;
                    updatebytes[i++] = LightEP / 256;
                    updatebytes[i++] = 16;
                    updatebytes[i++] = 0;
                    updatebytes[i++] = 0;
                    updatebytes[i++] = 0;
                    Buffer.BlockCopy(light.LightColor.AsByte, 0, updatebytes, i, 3);

                    updatebytes[i + 3] = (byte)(light.Intensity * 255f);
                    i += 4;
                    ConversionMethods.Float2LEBytes((float)light.Radius, updatebytes, i);
                    i += 4;
                    ConversionMethods.Float2LEBytes((float)light.Cutoff, updatebytes, i);
                    i += 4;
                    ConversionMethods.Float2LEBytes((float)light.Falloff, updatebytes, i);
                    i += 4;
                }

                if (isLimitedLight)
                {
                    updatebyteslimited[limitedi++] = LightEP % 256;
                    updatebyteslimited[limitedi++] = LightEP / 256;
                    updatebyteslimited[limitedi++] = 16;
                    updatebyteslimited[limitedi++] = 0;
                    updatebyteslimited[limitedi++] = 0;
                    updatebyteslimited[limitedi++] = 0;
                    Buffer.BlockCopy(light.LightColor.AsByte, 0, updatebyteslimited, limitedi, 3);

                    double intensity = light.Intensity;
                    double radius    = light.Radius;

                    if (attachPoint == AttachmentPoint.NotAttached)
                    {
                        intensity = Math.Min(m_Part.UnattachedLightLimitIntensity, intensity);
                        radius    = Math.Min(m_Part.UnattachedLightLimitRadius, radius);
                    }
                    else if (IsPrivateAttachmentOrNone(attachPoint))
                    {
                        /* skip these as they are anyways hidden from anyone else */
                    }
                    else
                    {
                        if (attachPoint != AttachmentPoint.LeftHand &&
                            attachPoint != AttachmentPoint.RightHand)
                        {
                            intensity = Math.Min(m_Part.FacelightLimitIntensity, intensity);
                            radius    = Math.Min(m_Part.FacelightLimitRadius, radius);
                        }
                        intensity = Math.Min(m_Part.AttachmentLightLimitIntensity, intensity);
                        radius    = Math.Min(m_Part.AttachmentLightLimitRadius, radius);
                    }

                    updatebyteslimited[limitedi + 3] = (byte)(intensity * 255f);
                    limitedi += 4;
                    ConversionMethods.Float2LEBytes((float)light.Radius, updatebyteslimited, limitedi);
                    limitedi += 4;
                    ConversionMethods.Float2LEBytes((float)light.Cutoff, updatebyteslimited, limitedi);
                    limitedi += 4;
                    ConversionMethods.Float2LEBytes((float)light.Falloff, updatebyteslimited, limitedi);
                    limitedi += 4;
                }

                if (isProjecting)
                {
                    /* full block */
                    updatebytes[i++] = (ProjectionEP % 256);
                    updatebytes[i++] = (ProjectionEP / 256);
                    updatebytes[i++] = 28;
                    updatebytes[i++] = 0;
                    updatebytes[i++] = 0;
                    updatebytes[i++] = 0;
                    proj.ProjectionTextureID.ToBytes(updatebytes, i);
                    i += 16;
                    ConversionMethods.Float2LEBytes((float)proj.ProjectionFOV, updatebytes, i);
                    i += 4;
                    ConversionMethods.Float2LEBytes((float)proj.ProjectionFocus, updatebytes, i);
                    i += 4;
                    ConversionMethods.Float2LEBytes((float)proj.ProjectionAmbience, updatebytes, i);

                    /* limited block */
                    updatebyteslimited[limitedi++] = (ProjectionEP % 256);
                    updatebyteslimited[limitedi++] = (ProjectionEP / 256);
                    updatebyteslimited[limitedi++] = 28;
                    updatebyteslimited[limitedi++] = 0;
                    updatebyteslimited[limitedi++] = 0;
                    updatebyteslimited[limitedi++] = 0;
                    proj.ProjectionTextureID.ToBytes(updatebyteslimited, limitedi);
                    limitedi += 16;
                    ConversionMethods.Float2LEBytes((float)proj.ProjectionFOV, updatebytes, limitedi);
                    limitedi += 4;
                    ConversionMethods.Float2LEBytes((float)proj.ProjectionFocus, updatebytes, limitedi);
                    limitedi += 4;
                    ConversionMethods.Float2LEBytes((float)proj.ProjectionAmbience, updatebytes, limitedi);
                }

                if (emeshFlags != ExtendedMeshParams.MeshFlags.None)
                {
                    /* full block */
                    updatebytes[i++] = (ExtendedMeshEP % 256);
                    updatebytes[i++] = (ExtendedMeshEP / 256);
                    updatebytes[i++] = 4;
                    updatebytes[i++] = 0;
                    updatebytes[i++] = 0;
                    updatebytes[i++] = 0;
                    updatebytes[i++] = (byte)(((uint)emeshFlags) & 0xFF);
                    updatebytes[i++] = (byte)((((uint)emeshFlags) >> 8) & 0xFF);
                    updatebytes[i++] = (byte)((((uint)emeshFlags) >> 16) & 0xFF);
                    updatebytes[i++] = (byte)((((uint)emeshFlags) >> 24) & 0xFF);

                    /* limited block */
                    updatebyteslimited[limitedi++] = (ExtendedMeshEP % 256);
                    updatebyteslimited[limitedi++] = (ExtendedMeshEP / 256);
                    updatebyteslimited[limitedi++] = 4;
                    updatebyteslimited[limitedi++] = 0;
                    updatebyteslimited[limitedi++] = 0;
                    updatebyteslimited[limitedi++] = 0;
                    updatebyteslimited[limitedi++] = (byte)(((uint)emeshFlags) & 0xFF);
                    updatebyteslimited[limitedi++] = (byte)((((uint)emeshFlags) >> 8) & 0xFF);
                    updatebyteslimited[limitedi++] = (byte)((((uint)emeshFlags) >> 16) & 0xFF);
                    updatebyteslimited[limitedi++] = (byte)((((uint)emeshFlags) >> 24) & 0xFF);
                }

                m_ExtraParamsBytes             = updatebytes;
                m_ExtraParamsBytesLimitedLight = updatebyteslimited;
            }
        }
예제 #17
0
        private async Task <bool> UpdateLocation()
        {
            bool locationChanged = false;

            if (Settings.FollowGPS && (location == null || location.locationType == LocationType.GPS))
            {
                Geoposition newGeoPos = null;

                try
                {
                    newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10));
                }
                catch (Exception)
                {
                    var geoStatus = GeolocationAccessStatus.Unspecified;

                    try
                    {
                        geoStatus = await Geolocator.RequestAccessAsync();
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteLine(LoggerLevel.Error, ex, "WeatherNow: GetWeather error");
                    }
                    finally
                    {
                        if (geoStatus == GeolocationAccessStatus.Allowed)
                        {
                            try
                            {
                                newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10));
                            }
                            catch (Exception ex)
                            {
                                Logger.WriteLine(LoggerLevel.Error, ex, "WeatherNow: GetWeather error");
                            }
                        }
                        else if (geoStatus == GeolocationAccessStatus.Denied)
                        {
                            // Disable gps feature
                            Settings.FollowGPS = false;
                        }
                    }

                    if (!Settings.FollowGPS)
                    {
                        return(false);
                    }
                }

                // Access to location granted
                if (newGeoPos != null)
                {
                    LocationData lastGPSLocData = await Settings.GetLastGPSLocData();

                    // Check previous location difference
                    if (lastGPSLocData.query != null &&
                        geoPos != null && ConversionMethods.CalculateGeopositionDistance(geoPos, newGeoPos) < geolocal.MovementThreshold)
                    {
                        return(false);
                    }

                    if (lastGPSLocData.query != null &&
                        Math.Abs(ConversionMethods.CalculateHaversine(lastGPSLocData.latitude, lastGPSLocData.longitude,
                                                                      newGeoPos.Coordinate.Point.Position.Latitude, newGeoPos.Coordinate.Point.Position.Longitude)) < geolocal.MovementThreshold)
                    {
                        return(false);
                    }

                    LocationQueryViewModel view = null;

                    await Task.Run(async() =>
                    {
                        view = await wm.GetLocation(newGeoPos);

                        if (String.IsNullOrEmpty(view.LocationQuery))
                        {
                            view = new LocationQueryViewModel();
                        }
                    });

                    if (String.IsNullOrWhiteSpace(view.LocationQuery))
                    {
                        // Stop since there is no valid query
                        return(false);
                    }

                    // Save oldkey
                    string oldkey = lastGPSLocData.query;

                    // Save location as last known
                    lastGPSLocData.SetData(view, newGeoPos);
                    Settings.SaveLastGPSLocData(lastGPSLocData);

                    // Update tile id for location
                    if (oldkey != null && SecondaryTileUtils.Exists(oldkey))
                    {
                        await SecondaryTileUtils.UpdateTileId(oldkey, lastGPSLocData.query);
                    }

                    location        = lastGPSLocData;
                    geoPos          = newGeoPos;
                    locationChanged = true;
                }
            }

            return(locationChanged);
        }
        private async Task <bool> UpdateLocation()
        {
            bool locationChanged = false;

            if (Settings.FollowGPS)
            {
                if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) != Permission.Granted)
                {
                    return(false);
                }

                Android.Locations.Location location = null;

                if (WearableHelper.IsGooglePlayServicesInstalled && !WearableHelper.HasGPS)
                {
                    var mFusedLocationClient = new FusedLocationProviderClient(this);
                    location = await mFusedLocationClient.GetLastLocationAsync();
                }
                else
                {
                    LocationManager locMan       = GetSystemService(Context.LocationService) as LocationManager;
                    bool            isGPSEnabled = (bool)locMan?.IsProviderEnabled(LocationManager.GpsProvider);
                    bool            isNetEnabled = (bool)locMan?.IsProviderEnabled(LocationManager.NetworkProvider);

                    if (isGPSEnabled || isNetEnabled)
                    {
                        Criteria locCriteria = new Criteria()
                        {
                            Accuracy = Accuracy.Coarse, CostAllowed = false, PowerRequirement = Power.Low
                        };
                        string provider = locMan.GetBestProvider(locCriteria, true);
                        location = locMan.GetLastKnownLocation(provider);
                    }
                    else
                    {
                        Toast.MakeText(this, Resource.String.error_retrieve_location, ToastLength.Short).Show();
                    }
                }

                if (location != null)
                {
                    LocationData lastGPSLocData = await Settings.GetLastGPSLocData();

                    // Check previous location difference
                    if (lastGPSLocData.query != null &&
                        Math.Abs(ConversionMethods.CalculateHaversine(lastGPSLocData.latitude, lastGPSLocData.longitude,
                                                                      location.Latitude, location.Longitude)) < 1600)
                    {
                        return(false);
                    }

                    LocationQueryViewModel view = null;

                    await Task.Run(async() =>
                    {
                        view = await wm.GetLocation(location);

                        if (String.IsNullOrEmpty(view.LocationQuery))
                        {
                            view = new LocationQueryViewModel();
                        }
                    });

                    if (String.IsNullOrWhiteSpace(view.LocationQuery))
                    {
                        // Stop since there is no valid query
                        return(false);
                    }

                    // Save location as last known
                    lastGPSLocData.SetData(view, location);
                    Settings.SaveHomeData(lastGPSLocData);

                    locationChanged = true;
                }
            }

            return(locationChanged);
        }
        private async Task <bool> UpdateLocation()
        {
            bool locationChanged = false;

            if (Settings.FollowGPS && (location == null || location.locationType == LocationType.GPS))
            {
                if (AppCompatActivity != null && ContextCompat.CheckSelfPermission(AppCompatActivity, Manifest.Permission.AccessFineLocation) != Permission.Granted &&
                    ContextCompat.CheckSelfPermission(AppCompatActivity, Manifest.Permission.AccessCoarseLocation) != Permission.Granted)
                {
                    ActivityCompat.RequestPermissions(AppCompatActivity, new String[] { Manifest.Permission.AccessCoarseLocation, Manifest.Permission.AccessFineLocation },
                                                      PERMISSION_LOCATION_REQUEST_CODE);
                    return(false);
                }

                LocationManager locMan       = AppCompatActivity?.GetSystemService(Context.LocationService) as LocationManager;
                bool            isGPSEnabled = (bool)locMan?.IsProviderEnabled(LocationManager.GpsProvider);
                bool            isNetEnabled = (bool)locMan?.IsProviderEnabled(LocationManager.NetworkProvider);

                Android.Locations.Location location = null;

                if (isGPSEnabled || isNetEnabled)
                {
                    Criteria locCriteria = new Criteria()
                    {
                        Accuracy = Accuracy.Coarse, CostAllowed = false, PowerRequirement = Power.Low
                    };
                    string provider = locMan.GetBestProvider(locCriteria, true);
                    location = locMan.GetLastKnownLocation(provider);

                    if (location == null)
                    {
                        locMan.RequestSingleUpdate(provider, mLocListnr, null);
                    }
                    else
                    {
                        LocationData lastGPSLocData = await Settings.GetLastGPSLocData();

                        // Check previous location difference
                        if (lastGPSLocData.query != null &&
                            mLocation != null && ConversionMethods.CalculateGeopositionDistance(mLocation, location) < 1600)
                        {
                            return(false);
                        }

                        if (lastGPSLocData.query != null &&
                            Math.Abs(ConversionMethods.CalculateHaversine(lastGPSLocData.latitude, lastGPSLocData.longitude,
                                                                          location.Latitude, location.Longitude)) < 1600)
                        {
                            return(false);
                        }

                        LocationQueryViewModel view = null;

                        await Task.Run(async() =>
                        {
                            view = await wm.GetLocation(location);

                            if (String.IsNullOrEmpty(view.LocationQuery))
                            {
                                view = new LocationQueryViewModel();
                            }
                        });

                        if (String.IsNullOrWhiteSpace(view.LocationQuery))
                        {
                            // Stop since there is no valid query
                            return(false);
                        }

                        // Save oldkey
                        string oldkey = lastGPSLocData.query;

                        // Save location as last known
                        lastGPSLocData.SetData(view, location);
                        Settings.SaveLastGPSLocData(lastGPSLocData);

                        App.Context.StartService(
                            new Intent(App.Context, typeof(WearableDataListenerService))
                            .SetAction(WearableDataListenerService.ACTION_SENDLOCATIONUPDATE));

                        this.location = lastGPSLocData;
                        mLocation     = location;

                        // Update widget ids for location
                        if (oldkey != null && WidgetUtils.Exists(oldkey))
                        {
                            WidgetUtils.UpdateWidgetIds(oldkey, lastGPSLocData);
                        }

                        locationChanged = true;
                    }
                }
                else
                {
                    AppCompatActivity?.RunOnUiThread(() =>
                    {
                        Toast.MakeText(AppCompatActivity, Resource.String.error_retrieve_location, ToastLength.Short).Show();
                    });
                }
            }

            return(locationChanged);
        }
예제 #20
0
 //Not Implemented - MSH.19 -> MSH.21
 public override string ToString()
 {
     return
         ($"{Prefix}{FieldSeparator}{ConversionMethods.BuildOrderedCollection(this).Result.ToFieldSeparatorString()}");
 }
        private void kbtnConvertToRGB_Click(object sender, EventArgs e)
        {
            ConversionMethods conversionMethods = new ConversionMethods();

            cpbColourPreview.BackColor = conversionMethods.ConvertHexadecimalToRGB($"#{ ktxtHexValue.Text }");
        }
예제 #22
0
 public override string ToString()
 {
     return
         ($"{Prefix}{Configuration.Configuration.ConfigurationData.Instance.ParsingData.FieldSeparator}{ConversionMethods.BuildOrderedCollection(this).Result.ToFieldSeparatorString()}");
 }