Beispiel #1
0
        private static void GetContactsFromResponse(WebResponse response, StatusDownload loghandler)
        {
            var httpResponse = response.GetResponseStream();

            using (var streamReader = new StreamReader(httpResponse))
            {
                var result = streamReader.ReadToEnd();

                var receivedData = JsonConvert.DeserializeObject <CustomerSyncResult>(result);
                if (receivedData.success)
                {
                    var contacts = receivedData.contacts;
                    DBLocalDataStore.GetInstance().ClearAllContacts();
                    foreach (var contact in contacts)
                    {
                        if (string.IsNullOrEmpty(contact.uid))
                        {
                            Console.WriteLine("Received contact {0} has no UID, ignoring", JsonConvert.SerializeObject(contact, Formatting.Indented));
                            continue;
                        }
                        var localContact = new DBlocalContact(contact);
                        localContact.source = ContactSource.Server;
                        DBLocalDataStore.GetInstance().AddLocalContact(localContact);
                        Console.Error.WriteLine("Contact with UID {0} added", contact.uid);
                    }
                    loghandler(true, "Contacts updated from server");
                }
                else
                {
                    loghandler(false, receivedData.error);
                }
            }
        }
Beispiel #2
0
        public static async Task performAuth(DBUserLoginRequest user, statusResponseList <DBBasicAuthority> callback)
        {
            //throw new Exception("TEST EXCEPTION");

            if (callback == null)
            {
                throw new Exception("Callback must not be null");
            }

            var httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(ServerURLs.authURL);

            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method      = "POST";
            httpWebRequest.ServicePoint.ConnectionLimit = 3;
            httpWebRequest.Timeout   = 30000;
            httpWebRequest.KeepAlive = false;

            var loginContext = new LoginContext(user);

            var jsonUser = JsonConvert.SerializeObject(loginContext);

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(jsonUser);
            }

            var response = await httpWebRequest.GetResponseAsync();

            string responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();

            httpWebRequest.Abort();

            var exchangeInfo = JsonConvert.DeserializeObject <ExchengeInfo>(responseData);

            if (!exchangeInfo.success)
            {
                callback(false, "Login failed", "Incorrect username/password detected, please try again", null);
                return;
            }

            if (exchangeInfo.profiles == null || exchangeInfo.profiles.Length == 0)
            {
                callback(false, "Warning:", "You currently have no app setups available, go to your dashboard and create one!", null);
                return;
            }

            var localDataStore = DBLocalDataStore.GetInstance();

            localDataStore.AddUserInfo(user);
            localDataStore.ClearBasicAuthority();

            var profilesList = new List <DBBasicAuthority>();

            foreach (DBBasicAuthority profile in exchangeInfo.profiles)
            {
                profilesList.Add(profile);
                localDataStore.AddBasicAuthority(profile);
            }
            callback(true, null, "OK", profilesList);
        }
Beispiel #3
0
        public static void ClearDataSelected(bool clearContactsToServer = true)
        {
            DBLocalDataStore ds   = DBLocalDataStore.GetInstance();
            var allactivecontacts = DBLocalDataStore.GetInstance().GetLocalContacts().Where(s => s.activeContact).ToList();
            var allactivefiles    = DBLocalDataStore.GetInstance().GetAllLocalFiles().Where(s => s.activeFile).ToList();

            allactivecontacts.ForEach((c) =>
            {
                c.activeContact = false;
                ds.UpdateLocalContact(c);
            });
            allactivefiles.ForEach((f) =>
            {
                f.activeFile = false;
                ds.UpdateLocalFile(f);
            });

            if (clearContactsToServer)
            {
                ds.ClearAllContactsToServer();
            }

            ds.resetAnswers();
            //SaveAndLoad.files_selected.Clear();
        }
Beispiel #4
0
        private static void UpdateContactsFromResponse(List <CustomerType> contactsList)
        {
            var localContacts = DBLocalDataStore.GetInstance().GetLocalContacts();

            localContacts.RemoveAll((c) => string.IsNullOrWhiteSpace(c.uid));
            var serverContacts = contactsList;

            if (serverContacts != null)
            {
                foreach (var contact in serverContacts)
                {
                    if (string.IsNullOrWhiteSpace(contact.uid))
                    {
                        Console.WriteLine("Received contact {0} has no UID, ignoring", JsonConvert.SerializeObject(contact, Formatting.Indented));
                        continue;
                    }
                    var existingLocalContact = localContacts.Find(c => c.uid.Equals(contact.uid));
                    var newContact           = new DBlocalContact(contact);
                    if (existingLocalContact != null)
                    {
                        existingLocalContact       += newContact;
                        existingLocalContact.source = ContactSource.Server;
                        DBLocalDataStore.GetInstance().UpdateLocalContact(existingLocalContact);
                        Console.Error.WriteLine("Contact with UID {0} updated from server", contact.uid);
                    }
                    else
                    {
                        newContact.source = ContactSource.Server;
                        DBLocalDataStore.GetInstance().AddLocalContact(newContact);
                        Console.Error.WriteLine("Contact with UID {0} added", contact.uid);
                    }
                }
            }
        }
Beispiel #5
0
        private static void GetFilesAndFormsFromResponse(WebResponse response, StatusDownloadFilesAndForms loghandler)
        {
            var httpResponse = response.GetResponseStream();

            using (var streamReader = new StreamReader(httpResponse))
            {
                var result = streamReader.ReadToEnd();

                var receivedData = JsonConvert.DeserializeObject <CampaignAppUpdateRequestResult>(result);
                if (receivedData.success)
                {
                    if (receivedData.defaultForm != null)
                    {
                        DBLocalDataStore.GetInstance().AddLocalFormDefinitions(new[] { receivedData.defaultForm }, receivedData.defaultForm.uuid);
                    }
                    else
                    {
                        DBLocalDataStore.GetInstance().AddLocalFormDefinitions(receivedData.forms);
                    }

                    DBLocalDataStore.GetInstance().ClearAllFiles();
                    DBLocalDataStore.GetInstance().ClearAllFolders();
                    DBLocalDataStore.GetInstance().AddLocalFolders(receivedData.folders);
                    DBAppInfo appInfo = new DBAppInfo();

                    appInfo.appType           = (receivedData.appType != null) ? receivedData.appType.ToLower() : null;
                    appInfo.campaignReference = receivedData.campaignReference;

                    appInfo.welcomeImageURL  = (receivedData.welcomeScreenImage != null) ? receivedData.welcomeScreenImage.downloadUrl : null;
                    appInfo.finishedImageURL = (receivedData.finishedScreenImage != null) ? receivedData.finishedScreenImage.downloadUrl : null;

                    appInfo.welcomeImageFileType  = (receivedData.welcomeScreenImage != null) ? receivedData.welcomeScreenImage.fileType : null;
                    appInfo.finishedImageFileType = (receivedData.finishedScreenImage != null) ? receivedData.finishedScreenImage.fileType : null;

                    appInfo.welcomeImageLocalPath  = null;
                    appInfo.finishedImageLocalPath = null;

                    appInfo.welcomeImageMD5  = (receivedData.welcomeScreenImage != null) ? receivedData.welcomeScreenImage.md5 : null;
                    appInfo.finishedImageMD5 = (receivedData.finishedScreenImage != null) ? receivedData.finishedScreenImage.md5 : null;

                    DBLocalDataStore.GetInstance().SetAppInfo(appInfo);

                    if (receivedData.folders.Length == 0)
                    {
                        DBLocalDataStore.GetInstance().ShowLocalFiles(true);
                    }
                    else
                    {
                        DBLocalDataStore.GetInstance().ShowLocalFiles(false);
                    }

                    loghandler(true, "Files and forms updated from server", appInfo.appType.ToLower().Equals("kiosk"));
                }
                else
                {
                    loghandler(false, receivedData.error, false);
                }
            }
        }
Beispiel #6
0
        public static async Task <DBlocalContact> contactLookup(string contactUID)
        {
            Console.Error.WriteLine("Lookup started at: {0:HH:mm:ss.ffff}", DateTime.Now);

            DBAppInfo appInfo = DBLocalDataStore.GetInstance().GetAppInfo();

            var user = DBLocalDataStore.GetInstance().GetLocalUserInfo();

            LookupContext lookup = new LookupContext(contactUID);

            lookup.context = new RequestData();
            var output = lookup.context;

            output.password          = user.password;
            output.username          = user.username;
            output.profile           = DBLocalDataStore.GetInstance().GetSelectProfile().shortName;
            output.tags              = new string[] { user.tags };
            output.campaignReference = appInfo.campaignReference;

            var jsonUser = JsonConvert.SerializeObject(lookup);

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(ServerURLs.contactLookupURL);

            try
            {
                //throw new Exception("TEST EXCEPTION");
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method      = "POST";
                httpWebRequest.Timeout     = 30000;
                httpWebRequest.KeepAlive   = false;

                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    streamWriter.Write(jsonUser);
                }

                var response = await httpWebRequest.GetResponseAsync();

                return(NetworkRequests.getContactFromLookup(response));
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                throw;
            }
            finally
            {
                Console.Error.WriteLine("Lookup finished at: {0:HH:mm:ss.ffff}", DateTime.Now);
                httpWebRequest.Abort();
            }
        }
Beispiel #7
0
        public static async Task GetContacts(StatusDownload loghandler)
        {
            SyncContext scr = new SyncContext();

            DBAppInfo appInfo = DBLocalDataStore.GetInstance().GetAppInfo();

            var user = DBLocalDataStore.GetInstance().GetLocalUserInfo();

            scr.context = new RequestData();
            var output = scr.context;

            output.password          = user.password;
            output.username          = user.username;
            output.profile           = DBLocalDataStore.GetInstance().GetSelectProfile().shortName;
            output.tags              = new string[] { user.tags };
            output.campaignReference = appInfo.campaignReference;

            var jsonUser = JsonConvert.SerializeObject(scr);

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(ServerURLs.contactsURLNew);

            try
            {
                //throw new Exception("TEST EXCEPTION");
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method      = "POST";
                httpWebRequest.Timeout     = 30000;
                httpWebRequest.KeepAlive   = false;

                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    streamWriter.Write(jsonUser);
                }

                var response = await httpWebRequest.GetResponseAsync();

                NetworkRequests.GetContactsFromResponse(response, loghandler);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                throw;
            }
            finally
            {
                httpWebRequest.Abort();
            }
        }
Beispiel #8
0
        public static void createOrUpdateContact(DBlocalContact newContact)
        {
            DBlocalContact    oldLocalContact = DBLocalDataStore.GetInstance().GetLocalContactsByUID(newContact.uid);
            DBContactToServer existingChanges = DBLocalDataStore.GetInstance().GetContactsToServerByUID(newContact.uid);

            if (oldLocalContact != null)
            {
                if (existingChanges == null)
                {
                    existingChanges  = new DBContactToServer(oldLocalContact);
                    existingChanges -= newContact;
                    DBLocalDataStore.GetInstance().AddContactToServer(existingChanges);
                }
                else
                {
                    DBContactToServer lastChanges = new DBContactToServer(oldLocalContact);
                    lastChanges     -= newContact;
                    existingChanges &= lastChanges;
                    DBLocalDataStore.GetInstance().UpdateContactToServer(existingChanges);
                }
                newContact.Id            = oldLocalContact.Id;
                newContact.activeContact = true;

                DBLocalDataStore.GetInstance().UpdateLocalContact(newContact);
                Console.WriteLine("updated contact: \n{0}", JsonConvert.SerializeObject(newContact));
            }
            else
            {
                existingChanges = new DBContactToServer(newContact, true);
                //existingChanges = existingChanges.newContact(existingChanges);
                DBLocalDataStore.GetInstance().AddContactToServer(existingChanges);
                newContact.activeContact = true;
                if (newContact.Id == 0)
                {
                    DBLocalDataStore.GetInstance().AddLocalContact(newContact);
                }
                else
                {
                    DBLocalDataStore.GetInstance().UpdateLocalContact(newContact);
                }
                Console.WriteLine("created contact: \n{0}", JsonConvert.SerializeObject(newContact));
            }
        }
Beispiel #9
0
        public static async Task GetFilesAndForms(StatusDownloadFilesAndForms loghandler)
        {
            RequestData requestData = new RequestData();
            var         user        = DBLocalDataStore.GetInstance().GetLocalUserInfo();

            requestData.password = user.password;
            requestData.username = user.username;
            requestData.profile  = DBLocalDataStore.GetInstance().GetSelectProfile().shortName;
            requestData.tags     = new string[] { user.tags };

            var jsonUser = JsonConvert.SerializeObject(requestData);

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(ServerURLs.filesAndFormsURL);

            try
            {
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method      = "POST";
                httpWebRequest.ServicePoint.ConnectionLimit = 3;
                httpWebRequest.Timeout   = 30000;
                httpWebRequest.KeepAlive = false;

                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    streamWriter.Write(jsonUser);
                }

                var response = await httpWebRequest.GetResponseAsync();

                NetworkRequests.GetFilesAndFormsFromResponse(response, loghandler);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                throw;
            }
            finally
            {
                httpWebRequest.Abort();
            }
        }
Beispiel #10
0
        public static async Task getProfiles(DBUserLoginRequest user)
        {
            var httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(ServerURLs.profilesURL);

            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method      = "POST";
            httpWebRequest.ServicePoint.ConnectionLimit = 3;
            httpWebRequest.Timeout   = 30000;
            httpWebRequest.KeepAlive = false;

            var loginContext = new LoginContext(user);

            var jsonUser = JsonConvert.SerializeObject(loginContext);

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(jsonUser);
            }
            var response = await httpWebRequest.GetResponseAsync();

            string responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();

            httpWebRequest.Abort();

            var exchangeInfo   = JsonConvert.DeserializeObject <ExchengeInfo>(responseData);
            var localDataStore = DBLocalDataStore.GetInstance();

            var profilesList = new List <DBBasicAuthority>();

            localDataStore.ClearBasicAuthority();
            foreach (DBBasicAuthority profile in exchangeInfo.profiles)
            {
                profilesList.Add(profile);
                localDataStore.AddBasicAuthority(profile);
            }
        }
Beispiel #11
0
        public static async Task SyncDataServer()
        {
            var SyncData = DBLocalDataStore.GetInstance().getSyncRequests().Where(s => !s.isSent).ToList();
            var user     = DBLocalDataStore.GetInstance().GetLocalUserInfo();
            List <CustomerType> receivedContacts = new List <CustomerType>();

            if (user.invalidPassword)
            {
                return;
            }

            if (SyncData.Count > 0 && NetworkRequests.onBeginSync != null)
            {
                NetworkRequests.onBeginSync();
            }

            var           appInfo     = DBLocalDataStore.GetInstance().GetAppInfo();
            DBAppSettings appSettings = DBLocalDataStore.GetInstance().GetAppSettings();

            for (int i = 0; i < SyncData.Count; i++)
            {
                string jsonUser = SyncData[i].serializedSyncContext;
                var    data     = JsonConvert.DeserializeObject <SyncContext>(jsonUser);

                data.context = new RequestData();
                var context = data.context;
                context.password = user.password;
                //context.password = "******";
                context.username          = user.username;
                context.profile           = DBLocalDataStore.GetInstance().GetSelectProfile().shortName;
                context.tags              = new string[] { user.tags };
                context.campaignReference = appInfo.campaignReference;

                JsonSerializerSettings serializationSettings = new JsonSerializerSettings();
                serializationSettings.DefaultValueHandling = DefaultValueHandling.Ignore;

                jsonUser = JsonConvert.SerializeObject(data, Formatting.Indented, serializationSettings);

                Console.WriteLine("Sending to sync server:\n{0}", jsonUser);

                var httpWebRequest = (HttpWebRequest)WebRequest.Create(ServerURLs.contactsURLNew);
                try
                {
                    //throw new Exception("TEST EXCEPTION");
                    httpWebRequest.ContentType     = "application/json";
                    httpWebRequest.Method          = "POST";
                    httpWebRequest.Timeout         = 30000;
                    httpWebRequest.KeepAlive       = false;
                    httpWebRequest.PreAuthenticate = false;

                    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                    {
                        streamWriter.Write(jsonUser);
                    }

                    var response = await httpWebRequest.GetResponseAsync();

                    using (var streamReader = new StreamReader(response.GetResponseStream()))
                    {
                        var result = streamReader.ReadToEnd();

                        Console.Error.WriteLine("Received from sync server:\n{0}", result);

                        var receivedData = JsonConvert.DeserializeObject <CustomerSyncResult>(result);
                        if (receivedData.success)
                        {
                            SyncData[i].isSent = true;
                            DBLocalDataStore.GetInstance().updateSyncReqest(SyncData[i]);
                            if (appSettings.getSharedContacts)
                            {
                                receivedContacts.AddRange(receivedData.contacts);
                            }
                        }
                        else
                        {
                            user.invalidPassword = true;
                            DBLocalDataStore.GetInstance().AddUserInfo(user);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Sync exception: {0}", ex.Message);
                    if (NetworkRequests.onFailSync != null)
                    {
                        onFailSync();
                    }
                    throw;
                }
                finally
                {
                    httpWebRequest.Abort();
                }
            }

            if (receivedContacts.Count > 0)
            {
                //CustomerTypeComparer comparer = new CustomerTypeComparer();
                //receivedContacts = receivedContacts.Distinct(comparer).ToList();

                NetworkRequests.UpdateContactsFromResponse(receivedContacts);

                if (NetworkRequests.onFinishSync != null)
                {
                    onFinishSync();
                }
            }
            else
            {
                if (NetworkRequests.onFailSync != null)
                {
                    onFailSync();
                }
            }
        }
Beispiel #12
0
        public static async Task sendBadge(DBlocalContact contact, string URL)
        {
            try
            {
                var uri = new Uri(URL);
                uri.ToString();
            }
            catch
            {
                throw new ArgumentException("Invalid webhook URL");
            }
            SyncContext scr = new SyncContext();

            scr.context  = new RequestData();
            scr.contacts = new List <CustomerType>();
            scr.contacts.Add(new CustomerType(contact));

            var appInfo = DBLocalDataStore.GetInstance().GetAppInfo();
            var user    = DBLocalDataStore.GetInstance().GetLocalUserInfo();
            var context = scr.context;

            context.password          = user.password;
            context.username          = user.username;
            context.profile           = DBLocalDataStore.GetInstance().GetSelectProfile().shortName;
            context.tags              = new string[] { user.tags };
            context.campaignReference = appInfo.campaignReference;

            string json = JsonConvert.SerializeObject(scr, Formatting.Indented);

            Console.WriteLine("Trying to send to webhook:\n{0}", json);

            //var httpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
            var httpWebRequest = WebRequest.CreateHttp(URL);

            try
            {
                //throw new Exception("TEST EXCEPTION");
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method      = "POST";
                httpWebRequest.Timeout     = 30000;
                httpWebRequest.ServicePoint.ConnectionLimit = 3;
                httpWebRequest.KeepAlive = false;

                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    streamWriter.Write(json);
                }

                var response = await httpWebRequest.GetResponseAsync();

                using (var streamReader = new StreamReader(response.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();

                    Console.WriteLine("Received from webhook:\n{0}", result);

                    var settings = new JsonSerializerSettings();
                    settings.MissingMemberHandling = MissingMemberHandling.Ignore;
                    var receivedData = JsonConvert.DeserializeObject <CustomerSyncResult>(result, settings);
                    if (NetworkRequests._onFinishPrint != null)
                    {
                        NetworkRequests._onFinishPrint(receivedData.success);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Webhook exception: {0}", ex.Message);
                if (NetworkRequests._onFinishPrint != null)
                {
                    NetworkRequests._onFinishPrint(false);
                }
                //throw;
            }
            finally
            {
                httpWebRequest.Abort();
            }
        }
Beispiel #13
0
        public static void prepareSync(bool isKiosk = false)
        {
            var dateNow = string.Format("{0:yyyy-MM-ddTH:mm:sszzz}", DateTime.Now);

            var activeLocalContacts = DBLocalDataStore.GetInstance().GetLocalContacts().Where(c => c.activeContact).ToList();

            if (activeLocalContacts.Count == 0 && !isKiosk)
            {
                throw new InvalidOperationException("Please select at least one contact.");
            }

            var allactivefiles = DBLocalDataStore.GetInstance().GetAllLocalFiles().Where(s => s.activeFile).ToList();

            var appInfo               = DBLocalDataStore.GetInstance().GetAppInfo();
            var user                  = DBLocalDataStore.GetInstance().GetLocalUserInfo();
            var contactsToSend        = DBLocalDataStore.GetInstance().GetContactsToServer();
            var invalidContactsToSend = contactsToSend.Where(c => string.IsNullOrWhiteSpace(c.uid));

            foreach (var invalidItem in invalidContactsToSend)
            {
                DBLocalDataStore.GetInstance().RemoveContactToServer(invalidItem);
            }

            contactsToSend.RemoveAll(c => string.IsNullOrWhiteSpace(c.uid));

            var            answersToSend  = DBLocalDataStore.GetInstance().getAnswers();
            var            formDefinition = DBLocalDataStore.GetInstance().GetLocalFormDefinitions().Find(s => s.uuid == DBLocalDataStore.GetInstance().GetSelectedQuestionPosition());
            var            questions      = DBLocalDataStore.GetInstance().GetLocalQuestions(formDefinition.uuid);
            List <DBOrder> orders         = new List <DBOrder>();

            List <DBOrderLine> orderLines = new List <DBOrderLine>();

            allactivefiles.ForEach((f) =>
            {
                DBOrderLine orderLine     = new DBOrderLine();
                orderLine.itemDescription = f.name;
                orderLine.item            = f.uuid;
                orderLines.Add(orderLine);
            });

            activeLocalContacts.ForEach((lc) =>
            {
                if (string.IsNullOrWhiteSpace(lc.uid))
                {
                    return;
                }

                var serverContact = contactsToSend.Find(sc => sc.uid.Equals(lc.uid));
                if (serverContact == null)
                {
                    DBContactToServer newServerContact = new DBContactToServer(true);
                    newServerContact.uid = lc.uid;
                    DBLocalDataStore.GetInstance().AddContactToServer(newServerContact);
                    contactsToSend.Add(newServerContact);
                }

                DBOrder order    = new DBOrder();
                order.contactUid = lc.uid;
                order.created    = DateTime.Now.ToString("yyyy-MM-ddTH:mm:sszzz");
                order.creator    = user.username;
                order.orderLine  = orderLines;
                orders.Add(order);
            });


            SyncContext scr = new SyncContext();

            scr.context  = new RequestData();
            scr.contacts = new List <CustomerType>();
            scr.forms    = new List <AnsweredForm>();
            scr.orders   = orders;

            contactsToSend.ForEach((c) =>
            {
                //scr.contacts.Add(new CustomerType(c));
                if (!string.IsNullOrWhiteSpace(c.uid))
                {
                    scr.contacts.Add(new CustomerType(c));
                }
            });

            bool   isAnyQuestionAnswered = answersToSend.Count(s => OfflineLogic.isAnswerValid(s.answer)) > 0;
            string profileName           = DBLocalDataStore.GetInstance().GetSelectProfile().shortName;

            foreach (var contact in activeLocalContacts)
            {
                bool isAnswersValid = true;

                if (isAnyQuestionAnswered)
                {
                    var           form       = new AnsweredForm();
                    List <Answer> tmpAnswers = new List <Answer>();
                    form.contactUid = contact.uid;
                    form.startdate  = dateNow;
                    form.enddate    = dateNow;
                    form.name       = formDefinition.objectName;
                    form.user       = new DeviceUser {
                        username = user.username, profile = profileName
                    };
                    form.answers = new Answer[] { };

                    for (int index = 0; (index < answersToSend.Count) && isAnyQuestionAnswered; index++)
                    {
                        if (OfflineLogic.isAnswerValid(answersToSend[index].answer))
                        {
                            Answer answer = new Answer();
                            answer.answer = answersToSend[index].answer;
                            answer.name   = questions[index].name;
                            answer.type   = questions[index].type;
                            tmpAnswers.Add(answer);
                        }
                        else
                        {
                            if (OfflineLogic.isQuestionRequired(questions[index]))
                            {
                                isAnswersValid = false;
                            }
                        }
                    }
                    if (isAnswersValid)
                    {
                        form.answers = tmpAnswers.ToArray();
                        scr.forms.Add(form);
                    }
                    else
                    {
                        if (!isKiosk)
                        {
                            throw new InvalidOperationException("Not all mandatory questions are completed");
                        }
                    }
                }
            }
            var Counts = DBLocalDataStore.GetInstance().GetCountHomeScreen();

            for (int i = 0; i < scr.contacts.Count; i++)
            {
                activeLocalContacts[i].useInRequest = true;
                DBLocalDataStore.GetInstance().UpdateLocalContact(activeLocalContacts[i]);
            }
            if (scr.orders[0].orderLine.Count != 0)
            {
                Counts.countShare += scr.orders.Count;
            }
            Counts.countQuestion += scr.forms.Count;
            Counts.countContacts  = DBLocalDataStore.GetInstance().GetLocalContacts().Where(c => c.useInRequest).ToList().Count;
            DBLocalDataStore.GetInstance().SetCountHomeScreen(Counts);

            JsonSerializerSettings serializationSettings = new JsonSerializerSettings();

            serializationSettings.DefaultValueHandling = DefaultValueHandling.Ignore;
            string        json        = JsonConvert.SerializeObject(scr, Formatting.Indented, serializationSettings);
            DBSyncRequest syncRequest = new DBSyncRequest();

            syncRequest.serializedSyncContext = json;

            Console.Error.WriteLine("Saving request: {0}", json);
            DBLocalDataStore.GetInstance().addSyncRequest(syncRequest);


            // DBLocalDataStore.GetInstance().SetCountHomeScreen(new DBHomeScreenCounts() { countContacts = ActivityHomescreen.counts[0], countShare = ActivityHomescreen.counts[1], countQuestion = ActivityHomescreen.counts[2] });



            if (!isKiosk)
            {
                OfflineLogic.ClearDataSelected();
            }
        }
Beispiel #14
0
        public static void updateForms(string uid)
        {
            var dateNow        = string.Format("{0:yyyy-MM-ddTH:mm:sszzz}", DateTime.Now);
            var answersToSend  = DBLocalDataStore.GetInstance().getAnswers();
            var appInfo        = DBLocalDataStore.GetInstance().GetAppInfo();
            var user           = DBLocalDataStore.GetInstance().GetLocalUserInfo();
            var formDefinition = DBLocalDataStore.GetInstance().GetLocalFormDefinitions().Find(s => s.uuid == DBLocalDataStore.GetInstance().GetSelectedQuestionPosition());
            var questions      = DBLocalDataStore.GetInstance().GetLocalQuestions(formDefinition.uuid);

            UpdateForms scr = new UpdateForms();

            scr.context = new RequestData();
            scr.forms   = new List <AnsweredForm>();

            var context = scr.context;

            context.password          = user.password;
            context.username          = user.username;
            context.profile           = DBLocalDataStore.GetInstance().GetSelectProfile().shortName;
            context.tags              = new string[] { user.tags };
            context.campaignReference = appInfo.campaignReference;

            var           form       = new AnsweredForm();
            List <Answer> tmpAnswers = new List <Answer>();

            form.contactUid = uid;
            form.startdate  = dateNow;
            form.enddate    = dateNow;
            form.name       = formDefinition.objectName;
            form.user       = new DeviceUser {
                username = user.username, profile = context.profile
            };
            form.answers = new Answer[] { };
            bool isAnyQuestionAnswered = answersToSend.Count(s => OfflineLogic.isAnswerValid(s.answer)) > 0;
            bool isAnswersValid        = true;

            for (int index = 0; (index < answersToSend.Count) && isAnyQuestionAnswered; index++)
            {
                if (OfflineLogic.isAnswerValid(answersToSend[index].answer))
                {
                    Answer answer = new Answer();
                    answer.answer = answersToSend[index].answer;
                    answer.name   = questions[index].name;
                    answer.type   = questions[index].type;
                    tmpAnswers.Add(answer);
                }
                else
                {
                    if (OfflineLogic.isQuestionRequired(questions[index]))
                    {
                        isAnswersValid = false;
                    }
                }
            }
            if (isAnswersValid)
            {
                form.answers = tmpAnswers.ToArray();
                scr.forms.Add(form);
            }
            else
            {
                throw new InvalidOperationException("You did not complete all mandatory fields in the info screen. Please correct.");
            }

            string        json        = JsonConvert.SerializeObject(scr);
            DBSyncRequest syncRequest = new DBSyncRequest();

            syncRequest.serializedSyncContext = json;

            DBLocalDataStore.GetInstance().addSyncRequest(syncRequest);
            OfflineLogic.ClearDataSelected();
        }
Beispiel #15
0
        public static void updateForms(string uid, List <Answer> answers, int originalRequestID)
        {
            if (answers == null)
            {
                throw new ArgumentException("Answers must not be null");
            }

            var dateNow = string.Format("{0:yyyy-MM-ddTH:mm:sszzz}", DateTime.Now);
            //var answersToSend = DBLocalDataStore.GetInstance().getAnswers();
            var appInfo        = DBLocalDataStore.GetInstance().GetAppInfo();
            var user           = DBLocalDataStore.GetInstance().GetLocalUserInfo();
            var formDefinition = DBLocalDataStore.GetInstance().GetLocalFormDefinitions().Find(s => s.uuid == DBLocalDataStore.GetInstance().GetSelectedQuestionPosition());
            var questions      = DBLocalDataStore.GetInstance().GetLocalQuestions(formDefinition.uuid);

            UpdateForms scr = new UpdateForms();

            scr.forms = new List <AnsweredForm>();
            string profileName = DBLocalDataStore.GetInstance().GetSelectProfile().shortName;

            var form = new AnsweredForm();

            form.contactUid = uid;
            form.startdate  = dateNow;
            form.enddate    = dateNow;
            form.name       = formDefinition.objectName;
            form.user       = new DeviceUser {
                username = user.username, profile = profileName
            };

            bool          isAnyQuestionAnswered = answers.Count(s => OfflineLogic.isAnswerValid(s.answer)) > 0;
            bool          isAnswersValid        = true;
            List <Answer> tmpAnswers            = new List <Answer>();

            for (int index = 0; (index < answers.Count) && isAnyQuestionAnswered; index++)
            {
                if (OfflineLogic.isAnswerValid(answers[index].answer))
                {
                    Answer answer = new Answer();
                    answer.answer = answers[index].answer;
                    answer.name   = questions[index].name;
                    answer.type   = questions[index].type;
                    tmpAnswers.Add(answer);
                }
                else
                {
                    if (OfflineLogic.isQuestionRequired(questions[index]))
                    {
                        isAnswersValid = false;
                    }
                }
            }
            if (isAnswersValid)
            {
                form.answers = tmpAnswers.ToArray();
                scr.forms.Add(form);

                string        json        = JsonConvert.SerializeObject(scr);
                DBSyncRequest syncRequest = new DBSyncRequest();
                syncRequest.serializedSyncContext = json;

                DBLocalDataStore.GetInstance().addSyncRequest(syncRequest);

                var originalSyncRequest = DBLocalDataStore.GetInstance().getSyncRequests().Find(r => r.Id == originalRequestID);
                var originalContext     = JsonConvert.DeserializeObject <SyncContext>(originalSyncRequest.serializedSyncContext);
                originalContext.forms.RemoveAll(c => c.contactUid.Equals(uid));

                if (originalContext.contacts.isNullOrEmpty() && originalContext.forms.isNullOrEmpty() && originalContext.orders.isNullOrEmpty())
                {
                    DBLocalDataStore.GetInstance().deleteSyncRequest(originalSyncRequest);
                }
                else
                {
                    originalSyncRequest.serializedSyncContext = JsonConvert.SerializeObject(originalContext);
                    DBLocalDataStore.GetInstance().updateSyncReqest(originalSyncRequest);
                }
            }
            else
            {
                throw new InvalidOperationException("You did not complete all mandatory fields in the info screen. Please correct.");
            }
        }
Beispiel #16
0
        public static async Task <DBlocalContact> didScanBarcode(string barcode_, string symbology, StatusLookup callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("Callback must not be null to handle result");
            }

            var barcode = barcode_.Trim();

            DBlocalContact temporaryContact = null;

            if (symbology == "QR")
            {
                if (!OfflineLogic.isBarcodeValid(barcode))
                {
                    throw new InvalidOperationException("The QR code cannot be used by BoaBee because it is not a contact or an ID.");
                }
                else if (barcode.Contains("BEGIN:VCARD"))
                {
                    //VCard
                    temporaryContact = OfflineLogic.parseAsVCard(barcode);
                }
                else if (barcode.StartsWith("[[") && barcode.EndsWith("]]"))
                {
                    //Artexis
                    temporaryContact = OfflineLogic.parseAsArtexis(barcode);
                }
                else
                {
                    //unknown format
                    temporaryContact     = new DBlocalContact();
                    temporaryContact.uid = barcode;
                }
            }
            else
            {
                //unknown format
                temporaryContact     = new DBlocalContact();
                temporaryContact.uid = barcode;
            }
            DBAppSettings appSettings = DBLocalDataStore.GetInstance().GetAppSettings();

            if (appSettings == null)
            {
                appSettings = new DBAppSettings();
                appSettings.instantContactCheck = true;
                DBLocalDataStore.GetInstance().SetAppSettings(appSettings);
            }

            string message = string.Empty;

            if (appSettings.instantContactCheck)
            {
                var localContact = DBLocalDataStore.GetInstance().GetLocalContactsByUID(temporaryContact.uid);
                if (localContact != null)
                {
                    temporaryContact   &= localContact;
                    temporaryContact.Id = localContact.Id;
                }

                if (await Reachability.isConnected())
                {
                    try
                    {
                        int timeout = 10000;
                        var timeoutCancellationTokenSource = new CancellationTokenSource();
                        var timeoutTask = Task.Delay(timeout, timeoutCancellationTokenSource.Token);

                        var task = NetworkRequests.contactLookup(temporaryContact.uid);

                        DBlocalContact serverContact = null;
                        if (await Task.WhenAny(task, timeoutTask) == task)
                        {
                            // Task completed within timeout.
                            // Consider that the task may have faulted or been canceled.
                            // We re-await the task so that any exceptions/cancellation is rethrown.

                            timeoutCancellationTokenSource.Cancel();

                            serverContact = await task;
                            if (serverContact != null)
                            {
                                if (serverContact.hasOnlyUID() || serverContact.hasOnlyUIDAndName())
                                {
                                    message = "Check for additional contact details can't be executed at this moment. More details will be added to your report if available.";
                                }
                                else
                                {
                                    message = "These are the details we have found for you. Feel free to complete the rest below.";
                                }
                            }
                            else
                            {
                                message = "Check for additional contact details can't be executed at this moment. More details will be added to your report if available.";
                            }
                            Console.Error.WriteLine("Server has contact: {0}", serverContact != null);
                        }
                        else
                        {
                            // timeout/cancellation logic
                            message = "Check for additional contact details can't be executed at this moment. More details will be added to your report if available.";
                            Console.Error.WriteLine("Timed out");
                        }

                        temporaryContact *= serverContact;
                    }
                    catch (Exception e)
                    {
                        message = "Check for additional contact details can't be executed at this moment. More details will be added to your report if available.";
                        Console.Error.WriteLine("contactLookup exception: {0}", e.Message);
                    }
                }
                else
                {
                    message = "Check for additional contact details can't be executed at this moment. More details will be added to your report if available.";
                }
            }
            else
            {
                message = "Instant contact checking is turned off";
            }
            callback(message);
            return(temporaryContact);
        }