コード例 #1
0
        private void Accelerometer_ReadingChanged(object sender, AccelerometerChangedEventArgs e)
        {
            //==============================================================================================
            // Reference D4: Externally sourced program
            // Purpose: Steps counting Algorithm
            // Date: 05 Nov 2020
            // Source: YouTube Video
            // Author: Programmer world
            // Url: https://www.youtube.com/watch?v=o-qpVefrfVA
            // Adaptation: Got the idea on how to calculate magnitude,
            //===============================================================================================

            // Get the X,Y,Z Acceleration readings from the phone, and saving the, into variables as doubles
            float valueX = e.Reading.Acceleration.X;
            float valueY = e.Reading.Acceleration.Y;
            float valueZ = e.Reading.Acceleration.Z;

            // Calculates magnitude which represents the vibration on three axis coordinates (X,Y,Z)
            double currentMagnitude = Math.Sqrt((valueX * valueX) + (valueY * valueY) + (valueZ * valueZ));

            // Calculates the difference between the current and the last magnitude & checks how much of those
            // coordinate calues went up or low
            double differenceMagnitude = currentMagnitude - lastMagnitude;

            lastMagnitude = currentMagnitude;

            // If the difference is greater than 4, Count that step as walking
            if (differenceMagnitude > 4)
            {
                stepCount++;
                walkingSteps++;
            }

            //===============================================================================================
            // End reference D4
            //===============================================================================================

            // If the difference is greater than 6, Count that step as Running
            else if (differenceMagnitude > 6)
            {
                stepCount++;
                runningSteps++;
            }

            walkingCalories = walkingSteps * calorieBurntPerStep;   //
            runningCalories = runningSteps * calorieBurntPerStep;

            lblSteps.Text      = stepCount.ToString();              // Update steps (in circle)
            lblTotalSteps.Text = stepCount.ToString();              // Update total steps

            lblWalkSteps.Text = walkingSteps.ToString();            // Update walking steps done so far
            lblRunSteps.Text  = runningSteps.ToString();            // Update running steps done so far

            lblWalkCalorie.Text = walkingCalories.ToString();       // Update calories burnt when walking
            lblRunCalorie.Text  = runningCalories.ToString();       // Update calories burnt when running

            var copy = new PersonalData();

            copy.MySteps = stepCount;
        }
コード例 #2
0
        public PersonalData GetXMLNode()
        {
            PersonalData personalData = new PersonalData();

            string region = StateHelper.GetStateById(_user.StateId).AlphaCode;

            personalData.PersonName            = new PersonName();
            personalData.PersonName.GivenName  = _user.FirstName;
            personalData.PersonName.MiddleName = _user.MiddleName;
            personalData.PersonName.FamilyName = _user.LastName;

            personalData.DemographicDetail                    = new DemographicDetail();
            personalData.DemographicDetail.DateOfBirth        = DateTime.Parse(_user.Birthday.ToString()).ToShortDateString();
            personalData.DemographicDetail.GovernmentId       = new GovernmentId();
            personalData.DemographicDetail.GovernmentId.Value = string.IsNullOrEmpty(_user.IdentificationValue)?null: Decryptdata(_user.IdentificationValue);

            personalData.PostalAddress                             = new PostalAddress();
            personalData.PostalAddress.PostalCode                  = _user.Zip;
            personalData.PostalAddress.Region                      = region;
            personalData.PostalAddress.Municipality                = region;
            personalData.PostalAddress.DeliveryAddress             = new DeliveryAddress();
            personalData.PostalAddress.DeliveryAddress.AddressLine = _user.Address1;
            personalData.PostalAddress.DeliveryAddress.StreetName  = _user.Address2;

            personalData.EmailAddress = _user.Email;
            personalData.Telephone    = _user.CellPhone;

            return(personalData);
        }
コード例 #3
0
 void Awake()
 {
     fbManager.onLogged    += OnPlayerLogged;
     fbManager.onLoggedOut += OnPlayerLoggedOut;
     playerData             = null;
     friendsList            = null;
 }
コード例 #4
0
    IEnumerator GetPlayersInfo()
    {
        //yield return new WaitForSeconds(5); //try to solve the bug with getting another profile's data
        playerData = new PersonalData();
        yield return(StartCoroutine(TryGetUserName()));

        yield return(StartCoroutine(TryGetUserImage()));

        yield return(StartCoroutine(TryGetUserFriends()));

        playerData.score = GetRandomScore();
        List <PersonalData> players = new List <PersonalData>();

        players.Add(playerData);
        yield return(StartCoroutine(AddPlayersData(players)));

        players.Sort((PersonalData x, PersonalData y) =>
        {
            return(y.score.CompareTo(x.score));
        });

        for (int i = 0; i < players.Count; i++)
        {
            PlayerInfo info = Instantiate(playerInfoPrefab, scoreObjectsParent).GetComponent <PlayerInfo>();
            info.SetData(players[i]);
        }

        loadingText.SetActive(false);
    }
コード例 #5
0
        // for PersonalDetail
        //public static async Task<List<PersonalDivisionSection>> GetPersonalById(int id)
        //{
        //    string url = string.Format("/api/Personal/GetPersonalById?Id=" + id);
        //    List<PersonalDivisionSection> result = await ApiRequest<List<PersonalDivisionSection>>.GetRequest(url);
        //    return result;

        //}


        public static async Task <PersonalData> GetPersonalById(int id)
        {
            string       url    = string.Format("/api/PersonalDetail/GetPersonalById?Id=" + id);
            PersonalData result = await ApiRequest <PersonalData> .GetRequest(url);

            return(result);
        }
コード例 #6
0
        public async Task <string> GetAccount([FromRoute] int id)
        {
            //if (!ModelState.IsValid)
            //{
            //    return BadRequest(ModelState);
            //}

            //var account = await _context.YnabAccounts.FindAsync(id);

            //if (account == null)
            //{
            //    return NotFound();
            //}

            //return Ok(account);
            PersonalData   personalData   = _context.PersonalDatas.Where(x => x.ID == id).FirstOrDefault();
            List <Account> serverAccounts = await _context.YnabAccounts.Where(y => y.PersonalData == personalData).ToListAsync();

            List <string> accountNames = new List <string>()
            {
                "Name",
                "Type",
                "Balance",
            };
            var settings = new JsonSerializerSettings()
            {
                ContractResolver = new JsonPropRenderSettings(true, accountNames)
            };
            var json = JsonConvert.SerializeObject(serverAccounts, settings);

            return(json);
        }
コード例 #7
0
        public void TestIdentityCardNumber()
        {
            UserAccount  userAcc      = new UserAccount();
            PersonalData personalData = new PersonalData();

            personalData.PESEL              = PESEL;
            personalData.Sex                = SEX;
            personalData.FirstName          = firstName;
            personalData.LastName           = lastName;
            personalData.IdentityCardNumber = IDCN;
            personalData.PhoneNumber        = PHONE;
            userAcc.PersonalData            = personalData;

            List <UserAccount> userAccounts = new List <UserAccount>();

            NMock.Actions.InvokeAction addUserAccounts = new NMock.Actions.InvokeAction(() => userAccounts.Add(userAcc));
            accountAdministrationDao.Expects.One.MethodWith(x => x.SaveOrUpdateUser(userAcc)).Will(addUserAccounts);

            aas.SaveOrUpdateUser(userAcc);
            userInformationService.Expects.One.MethodWith(x => x.GetUserAccountById(userAcc.Id)).WillReturn(userAcc);
            PersonalData returnedPD = sps.GetUserPersonalDataById(userAcc.Id);

            Assert.AreEqual(PESEL, returnedPD.PESEL);
            Assert.AreEqual(SEX, returnedPD.Sex);
            Assert.AreEqual(firstName, returnedPD.FirstName);
            Assert.AreEqual(lastName, returnedPD.LastName);
            Assert.AreEqual(IDCN, returnedPD.IdentityCardNumber);
            Assert.AreEqual(PHONE, returnedPD.PhoneNumber);
        }
コード例 #8
0
ファイル: ParcelController.cs プロジェクト: kamiljan199/IOP
        public bool PostParcel(StorePlace storePlace, PersonalData senderData, PersonalData receiverData, float height, float length, float width, float weight, int priority, string type)
        {
            var parcel = new Parcel
            {
                StorePlaceId = storePlace.Id,
                SenderData   = senderData,
                ReceiverData = receiverData,
                ParcelHeight = height,
                ParcelWidth  = width,
                ParcelLength = length,
                ParcelWeight = weight,
                Priority     = priority,
                ReferenceId  = 0,
                ParcelStatus = ParcelStatus.AtPostingPoint
            };

            try
            {
                _parcelService.PostParcel(parcel);
            }
            catch (NothingAddedToDatabaseException e)
            {
                Console.WriteLine(e.ToString());
                return(false);
            }
            return(true);
        }
コード例 #9
0
        public static IForm <RegistrationForm> BuildForm()
        {
            OnCompletionAsyncDelegate <RegistrationForm> processOrder = async(context, state) =>
            {
                var personalData = new PersonalData
                {
                    Email          = state.Email,
                    FirstName      = state.FirstName,
                    Interests      = state.Interests,
                    IsAccepted     = state.IsAccepted,
                    LastName       = state.LastName,
                    PhoneNumber    = state.PhoneNumber,
                    Specialization = state.Specialization,
                    Year           = state.Year
                };
                DataProviderService.Instance.SetUserData(context.Activity.From.Id, personalData);
                var reply = context.MakeMessage();
                reply.Text = "Сейчас сделаю для тебя билет, приноси его с собой на мастер класс!";
                await context.PostAsync(reply);
            };

            return(new FormBuilder <RegistrationForm>()
                   .Message("Регистрация")
                   .AddRemainingFields()
                   .OnCompletion(processOrder)
                   .Build());
        }
コード例 #10
0
 public MainWindow()
 {
     InitializeComponent();
     InitializeMainWindow();
     PersonalData = new PersonalData(_companyPage.viewModel, _clientPage.viewModel);
     _commissionPage.CommissionGenerated += _commissionPage_CommissionGenerated;
 }
コード例 #11
0
        public void TheUntitled2Test()
        {
            OpenHomePage();
            Login(new AccountData("admin", "secret"));
            InitAddingNewPersonalData();

            PersonalData personalinfo = new PersonalData();

            personalinfo.Title    = "jgj";
            personalinfo.Company  = ";lh";
            personalinfo.Address  = "kj";
            personalinfo.Home     = "07";
            personalinfo.Mobile   = "df";
            personalinfo.Work     = "fbdg";
            personalinfo.Fax      = "fd";
            personalinfo.Email    = "tg";
            personalinfo.Email2   = "tg";
            personalinfo.Email3   = "tg";
            personalinfo.Homepage = "tg";
            personalinfo.Address2 = "uygf";
            personalinfo.Phone2   = "5346";
            personalinfo.Notes    = "uids dfsdfs";



            FillPersonalData(personalinfo);
            // ERROR: Caught exception [Error: Dom locators are not implemented yet!]
            ReturnToGroupPage();
        }
コード例 #12
0
        private void AddPatient(string login, string pass, string name, string surname, int specialityId, string sex, DateTime?date, string email, string phone)
        {
            using (MedicalClinicContext context = new MedicalClinicContext())
            {
                Doctor doctor = new Doctor();
                doctor.SpecialityId = specialityId;

                PersonalData patientPersonalData = new PersonalData();
                patientPersonalData.Name        = name;
                patientPersonalData.Surname     = surname;
                patientPersonalData.Sex         = sex;
                patientPersonalData.DateOfBirth = (DateTime)date;
                patientPersonalData.Email       = email;
                patientPersonalData.PhoneNumber = phone;

                context.PersonalData.Add(patientPersonalData);
                context.SaveChanges();

                User patientUser = new User();
                patientUser.Login    = login;
                patientUser.Password = pass;

                context.User.Add(patientUser);
                context.SaveChanges();

                doctor.User         = patientUser;
                doctor.PersonalData = patientPersonalData;

                doctor.UserId          = patientUser.Id;
                doctor.PersonalData.Id = patientPersonalData.Id;

                context.Doctor.Add(doctor);
                context.SaveChanges();
            }
        }
コード例 #13
0
 private static void ReplaceCompanyInfo(PersonalData UserData, DocX doc, bool replaceOnlyValues)
 {
     if (doc.FindAll("<CompanyInfo>").Count > 0)
     {
         doc.ReplaceText("<CompanyInfo>", UserData.Company.ToString());
     }
     else if (replaceOnlyValues == false)
     {
         doc.ReplaceText("<CompanyName>", UserData.Company.CompanyName);
         doc.ReplaceText("<CompanyEmail>", UserData.Company.EmailAddress.ToString());
         doc.ReplaceText("<CompanyAddress>", UserData.Company.Address.ToString());
         doc.ReplaceText("<CompanyAddressPostalCode>", UserData.Company.Address.ToString());
         doc.ReplaceText("<CompanyAddressStreet>", UserData.Company.Address.ToString());
         doc.ReplaceText("<CompanyAddressCity>", UserData.Company.Address.ToString());
         doc.ReplaceText("<CompanyPhoneNumber>", UserData.Company.PhoneNumber.ToString());
         doc.ReplaceText("<CompanyNIP>", UserData.Company.NIP.ToString());
         doc.ReplaceText("<CompanyREGON>", UserData.Company.REGON.ToString());
     }
     else
     {
         ReplaceEmail("<CompanyEmail>", UserData.Company.EmailAddress.Address, doc);
         doc.ReplaceText("<CompanyName>", UserData.Company.CompanyName);
         doc.ReplaceText("<CompanyAddressPostalCode>", UserData.Company.Address.ToString());
         doc.ReplaceText("<CompanyAddressStreet>", UserData.Company.Address.ToString());
         doc.ReplaceText("<CompanyAddressCity>", UserData.Company.Address.ToString());
         doc.ReplaceText("<CompanyAddress>", UserData.Company.Address.ToString());
         doc.ReplaceText("<CompanyPhoneNumber>", UserData.Company.PhoneNumber.Number);
         doc.ReplaceText("<CompanyNIP>", UserData.Company.NIP.Number);
         doc.ReplaceText("<CompanyREGON>", UserData.Company.REGON.Number);
     }
 }
コード例 #14
0
        public IHttpActionResult PutPersonalData(int id, PersonalData personalData)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != personalData.FriendId)
            {
                return(BadRequest());
            }

            db.Entry(personalData).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PersonalDataExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
コード例 #15
0
        public PersonalData ReadEmployeeData(int objectId)
        {
            var bsObj = new BindingSource(_dsQuarry, OBJECT_TABLE_NAME)
            {
                Filter = string.Format("ObjectId={0}", objectId)
            };

            Image imgTmp   = Properties.Resources.NoEmployeeImage2;
            var   persData = new PersonalData();

            if (bsObj.Count != 1)
            {
                return(persData);
            }

            DataRow row = ((DataRowView)(bsObj.Current)).Row;

            if (!Convert.IsDBNull(row["Photo"]))
            {
                using (var ms = new MemoryStream())
                {
                    ms.Write((byte[])row["Photo"], 0, ((byte[])row["Photo"]).Length);
                    imgTmp = Image.FromStream(ms);
                }
            }
            persData.Photo    = imgTmp;
            persData.ObjectId = objectId;
            persData.Fio      = string.Format("{0} {1} {2}", row["Surname"], row["Name"], row["Patronymic"]);
            persData.Dolj     = row["Position"].ToString();
            return(persData);
        }
コード例 #16
0
        protected override async Task <OperationResult> DoExecute(AddOrUpdateProfileDataCommandRequest request)
        {
            var data = await _dbContext.PersonalData.FirstOrDefaultAsync(e => e.UserId == request.UserId);

            if (data == null)
            {
                data = new PersonalData()
                {
                    Adress        = request.Data.Adress,
                    FatherName    = request.Data.FatherName,
                    MotherName    = request.Data.MotherName,
                    PrimarySchool = request.Data.PrimarySchool,
                    UserId        = request.UserId
                };
                _dbContext.PersonalData.Add(data);
            }
            else
            {
                data.Adress        = request.Data.Adress;
                data.FatherName    = request.Data.FatherName;
                data.MotherName    = request.Data.MotherName;
                data.PrimarySchool = request.Data.PrimarySchool;
            }

            await _dbContext.SaveChangesAsync();

            return(new OperationSucceded());
        }
コード例 #17
0
        public static ProfileDataDto FromPersonalDataEntity(User user, PersonalData entity, IEnumerable <PersonalDocument> documents)
        {
            var docs = documents?
                       .Where(d => d.Id != entity?.ProfilePictureFileId)
                       .Select(d => new DocumentDto()
            {
                FileUrl     = d.FileUrl,
                Id          = d.Id,
                Name        = d.Name,
                ContentType = d.ContentType
            }).ToList() ?? new List <DocumentDto>();

            var result = new ProfileDataDto()
            {
                UserId               = user.Id,
                Email                = user.Email,
                Name                 = user.Name,
                Surname              = user.Surname,
                BirthDate            = user.BirthDate,
                CandidateId          = user.CandidateId,
                Pesel                = user.Pesel,
                Adress               = entity?.Adress,
                FatherName           = entity?.FatherName,
                MotherName           = entity?.MotherName,
                PrimarySchool        = entity?.PrimarySchool,
                ProfilePictureFileId = entity?.ProfilePictureFileId,
                Status               = entity?.Status,
                ProfilePictureName   = documents.FirstOrDefault(d => d.Id == entity?.ProfilePictureFileId)?.Name,
                Documents            = docs
            };

            return(result);
        }
コード例 #18
0
        public void TestCollectionCreated()
        {
            _PersonData = new PersonalData(1, "haha", "hihi", "20.09.2019", "SV", "Upp", "Swe", "75626");
            _PD.AddData(_PersonData);

            Assert.IsNotNull(_PD.GetPDCollection());
        }
コード例 #19
0
ファイル: ClientObjectMothers.cs プロジェクト: pawlo601/Bazy
 public static Client CreateClientPrivateWithoutDiscount()
 {
     PersonalData per = new PersonalData("Imie", "Nazwisko");
     Address addr = new Address();
     Client a = new Client(per, addr);
     return a;
 }
コード例 #20
0
        public ActionResult ChangePersonalData()
        {
            var          userId       = User.Identity.GetUserId();
            PersonalData personalData = new PersonalData();

            personalData.ErrorMessage = "Konto nie posiada przypisanych danych pracownika.";
            personalData.CanSave      = false;
            Employee employee = _db.T_Employees.Where(e => e.UserId == userId).FirstOrDefault();

            if (employee == null)
            {
                return(View(personalData));
            }

            personalData = new PersonalData()
            {
                Id           = employee.Id,
                UserId       = userId,
                FirstName    = employee.FirstName,
                LastName     = employee.LastName,
                EMail        = UserManager.FindById(userId.ToString()).Email,
                ErrorMessage = "",
                CanSave      = true
            };

            return(View(personalData));
        }
コード例 #21
0
        private void ConfirmAppointmentButtonClick(object sender, RoutedEventArgs e)
        {
            int      doctorsId;
            int      patientId     = patient.Id;
            string   description   = DescriptionOfAppointment.Text;
            DateTime?dateOfMeeting = DateOfAppointment.SelectedDate;
            string   timeOfMeeting = TimeOfAppointment.SelectedItem == null ? "" : TimeOfAppointment.SelectedItem.ToString();

            using (MedicalClinicContext context = new MedicalClinicContext())
            {
                PersonalData doctorsPersData = (DoctorsField.SelectedItem as PersonalData);
                doctorsId = context.Doctor
                            .FirstOrDefault(doc => doc.PersonalDataId == doctorsPersData.Id).Id;
            }

            string errorMessage = CheckAppointmentPageValues(patientId, (DateTime)dateOfMeeting, timeOfMeeting);

            if (!String.IsNullOrEmpty(errorMessage))
            {
                MessageBox.Show(errorMessage);
            }
            else
            {
                AddAppointment(doctorsId, patientId, description, (DateTime)dateOfMeeting, timeOfMeeting);
                MessageBox.Show("Реєстрація на зустріч пройшла успішно");
                ClearAppointmentPage();
            }
        }
コード例 #22
0
 ///   
 /// Create instance based on any Source class as example based on PersonalData
 ///
 public static object CreateAnonymousDynamicInstance(PersonalData personalData, Type dynamicType, List<ClassDescriptorKeyValue> classDescriptionList)
 {
     var obj = Activator.CreateInstance(dynamicType);
     var propInfos = dynamicType.GetProperties();
     classDescriptionList.ForEach(x => SetValueToProperty(obj, propInfos, personalData, x));
     return obj;
 }
コード例 #23
0
ファイル: Reservations.cs プロジェクト: JanJPK/S5-IO
        /// <summary>
        ///     Dodaje nową rezerwacje. ID jest generowane automatycznie.
        /// </summary>
        /// <param name="personalData">Dane klienta.</param>
        /// <param name="show">Seans.</param>
        /// <param name="seat">Miejsce w sali.</param>
        /// <returns>Utworzoną rezerwację lub null jeżeli się nie udało.</returns>
        public Reservation Add(PersonalData personalData, Show show, Tuple <int, int> seat)
        {
            bool IsSeatAvailable() =>
            !show.Seats[seat.Item1, seat.Item2];

            // Sprawdzenie czy miejsce jest wolne.
            //if (show.Seats[seat.Item1, seat.Item2]) return null;
            if (!IsSeatAvailable())
            {
                return(null);
            }

            // ID rezerwacji = SRRR
            //      S - ID seansu
            //      RRR - ID rezerwacji
            int id = Items.Count == 0 ? 0 : Items.Keys.Max();

            id++;
            id += show.ID * 100;

            var reservation = new Reservation(id, personalData, show, seat);

            Items.Add(id, reservation);
            show.Seats[seat.Item1, seat.Item2] = true;
            return(reservation);
        }
コード例 #24
0
        public ActionResult DeleteConfirmed(int id)
        {
            PersonalData personalData = db.PersonalDatas.Find(id);

            db.PersonalDatas.Remove(personalData);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
コード例 #25
0
        public void AssertCDAutoFieldsData(PersonalData data)
        {
            var birthValue = this.BirthDate.GetAttribute("value");
            var gender     = this.Gender.GetAttribute("value");

            Assert.IsTrue(birthValue == data.BirthDate);
            Assert.IsTrue(gender != string.Empty);
        }
コード例 #26
0
ファイル: Client_panel.cs プロジェクト: 231014/Wypozyczalnia
        private void button1_Click(object sender, EventArgs e)
        {
            PersonalData pers = new PersonalData(txtImie.Text, txtNazwisko.Text, dateTimePicker1.Value);

            Data.Clients.Add(new WypozyczalniaDane.Client(pers));

            this.Close();
        }
コード例 #27
0
        private static string PersonalDataToString(PersonalData data)
        {
            string temp = data.FirstName + " " + data.LastName + "\n";

            temp += AddressToString(data.PersonalAddress);
            temp += "\nNr telefonu: " + data.PhoneNumber + "\n";
            return(temp);
        }
コード例 #28
0
 public User_JSON(string UserId, string NickName, bool IsLocal, PersonalData PersonalData = null, int AvatarId = 0)
 {
     this._userId       = UserId;
     this._nickName     = NickName;
     this._isLocal      = IsLocal;
     this._avatarId     = AvatarId;
     this._personalData = PersonalData;
 }
コード例 #29
0
        public void CreatePDColl()
        {
            _PersonData = new PersonalData(1, "haha", "hihi", "20.09.2019", "SV", "Upp", "Swe", "75626");
            _PD.AddData(_PersonData);
            _PD.SetEnum();

            Assert.AreEqual(_PersonData, _PD.SearchByID(1));
        }
コード例 #30
0
        public void SaveNewUserPersonalData(long userAccountId, PersonalData personalData, Address address)
        {
            UserAccount userAccount = ServiceLocator.UserInformationService.GetUserAccountById(userAccountId);

            userAccount.PersonalData = personalData;
            personalData.Address     = address;
            ServiceLocator.AccountAdministrationService.SaveOrUpdateUser(userAccount);
        }
コード例 #31
0
 public Message GetData()
 {
     // Create object
     PersonalData data = new PersonalData() { Name = "Mark", Age = 35 };
     // Create message
     MessageVersion ver = OperationContext.Current.IncomingMessageVersion;
     Message msg = Message.CreateMessage(ver, "ResponseToGetDataRequest", data);
     Debug.WriteLine(msg.ToString());
     return msg;
 }
コード例 #32
0
ファイル: Test.cs プロジェクト: marekrydlewski/get-ocr
    public static void Main()
    {
        PersonalData personalData = new PersonalData(); // creates instance of PersonalData to save result
        OcrReader OcrClient = new OcrReader("appka_testowa","9hWxj/lQvS/TdU193saHrhLG");//sets username && password
        byte[] data = File.ReadAllBytes("./dow_osob_rewers.gif");//image of document

        var postImageTask = OcrClient.PostImage(data); //uploads image
        string id = postImageTask.Result; //id of request, waiting for finishing PostImageTask

        var getOcrTask = OcrClient.GetOcr(id,2); //gets url with ocr data from passed id, 2 trials
        var result = getOcrTask.Result; // resulted URL , waiting for finishing getOCrTask
        personalData = OcrClient.GetPersonalData(result.Url); // reads data from URL

        Console.WriteLine(personalData.Name + " " + personalData.Surname + " " + personalData.BirthDate);
        Console.Read();
    }
コード例 #33
0
ファイル: Program.cs プロジェクト: marekrydlewski/get-ocr
    /// <summary>
    /// get personal data from passed url </summary>
    /// <param name="filePath"> string, url with requested data</param>
    /// <returns> returns personalData, empty properties in case of failure</returns>
    public PersonalData GetPersonalData(string filePath)
    {

        PersonalData personalData = new PersonalData();
          if (filePath != null && filePath != "")
          {
            try
            {
              XDocument xDoc = XDocument.Load(filePath);
              var ns = xDoc.Root.GetDefaultNamespace();

              personalData.BirthDate = (from xml2 in xDoc.Root.Descendants(ns + "field")
                                        where xml2.Attribute("type").Value == "BirthDate"
                                        select xml2.Element(ns + "value")).FirstOrDefault().Value;

              personalData.Name = (from xml2 in xDoc.Root.Descendants(ns + "field")
                                   where xml2.Attribute("type").Value == "GivenName"
                                   select xml2.Element(ns + "value")).FirstOrDefault().Value;

              personalData.Surname = (from xml2 in xDoc.Root.Descendants(ns + "field")
                                      where xml2.Attribute("type").Value == "LastName"
                                      select xml2.Element(ns + "value")).FirstOrDefault().Value;
              return personalData;
            }
            catch (Exception exception)
            {
              //Console.WriteLine("CAUGHT EXCEPTION:");
              //Console.WriteLine(exception);
              personalData.Name = "";
              personalData.Surname = "";
              personalData.BirthDate = "";
              return personalData;
            }
          }
          personalData.Name = "";
          personalData.Surname = "";
          personalData.BirthDate = "";
          return personalData;
    }