Ejemplo n.º 1
0
        public async void Search(string HostIDOne, string HostIDTwo, string NetworkIDOne, string NetworkIDTwo, int timeout, int start, int end)
        {
            var approximateNetwork = DataConversion.GetHttpStringFromStrings(HostIDOne, HostIDTwo, NetworkIDOne, NetworkIDTwo);

            try
            {
                Uri approximateNetworkUri = new Uri(approximateNetwork);
                if (approximateNetwork != null)
                {
                    WebServerCentralManager.SetApproximateNetwork(approximateNetworkUri);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            var deviceState = WebServerCentralManager.GetDeviceState();

            if (deviceState.State == States.On)
            {
                WebServerCentralManager.Search(start, end, timeout);
            }
            else
            {
                DialogBoxYesOrNo dialogButton = new DialogBoxYesOrNo();
                var result = await dialogButton.ShowDialogBox("It doesn't look like WiFi is on. Go to settings?");

                if (result)
                {
                    bool settingsResult = await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:network-wifi"));
                }
            }
        }
Ejemplo n.º 2
0
        private static void processProviderWeeklyStatement(Provider p, IQueryable <Claim> claims)
        {
            IReportService Writer       = ServiceFactory.getReportService();
            IEmailService  emailServer  = ServiceFactory.getEmailService();
            IClaimService  claimService = ServiceFactory.getClaimService();
            int            personId;
            string         statement = "";

            personId = (p as Provider).ProviderID;
            var personClaims = claims.Where(e => e.Provider.ProviderID == personId);

            statement = p.generateProviderCoverStatment(personClaims);
            var serializedClaims = claimService.generateSerializedReport(p, personClaims);

            statement += DataConversion.ConvertDataTableToHTML(DataConversion.ToDataTable(serializedClaims));
            MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(statement));
            //Add a new attachment to the E-mail message, using the correct MIME type
            Attachment attachment = new Attachment(stream, new ContentType("text/plain"));

            attachment.Name = "statment.html";
            //send email
            emailServer.sendEmail("*****@*****.**", p.Email, "ChocAn Statment", "Attached your statment for this week.", new Attachment[] { attachment });
            //store file
            Writer.writeWeeklyStatment(p, statement);
        }
Ejemplo n.º 3
0
        // TODO: use database ID for edit
        public EditRegularItemVM(bool _IsIncome, bool _IsAdd, int _RegularItemId)   // _RegularItemId could be NEW_REGULAR_ITEM_ID
        {
            m_IsIncome = _IsIncome;

            string action    = _IsAdd ? "Add" : "Update";
            string direction = _IsIncome ? "Income" : "Expense";

            Header      = string.Format("{0} {1}", action, direction);
            HeaderColor = _IsIncome ? "ForestGreen" : "DarkRed";

            EditButtonText = string.Format("{0} {1}", action, direction);

            if (_RegularItemId != RegularItemVM.NEW_REGULAR_ITEM_ID)
            {
                RegularItemId = _RegularItemId;

                RegularStorage db = new RegularStorage();
                RegularItem    ri = db.GetRegular(_RegularItemId);

                this.Name   = ri.Name;
                this.Amount = DataConversion.ConvertCentsToCurrency(Math.Abs(ri.Amount)).ToString();
                SetPeriod(ri.Period);
            }
            else
            {
                RegularItemId = RegularItemVM.NEW_REGULAR_ITEM_ID;

                Name   = "";
                Amount = "";
                SetPeriod(REGULARS_PERIOD.YEARLY);
            }
        }
Ejemplo n.º 4
0
    void FixedUpdate()
    {
        float XmoveHorizontal = DataConversion.GetHorizontalMove();
        //float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        //		Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
        //		GetComponent<Rigidbody>().velocity = movement * speed;

        GetComponent <Rigidbody>().position = new Vector3
                                              (
            XmoveHorizontal,
            0.0f,
            0.0f
                                              );


        GetComponent <Rigidbody>().position = new Vector3
                                              (
            Mathf.Clamp(GetComponent <Rigidbody>().position.x, boundary.xMin, boundary.xMax),
            0.0f,
            Mathf.Clamp(GetComponent <Rigidbody>().position.z, boundary.zMin, boundary.zMax)
                                              );
//
        if (((GetComponent <Rigidbody>().position.x < 0.3) && (GetComponent <Rigidbody>().position.x > -0.3)) || (GetComponent <Rigidbody>().position.x == 6) || (GetComponent <Rigidbody>().position.x == -6))
        {
            openFire = true;
        }


        GetComponent <Rigidbody>().rotation = Quaternion.Euler(0.0f, 0.0f, GetComponent <Rigidbody>().velocity.x * -tilt);
    }
Ejemplo n.º 5
0
    /// <summary>
    /// 获取照片
    /// </summary>
    private void UploadPicture()
    {
        //获取到动态图片的Texture
        baseTexture = UIManager.instance.camera_display.mainTexture;
        //转换贴图格式
        Texture2D completeTexture2D = DataConversion.TextureToTexture2D(baseTexture);
        //创建精灵
        Sprite competeSprite = Sprite.Create(completeTexture2D, new Rect(0, 0, completeTexture2D.width, completeTexture2D.height), new Vector2(0.5f, 0.5f));

        //应用精灵到指定图片
        UIManager.instance.picture_get.sprite = competeSprite;
        //打开截图(识别已完成)
        UIManager.instance.picture_get.gameObject.SetActive(true);
        //关闭视频窗口
        UIManager.instance.camera_display.gameObject.SetActive(false);
        //转换成.jpg文件
        byte[] jpgPicture = completeTexture2D.EncodeToJPG();
        //保存图片到电脑指定目录
        //SaveImage.SaveToFile(jpgPicture);
        //保存图片到手机相册
        SaveImage.SaveToFileAndroid(jpgPicture);
        //停止相机
        //GetComponent<CameraControl>().StopCamera();
        //PlantDetectDemo();
        AdvancedGeneralDemo();
    }
Ejemplo n.º 6
0
 public static double[] GetZValues(DicomDataset doseData)
 //This method gives back a double array with elements corresponding to the z-values for the doseMatrix 3rd dimension.
 {
     double[] offsetVector = doseData.Get <double[]>(DicomTag.GridFrameOffsetVector);
     double[] doseCorner   = doseData.Get <double[]>(DicomTag.ImagePositionPatient);
     //If first element starts with a 0, its a relative offset. if it starts with non-zero, it is patient coordinate system values
     if (offsetVector[0] != 0)
     {
         for (int i = 0; i < offsetVector.Length; i++)
         {
             offsetVector[i] -= offsetVector[0];
         }
     }
     double[] zValues = new double[offsetVector.Length];
     for (int i = 0; i < offsetVector.Length; i++)
     {
         zValues[i] = offsetVector[i] + doseCorner[2];
     }
     //Now flip if sorted by descending z.
     if (zValues[1] - zValues[0] < 0)
     {
         zValues = DataConversion.ReverseArray(zValues);
     }
     return(zValues);
 }
Ejemplo n.º 7
0
 public void SetActive(bool active, float[] position, float rotation)
 {
     transform.position = DataConversion.FloatArrayToVector3(position);
     transform.rotation = Quaternion.identity;
     transform.RotateAround(transform.position, Vector3.up, rotation);
     gameObject.SetActive(active);
 }
Ejemplo n.º 8
0
        public static double[] GetYValues(DicomDataset doseData)
        {
            int[]    orientation = doseData.Get <int[]>(DicomTag.ImageOrientationPatient);
            double[] doseCorner  = doseData.Get <double[]>(DicomTag.ImagePositionPatient);
            int      rows        = doseData.Get <int>(DicomTag.Rows);

            double[] pixelSpacing = doseData.Get <double[]>(DicomTag.PixelSpacing);
            double[] yValues      = new double[rows];
            if ((orientation[0] == 1) && (orientation[1] == 0) && (orientation[2] == 0))
            {
                for (int i = 0; i < rows; i++)
                {
                    yValues[i] = pixelSpacing[1] * i + doseCorner[1];
                }
            }
            else if ((orientation[0] == -1) && (orientation[1] == 0) && (orientation[2] == 0))
            {
                for (int i = 0; i < rows; i++)
                {
                    yValues[i] = -pixelSpacing[1] * i + doseCorner[1];
                    yValues    = DataConversion.ReverseArray(yValues);
                }
            }
            else
            {
                Console.WriteLine("patient orientation error encountered. Terminating.");
                Environment.Exit(2);
            }
            return(yValues);
        }
Ejemplo n.º 9
0
        public static double[] GetXValues(DicomDataset doseData)
        {
            int[]    orientation = doseData.Get <int[]>(DicomTag.ImageOrientationPatient);
            double[] doseCorner  = doseData.Get <double[]>(DicomTag.ImagePositionPatient);
            int      cols        = doseData.Get <int>(DicomTag.Columns);

            double[] pixelSpacing = doseData.Get <double[]>(DicomTag.PixelSpacing);
            double[] xValues      = new double[cols];
            if ((orientation[3] == 0) && (orientation[4] == 1) && (orientation[5] == 0))
            {
                for (int i = 0; i < cols; i++)
                {
                    xValues[i] = pixelSpacing[0] * i + doseCorner[0];
                }
            }
            else if ((orientation[3] == 0) && (orientation[4] == -1) && (orientation[5] == 0))
            {
                for (int i = 0; i < cols; i++)
                {
                    xValues[i] = -pixelSpacing[0] * i + doseCorner[0];
                    xValues    = DataConversion.ReverseArray(xValues);
                }
            }
            else
            {
                Console.WriteLine("patient orientation error encountered. Terminating.");
                Environment.Exit(2);
            }
            return(xValues);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Check that data is valid.
        /// </summary>
        public override void CheckData()
        {
            base.CheckData();
            if (DataConversion.IsNotNull())
            {
                throw new ApplicationException("Not yet implemented");
            }
            if (DataLimitation.IsNotNull())
            {
                throw new ApplicationException("Not yet implemented");
            }

            if (DataCondition.IsNull())
            {
                DataConversion.CheckNotNull("DataConversion");
            }
            else
            {
                DataConversion.CheckNull("DataConversion");
            }

            if (DataCondition.IsNotNull())
            {
                DataCondition.CheckData();
            }
            if (DataConversion.IsNotNull())
            {
                DataConversion.CheckData();
            }
            if (DataLimitation.IsNotNull())
            {
                DataLimitation.CheckData();
            }
        }
Ejemplo n.º 11
0
        public int GetAverageExpense()
        {
            try
            {
                using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
                {
                    var allExpenses = conn.Table <ExpenseItem>();

                    var expenses = (from r in allExpenses
                                    group r by r.Date into g
                                    select new { Amount = g.Sum((t) => (t.Amount)) }
                                    );

                    float avgCurrency = (float)expenses.Average(o => o.Amount) / 100.0f;

                    int avg = DataConversion.ConvertCurrencyToCents(avgCurrency);

                    return(avg);
                }
            }
            catch
            {
                return(0);   // error!!
            }
        }
Ejemplo n.º 12
0
        public static UploadConfigModel GetUploadConfig()
        {
            UploadConfigModel model = new UploadConfigModel
            {
                UploadWebPath       = ConfigurationManager.AppSettings["UploadWebPath"],
                AttachPath          = ConfigurationManager.AppSettings["AttachPath"],
                AttachExtension     = ConfigurationManager.AppSettings["AttachExtension"],
                AttachFileSize      = DataConversion.StrToInt(ConfigurationManager.AppSettings["AttachFileSize"]),
                AttachImgSize       = DataConversion.StrToInt(ConfigurationManager.AppSettings["AttachImgSize"]),
                AttachImgMaxHeight  = DataConversion.StrToInt(ConfigurationManager.AppSettings["AttachImgMaxHeight"]),
                AttachImgMaxWidth   = DataConversion.StrToInt(ConfigurationManager.AppSettings["AttachImgMaxWidth"]),
                ThumbnailHeight     = DataConversion.StrToInt(ConfigurationManager.AppSettings["ThumbnailHeight"]),
                ThumbnailWidth      = DataConversion.StrToInt(ConfigurationManager.AppSettings["ThumbnailWidth"]),
                WatermarkPosition   = DataConversion.StrToInt(ConfigurationManager.AppSettings["WatermarkPosition"]),
                WatermarkImgQuality = DataConversion.StrToInt(ConfigurationManager.AppSettings["WatermarkImgQuality"]),
                //水印暂无
                WatermarkType         = 0,
                WatermarkPic          = "",
                WatermarkTransparency = 0,
                WatermarkText         = "",
                WatermarkFont         = "",
                WatermarkFontSize     = 0,
            };

            return(model);
        }
Ejemplo n.º 13
0
        private void HttpPeripheral_ReceivedData(object source, ReceivedDataEventArgs args)
        {
            var argsByteArray = args.ReceivedData;
            var str           = DataConversion.ByteArrayToAsciiString(argsByteArray);

            Debug.Write(str);
        }
Ejemplo n.º 14
0
        // TODO: use database ID for edit
        public EditUniqueItemVM(bool _IsAdd, int _ItemId)   // _RegularItemId could be NEW_REGULAR_ITEM_ID
        {
            m_ShowAddButton = _IsAdd;

            if (_ItemId != NEW_REGULAR_ITEM_ID)
            {
                UniqueExpenseItemId = _ItemId;

                UniqueExpensesStorage db = App.GlobalPersistanceService.GetUniqueExpensesStorage();
                UniqueExpenseItem     ri = db.GetUniqueExpense(_ItemId);

                this.Date = ri.Date.ToLocalTime();
                this.Name = ri.Name;
                int am = ri.Amount;
                m_IsIncome  = am > 0;                                                         // save "income" or "expense"
                this.Amount = DataConversion.ConvertCentsToCurrency(Math.Abs(am)).ToString(); // display abs amount
            }
            else
            {
                UniqueExpenseItemId = NEW_REGULAR_ITEM_ID;

                Name   = "";
                Amount = "";
                Date   = DateTimeOffset.Now.Date;
            }

            UpdateButtonColor = m_IsIncome ? "ForestGreen" : "DarkRed";

            UpdateButtonText = m_IsIncome ? "Update Income" : "Update Expense";
        }
Ejemplo n.º 15
0
        public DisplayEntry(Entry entry)
        {
            Dict entryDict = new ManageDicts().Dicts.Where(p => p.DictID == entry.DictId).FirstOrDefault();

            if (entryDict != null)
            {
                DictId         = entryDict.DictID;
                BookName       = entryDict.BookName;
                WordStr        = entry.WordStr;
                wordDataOffset = entry.wordDataOffset;
                wordDataSize   = entry.wordDataSize;

                string dictPath = entryDict.dictPath;

                using (FileStream fileStream = new FileStream(dictPath, FileMode.Open, FileAccess.Read))
                {
                    byte[] buffer     = new byte[entry.wordDataSize]; // create buffer
                    int    seekOffset = checked ((int)UInt64.Parse(entry.wordDataOffset));
                    int    length     = checked ((int)entry.wordDataSize);

                    fileStream.Seek(seekOffset, SeekOrigin.Begin);
                    fileStream.Read(buffer, 0, length);

                    string charString = DataConversion.GetString(buffer);

                    Definition = new List <Paragraph>();
                    Paragraph[] paragraphs = DataConversion.FormatDefinition(charString, entryDict.sameTypeSequence);

                    foreach (Paragraph paragraph in paragraphs)
                    {
                        Definition.Add(paragraph);
                    }
                }
            }
        }
Ejemplo n.º 16
0
        public GetPagingResponse <ActivityUser> GetActivityUser(GetPagePostsRequest request)
        {
            var response = new GetPagingResponse <ActivityUser>();
            var result   = DbBase.Query <ActivityUser>().Where(p => p.ActivityId == request.activityid) //查询状态为显示的数据
                           .OrderByDescending(p => p.voteNum)                                           //排序方式:倒序,顺序:是否置顶->排序值->创建时间
                           .ThenByDescending(p => p.AddTime)
                           .ToPage(request.PageIndex, request.PageSize);

            if (request.Title != "" && request.Title != null)
            {
                result = DbBase.Query <ActivityUser>().Where(p => p.Name.Contains(request.Title) || p.Class.Contains(request.Title) && p.ActivityId == request.activityid) //查询状态为显示的数据
                         .OrderByDescending(p => p.voteNum)                                                                                                                //排序方式:倒序,顺序:是否置顶->排序值->创建时间
                         .ThenByDescending(p => p.AddTime)
                         .ToPage(request.PageIndex, request.PageSize);
            }
            if (DataConversion.StrToInt(request.Title) > 0)
            {
                result = DbBase.Query <ActivityUser>().Where(p => p.Id == DataConversion.StrToInt(request.Title) && p.ActivityId == request.activityid) //查询状态为显示的数据
                         .OrderByDescending(p => p.voteNum)                                                                                             //排序方式:倒序,顺序:是否置顶->排序值->创建时间
                         .ThenByDescending(p => p.AddTime)
                         .ToPage(request.PageIndex, request.PageSize);
            }
            if (result.Items != null && result.Items.Count > 0)
            {
                response.IsSuccess = true;
                response.Message   = "获取成功!";
                response.Pages     = result;
                return(response);
            }
            response.Message = "暂无数据!";
            return(response);
        }
Ejemplo n.º 17
0
        public static int[] LowestValIndices(double[,] a, int dim, int numberPoints)
        //returns a list of indices corresponding to the lowest values within a list at a certain dimension.
        {
            double[]   min  = { a[0, dim], 0 }; //first entry min, second corresponding index
            List <int> used = new List <int>();

            int[] smalls = new int[numberPoints];

            for (int i = 0; i < numberPoints; i++)
            {
                for (int j = 0; j < a.GetLength(0); j++)
                {
                    if ((a[j, dim] < min[0]) && (!used.Contains(j)))
                    {
                        min[0] = a[j, dim];
                        min[1] = j;
                    }
                }
                smalls[i] = (int)min[1];
                used.Add(smalls[i]);
                min[0] = 1000;
                min[1] = 0;
            }
            smalls = Sort(smalls);
            smalls = DataConversion.ReverseArray(smalls);
            return(smalls);
        }
Ejemplo n.º 18
0
 private void InitializeRegularItem(int _Id, string _Name, int _Amount, REGULARS_PERIOD _Period)
 {
     this.Id     = _Id;
     this.Name   = _Name;
     this.Amount = DataConversion.ConvertCentsToCurrency(_Amount);
     InitializePeriod(_Period);
 }
Ejemplo n.º 19
0
        internal long GetWeight(HttpRequestBase httpRequest, long kgWeight, StatisticsDbModel userStatistics)
        {
            var  dbContext      = new ApplicationDbContext();
            long convertedValue = kgWeight;

            if (string.IsNullOrEmpty(userStatistics.WeightUnit))
            {
                if (httpRequest != null && httpRequest.Cookies[DataConversion.WeightUnitCookie] != null &&
                    httpRequest.Cookies[DataConversion.WeightUnitCookie].Value != null)
                {
                    if (httpRequest.Cookies[DataConversion.WeightUnitCookie].Value == DataConversion.WeightPounds)
                    {
                        userStatistics.WeightUnit = DataConversion.WeightPounds;
                        convertedValue            = DataConversion.ConvertKilogramsToPounds(kgWeight);
                    }
                    else
                    {
                        userStatistics.WeightUnit = DataConversion.WeightKilograms;
                    }
                    dbContext.SaveChanges();
                }
            }
            else
            {
                convertedValue = userStatistics.WeightUnit == DataConversion.WeightPounds ?
                                 DataConversion.ConvertKilogramsToPounds(kgWeight) : kgWeight;
            }

            return(convertedValue);
        }
Ejemplo n.º 20
0
        public async void Search(int startIndex, int endIndex, int timeout = 300)
        {
            // 1. Convert the passed IP down to 3 places.
            // 2. Create System.Net.Http.HttpClient (NOTE: Windows HttpClient doesn't seem to have
            //    adjustable timeout.)
            // 3. Set the POST string to "name".  This will be used as a handshake.
            // 4. Iterate over the IP range, POSTing handshake.
            // 5. If handshake successful at IP, create a peripheral and add it to list.
            // 6. Update DeviceState: Searching->On
            // 7. After iteration, return list, even if empty.

            DiscoveredPeripherals = new Dictionary <string, WebServerPeripheral>();

            DataConversion dataConverter  = new DataConversion();
            var            fourthPartOfIp = DataConversion.SeperateStringByCharacterIndex(IP.ToString(), 3, '.');
            var            threePartIP    = IP.ToString().Replace(fourthPartOfIp, "");
            var            httpClient     = new System.Net.Http.HttpClient();

            httpClient.Timeout = new TimeSpan(0, 0, 0, 0, timeout);

            DeviceState.State = States.Searching;
            OnDeviceStateChange(DeviceState);

            for (int i = startIndex; i < endIndex; i++)
            {
                try
                {
                    string ip          = threePartIP + i.ToString() + "/";
                    var    resourceUri = new Uri(ip + WebServerPeripheral.WebServiceGetName);
                    var    response    = await httpClient.PostAsync(resourceUri, null);

                    if (response.IsSuccessStatusCode == true)
                    {
                        var deviceName = await response.Content.ReadAsStringAsync();

                        if (deviceName != "")
                        {
                            try
                            {
                                WebServerPeripheral peripheral = new WebServerPeripheral(deviceName, new Uri(ip));
                                DiscoveredPeripherals.Add(deviceName, peripheral);
                                OnDiscoveringDevice(peripheral);
                            } catch (Exception ex)
                            {
                                Debug.WriteLine("Exception in WifiCentralManager.Search: " + ex.Message);
                            }
                        }
                    }
                    response.Dispose();
                }
                catch (Exception ex)
                {
                    OnDiscoveringDevice(null);
                    Debug.WriteLine("Exception in WifiCentralManager.Search: " + ex.Message);
                    DeviceState.State = States.Unknown;
                }
            }
            UpdateDeviceStateWithWifiStatus();
        }
Ejemplo n.º 21
0
        private T ReplaceConstants <T>(XElement root, string attributeName)
        {
            var value = root.GetAttributeValue <string>(attributeName);

            value = ReplaceConstants(value);

            return(DataConversion.Convert <T>(value));
        }
Ejemplo n.º 22
0
 public UniqueExpenseVM(int _Id, DateTime _Date, int _Amount, string _Name)
 {
     this.Id           = _Id;
     this.Date         = _Date;
     this.Amount       = DataConversion.ConvertCentsToCurrency(Math.Abs(_Amount));
     this.SignedAmount = DataConversion.ConvertCentsToCurrency(_Amount);
     this.AmountColor  = ViewHelpers.GetColorByAmount(_Amount);
     this.Name         = _Name;
 }
Ejemplo n.º 23
0
    }//end method GetDataGetDataFromNotification

    private void myCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
    {
        /* Create an array to hold sensor data */
        byte[] sensorData = new byte[args.CharacteristicValue.Length];

        DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(sensorData);

        sensorValue.Buffer = DataConversion.convertSensorData(sensorData);
    } //end method myCharacteristic_ValueChanged
Ejemplo n.º 24
0
        public ExpenseVM(int _Id, DateTime _Date, int _Amount)
        {
            m_Date = _Date;

            this.Id = _Id;
            SetDate(_Date);
            this.Amount      = DataConversion.ConvertCentsToCurrency(_Amount);
            this.AmountColor = GetColorByAmount(_Amount);
        }
Ejemplo n.º 25
0
        public void writeServiceDirectory(Provider provider, List <ServiceReportItem> services)
        {
            string    fileName = String.Format("ServiceDirectory_{0}_{1:MM-dd-yyyy}", provider.Name.Replace(" ", "-"), DateTime.Now);
            string    filePath = System.Web.HttpContext.Current.Server.MapPath("~/Reports/" + fileName);
            DataTable dt       = DataConversion.ToDataTable(services);

            //you can activate next line to do CSV file
            // ReportWriter.CreateCSVFile(dt, filePath + ".txt");
            ReportWriter.CreateHtmlFile(dt, filePath + ".html");
        }
Ejemplo n.º 26
0
        public async Task <IHttpActionResult> Performance(Performance model)
        {
            try
            {
                List <DriverScore> driverScoreList = new List <DriverScore>();
                var         strPath     = @"G:\Projects\APTCAPI\CTAPI\Performance.json";
                string      localPath   = new Uri(strPath).LocalPath;
                Performance performance = new Performance();
                using (StreamReader read = new StreamReader(strPath))
                {
                    string json = read.ReadToEnd();
                    performance = JsonConvert.DeserializeObject <Performance>(json);
                }
                foreach (var score in performance.DriverScore)
                {
                    DriverScore driverScore = new DriverScore();
                    driverScore.DriverId     = score.DriverId;
                    driverScore.KmsTravelled = score.KmsTravelled;
                    driverScore.Braking      = score.Braking;
                    driverScore.Accel        = score.Accel;
                    driverScore.Corner       = score.Corner;
                    driverScore.Idle         = score.Idle;
                    driverScore.Speeding     = score.Speeding;
                    driverScore.AverageTotal = score.Speeding;
                    driverScoreList.Add(score);
                }

                var performanceDoc = new Document <Performance>()
                {
                    Id      = CreateUserKey(),
                    Content = new Performance
                    {
                        //Id = CreateUserKey(),
                        StartDateTime = performance.StartDateTime,
                        EndDateTime   = performance.EndDateTime,
                        Created_On    = DataConversion.ConvertYMDHMS(DateTime.Now.ToString()),
                        DriverScore   = driverScoreList
                    }
                };
                //IBucket _bucketperformance = ClusterHelper.GetBucket("DriverPerfoemance");
                var result = await _bucket.InsertAsync(performanceDoc);

                if (!result.Success)
                {
                    return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), result.Message), new JsonMediaTypeFormatter()));
                }
                return(Content(HttpStatusCode.OK, MessageResponse.Message(HttpStatusCode.OK.ToString(), MessageDescriptions.Add, result.Document.Id), new JsonMediaTypeFormatter()));
            }
            catch (Exception ex)
            {
                return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), ex.StackTrace), new JsonMediaTypeFormatter()));
            }
        }
Ejemplo n.º 27
0
        public async Task <IHttpActionResult> RegisterIncidentMessage(IncidentMessageModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var modelErrors = new List <string>();
                    foreach (var modelState in ModelState.Values)
                    {
                        foreach (var modelError in modelState.Errors)
                        {
                            modelErrors.Add(modelError.ErrorMessage);
                        }
                    }
                    return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), modelErrors[0].ToString()), new JsonMediaTypeFormatter()));
                }

                var userKey = "IncidentMessage_" + model.DriverID + "_" + DateTime.Now.Ticks.ToString();
                //if (await _bucket.ExistsAsync(userKey))
                //{
                //    //return Content(HttpStatusCode.Conflict, new Error($"Incident Message '{model.DriverID}' already exists"));
                //    return Content(HttpStatusCode.Conflict, MessageResponse.Message(HttpStatusCode.Conflict.ToString(), "167-Driver ID already exists"), new JsonMediaTypeFormatter());
                //}
                // call third part api to check Vehicle is valid or not
                var incidentMessageMessageDoc = new Document <IncidentMessageModel>()
                {
                    Id      = userKey,
                    Content = new IncidentMessageModel
                    {
                        DriverID = model.DriverID,
                        DateTime = model.DateTime,
                        Notes    = model.Notes,
                        // this is only UAT testing for check when ct created.
                        Created_On = DataConversion.ConvertYMDHMS(DateTime.Now.ToString()),
                        Created_By = "CarTrack"
                    }
                };
                var result = await _bucket.InsertAsync(incidentMessageMessageDoc);

                if (!result.Success)
                {
                    //return Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), EncryptDecrypt.Encryptword(result.Message)), new JsonMediaTypeFormatter());
                    return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), result.Message), new JsonMediaTypeFormatter()));
                }
                //return Content(HttpStatusCode.OK, MessageResponse.Message(HttpStatusCode.OK.ToString(),MessageDescriptions.Add, EncryptDecrypt.Encryptword(result.Document.Id)), new JsonMediaTypeFormatter());
                return(Content(HttpStatusCode.OK, MessageResponse.Message(HttpStatusCode.OK.ToString(), MessageDescriptions.Add, result.Document.Id), new JsonMediaTypeFormatter()));
            }
            catch (Exception ex)
            {
                return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), ex.StackTrace), new JsonMediaTypeFormatter()));
            }
        }
Ejemplo n.º 28
0
 public bool AddStringToSendBuffer(string str)
 {
     try
     {
         var listByteArray = DataConversion.StringToListByteArray(str);
         AddDataToSendBuffer(listByteArray.ToArray());
         return(true);
     } catch (Exception ex)
     {
         Debug.WriteLine("Exception in AddStringToSendBuffer: " + ex.Message);
         return(false);
     }
 }
Ejemplo n.º 29
0
        public async Task <IHttpActionResult> Register(License model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var modelErrors = new List <string>();
                    foreach (var modelState in ModelState.Values)
                    {
                        foreach (var modelError in modelState.Errors)
                        {
                            modelErrors.Add(modelError.ErrorMessage);
                        }
                    }
                    return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), modelErrors[0].ToString()), new JsonMediaTypeFormatter()));
                }

                var licenseId = "License" + CreateUserKey(model.LicenseNumber);
                if (await _bucket.ExistsAsync(model.LicenseNumber))
                {
                    //return Content(HttpStatusCode.Conflict, new Error($"License:-'{model.LicenseNumber}' already exists"));
                    return(Content(HttpStatusCode.Conflict, MessageResponse.Message(HttpStatusCode.Conflict.ToString(), "License already exists"), new JsonMediaTypeFormatter()));
                }
                //call api check driver varification  with EmiratiId if driver valid the driver valid will be true otherwise false
                var licenseDoc = new Document <License>()
                {
                    Id      = licenseId,
                    Content = new License
                    {
                        Id         = licenseId,
                        Action     = "Add",
                        IssueDate  = model.IssueDate,
                        ExpiryDate = model.ExpiryDate,
                        IsActive   = true,
                        IsDeleted  = true,
                        Created_On = DataConversion.ConvertYMDHMS(DateTime.Now.ToString()),
                    }
                };
                var result = await _bucket.InsertAsync(licenseDoc);

                if (!result.Success)
                {
                    return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), result.Message), new JsonMediaTypeFormatter()));
                }
                return(Content(HttpStatusCode.OK, MessageResponse.Message(HttpStatusCode.OK.ToString(), MessageDescriptions.Add, result.Document.Id), new JsonMediaTypeFormatter()));
            }
            catch (Exception ex)
            {
                return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), ex.StackTrace), new JsonMediaTypeFormatter()));
            }
        }
Ejemplo n.º 30
0
        private void UpdateContact_Click(object sender, RoutedEventArgs e)
        {
            // parse widgets values to data
            m_CurrentExpense.SetDate(w_DateOfExpense.Date.DateTime);
            int valCents = DataConversion.ConvertCurrencyStringToIntegerCents(w_AmountOfExpense.Text);

            // store data
            ExpenseItem spend = new ExpenseItem(m_CurrentExpense.Id, m_CurrentExpense.GetDateOnly(), valCents);

            App.GlobalPersistanceService.GetExpensesStorage().UpdateDetails(spend);//Update selected DB contact Id

            // interface transition
            Frame.Navigate(typeof(HomePage));
        }
Ejemplo n.º 31
0
 public void Setup()
 {
     this.dataConversion = Dependencies.Container.Resolve<DataConversion>();
 }