public void StopScan()
 {
     if (CurrenRfidReader.IsInScan)
     {
         LogToFile.LogMessageToFile("InScan - Stop it");
         CurrenRfidReader.RequestEndScan();
     }
 }
        public static async Task <bool> UpdateSelectionAsync(int IdSel, List <string> TagToRemove)
        {
            try
            {
                string serverIP   = Properties.Settings.Default.ServerIp;
                int    serverPort = Properties.Settings.Default.ServerPort;

                string urlServer = "http://" + serverIP + ":" + serverPort;
                var    client    = new RestClient(urlServer);
                client.Authenticator = new HttpBasicAuthenticator(publicApiLogin, publicApiMdp);
                var request = new RestRequest("selections/" + IdSel, Method.GET);
                client.Timeout           = timeout;
                client.ReadWriteTimeout  = timeout;
                request.Timeout          = timeout;
                request.ReadWriteTimeout = timeout;
                var response = await client.ExecuteTaskAsync(request);

                if (response.IsSuccessful)
                {
                    var Selection = JsonSelectionList.DeserializedJsonAlone(response.Content);
                    if (Selection != null)
                    {
                        if (Selection.state == "closed")
                        {
                            return(false);
                        }

                        var request2 = new RestRequest("/selections/" + IdSel, Method.PUT);

                        foreach (string uid in TagToRemove)
                        {
                            request2.AddParameter("listOfTagPulled", uid);
                        }

                        var client2 = new RestClient(urlServer);
                        client2.Authenticator = new HttpBasicAuthenticator(privateApiLogin, privateApiMdp);
                        LogToFile.LogMessageToFile("------- Start Update selection --------");
                        var response2 = await client2.ExecuteTaskAsync(request2);

                        LogToFile.LogMessageToFile(response2.Content);
                        LogToFile.LogMessageToFile("------- End Updateselection --------");
                        return(response2.IsSuccessful);
                    }
                    return(false);
                }
                return(false);
            }
            catch (Exception error)
            {
                ExceptionMessageBox exp = new ExceptionMessageBox(error, "Error update selection");
                exp.ShowDialog();
                return(false);
            }
        }
 private void UpdateMessage(object sender, MessageReceivedEvent e)
 {
     StrBadgeRead = (e.Message.Substring(0, 10));
     if (CurrenRfidReader != null)
     {
         if (CurrenRfidReader.TCPActionPending == false)
         {
             CurrenRfidReader.UserActionPending = true;
             DisplayBadge = true;
             string str = string.Format("------Badge Received : {0} ------", StrBadgeRead);
             LogToFile.LogMessageToFile(str);
         }
     }
 }
        public static async Task <bool> PostRequest(string user, string description, List <string> uids)
        {
            try
            {
                string serverIP   = Properties.Settings.Default.ServerIp;
                int    serverPort = Properties.Settings.Default.ServerPort;
                string urlServer  = "http://" + serverIP + ":" + serverPort;
                var    client     = new RestClient(urlServer);
                client.Authenticator = new HttpBasicAuthenticator(publicApiLogin, publicApiMdp);
                var request = new RestRequest("selections", Method.POST);
                client.Timeout           = timeout;
                client.ReadWriteTimeout  = timeout;
                request.Timeout          = timeout;
                request.ReadWriteTimeout = timeout;

                request.AddParameter("user_login", user);
                request.AddParameter("description", description);

                foreach (string uid in uids)
                {
                    request.AddParameter("listOfTagToPull", uid);
                }
                var response = await client.ExecuteTaskAsync(request);

                LogToFile.LogMessageToFile(response.ResponseStatus.ToString());
                LogToFile.LogMessageToFile(response.Content.ToString());

                return(response.IsSuccessful);
            }
            catch (Exception error)
            {
                LogToFile.LogMessageToFile(error.InnerException.ToString());
                LogToFile.LogMessageToFile(error.Message);
                LogToFile.LogMessageToFile(error.StackTrace);
            }
            return(false);
        }
        public static void HandleNewScanCompleted(int drawerId)
        {
            lock (lockMethodInventory)
            {
                LogToFile.LogMessageToFile("______________________________________________________________ ");
                LogToFile.LogMessageToFile("Process Inventory for drawer " + drawerId);

                var ctx = RemoteDatabase.GetDbContext();
                ctx.Configuration.AutoDetectChangesEnabled = false;
                //ctx.Configuration.ValidateOnSaveEnabled = false;
                Inventory newInventory = null;
                try
                {
                    if (_deviceEntity == null)
                    {
                        _deviceEntity = DevicesHandler.GetDeviceEntity();
                        if (_deviceEntity == null)
                        {
                            return;
                        }
                    }


                    //remove previous entry Older than 7 days
                    DateTime dtToKeep = DateTime.Now.AddDays(-7.0);

                    using (new PerfTimerLogger("remove previous entry Older than 7 days"))
                    {
                        //remove event drawer
                        var itemBinding2 = ctx.EventDrawerDetails.Where(i => i.DrawerNumber == drawerId && i.DeviceId == _deviceEntity.DeviceId && i.EventDrawerDate < dtToKeep);
                        if (itemBinding2 != null)
                        {
                            foreach (var ib in itemBinding2)
                            {
                                ctx.EventDrawerDetails.Remove(ib);
                            }
                        }

                        //removed inventory
                        var itemBinding = ctx.Inventories.Where(i => i.DrawerNumber == drawerId && i.DeviceId == _deviceEntity.DeviceId && i.InventoryDate < dtToKeep);
                        if (itemBinding != null)
                        {
                            foreach (var ib in itemBinding)
                            {
                                ctx.Inventories.Remove(ib);
                            }
                        }
                        ctx.ChangeTracker.DetectChanges();
                        ctx.SaveChanges();
                    }

                    using (new PerfTimerLogger("Store inventory"))
                    {
                        AccessType newInventoryAccessType    = null;
                        int?       newInventoryGrantedUserId = null;

                        switch (DevicesHandler.LastScanAccessTypeName)
                        {
                        case AccessType.Badge:
                            newInventoryAccessType    = ctx.AccessTypes.Badge();
                            newInventoryGrantedUserId = GrantedUsersCache.LastAuthenticatedUser.GrantedUserId;
                            break;

                        case AccessType.Fingerprint:
                            newInventoryAccessType    = ctx.AccessTypes.Fingerprint();
                            newInventoryGrantedUserId = GrantedUsersCache.LastAuthenticatedUser.GrantedUserId;
                            break;

                        default:
                            newInventoryAccessType    = ctx.AccessTypes.Manual();
                            newInventoryGrantedUserId = null;
                            break;
                        }

                        newInventory = new Inventory
                        {
                            DeviceId        = _deviceEntity.DeviceId,
                            DrawerNumber    = drawerId,
                            GrantedUserId   = newInventoryGrantedUserId,
                            AccessTypeId    = newInventoryAccessType.AccessTypeId,
                            TotalAdded      = DevicesHandler.ListTagAddedPerDrawer.Where(kvp => kvp.Value == drawerId).ToList().Count(),
                            TotalPresent    = DevicesHandler.ListTagPerDrawer.Where(kvp => kvp.Value == drawerId).ToList().Count(),
                            TotalRemoved    = DevicesHandler.ListTagRemovedPerDrawer.Where(kvp => kvp.Value == drawerId).ToList().Count(),
                            InventoryDate   = DateTime.Now,
                            InventoryStream = SerializeHelper.SeralizeObjectToXML(DevicesHandler.Device.ReaderData),
                        };

                        ctx.Inventories.Add(newInventory);
                        ctx.ChangeTracker.DetectChanges();
                        ctx.SaveChanges(); // now the inventory is saved, we can use its ID
                    }


                    using (new PerfTimerLogger("Store movement added"))
                    {
                        var addedTags = DevicesHandler.GetTagFromDictionnary(drawerId, DevicesHandler.ListTagAddedPerDrawer);
                        AddMovementToInventory(ctx, newInventory, addedTags, MovementType.Added, drawerId);
                        //ctx.ChangeTracker.DetectChanges();
                        ctx.SaveChanges();
                    }
                    using (new PerfTimerLogger("Store movement present"))
                    {
                        var presentTags = DevicesHandler.GetTagFromDictionnary(drawerId, DevicesHandler.ListTagPerDrawer);
                        AddMovementToInventory(ctx, newInventory, presentTags, MovementType.Present, drawerId);
                        ctx.ChangeTracker.DetectChanges();
                        ctx.SaveChanges();
                    }
                    using (new PerfTimerLogger("Store movement removed"))
                    {
                        var removedTags = DevicesHandler.GetTagFromDictionnary(drawerId, DevicesHandler.ListTagRemovedPerDrawer);
                        AddMovementToInventory(ctx, newInventory, removedTags, MovementType.Removed, drawerId);
                        ctx.ChangeTracker.DetectChanges();
                        ctx.SaveChanges();
                    }

                    //Update event drawer
                    using (new PerfTimerLogger("Update Inventory"))
                    {
                        ctx.EventDrawerDetails.UpdateInventoryForEventDrawer(_deviceEntity, drawerId, newInventory);
                        ctx.ChangeTracker.DetectChanges();
                        ctx.SaveChanges();
                    }


                    using (new PerfTimerLogger("Send to  Indian server"))
                    {
                        ProcessSelectionFromServer.PostInventoryForDrawer(_deviceEntity, drawerId, newInventory);
                    }

                    var handler = InventoryCompleted;
                    if (handler != null)
                    {
                        handler(new InventoryEventArgs(newInventory, null));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.GetType().FullName);
                    Console.WriteLine(ex.Message);
                    var handler = InventoryAborted;
                    if (handler != null)
                    {
                        handler(null);
                    }
                    if (newInventory != null)
                    {
                        ctx.Inventories.Remove(newInventory);
                        ctx.SaveChanges();
                    }
                }
                finally
                {
                    ctx.Database.Connection.Close();
                    ctx.Dispose();
                }
            }
        }
 private void MetroWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
 {
     LogToFile.LogMessageToFile("------- Close Application  --------");
     Application.Current.Shutdown();
 }
        protected override void myDevice_NotifyEvent(object sender, rfidReaderArgs args)
        {
            switch (args.RN_Value)
            {
            case rfidReaderArgs.ReaderNotify.RN_ScanStarted:
                bDoorJustClosed = false;
                _channelInScan  = 1;
                // _listTagWithChannel = new Hashtable();
                // Clock.Stop();
                WriteLCDLine(1, " - IDENTIFICATION - ");
                WriteLCDLine(2, " ");
                break;

            case rfidReaderArgs.ReaderNotify.RN_ReaderFailToStartScan:
            case rfidReaderArgs.ReaderNotify.RN_ReaderScanTimeout:
                WriteLCDLine(1, " - IDENTIFICATION - ");
                WriteLCDLine(2, " ID failure ");
                break;

            case rfidReaderArgs.ReaderNotify.RN_ScanCompleted:
            case rfidReaderArgs.ReaderNotify.RN_ErrorDuringScan:
                string tmp = string.Format(" {0:D3} TAG(S) SCANNED", CurrenRfidReader.ReaderData.nbTagScan);
                WriteLCDLine(1, " - IDENTIFICATION - ");
                WriteLCDLine(2, tmp);

                Thread.Sleep(2000);
                Clock.Start();
                ClearLCD();
                break;

            case rfidReaderArgs.ReaderNotify.RN_Door_Closed:
                LogToFile.LogMessageToFile("door Close Medical cabinet");
                if (DoorEventNormal != null)
                {
                    DoorEventNormal.Set();
                }
                break;

            case rfidReaderArgs.ReaderNotify.RN_Door_Opened:

                LogToFile.LogMessageToFile("door Open Medical cabinet");
                if (LedThread != null)
                {
                    LogToFile.LogMessageToFile("Thred led - stop it in medical");
                    LedThread.Abort();
                    LedThread.Join(1000);
                    LedThread = null;
                }
                Thread.Sleep(3000);
                //if ((CurrenRfidReader != null) && (CurrenRfidReader.IsConnected)) CurrenRfidReader.SetLightPower(300);
                LogToFile.LogMessageToFile("Close door in medical");
                CloseDoor();
                WriteLCDLine(1, "  - INFORMATION - ");
                WriteLCDLine(2, " WAIT DOOR CLOSING");
                bDoorJustClosed = true;
                break;

            case rfidReaderArgs.ReaderNotify.RN_ActiveChannnelChange:
                byte.TryParse(args.Message, out _channelInScan);
                break;

            case rfidReaderArgs.ReaderNotify.RN_TagAdded:
                // if (!_listTagWithChannel.ContainsKey(args.Message))
                //    _listTagWithChannel.Add(args.Message, _channelInScan);
                break;
            }
        }
        private void EventThreadProc()
        {
            while (!StoppingThread)
            {
                LogToFile.LogMessageToFile("------Wait Badge ------");
                badgeset = false;
                while (!badgeset)
                {
                    if (CancelOps)
                    {
                        return;
                    }
                    NonBlockingSleep(1000);
                }

                //BadgeEvent.WaitOne();
                // if (CancelOps) return;
                LogToFile.LogMessageToFile("Event Badge received in thread");
                Clock.Stop();
                WaitDoor = true;
                StopScan();
                LogToFile.LogMessageToFile("Unlock door  in thread");
                OpenDoor();
                Clock.Start();
                CptDoor = 10;
                DoorEventNormal.Reset();
                LogToFile.LogMessageToFile("------Wait Door Close ------");
                if (DoorEventNormal.WaitOne(10000, false))
                {
                    LogToFile.LogMessageToFile("------Door Close event ----");
                    CloseDoor();
                    continue; // next loop iteration as the process will continue to classic door event
                }
                else
                {
                    LogToFile.LogMessageToFile("------Door Close timeout  ----");
                }
                if (LedThread != null)
                {
                    LedThread.Abort();
                    LedThread.Join(1000);
                    LedThread = null;
                }

                Thread.Sleep(500);

                WaitDoor     = false;
                DisplayBadge = false;
                //if ((CurrenRfidReader != null) && (CurrenRfidReader.IsConnected)) CurrenRfidReader.SetLightPower(300);
                CloseDoor();
                if (CurrenRfidReader != null)
                {
                    CurrenRfidReader.NotifyRelock();
                }

                Clock.Start();
            }
            if (ThreadEvent != null)
            {
                ThreadEvent.Set();
            }
        }
 public void CloseDoor()
 {
     LogToFile.LogMessageToFile("lock cmd sent");
     CurrenRfidReader.CloseDoorMaster();
 }
 public void OpenDoor()
 {
     LogToFile.LogMessageToFile("Unlock cmd sent");
     CurrenRfidReader.OpenDoorMaster();
 }
        private void Timer_Tick(object sender, EventArgs eArgs)
        {
            ambiantTemp = double.MinValue;
            if (sender != Clock)
            {
                return;
            }
            if (!DisplayBadge)
            {
                if ((!CurrenRfidReader.IsConnected) || (bDoorJustClosed) ||
                    ((CurrenRfidReader.IsInScan) || (CurrenRfidReader.Door_Status == Door_Status.Door_Open)))
                {
                    return;
                }

                if (bTempReady)
                {
                    if (myPT100Probe == null)
                    {
                        myPT100Probe = YTemperature.FirstTemperature();
                    }
                    if ((myPT100Probe != null) && (myPT100Probe.isOnline()))
                    {
                        ambiantTemp = myPT100Probe.get_currentValue();
                    }
                }

                if (ambiantTemp != double.MinValue)
                {
                    WriteLCDLine(1, " - WAIT FOR USER -");
                    WriteLCDLine(2, " " + GetTime() + " - " + ambiantTemp.ToString("00.0") + "C");
                }
                else
                {
                    WriteLCDLine(1, " - WAIT FOR USER -");
                    WriteLCDLine(2, "      " + GetTime());
                }

                return;
            }
            else
            {
                Clock.Stop();
                DisplayBadge = false;
                WriteLCDLine(1, "       BADGE :");
                WriteLCDLine(2, "     " + StrBadgeRead);
                Thread.Sleep(100);
                if (!CurrenRfidReader.TCPActionPending)
                {
                    LogToFile.LogMessageToFile("Before check badge in timer");
                    if (CheckBadge(StrBadgeRead))
                    {
                        LogToFile.LogMessageToFile("Badge Checked in timer");
                        OnBadgeReader(StrBadgeRead);

                        badgeset = true;
                        LogToFile.LogMessageToFile("Unlock DOOR event in timer");
                        OpenDoor();
                        if (BadgeEvent != null)
                        {
                            BadgeEvent.Set();
                            LogToFile.LogMessageToFile("Badge event SET in timer");
                        }
                    }

                    else
                    {
                        LogToFile.LogMessageToFile("Badge not granted");
                        WriteLCDLine(1, "       BADGE :");
                        WriteLCDLine(2, " BADGE NOT GRANTED!");
                        Clock.Start();
                        //Enable TCP Scan
                        CurrenRfidReader.UserActionPending = false;
                    }
                }
                else
                {
                    LogToFile.LogMessageToFile("TCP action pending");
                    WriteLCDLine(1, "       INFO  :");
                    WriteLCDLine(2, " NETWORK QUERY");
                    Clock.Start();
                    //Enable TCP Scan
                    CurrenRfidReader.UserActionPending = false;
                }
            }
        }
        public void CanStartScan()
        {
            bIsWaitingScan = true;
            if (bUseSynchonisation)
            {
                LogToFile.LogMessageToFile("------ Sync Scan  ------");
                bool bFirstPass     = true;
                int  bQuitValue     = 0;
                int  bQuitCondition = 0;

                int waitRight = 0;
                int waitLeft  = 0;
                int doorOpen  = 0;
                if (!string.IsNullOrEmpty(DeviceIpRight))
                {
                    bQuitCondition++;
                }
                if (!string.IsNullOrEmpty(DeviceIpLeft))
                {
                    bQuitCondition++;
                }
                TcpIpClient         tcp = new TcpIP_class.TcpIpClient();
                TcpIpClient.RetCode ret;
                expiredTime = DateTime.Now.AddSeconds(TimeoutInSec); //time to quit in any case

                Random rnd = new Random();

                do
                {
                    if (!bIsWaitingScan)
                    {
                        return;                   //quit if requested
                    }
                    //remove for LED

                    /*
                     * TimeSpan ts = expiredTime - DateTime.Now;
                     * if (ts.TotalSeconds < 0)
                     * {
                     *  bIsWaitingScan = false;
                     *  return;
                     * } */

                    bQuitValue = 0;

                    if (!string.IsNullOrEmpty(DeviceIpLeft)) // J'ai un device à gauche
                    {
                        // if (tcpUtils.PingAddress(DeviceIpLeft, 1000))
                        //{
                        ret = tcp.pingServer(DeviceIpLeft, DevicePortLeft);
                        if (ret == TcpIpClient.RetCode.RC_Succeed)
                        {
                            DeviceStatus ds = DeviceStatus.DS_NotReady;
                            string       status;
                            ret = tcp.getStatus(DeviceIpLeft, DevicePortLeft, null, out status);
                            if (ret == TcpIpClient.RetCode.RC_Succeed)
                            {
                                ds = (DeviceStatus)Enum.Parse(typeof(DeviceStatus), status);
                                if ((ds == DeviceStatus.DS_WaitForScan) || (ds == DeviceStatus.DS_WaitForLed))
                                {
                                    waitLeft++;
                                }
                                else
                                {
                                    waitLeft = 0;
                                }

                                if (bFirstPass)
                                {
                                    if (ds == DeviceStatus.DS_DoorOpen)
                                    {
                                        doorOpen++;
                                        if (doorOpen > 2)
                                        {
                                            bQuitValue++;
                                        }
                                    }
                                    else if ((ds == DeviceStatus.DS_InScan) || (ds == DeviceStatus.DS_LedOn) || (ds == DeviceStatus.DS_WaitForScan) || (ds == DeviceStatus.DS_WaitForLed))
                                    {
                                        // need to wait
                                        if (waitLeft > 4) //gauche  en wait depuis long temps on lance
                                        {
                                            bQuitValue++;
                                        }
                                    }
                                    else
                                    {
                                        bQuitValue++;
                                    }
                                }
                                else
                                {
                                    if (ds == DeviceStatus.DS_DoorOpen)
                                    {
                                        doorOpen++;
                                        if (doorOpen > 2)
                                        {
                                            bQuitValue++;
                                        }
                                    }
                                    else if ((ds == DeviceStatus.DS_InScan) || (ds == DeviceStatus.DS_LedOn) || (ds == DeviceStatus.DS_WaitForScan) || (ds == DeviceStatus.DS_WaitForLed))
                                    {
                                        // need to wait
                                        if (waitLeft > 4) //gauche  en wait depuis long temps on lance
                                        {
                                            bQuitValue++;
                                        }
                                    }
                                    else
                                    {
                                        bQuitValue++;
                                    }
                                }
                            }
                            else
                            {
                                bQuitValue++;
                            }
                        }
                        else
                        {
                            bQuitValue++;
                        }
                        //  }
                        // else //pas de ping
                        //     bQuitValue++;
                    }
                    if (!string.IsNullOrEmpty(DeviceIpRight)) // J'ai un device à droite
                    {
                        //if (tcpUtils.PingAddress(DeviceIpRight, 1000))
                        //{
                        ret = tcp.pingServer(DeviceIpRight, DevicePortRight);
                        if (ret == TcpIpClient.RetCode.RC_Succeed)
                        {
                            DeviceStatus ds = DeviceStatus.DS_NotReady;
                            string       status;
                            ret = tcp.getStatus(DeviceIpRight, DevicePortRight, null, out status);
                            if (ret == TcpIpClient.RetCode.RC_Succeed)
                            {
                                ds = (DeviceStatus)Enum.Parse(typeof(DeviceStatus), status);
                                if ((ds == DeviceStatus.DS_WaitForScan) || (ds == DeviceStatus.DS_WaitForLed))
                                {
                                    waitRight++;
                                }
                                else
                                {
                                    waitRight = 0;
                                }
                                if ((ds == DeviceStatus.DS_InScan) || (ds == DeviceStatus.DS_LedOn) || (ds == DeviceStatus.DS_WaitForScan) || (ds == DeviceStatus.DS_WaitForLed))
                                {
                                    // need to wait
                                    if (waitRight > 2) //droite en wait depuis long temps on lance
                                    {
                                        bQuitValue++;
                                    }
                                }
                                else
                                {
                                    bQuitValue++;
                                }
                            }
                            else
                            {
                                bQuitValue++;
                            }
                        }
                        else
                        {
                            bQuitValue++;
                        }
                        //}
                        //else //pas de ping
                        //    bQuitValue++;
                    }

                    if (bFirstPass)
                    {
                        bFirstPass = false;
                    }
                    else
                    {
                        tcpUtils.NonBlockingSleep(rnd.Next(1000, 3000));
                    }
                }while (bQuitValue != bQuitCondition);
            }
            bIsWaitingScan = false;
            LogToFile.LogMessageToFile("------ End Sync Scan  ------");
        }
        public static async Task <bool> PostInventoryForDrawer(Device device, int drawerId, Inventory inventory)
        {
            try
            {
                string serverIP   = Properties.Settings.Default.ServerIp;
                int    serverPort = Properties.Settings.Default.ServerPort;
                string urlServer  = "http://" + serverIP + ":" + serverPort;
                var    client     = new RestClient(urlServer);
                client.Authenticator = new HttpBasicAuthenticator(privateApiLogin, privateApiMdp);
                var request = new RestRequest("stockhistories", Method.POST);
                client.Timeout           = timeout;
                client.ReadWriteTimeout  = timeout;
                request.Timeout          = timeout;
                request.ReadWriteTimeout = timeout;

                request.AddParameter("serial_num", device.DeviceSerial);
                request.AddParameter("drawer", drawerId.ToString());
                request.AddParameter("created_at", inventory.InventoryDate.ToUniversalTime().ToString("u"));

                foreach (InventoryProduct ip in inventory.InventoryProducts)
                {
                    switch (ip.MovementType)
                    {
                    case -1:
                        request.AddParameter("removed_tags", ip.RfidTag.TagUid);
                        break;

                    case 0:
                        request.AddParameter("present_tags", ip.RfidTag.TagUid);
                        break;

                    case 1:
                        request.AddParameter("added_tags", ip.RfidTag.TagUid);
                        break;
                    }
                }

                var ctx = await RemoteDatabase.GetDbContextAsync();

                var invUser = ctx.EventDrawerDetails.GetEventForDrawerByInventoryID(device, drawerId, inventory.InventoryId);
                if (invUser != null)
                {
                    foreach (EventDrawerDetail edd in invUser)
                    {
                        if ((edd.GrantedUser != null) && (!string.IsNullOrEmpty(edd.GrantedUser.Login)))
                        {
                            request.AddParameter("user_login", edd.GrantedUser.Login);
                        }
                    }
                }
                var response = await client.ExecuteTaskAsync(request);

                LogToFile.LogMessageToFile(response.ResponseStatus.ToString());
                LogToFile.LogMessageToFile(response.Content.ToString());

                return(response.IsSuccessful);
            }
            catch (Exception error)
            {
                LogToFile.LogMessageToFile(error.InnerException.ToString());
                LogToFile.LogMessageToFile(error.Message);
                LogToFile.LogMessageToFile(error.StackTrace);
            }
            return(false);
        }
        public static async Task <bool> GetAndStoreSelectionAsync()
        {
            try
            {
                string serverIP   = Properties.Settings.Default.ServerIp;
                int    serverPort = Properties.Settings.Default.ServerPort;

                string urlServer = "http://" + serverIP + ":" + serverPort;
                var    client    = new RestClient(urlServer);
                client.Authenticator = new HttpBasicAuthenticator(publicApiLogin, publicApiMdp);
                var request = new RestRequest("selections", Method.GET);
                client.Timeout           = timeout;
                client.ReadWriteTimeout  = timeout;
                request.Timeout          = timeout;
                request.ReadWriteTimeout = timeout;
                var response = await client.ExecuteTaskAsync(request);

                if (response.IsSuccessful)
                {
                    var ctx = await RemoteDatabase.GetDbContextAsync();

                    ctx.PullItems.Clear();
                    await ctx.SaveChangesAsync();

                    lock (somePublicStaticObject)
                    {
                        var lstSelection = JsonSelectionList.DeserializedJsonList(response.Content);
                        if ((lstSelection != null) && (lstSelection.Length > 0))
                        {
                            foreach (var sel in lstSelection)
                            {
                                if (sel == null)
                                {
                                    LogToFile.LogMessageToFile("------- Start Error in selection --------");
                                    LogToFile.LogMessageToFile(response.Content);
                                    LogToFile.LogMessageToFile("------- End Error in selection --------");
                                    break;
                                }
                            }
                            lastSelection = lstSelection;
                        }
                        else
                        {
                            lastSelection = null;
                        }
                        ctx.Database.Connection.Close();
                        ctx.Dispose();
                        return(true);
                    }
                }
                return(false);
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                      eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                          ve.PropertyName, ve.ErrorMessage);
                    }
                }
                return(false);
            }
            catch (Exception error)
            {
                ExceptionMessageBox exp = new ExceptionMessageBox(error, "Error getting selection");
                exp.ShowDialog();
                return(false);
            }
        }