Example #1
0
        public static HashSet <(string jurisdiction_id, string user_id, string role_name)> get_user_jurisdiction_set()
        {
            HashSet <(string, string, string)> result = new HashSet <(string, string, string)>();

            string jurisdicion_view_url      = $"{Program.config_couchdb_url}/jurisdiction/_design/sortable/_view/by_user_id";
            var    jurisdicion_curl          = new cURL("GET", null, jurisdicion_view_url, null, Program.config_timer_user_name, Program.config_timer_password);
            string jurisdicion_result_string = null;

            try
            {
                jurisdicion_result_string = jurisdicion_curl.execute();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex);
                return(result);
            }

            var jurisdiction_view_response = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.get_sortable_view_reponse_header <mmria.common.model.couchdb.user_role_jurisdiction> >(jurisdicion_result_string);

            foreach (mmria.common.model.couchdb.get_sortable_view_response_item <mmria.common.model.couchdb.user_role_jurisdiction> jvi in jurisdiction_view_response.rows)
            {
                if (jvi.key != null)
                {
                    result.Add((jvi.value.jurisdiction_id, jvi.value.user_id, jvi.value.role_name));
                }
            }

            return(result);
        }
Example #2
0
        private static bool url_endpoint_exists(string p_target_server, string p_user_name, string p_password, string p_method = "HEAD")
        {
            bool result = false;

            var curl = new cURL(p_method, null, p_target_server, null, p_user_name, p_password);

            try
            {
                curl.execute();

                /*
                 * HTTP/1.1 200 OK
                 * Cache-Control: must-revalidate
                 * Content-Type: application/json
                 * Date: Mon, 12 Aug 2013 01:27:41 GMT
                 * Server: CouchDB (Erlang/OTP)*/
                result = true;
            }
            catch (Exception ex)
            {
                // do nothing for now
            }


            return(result);
        }
Example #3
0
        public async Task <IActionResult> Profile()
        {
            var days_til_password_expires = -1;

            var password_days_before_expires = Program.config_password_days_before_expires;

            if (password_days_before_expires > 0)
            {
                try
                {
                    var userName = User.Identities.First(
                        u => u.IsAuthenticated &&
                        u.HasClaim(c => c.Type == ClaimTypes.Name)).FindFirst(ClaimTypes.Name).Value;

                    //var session_event_request_url = $"{Program.config_couchdb_url}/session/_design/session_event_sortable/_view/by_date_created_user_id?startkey=[" + "{}" + $",\"{user.UserName}\"]&decending=true&limit={unsuccessful_login_attempts_number_before_lockout}";
                    var session_event_request_url = $"{Program.config_couchdb_url}/session/_design/session_event_sortable/_view/by_user_id?startkey=\"{userName}\"&endkey=\"{userName}\"";

                    var    session_event_curl   = new cURL("GET", null, session_event_request_url, null, Program.config_timer_user_name, Program.config_timer_password);
                    string response_from_server = await session_event_curl.executeAsync();

                    //var session_event_response = Newtonsoft.Json.JsonConvert.DeserializeObject<mmria.common.model.couchdb.get_sortable_view_reponse_object_key_header<mmria.common.model.couchdb.session_event>>(response_from_server);
                    var session_event_response = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.get_sortable_view_reponse_header <mmria.common.model.couchdb.session_event> >(response_from_server);

                    DateTime first_item_date = DateTime.Now;
                    DateTime last_item_date  = DateTime.Now;

                    session_event_response.rows.Sort(new mmria.common.model.couchdb.Compare_Session_Event_By_DateCreated <mmria.common.model.couchdb.session_event>());

                    var date_of_last_password_change = DateTime.MinValue;

                    foreach (var session_event in session_event_response.rows)
                    {
                        if (session_event.value.action_result == mmria.common.model.couchdb.session_event.session_event_action_enum.password_changed)
                        {
                            date_of_last_password_change = session_event.value.date_created;
                            break;
                        }
                    }

                    if (date_of_last_password_change != DateTime.MinValue)
                    {
                        days_til_password_expires = password_days_before_expires - (int)(DateTime.Now - date_of_last_password_change).TotalDays;
                    }
                    else if (session_event_response.rows.Count > 0)
                    {
                        days_til_password_expires = password_days_before_expires - (int)(DateTime.Now - session_event_response.rows[session_event_response.rows.Count - 1].value.date_created).TotalDays;
                    }
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine($"{ex}");
                }
            }

            ViewBag.days_til_password_expires           = days_til_password_expires;
            ViewBag.config_password_days_before_expires = password_days_before_expires;
            ViewBag.sams_is_enabled = _configuration["sams:is_enabled"];

            return(View());
        }
Example #4
0
        private async System.Threading.Tasks.Task <string> get_revision(string p_document_url)
        {
            string result = null;

            var    document_curl      = new cURL("GET", null, p_document_url, null, Program.config_timer_user_name, Program.config_timer_password);
            string temp_document_json = null;

            try
            {
                temp_document_json = await document_curl.executeAsync();

                var request_result = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject>(temp_document_json);
                IDictionary <string, object> updater = request_result as IDictionary <string, object>;
                result = updater["_rev"].ToString();
            }
            catch (Exception ex)
            {
                if (!(ex.Message.IndexOf("(404) Object Not Found") > -1))
                {
                    //System.Console.WriteLine ("c_sync_document.get_revision");
                    //System.Console.WriteLine (ex);
                }
            }

            return(result);
        }
Example #5
0
        public static bool is_authorized_to_handle_jurisdiction_id
        (
            System.Security.Claims.ClaimsPrincipal p_claims_principal,
            mmria.common.model.couchdb.user p_user
        )
        {
            bool result = false;

            var jurisdiction_hashset = mmria.server.util.authorization.get_current_jurisdiction_id_set_for(p_claims_principal);


            string jurisdicion_view_url      = $"{Program.config_couchdb_url}/jurisdiction/_design/sortable/_view/by_user_id?{p_user.name}";
            var    jurisdicion_curl          = new cURL("GET", null, jurisdicion_view_url, null, Program.config_timer_user_name, Program.config_timer_password);
            string jurisdicion_result_string = null;

            try
            {
                jurisdicion_result_string = jurisdicion_curl.execute();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex);
                return(result);
            }

            var user_role_response = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.get_sortable_view_reponse_header <mmria.common.model.couchdb.user_role_jurisdiction> >(jurisdicion_result_string);

            foreach (mmria.common.model.couchdb.get_sortable_view_response_item <mmria.common.model.couchdb.user_role_jurisdiction> cvi in user_role_response.rows)
            {
                bool is_jurisdiction_ok = false;
                foreach ((string, ResourceRightEnum)jurisdiction_item in jurisdiction_hashset)
                {
                    var regex = new System.Text.RegularExpressions.Regex("^" + @jurisdiction_item.Item1);
                    if (cvi.value.jurisdiction_id == null)
                    {
                        cvi.value.jurisdiction_id = "/";
                    }

                    if (regex.IsMatch(cvi.value.jurisdiction_id))
                    {
                        return(true);
                    }
                }

/*
 *              foreach(string jurisdiction_id in  jurisdiction_hashset)
 *              {
 *                  var regex = new System.Text.RegularExpressions.Regex("^" + jurisdiction_id);
 *                  if(p_user._role_jurisdiction.jurisdiction_id != null && regex.IsMatch(p_user_role_jurisdiction.jurisdiction_id))
 *                  {
 *                      result = true;
 *                      break;
 *                  }
 *              }
 */
            }


            return(result);
        }
Example #6
0
        public mmria.server.model.couchdb.c_change_result GetJobInfo(string p_last_sequence)
        {
            mmria.server.model.couchdb.c_change_result result = new mmria.server.model.couchdb.c_change_result();
            string url = null;

            if (string.IsNullOrWhiteSpace(p_last_sequence))
            {
                url = Program.config_couchdb_url + "/mmrds/_changes";
            }
            else
            {
                url = Program.config_couchdb_url + "/mmrds/_changes?since=" + p_last_sequence;
            }
            var    curl = new cURL("GET", null, url, null, this.user_name, this.password);
            string res  = curl.execute();

            result = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.server.model.couchdb.c_change_result>(res);
            //System.Console.WriteLine("get_job_info.last_seq");
            //System.Console.WriteLine(result.last_seq);


            /*
             * curl -X GET $HOST/db/_changes
             * curl -X GET $HOST/db/_changes?since=1
             *
             *      http://db1.mmria.org/mmrds/_changes?since=3235-g1AAAAIseJyV0UEKwjAQBdDRKorgGSqeIEntNK7sTTSxhVJqIuheb1L3HkJPIN5Ab1LTpCtFaDcTGIZH-L8AgHHmJTBVWukkjZXO9OFYmHVfgPSrqsozTwJ4_s7sRilyzgj5vv8jyJmZcuUQ8bACCZdbTMO2QlwL60bYWwEjwmUg2gqbWjg1wtMKQiAiW7QU1MBMOJvHIKWLYzhxcRAZIOWdoIuDbvV3rlaRgiaUR52Uu1NetVJahTOT6hY7KW-nNB335q6hCDllPw3lHw3Uqkc
             *
             * {
             *      "seq":12, // update_seq created when document changed
             *      "id":"foo", // document id
             *      "changes":  /// one or more changes
             *              [
             *                      {"rev":"1-23202479633c2b380f79507a776743d5"}
             *              ]
             * }
             *
             * string get_job_search_result_json = Get_Job_Set();
             *
             * DGJobAPI.Models.GetJobSearchResult get_job_search_result = Newtonsoft.Json.JsonConvert.DeserializeObject<DGJobAPI.Models.GetJobSearchResult>(get_job_search_result_json);
             *
             * // remove duplicates
             * IEnumerable<DGJobAPI.Models.JsonSummary> de_deplicated_list = get_job_search_result.searchResults
             * .GroupBy(summary => summary.id)
             * .Select(group => group.First());
             *
             *
             * foreach (DGJobAPI.Models.JsonSummary json_summary in de_deplicated_list)
             * {
             *
             * string get_job_detail_result_json = Get_Job(json_summary.id.ToString());
             * DGJobAPI.Models.GetJobDetailResult get_job_detail_result = Newtonsoft.Json.JsonConvert.DeserializeObject<DGJobAPI.Models.GetJobDetailResult>(get_job_detail_result_json);
             * result.Add(new DGJobAPI.Models.JobInfo(json_summary.id.ToString(), get_job_detail_result));
             * }
             *
             * return result.OrderByDescending(j => j.date_last_updated).Take(100).ToList();
             */
            return(result);
        }
Example #7
0
        protected override void OnReceive(object message)
        {
            switch (message)
            {
            case Session_Message session_message:

                try
                {
                    mmria.common.model.couchdb.document_put_response result = new mmria.common.model.couchdb.document_put_response();
                    string request_string = Program.config_couchdb_url + $"/session/{session_message._id}";

                    try
                    {
                        var    check_document_curl           = new cURL("GET", null, request_string, null, Program.config_timer_user_name, Program.config_timer_password);
                        string check_document_json           = check_document_curl.execute();
                        var    check_document_expando_object = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.session> (check_document_json);

                        if (!session_message.user_id.Equals(check_document_expando_object.user_id, StringComparison.OrdinalIgnoreCase))
                        {
                            Console.Write($"unauthorized PUT {session_message._id} by: {session_message.user_id}");
                            return;//result;
                        }
                    }
                    catch (Exception ex)
                    {
                        // do nothing for now document doesn't exsist.
                        System.Console.WriteLine($"err caseController.Post\n{ex}");
                    }

                    Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
                    settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                    var object_string = Newtonsoft.Json.JsonConvert.SerializeObject(session_message, settings);

                    cURL document_curl = new cURL("PUT", null, request_string, object_string, Program.config_timer_user_name, Program.config_timer_password);

                    try
                    {
                        string responseFromServer = document_curl.execute();
                        result = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.document_put_response>(responseFromServer);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }


                break;
            }
        }
Example #8
0
        private mmria.common.model.migration_plan get_migration_plan(string p_id)
        {
            string url = Program.config_couchdb_url + $"/metadata/{p_id}";

            var    curl = new cURL("GET", null, url, null, Program.config_timer_user_name, Program.config_timer_password);
            string responseFromServer = curl.execute();

            var migration_plan = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.migration_plan>(responseFromServer);

            return(migration_plan);
        }
Example #9
0
        protected override void OnReceive(object message)
        {
            switch (message)
            {
            case Session_Event_Message sem:


                try
                {
                    var se = new mmria.common.model.couchdb.session_event();
                    se.data_type    = "session-event";
                    se._id          = sem._id;
                    se.date_created = sem.date_created;
                    se.user_id      = sem.user_id;
                    se.ip           = sem.ip;

                    switch (sem.action_result)
                    {
                    case Session_Event_Message.Session_Event_Message_Action_Enum.successful_login:
                        se.action_result = mmria.common.model.couchdb.session_event.session_event_action_enum.successful_login;
                        break;

                    case Session_Event_Message.Session_Event_Message_Action_Enum.password_changed:
                        se.action_result = mmria.common.model.couchdb.session_event.session_event_action_enum.password_changed;
                        break;

                    case Session_Event_Message.Session_Event_Message_Action_Enum.failed_login:
                    default:
                        se.action_result = mmria.common.model.couchdb.session_event.session_event_action_enum.failed_login;
                        break;
                    }


                    Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
                    settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                    var session_event_json = Newtonsoft.Json.JsonConvert.SerializeObject(se, settings);

                    var request_url = $"{Program.config_couchdb_url}/session/{se._id}";
                    var curl        = new cURL("PUT", null, request_url, session_event_json, Program.config_timer_user_name, Program.config_timer_password);
                    curl.executeAsync().Wait();

                    //var session_event_response = Newtonsoft.Json.JsonConvert.DeserializeObject<mmria.common.model.couchdb.get_sortable_view_reponse_object_key_header<mmria.common.model.couchdb.session_event>>(response_from_server);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Session_Event_Message exception: {ex}");
                }

                break;
            }
        }
Example #10
0
        private async Task <string> Post_Document_List(mmria.console.model.couchdb.cBulkDocument p_bulk_document)
        {
            string result = null;
            string bulk_document_string = Newtonsoft.Json.JsonConvert.SerializeObject(p_bulk_document);
            string URL           = string.Format("{0}/_bulk_docs", this.database_url);
            cURL   document_curl = new cURL("POST", null, URL, bulk_document_string, this.user_name, this.password);

            try
            {
                result = await document_curl.executeAsync();
            }
            catch (Exception ex)
            {
                result = ex.ToString();
            }
            return(result);
        }
Example #11
0
        private mmria.console.model.couchdb.cBulkDocument GetDocumentList()
        {
            mmria.console.model.couchdb.cBulkDocument result = new model.couchdb.cBulkDocument();

            string  URL            = string.Format("{0}/_all_docs?include_docs=true", this.database_url);
            cURL    document_curl  = new cURL("GET", null, URL, null, this.user_name, this.password);
            dynamic all_cases      = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject> (document_curl.execute());
            dynamic all_cases_rows = all_cases.rows;

            foreach (System.Dynamic.ExpandoObject case_row in all_cases_rows)
            {
                IDictionary <string, object> case_doc = ((IDictionary <string, object>)case_row) ["doc"] as IDictionary <string, object>;
                case_doc.Remove("_rev");
                result.docs.Add(case_doc);
            }

            return(result);
        }
Example #12
0
        protected override Task HandleRequirementAsync
        (
            AuthorizationHandlerContext context,
            JurisdictionAuthorizationRequirement requirement,
            System.Dynamic.ExpandoObject caseExpandoObject
        )
        {
            if (!context.User.HasClaim(c => c.Type == "JurisdictionList" &&
                                       c.Issuer == "https://contoso.com"))
            {
                return(Task.CompletedTask);
            }



            string jurisdicion_view_url      = $"{Program.config_couchdb_url}/jurisdiction/_design/sortable/_view/by_user_id?";
            var    jurisdicion_curl          = new cURL("POST", null, jurisdicion_view_url, null, Program.config_timer_user_name, Program.config_timer_password);
            string jurisdicion_result_string = null;

            try
            {
                jurisdicion_result_string = jurisdicion_curl.execute();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex);
            }

            var jurisdiction_view_response = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.get_response_header <mmria.common.model.couchdb.jurisdiction_view_sortable_item> >(jurisdicion_result_string);

            //IDictionary<string, object> jurisdicion_result_dictionary = jurisdicion_result_data[0] as IDictionary<string, object>;
            //var juridiction_curl = new cURL();
            foreach (mmria.common.model.couchdb.get_response_item <mmria.common.model.couchdb.jurisdiction_view_sortable_item> jvi in jurisdiction_view_response.rows)
            {
            }



            context.Succeed(requirement);

            return(Task.CompletedTask);
        }
        public mmria.server.model.couchdb.c_change_result get_changes(string p_last_sequence, ScheduleInfoMessage p_scheduleInfo)
        {
            mmria.server.model.couchdb.c_change_result result = new mmria.server.model.couchdb.c_change_result();
            string url = null;

            if (string.IsNullOrWhiteSpace(p_last_sequence))
            {
                url = Program.config_couchdb_url + "/mmrds/_changes";
            }
            else
            {
                url = Program.config_couchdb_url + "/mmrds/_changes?since=" + p_last_sequence;
            }
            var    curl = new cURL("GET", null, url, null, p_scheduleInfo.user_name, p_scheduleInfo.password);
            string res  = curl.execute();

            result = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.server.model.couchdb.c_change_result>(res);

            return(result);
        }
Example #14
0
        private void process_migration_plan_by_id(string migration_plan_id)
        {
            try
            {
                //string migration_plan_id = message.ToString();

                Console.WriteLine($"Process_Migrate_Data Begin {System.DateTime.Now}");


                string url = Program.config_couchdb_url + "/mmrds/_all_docs?include_docs=true";

                var    case_curl          = new cURL("GET", null, url, null, Program.config_timer_user_name, Program.config_timer_password);
                string responseFromServer = case_curl.execute();

                var case_response = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.get_response_header <System.Dynamic.ExpandoObject> >(responseFromServer);

                var migration_plan = get_migration_plan(migration_plan_id);

                var lookup = get_look_up(migration_plan);

                foreach (var case_item in case_response.rows)
                {
                    var case_has_changed = false;
                    foreach (var plan_item in migration_plan.plan_items)
                    {
                        if
                        (
                            string.IsNullOrWhiteSpace(plan_item.old_mmria_path) ||
                            string.IsNullOrWhiteSpace(plan_item.new_mmria_path)
                        )
                        {
                            continue;
                        }

/*
 *                                              if
 *                                              (
 *                                                      plan_item.old_mmria_path == "er_visit_and_hospital_medical_records/onset_of_labor/is_artificial" &&
 *                                                      case_item.id == "ad52d04f-dced-60ed-ba09-3cdfbba390b0"
 *                                              )
 *                                              {
 *                                                      Console.Write("break");
 *                                              }
 */

                        var old_value_list = get_value(plan_item.old_mmria_path.TrimEnd('/'), case_item.doc);

                        for (var i = 0; i < old_value_list.Count; i++)
                        {
                            var old_value = old_value_list[i];

                            string new_value = old_value.value;
                            if
                            (
                                lookup[plan_item.old_mmria_path][plan_item.new_mmria_path].ContainsKey(old_value.value + "")

                            )
                            {
                                new_value = lookup[plan_item.old_mmria_path][plan_item.new_mmria_path][old_value.value];
                                if (old_value.value != new_value)
                                {
                                    var set_result = set_value(plan_item.new_mmria_path.TrimEnd('/'), new_value, case_item.doc, old_value.index);

                                    case_has_changed = true;
                                }
                            }

                            /*
                             * else if
                             * (
                             *      plan_item.old_mmria_path == plan_item.new_mmria_path
                             * )
                             * {
                             *      var set_result = set_value(plan_item.new_mmria_path.TrimEnd('/'), new_value, case_item.doc, old_value.index);
                             * }
                             */
                        }
                    }

                    if (case_has_changed)
                    {
                        set_value("date_last_updated", DateTime.UtcNow.ToString("o"), case_item.doc);
                        set_value("last_updated_by", "migration_plan", case_item.doc);


                        Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
                        settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                        var object_string = Newtonsoft.Json.JsonConvert.SerializeObject(case_item.doc, settings);

                        string put_url       = Program.config_couchdb_url + "/mmrds/" + case_item.id;
                        cURL   document_curl = new cURL("PUT", null, put_url, object_string, Program.config_timer_user_name, Program.config_timer_password);

                        try
                        {
                            responseFromServer = document_curl.execute();
                            var result = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.document_put_response>(responseFromServer);
                        }
                        catch (Exception ex)
                        {
                            //Console.Write("auth_session_token: {0}", auth_session_token);
                            Console.WriteLine(ex);
                        }
                    }
                }

                Console.WriteLine($"Process_Migrate_Data End {System.DateTime.Now}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Process_Migrate_Data exception {System.DateTime.Now}\n{ex}");
            }
        }
Example #15
0
        public async System.Threading.Tasks.Task executeAsync()
        {
            string de_identified_json = new mmria.server.util.c_de_identifier(document_json).execute();

            string de_identified_revision = await get_revision(Program.config_couchdb_url + "/de_id/" + this.document_id);

            System.Text.StringBuilder de_identfied_url = new System.Text.StringBuilder();

            if (!string.IsNullOrEmpty(de_identified_revision))
            {
                //de_identfied_url = Program.config_couchdb_url + "/de_id/" + this.document_id + "?new_edits=false";

                de_identified_json = set_revision(de_identified_json, de_identified_revision);
            }

            de_identfied_url.Append(Program.config_couchdb_url);
            de_identfied_url.Append("/de_id/");
            de_identfied_url.Append(this.document_id);

            if (this.method == "DELETE")
            {
                de_identfied_url.Append("?rev=");
                de_identfied_url.Append(de_identified_revision);
            }

            var de_identfied_curl = new cURL(this.method, null, de_identfied_url.ToString(), de_identified_json, Program.config_timer_user_name, Program.config_timer_password);

            try
            {
                string de_id_result = await de_identfied_curl.executeAsync();

                System.Console.WriteLine("sync de_id");
                System.Console.WriteLine(de_id_result);
            }
            catch (Exception ex)
            {
                //System.Console.WriteLine("c_sync_document de_id");
                //System.Console.WriteLine(ex);
            }


            //string aggregate_url = Program.config_couchdb_url + "/report/" + kvp.Key + "?new_edits=false";

            try
            {
                string aggregate_json = new mmria.server.util.c_convert_to_report_object(document_json).execute();

                string aggregate_revision = await get_revision(Program.config_couchdb_url + "/report/" + this.document_id);

                System.Text.StringBuilder aggregate_url = new System.Text.StringBuilder();

                if (!string.IsNullOrEmpty(aggregate_revision))
                {
                    //aggregate_url = Program.config_couchdb_url + "/report/" + this.document_id + "?new_edits=false";
                    aggregate_json = set_revision(aggregate_json, aggregate_revision);
                }


                aggregate_url.Append(Program.config_couchdb_url);
                aggregate_url.Append("/report/");
                aggregate_url.Append(this.document_id);

                if (this.method == "DELETE")
                {
                    aggregate_url.Append("?rev=");
                    aggregate_url.Append(aggregate_revision);
                }

                var aggregate_curl = new cURL(this.method, null, aggregate_url.ToString(), aggregate_json, Program.config_timer_user_name, Program.config_timer_password);

                string aggregate_result = await aggregate_curl.executeAsync();

                System.Console.WriteLine("c_sync_document aggregate_id");
                System.Console.WriteLine(aggregate_result);
            }
            catch (Exception ex)
            {
                //System.Console.WriteLine("sync aggregate_id");
                //System.Console.WriteLine(ex);
            }
        }
Example #16
0
        public static HashSet <(string jurisdiction_id, ResourceRightEnum ResourceRight)> get_current_jurisdiction_id_set_for(System.Security.Claims.ClaimsPrincipal p_claims_principal)
        {
            var result = new HashSet <(string jurisdiction_id, ResourceRightEnum ResourceRight)>();

            if (!p_claims_principal.HasClaim(c => c.Type == ClaimTypes.Name &&
                                             c.Issuer == "https://contoso.com"))
            {
                return(result);
            }

            if (p_claims_principal.HasClaim(c => c.Type == ClaimTypes.Role &&
                                            c.Value == "installation_admin"))
            {
                result.Add(("/", ResourceRightEnum.ReadUser));
                result.Add(("/", ResourceRightEnum.WriteUser));
                result.Add(("/", ResourceRightEnum.ReadJurisdiction));
                result.Add(("/", ResourceRightEnum.WriteJurisdiction));
            }

            var user_name = p_claims_principal.Claims.Where(c => c.Type == ClaimTypes.Name).FirstOrDefault().Value;

            string jurisdicion_view_url      = $"{Program.config_couchdb_url}/jurisdiction/_design/sortable/_view/by_user_id";
            var    jurisdicion_curl          = new cURL("GET", null, jurisdicion_view_url, null, Program.config_timer_user_name, Program.config_timer_password);
            string jurisdicion_result_string = null;

            try
            {
                jurisdicion_result_string = jurisdicion_curl.execute();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex);
                return(result);
            }

            var jurisdiction_view_response = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.get_sortable_view_reponse_header <mmria.common.model.couchdb.user_role_jurisdiction> >(jurisdicion_result_string);

            foreach (mmria.common.model.couchdb.get_sortable_view_response_item <mmria.common.model.couchdb.user_role_jurisdiction> jvi in jurisdiction_view_response.rows)
            {
                if (jvi.key != null && jvi.value.user_id == user_name)
                {
                    if
                    (
                        jvi.value.is_active == null ||
                        jvi.value.effective_start_date == null
                    )
                    {
                        continue;
                    }

                    if
                    (
                        !
                        (jvi.value.is_active.HasValue ||
                         jvi.value.effective_start_date.HasValue)
                    )
                    {
                        continue;
                    }



                    var now_date = DateTime.Now;

                    if
                    (
                        jvi.value.effective_end_date == null ||
                        jvi.value.effective_end_date.HasValue == false
                    )
                    {
                        jvi.value.effective_end_date = now_date;
                    }

                    if
                    (
                        !jvi.value.is_active.Value ||
                        !(jvi.value.effective_start_date.Value <= now_date) ||
                        !(now_date <= jvi.value.effective_end_date.Value)
                    )
                    {
                        continue;
                    }

                    switch (jvi.value.role_name)
                    {
                    case "abstractor":
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadCase));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.WriteCase));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadMetadata));
                        break;

                    case "committee_member":
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadDeidentifiedCase));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadMetadata));
                        break;

                    case "form_designer":
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.WriteMetadata));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadMetadata));
                        break;

                    case "jurisdiction_admin":
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadUser));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.WriteUser));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadMetadata));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadJurisdiction));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.WriteJurisdiction));
                        break;

                    case "installation_admin":
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadUser));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.WriteUser));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadMetadata));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.ReadJurisdiction));
                        result.Add((jvi.value.jurisdiction_id, ResourceRightEnum.WriteJurisdiction));
                        break;
                    }
                }
            }

            return(result);
        }
Example #17
0
        public static HashSet <(string jurisdiction_id, string user_id, string role_name)> get_current_user_role_jurisdiction_set_for(string p_user_name)
        {
            var result = new HashSet <(string jurisdiction_id, string user_id, string role_name)>();


            string jurisdicion_view_url      = $"{Program.config_couchdb_url}/jurisdiction/_design/sortable/_view/by_user_id";
            var    jurisdicion_curl          = new cURL("GET", null, jurisdicion_view_url, null, Program.config_timer_user_name, Program.config_timer_password);
            string jurisdicion_result_string = null;

            try
            {
                jurisdicion_result_string = jurisdicion_curl.execute();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex);
                return(result);
            }

            var jurisdiction_view_response = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.get_sortable_view_reponse_header <mmria.common.model.couchdb.user_role_jurisdiction> >(jurisdicion_result_string);

            foreach (mmria.common.model.couchdb.get_sortable_view_response_item <mmria.common.model.couchdb.user_role_jurisdiction> jvi in jurisdiction_view_response.rows)
            {
                if (jvi.key != null && jvi.value.user_id == p_user_name)
                {
                    if
                    (
                        jvi.value.is_active == null ||
                        jvi.value.effective_start_date == null
                    )
                    {
                        continue;
                    }

                    if
                    (
                        !
                        (jvi.value.is_active.HasValue ||
                         jvi.value.effective_start_date.HasValue)
                    )
                    {
                        continue;
                    }

                    var now_date = DateTime.Now;

                    if
                    (
                        jvi.value.effective_end_date == null ||
                        jvi.value.effective_end_date.HasValue == false
                    )
                    {
                        jvi.value.effective_end_date = now_date;
                    }

                    if
                    (
                        !jvi.value.is_active.Value ||
                        !(jvi.value.effective_start_date.Value <= now_date) ||
                        !(now_date <= jvi.value.effective_end_date.Value)
                    )
                    {
                        continue;
                    }


                    result.Add((jvi.value.jurisdiction_id, jvi.value.user_id, jvi.value.role_name));
                }
            }

            return(result);
        }
Example #18
0
        public void Process_Export_Queue_Delete()
        {
            //System.Console.WriteLine ("{0} check_for_changes_job.Process_Export_Queue_Delete: started", System.DateTime.Now);

            List <export_queue_item> result = new List <export_queue_item> ();

            var get_curl = new cURL("GET", null, Program.config_couchdb_url + "/export_queue/_all_docs?include_docs=true", null, this.user_name, this.password);

            string responseFromServer = get_curl.execute();

            IDictionary <string, object> response_result = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject> (responseFromServer) as IDictionary <string, object>;
            IList <object> enumerable_rows = response_result ["rows"] as IList <object>;

            foreach (IDictionary <string, object> enumerable_item in enumerable_rows)
            {
                IDictionary <string, object> doc_item = enumerable_item ["doc"] as IDictionary <string, object>;

                if (
                    doc_item ["status"] != null &&
                    doc_item ["status"].ToString().StartsWith("Deleted", StringComparison.OrdinalIgnoreCase))
                {
                    export_queue_item item = new export_queue_item();

                    item._id               = doc_item ["_id"].ToString();
                    item._rev              = doc_item ["_rev"].ToString();
                    item._deleted          = doc_item.ContainsKey("_deleted") ? doc_item["_deleted"] as bool?: null;
                    item.date_created      = doc_item ["date_created"] as DateTime?;
                    item.created_by        = doc_item.ContainsKey("created_by") && doc_item ["created_by"] != null ? doc_item ["created_by"].ToString() : null;
                    item.date_last_updated = doc_item ["date_last_updated"] as DateTime?;
                    item.last_updated_by   = doc_item.ContainsKey("last_updated_by") && doc_item["last_updated_by"] != null ? doc_item ["last_updated_by"].ToString() : null;
                    item.file_name         = doc_item ["file_name"] != null ? doc_item ["file_name"].ToString() : null;
                    item.export_type       = doc_item ["export_type"] != null ? doc_item ["export_type"].ToString() : null;
                    item.status            = doc_item ["status"] != null ? doc_item ["status"].ToString() : null;

                    result.Add(item);
                }
            }


            if (result.Count > 0)
            {
                if (result.Count > 1)
                {
                    var comparer = Comparer <export_queue_item> .Create
                                   (
                        (x, y) => x.date_created.Value.CompareTo(y.date_created.Value)
                                   );

                    result.Sort(comparer);
                }

                export_queue_item item_to_process = result [0];

                try
                {
                    string item_directory_name = item_to_process.file_name.Substring(0, item_to_process.file_name.LastIndexOf("."));
                    string export_directory    = System.IO.Path.Combine(System.Configuration.ConfigurationManager.AppSettings ["export_directory"], item_directory_name);

                    try
                    {
                        if (System.IO.Directory.Exists(export_directory))
                        {
                            System.IO.Directory.Delete(export_directory, true);
                        }
                    }
                    catch (Exception Ex)
                    {
                        // do nothing for now
                        System.Console.WriteLine("check_for_changes_job.Process_Export_Queue_Delete: Unable to Delete Directory {0}", export_directory);
                    }

                    string file_path = System.IO.Path.Combine(System.Configuration.ConfigurationManager.AppSettings ["export_directory"], item_to_process.file_name);
                    try
                    {
                        if (System.IO.File.Exists(file_path))
                        {
                            System.IO.File.Delete(file_path);
                        }
                    }
                    catch (Exception Ex)
                    {
                        // do nothing for now
                        System.Console.WriteLine("Program.Process_Export_Queue_Delete: Unable to Delete File {0}", file_path);
                    }

                    item_to_process.status          = "expunged";
                    item_to_process.last_updated_by = "mmria-server";
                    Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
                    settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                    string object_string = Newtonsoft.Json.JsonConvert.SerializeObject(item_to_process, settings);
                    var    set_curl      = new cURL("PUT", null, Program.config_couchdb_url + "/export_queue/" + item_to_process._id, object_string, this.user_name, this.password);

                    responseFromServer = get_curl.execute();
                }
                catch (Exception ex)
                {
                    // do nothing for now
                }
            }
        }
Example #19
0
        public async Task <IActionResult> Login(ApplicationUser user, string returnUrl = null)
        {
            var use_sams = false;

            if (!string.IsNullOrWhiteSpace(_configuration["sams:is_enabled"]))
            {
                bool.TryParse(_configuration["sams:is_enabled"], out use_sams);
            }

            if (use_sams)
            {
                return(RedirectToAction("SignIn"));
            }

            const string badUserNameOrPasswordMessage = "Username or password is incorrect.";

            if (
                user == null ||
                string.IsNullOrWhiteSpace(user.UserName) ||
                string.IsNullOrWhiteSpace(user.Password)
                )
            {
                return(BadRequest(badUserNameOrPasswordMessage));
            }



            try
            {
                var unsuccessful_login_attempts_number_before_lockout     = Program.config_unsuccessful_login_attempts_number_before_lockout;
                var unsuccessful_login_attempts_within_number_of_minutes  = Program.config_unsuccessful_login_attempts_within_number_of_minutes;
                var unsuccessful_login_attempts_lockout_number_of_minutes = Program.config_unsuccessful_login_attempts_lockout_number_of_minutes;
                var password_days_before_expires = Program.config_password_days_before_expires;


                var is_locked_out      = false;
                var failed_login_count = 0;


                DateTime grace_period_date = DateTime.Now;

                try
                {
                    //var session_event_request_url = $"{Program.config_couchdb_url}/session/_design/session_event_sortable/_view/by_date_created_user_id?startkey=[" + "{}" + $",\"{user.UserName}\"]&decending=true&limit={unsuccessful_login_attempts_number_before_lockout}";
                    var session_event_request_url = $"{Program.config_couchdb_url}/session/_design/session_event_sortable/_view/by_user_id?startkey=\"{user.UserName}\"&endkey=\"{user.UserName}\"";

                    var    session_event_curl   = new cURL("GET", null, session_event_request_url, null, Program.config_timer_user_name, Program.config_timer_password);
                    string response_from_server = await session_event_curl.executeAsync();

                    //var session_event_response = Newtonsoft.Json.JsonConvert.DeserializeObject<mmria.common.model.couchdb.get_sortable_view_reponse_object_key_header<mmria.common.model.couchdb.session_event>>(response_from_server);
                    var session_event_response = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.get_sortable_view_reponse_header <mmria.common.model.couchdb.session_event> >(response_from_server);

                    DateTime first_item_date = DateTime.Now;
                    DateTime last_item_date  = DateTime.Now;


                    var MaxRange = DateTime.Now.AddMinutes(-unsuccessful_login_attempts_within_number_of_minutes);
                    session_event_response.rows.Sort(new mmria.common.model.couchdb.Compare_Session_Event_By_DateCreated <mmria.common.model.couchdb.session_event>());

/*
 *                  if(password_days_before_expires > 0)
 *                  {
 *                      var date_of_last_password_change = DateTime.MinValue;
 *
 *                      foreach(var session_event in session_event_response.rows)
 *                      {
 *                          if(session_event.value.action_result == mmria.common.model.couchdb.session_event.session_event_action_enum.password_changed)
 *                          {
 *                              date_of_last_password_change = session_event.value.date_created;
 *                              break;
 *                          }
 *                      }
 *
 *                      if(date_of_last_password_change != DateTime.MinValue)
 *                      {
 *                          days_til_password_expires = password_days_before_expires - (int)(DateTime.Now - date_of_last_password_change).TotalDays;
 *                      }
 *                  }
 */

                    foreach (var session_event in session_event_response.rows.Where(row => row.value.date_created >= MaxRange))
                    {
                        if (session_event.value.action_result == mmria.common.model.couchdb.session_event.session_event_action_enum.failed_login)
                        {
                            failed_login_count++;
                            if (failed_login_count == 1)
                            {
                                first_item_date = session_event.value.date_created;
                            }

                            if (failed_login_count >= unsuccessful_login_attempts_number_before_lockout)
                            {
                                last_item_date    = session_event.value.date_created;
                                grace_period_date = first_item_date.AddMinutes(unsuccessful_login_attempts_lockout_number_of_minutes);
                                if (DateTime.Now < grace_period_date)
                                {
                                    is_locked_out = true;
                                    break;
                                }
                            }
                        }
                        else if (session_event.value.action_result == mmria.common.model.couchdb.session_event.session_event_action_enum.successful_login)
                        {
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine($"{ex}");
                }


                if (is_locked_out)
                {
                    return(RedirectToAction("Locked", new { user_name = user.UserName, grace_period_date = grace_period_date }));
                    //return View("~/Views/Account/Locked.cshtml");
                }


                string post_data       = string.Format("name={0}&password={1}", user.UserName, user.Password);
                byte[] post_byte_array = System.Text.Encoding.ASCII.GetBytes(post_data);

                string request_string         = Program.config_couchdb_url + "/_session";
                System.Net.WebRequest request = System.Net.WebRequest.Create(new Uri(request_string));
                //request.UseDefaultCredentials = true;

                request.PreAuthenticate = false;
                //request.Credentials = new System.Net.NetworkCredential("mmrds", "mmrds");
                request.Method        = "POST";
                request.ContentType   = "application/x-www-form-urlencoded";
                request.ContentLength = post_byte_array.Length;

                using (System.IO.Stream stream = request.GetRequestStream())
                {
                    stream.Write(post_byte_array, 0, post_byte_array.Length);
                }

                System.Net.WebResponse response   = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.Stream       dataStream = response.GetResponseStream();
                System.IO.StreamReader reader     = new System.IO.StreamReader(dataStream);
                string responseFromServer         = await reader.ReadToEndAsync();

                mmria.common.model.couchdb.login_response json_result = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.login_response>(responseFromServer);

                mmria.common.model.couchdb.login_response[] result = new mmria.common.model.couchdb.login_response[]
                {
                    json_result
                };


                this.Response.Headers.Add("Set-Cookie", response.Headers["Set-Cookie"]);

                string[] set_cookie = response.Headers["Set-Cookie"].Split(';');
                string[] auth_array = set_cookie[0].Split('=');
                if (auth_array.Length > 1)
                {
                    string auth_session_token = auth_array[1];
                    result[0].auth_session = auth_session_token;
                }
                else
                {
                    result[0].auth_session = "";
                }


                if (json_result.ok && !string.IsNullOrWhiteSpace(json_result.name))
                {
                    const string Issuer = "https://contoso.com";
                    var          claims = new List <Claim>();
                    claims.Add(new Claim(ClaimTypes.Name, json_result.name, ClaimValueTypes.String, Issuer));


                    foreach (var role in json_result.roles)
                    {
                        if (role == "_admin")
                        {
                            claims.Add(new Claim(ClaimTypes.Role, "installation_admin", ClaimValueTypes.String, Issuer));
                        }
                    }


                    foreach (var role in mmria.server.util.authorization.get_current_user_role_jurisdiction_set_for(json_result.name).Select(jr => jr.role_name).Distinct())
                    {
                        claims.Add(new Claim(ClaimTypes.Role, role, ClaimValueTypes.String, Issuer));
                    }


                    //Response.Cookies.Append("uid", json_result.name);
                    //Response.Cookies.Append("roles", string.Join(",",json_result.roles));

                    //claims.Add(new Claim("EmployeeId", string.Empty, ClaimValueTypes.String, Issuer));
                    //claims.Add(new Claim("EmployeeId", "123", ClaimValueTypes.String, Issuer));
                    //claims.Add(new Claim(ClaimTypes.DateOfBirth, "1970-06-08", ClaimValueTypes.Date));
                    //var userIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

                    var session_idle_timeout_minutes = 30;

                    if (_configuration["mmria_settings:session_idle_timeout_minutes"] != null)
                    {
                        int.TryParse(_configuration["mmria_settings:session_idle_timeout_minutes"], out session_idle_timeout_minutes);
                    }

                    var userIdentity = new ClaimsIdentity("SuperSecureLogin");
                    userIdentity.AddClaims(claims);
                    var userPrincipal = new ClaimsPrincipal(userIdentity);

                    await HttpContext.SignInAsync(
                        CookieAuthenticationDefaults.AuthenticationScheme,
                        userPrincipal,
                        new AuthenticationProperties
                    {
                        ExpiresUtc   = DateTime.UtcNow.AddMinutes(session_idle_timeout_minutes),
                        IsPersistent = false,
                        AllowRefresh = false,
                    });
                }

                var Session_Event_Message = new mmria.server.model.actor.Session_Event_Message
                                            (
                    DateTime.Now,
                    user.UserName,
                    this.GetRequestIP(),
                    json_result.ok && json_result.name != null? mmria.server.model.actor.Session_Event_Message.Session_Event_Message_Action_Enum.successful_login: mmria.server.model.actor.Session_Event_Message.Session_Event_Message_Action_Enum.failed_login
                                            );

                _actorSystem.ActorOf(Props.Create <mmria.server.model.actor.Record_Session_Event>()).Tell(Session_Event_Message);

                //this.ActionContext.Response.Headers.Add("Set-Cookie", auth_session_token);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);

                var Session_Event_Message = new mmria.server.model.actor.Session_Event_Message
                                            (
                    DateTime.Now,
                    user.UserName,
                    this.GetRequestIP(),
                    mmria.server.model.actor.Session_Event_Message.Session_Event_Message_Action_Enum.failed_login
                                            );

                _actorSystem.ActorOf(Props.Create <mmria.server.model.actor.Record_Session_Event>()).Tell(Session_Event_Message);
            }

/*
 *          var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
 *          identity.AddClaim(new Claim(ClaimTypes.Name, lookupUser.UserName));
 *
 *          await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
 */
            if (returnUrl == null)
            {
                returnUrl = TempData["returnUrl"]?.ToString();
            }

            if (returnUrl != null)
            {
                return(Redirect(returnUrl));
            }

            return(RedirectToAction(nameof(HomeController.Index), "Home"));
        }
Example #20
0
        protected override void OnReceive(object message)
        {
            Console.WriteLine($"Rebuild_Export_Queue Baby {System.DateTime.Now}");


            switch (message)
            {
            case ScheduleInfoMessage scheduleInfo:


                var midnight_timespan = new TimeSpan(0, 0, 0);
                var difference        = DateTime.Now - midnight_timespan;
                if (difference.Hour != 0 && difference.Minute != 0)
                {
                    return;
                }

                /*
                 * try
                 * {
                 *  Program.PauseSchedule ();
                 * }
                 * catch (Exception ex)
                 * {
                 *  System.Console.WriteLine ($"rebuild_queue_job. error pausing schedule\n{ex}");
                 * }
                 */

                try
                {
                    string export_directory = scheduleInfo.export_directory;

                    if (System.IO.Directory.Exists(export_directory))
                    {
                        RecursiveDirectoryDelete(new System.IO.DirectoryInfo(export_directory));
                    }

                    System.IO.Directory.CreateDirectory(export_directory);
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine($"rebuild_queue_job. error deleting directory queue\n{ex}");
                }


                if (url_endpoint_exists(Program.config_couchdb_url + "/export_queue", scheduleInfo.user_name, scheduleInfo.password))
                {
                    var delete_queue_curl = new cURL("DELETE", null, Program.config_couchdb_url + "/export_queue", null, scheduleInfo.user_name, scheduleInfo.password);
                    System.Console.WriteLine(delete_queue_curl.execute());
                }


                try
                {
                    System.Console.WriteLine("Creating export_queue db.");
                    var export_queue_curl = new cURL("PUT", null, Program.config_couchdb_url + "/export_queue", null, scheduleInfo.user_name, scheduleInfo.password);
                    System.Console.WriteLine(export_queue_curl.execute());
                    new cURL("PUT", null, Program.config_couchdb_url + "/export_queue/_security", "{\"admins\":{\"names\":[],\"roles\":[\"abstractor\"]},\"members\":{\"names\":[],\"roles\":[\"abstractor\"]}}", scheduleInfo.user_name, scheduleInfo.password).execute();
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine($"rebuild_queue_job. error creating queue\n{ex}");
                }

/*
 *
 *                  try
 *                  {
 *                      Program.ResumeSchedule ();
 *                  }
 *                  catch (Exception ex)
 *                  {
 *                      System.Console.WriteLine ($"rebuild_queue_job. error resuming schedule\n{ex}");
 *                  }
 */
                break;
            }
        }
Example #21
0
        public virtual Task Execute(IJobExecutionContext context)
        {
            //Common.Logging.ILog log = Common.Logging.LogManager.GetCurrentClassLogger();
            //log.Debug("IJob.Execute");

            JobKey jobKey = context.JobDetail.Key;

/*
 *
 *          try
 *          {
 *              Program.PauseSchedule ();
 *          }
 *          catch (Exception ex)
 *          {
 *              System.Console.WriteLine ($"rebuild_queue_job. error pausing schedule\n{ex}");
 *          }
 */
            try
            {
                string export_directory = Configuration["mmria_settings:export_directory"];

                if (System.IO.Directory.Exists(export_directory))
                {
                    RecursiveDirectoryDelete(new System.IO.DirectoryInfo(export_directory));
                }

                System.IO.Directory.CreateDirectory(export_directory);
            }
            catch (Exception ex)
            {
                System.Console.WriteLine($"rebuild_queue_job. error deleting directory queue\n{ex}");
            }


            if (url_endpoint_exists(Program.config_couchdb_url + "/export_queue", this.user_name, this.password))
            {
                var delete_queue_curl = new cURL("DELETE", null, Program.config_couchdb_url + "/export_queue", null, this.user_name, this.password);
                System.Console.WriteLine(delete_queue_curl.execute());
            }


            try
            {
                System.Console.WriteLine("Creating export_queue db.");
                var export_queue_curl = new cURL("PUT", null, Program.config_couchdb_url + "/export_queue", null, this.user_name, this.password);
                System.Console.WriteLine(export_queue_curl.execute());
                new cURL("PUT", null, Program.config_couchdb_url + "/export_queue/_security", "{\"admins\":{\"names\":[],\"roles\":[\"abstractor\"]},\"members\":{\"names\":[],\"roles\":[\"abstractor\"]}}", this.user_name, this.password).execute();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine($"rebuild_queue_job. error creating queue\n{ex}");
            }


/*
 *          try
 *          {
 *              Program.ResumeSchedule ();
 *          }
 *          catch (Exception ex)
 *          {
 *              System.Console.WriteLine ($"rebuild_queue_job. error resuming schedule\n{ex}");
 *          }
 */
            return(Task.CompletedTask);
        }
Example #22
0
        public void Process_Export_Queue_Item()
        {
            //System.Console.WriteLine ("{0} check_for_changes_job.Process_Export_Queue_Item: started", System.DateTime.Now);

            List <export_queue_item> result = new List <export_queue_item> ();

            var get_curl = new cURL("GET", null, Program.config_couchdb_url + "/export_queue/_all_docs?include_docs=true", null, this.user_name, this.password);

            string responseFromServer = get_curl.execute();

            IDictionary <string, object> response_result = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject> (responseFromServer) as IDictionary <string, object>;
            IList <object> enumerable_rows = response_result ["rows"] as IList <object>;

            foreach (IDictionary <string, object> enumerable_item in enumerable_rows)
            {
                IDictionary <string, object> doc_item = enumerable_item ["doc"] as IDictionary <string, object>;

                if (
                    doc_item ["status"] != null &&
                    doc_item ["status"].ToString().StartsWith("In Queue...", StringComparison.OrdinalIgnoreCase))
                {
                    export_queue_item item = new export_queue_item();

                    item._id               = doc_item ["_id"].ToString();
                    item._rev              = doc_item ["_rev"].ToString();
                    item._deleted          = doc_item.ContainsKey("_deleted") ? doc_item["_deleted"] as bool?: null;
                    item.date_created      = doc_item ["date_created"] as DateTime?;
                    item.created_by        = doc_item.ContainsKey("created_by") && doc_item ["created_by"] != null ? doc_item ["created_by"].ToString() : null;
                    item.date_last_updated = doc_item ["date_last_updated"] as DateTime?;
                    item.last_updated_by   = doc_item.ContainsKey("last_updated_by") && doc_item ["last_updated_by"] != null ? doc_item ["last_updated_by"].ToString() : null;
                    item.file_name         = doc_item ["file_name"] != null ? doc_item ["file_name"].ToString() : null;
                    item.export_type       = doc_item ["export_type"] != null ? doc_item ["export_type"].ToString() : null;
                    item.status            = doc_item ["status"] != null ? doc_item ["status"].ToString() : null;

                    result.Add(item);
                }
            }


            if (result.Count > 0)
            {
                if (result.Count > 1)
                {
                    var comparer = Comparer <export_queue_item> .Create
                                   (
                        (x, y) => x.date_created.Value.CompareTo(y.date_created.Value)
                                   );

                    result.Sort(comparer);
                }

                export_queue_item item_to_process = result [0];

                item_to_process.date_last_updated = new DateTime?();
                //item_to_process.last_updated_by = g_uid;


                List <string> args = new List <string>();
                args.Add("exporter:exporter");
                args.Add("user_name:" + this.user_name);
                args.Add("password:"******"database_url:" + this.couch_db_url);
                args.Add("item_file_name:" + item_to_process.file_name);
                args.Add("item_id:" + item_to_process._id);


                if (item_to_process.export_type.StartsWith("core csv", StringComparison.OrdinalIgnoreCase))
                {
                    item_to_process.status            = "Creating Export...";
                    item_to_process.last_updated_by   = "mmria-server";
                    item_to_process.date_last_updated = DateTime.Now;

                    Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
                    settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                    string object_string = Newtonsoft.Json.JsonConvert.SerializeObject(item_to_process, settings);
                    var    set_curl      = new cURL("PUT", null, Program.config_couchdb_url + "/export_queue/" + item_to_process._id, object_string, this.user_name, this.password);

                    responseFromServer = set_curl.execute();

                    try
                    {
                        mmria.server.model.actor.ScheduleInfoMessage scheduleInfo = new actor.ScheduleInfoMessage
                                                                                    (
                            Configuration["mmria_settings:cron_schedule"],
                            Configuration["mmria_settings:couchdb_url"],
                            Configuration["mmria_settings:timer_user_name"],
                            Configuration["mmria_settings:timer_password"],
                            Configuration["mmria_settings:export_directory"]
                                                                                    );

                        mmria.server.util.core_element_exporter core_element_exporter = new mmria.server.util.core_element_exporter(scheduleInfo);
                        core_element_exporter.Execute(args.ToArray());
                    }
                    catch (Exception ex)
                    {
                        System.Console.WriteLine(ex);
                    }
                }
                else if (item_to_process.export_type.StartsWith("all csv", StringComparison.OrdinalIgnoreCase))
                {
                    item_to_process.status            = "Creating Export...";
                    item_to_process.last_updated_by   = "mmria-server";
                    item_to_process.date_last_updated = DateTime.Now;

                    Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
                    settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                    string object_string = Newtonsoft.Json.JsonConvert.SerializeObject(item_to_process, settings);
                    var    set_curl      = new cURL("PUT", null, Program.config_couchdb_url + "/export_queue/" + item_to_process._id, object_string, this.user_name, this.password);

                    responseFromServer = set_curl.execute();


                    mmria.server.model.actor.ScheduleInfoMessage scheduleInfo = new actor.ScheduleInfoMessage
                                                                                (
                        Configuration["mmria_settings:cron_schedule"],
                        Configuration["mmria_settings:couchdb_url"],
                        Configuration["mmria_settings:timer_user_name"],
                        Configuration["mmria_settings:timer_password"],
                        Configuration["mmria_settings:export_directory"]
                                                                                );
                    try
                    {
                        mmria.server.util.mmrds_exporter mmrds_exporter = new mmria.server.util.mmrds_exporter(scheduleInfo);
                        mmrds_exporter.Execute(args.ToArray());
                    }
                    catch (Exception ex)
                    {
                        System.Console.WriteLine(ex);
                    }
                }
                else if (item_to_process.export_type.StartsWith("cdc csv", StringComparison.OrdinalIgnoreCase))
                {
                    item_to_process.status            = "Creating Export...";
                    item_to_process.last_updated_by   = "mmria-server";
                    item_to_process.date_last_updated = DateTime.Now;

                    Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
                    settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                    string object_string = Newtonsoft.Json.JsonConvert.SerializeObject(item_to_process, settings);
                    var    set_curl      = new cURL("PUT", null, Program.config_couchdb_url + "/export_queue/" + item_to_process._id, object_string, this.user_name, this.password);

                    responseFromServer = set_curl.execute();
                    args.Add("is_cdc_de_identified:true");

                    try
                    {
                        mmria.server.model.actor.ScheduleInfoMessage scheduleInfo = new actor.ScheduleInfoMessage
                                                                                    (
                            Configuration["mmria_settings:cron_schedule"],
                            Configuration["mmria_settings:couchdb_url"],
                            Configuration["mmria_settings:timer_user_name"],
                            Configuration["mmria_settings:timer_password"],
                            Configuration["mmria_settings:export_directory"]
                                                                                    );
                        mmria.server.util.mmrds_exporter mmrds_exporter = new mmria.server.util.mmrds_exporter(scheduleInfo);
                        mmrds_exporter.Execute(args.ToArray());
                    }
                    catch (Exception ex)
                    {
                        System.Console.WriteLine(ex);
                    }
                }
            }
        }
        protected override void OnReceive(object message)
        {
            Console.WriteLine($"Synchronize_Deleted_Case_Records Baby {System.DateTime.Now}");


            switch (message)
            {
            case ScheduleInfoMessage scheduleInfo:
                mmria.server.model.couchdb.c_change_result latest_change_set = GetJobInfo(Program.Last_Change_Sequence, scheduleInfo);

                Dictionary <string, KeyValuePair <string, bool> > response_results = new Dictionary <string, KeyValuePair <string, bool> > (StringComparer.OrdinalIgnoreCase);

                if (Program.Last_Change_Sequence != latest_change_set.last_seq)
                {
                    foreach (mmria.server.model.couchdb.c_seq seq in latest_change_set.results)
                    {
                        if (response_results.ContainsKey(seq.id))
                        {
                            if
                            (
                                seq.changes.Count > 0 &&
                                response_results [seq.id].Key != seq.changes [0].rev
                            )
                            {
                                if (seq.deleted == null)
                                {
                                    response_results [seq.id] = new KeyValuePair <string, bool> (seq.changes [0].rev, false);
                                }
                                else
                                {
                                    response_results [seq.id] = new KeyValuePair <string, bool> (seq.changes [0].rev, true);
                                }
                            }
                        }
                        else
                        {
                            if (seq.deleted == null)
                            {
                                response_results.Add(seq.id, new KeyValuePair <string, bool> (seq.changes [0].rev, false));
                            }
                            else
                            {
                                response_results.Add(seq.id, new KeyValuePair <string, bool> (seq.changes [0].rev, true));
                            }
                        }
                    }
                }


                if (Program.Change_Sequence_Call_Count < int.MaxValue)
                {
                    Program.Change_Sequence_Call_Count++;
                }

                if (Program.DateOfLastChange_Sequence_Call.Count > 9)
                {
                    Program.DateOfLastChange_Sequence_Call.Clear();
                }

                Program.DateOfLastChange_Sequence_Call.Add(DateTime.Now);

                Program.Last_Change_Sequence = latest_change_set.last_seq;

                foreach (KeyValuePair <string, KeyValuePair <string, bool> > kvp in response_results)
                {
                    System.Threading.Tasks.Task.Run
                    (
                        new Action(async() =>
                    {
                        if (kvp.Value.Value)
                        {
                            try
                            {
                                mmria.server.util.c_sync_document sync_document = new mmria.server.util.c_sync_document(kvp.Key, null, "DELETE");
                                await sync_document.executeAsync();
                            }
                            catch (Exception ex)
                            {
                                System.Console.WriteLine("Sync Delete case");
                                System.Console.WriteLine(ex);
                            }
                        }
                        else
                        {
                            string document_url  = Program.config_couchdb_url + "/mmrds/" + kvp.Key;
                            var document_curl    = new cURL("GET", null, document_url, null, Program.config_timer_user_name, Program.config_timer_password);
                            string document_json = null;

                            try
                            {
                                document_json = document_curl.execute();
                                if (!string.IsNullOrEmpty(document_json) && document_json.IndexOf("\"_id\":\"_design/") < 0)
                                {
                                    mmria.server.util.c_sync_document sync_document = new mmria.server.util.c_sync_document(kvp.Key, document_json);
                                    await sync_document.executeAsync();
                                }
                            }
                            catch (Exception ex)
                            {
                                System.Console.WriteLine("Sync PUT case");
                                System.Console.WriteLine(ex);
                            }
                        }
                    })
                    );
                }

                break;
            }
        }
        protected override void OnReceive(object message)
        {
            Console.WriteLine($"Process_DB_Synchronization_Set {System.DateTime.Now}");

            switch (message)
            {
            case ScheduleInfoMessage scheduleInfo:
                //System.Console.WriteLine ("{0} Beginning Change Synchronization.", System.DateTime.Now);
                //log.DebugFormat("iCIMS_Data_Call_Job says: Starting {0} executing at {1}", jobKey, DateTime.Now.ToString("r"));
                mmria.server.model.couchdb.c_change_result latest_change_set = get_changes(Program.Last_Change_Sequence, scheduleInfo);

                Dictionary <string, KeyValuePair <string, bool> > response_results = new Dictionary <string, KeyValuePair <string, bool> > (StringComparer.OrdinalIgnoreCase);

                if (Program.Last_Change_Sequence != latest_change_set.last_seq)
                {
                    foreach (mmria.server.model.couchdb.c_seq seq in latest_change_set.results)
                    {
                        if (response_results.ContainsKey(seq.id))
                        {
                            if (
                                seq.changes.Count > 0 &&
                                response_results [seq.id].Key != seq.changes [0].rev)
                            {
                                if (seq.deleted == null)
                                {
                                    response_results [seq.id] = new KeyValuePair <string, bool> (seq.changes [0].rev, false);
                                }
                                else
                                {
                                    response_results [seq.id] = new KeyValuePair <string, bool> (seq.changes [0].rev, true);
                                }
                            }
                        }
                        else
                        {
                            if (seq.deleted == null)
                            {
                                response_results.Add(seq.id, new KeyValuePair <string, bool> (seq.changes [0].rev, false));
                            }
                            else
                            {
                                response_results.Add(seq.id, new KeyValuePair <string, bool> (seq.changes [0].rev, true));
                            }
                        }
                    }
                }


                if (Program.Change_Sequence_Call_Count < int.MaxValue)
                {
                    Program.Change_Sequence_Call_Count++;
                }

                if (Program.DateOfLastChange_Sequence_Call.Count > 9)
                {
                    Program.DateOfLastChange_Sequence_Call.Clear();
                }

                Program.DateOfLastChange_Sequence_Call.Add(DateTime.Now);

                Program.Last_Change_Sequence = latest_change_set.last_seq;

                //List<System.Threading.Tasks.Task> TaskList = new List<System.Threading.Tasks.Task> ();

                foreach (KeyValuePair <string, KeyValuePair <string, bool> > kvp in response_results)
                {
                    System.Threading.Tasks.Task.Run
                    (
                        new Action(async() =>
                    {
                        if (kvp.Value.Value)
                        {
                            try
                            {
                                mmria.server.util.c_sync_document sync_document = new mmria.server.util.c_sync_document(kvp.Key, null, "DELETE");
                                await sync_document.executeAsync();
                            }
                            catch (Exception ex)
                            {
                                //System.Console.WriteLine ("Sync Delete case");
                                //System.Console.WriteLine (ex);
                            }
                        }
                        else
                        {
                            string document_url  = Program.config_couchdb_url + "/mmrds/" + kvp.Key;
                            var document_curl    = new cURL("GET", null, document_url, null, Program.config_timer_user_name, Program.config_timer_password);
                            string document_json = null;

                            try
                            {
                                document_json = await document_curl.executeAsync();
                                if (!string.IsNullOrEmpty(document_json) && document_json.IndexOf("\"_id\":\"_design/") < 0)
                                {
                                    mmria.server.util.c_sync_document sync_document = new mmria.server.util.c_sync_document(kvp.Key, document_json);
                                    await sync_document.executeAsync();
                                }
                            }
                            catch (Exception ex)
                            {
                                //System.Console.WriteLine ("Sync PUT case");
                                //System.Console.WriteLine (ex);
                            }
                        }
                    })
                    );
                }
                //System.Threading.Tasks.Task.WhenAll (TaskList);

                try
                {
                    HashSet <string> mmrds_id_set   = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    HashSet <string> de_id_set      = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    HashSet <string> report_id_set  = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    HashSet <string> deleted_id_set = null;

                    string json = null;
                    mmria.server.model.couchdb.c_all_docs all_docs = null;
                    cURL curl = null;

                    // get all non deleted cases in mmrds
                    curl     = new cURL("GET", null, Program.config_couchdb_url + "/mmrds/_all_docs", null, Program.config_timer_user_name, Program.config_timer_password);
                    json     = curl.execute();
                    all_docs = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.server.model.couchdb.c_all_docs> (json);
                    foreach (mmria.server.model.couchdb.c_all_docs_row all_doc_row in all_docs.rows)
                    {
                        mmrds_id_set.Add(all_doc_row.id);
                    }


                    // get all non deleted cases in de_id
                    curl     = new cURL("GET", null, Program.config_couchdb_url + "/de_id/_all_docs", null, Program.config_timer_user_name, Program.config_timer_password);
                    json     = curl.execute();
                    all_docs = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.server.model.couchdb.c_all_docs> (json);
                    foreach (mmria.server.model.couchdb.c_all_docs_row all_doc_row in all_docs.rows)
                    {
                        de_id_set.Add(all_doc_row.id);
                    }

                    deleted_id_set = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    deleted_id_set.Union(de_id_set.Except(mmrds_id_set));
                    foreach (string id in deleted_id_set)
                    {
                        string rev = all_docs.rows.Where(r => r.id == id).FirstOrDefault().rev.rev;
                        curl = new cURL("DELETE", null, Program.config_couchdb_url + "/de_id/" + id + "?rev=" + rev, null, Program.config_timer_user_name, Program.config_timer_password);
                        json = curl.execute();
                    }

                    // get all non deleted cases in report
                    curl     = new cURL("GET", null, Program.config_couchdb_url + "/report/_all_docs", null, Program.config_timer_user_name, Program.config_timer_password);
                    json     = curl.execute();
                    all_docs = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.server.model.couchdb.c_all_docs> (json);
                    foreach (mmria.server.model.couchdb.c_all_docs_row all_doc_row in all_docs.rows)
                    {
                        report_id_set.Add(all_doc_row.id);
                    }
                    deleted_id_set = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    deleted_id_set.Union(report_id_set.Except(mmrds_id_set));
                    foreach (string id in deleted_id_set)
                    {
                        string rev = all_docs.rows.Where(r => r.id == id).FirstOrDefault().rev.rev;
                        curl = new cURL("DELETE", null, Program.config_couchdb_url + "/report/" + id + "?rev=" + rev, null, Program.config_timer_user_name, Program.config_timer_password);
                        json = curl.execute();
                    }
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine("Delete sync error:\n{0}", ex);
                }

                //System.Console.WriteLine ("{0}- Ending Change Synchronization.", System.DateTime.Now);
                break;
            }
        }
Example #25
0
        public void execute()
        {
            try
            {
                var delete_de_id_curl = new cURL("DELETE", null, this.couchdb_url + "/de_id", null, this.user_name, this.password);
                delete_de_id_curl.execute();
            }
            catch (Exception ex)
            {
            }


            try
            {
                var delete_report_curl = new cURL("DELETE", null, this.couchdb_url + "/report", null, this.user_name, this.password);
                delete_report_curl.execute();
            }
            catch (Exception ex)
            {
            }



            try
            {
                var create_de_id_curl = new cURL("PUT", null, this.couchdb_url + "/de_id", null, this.user_name, this.password);
                create_de_id_curl.execute();
            }
            catch (Exception ex)
            {
            }



            try
            {
                string result            = System.IO.File.OpenText(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "database-scripts/case_design_sortable.json")).ReadToEnd();
                var    create_de_id_curl = new cURL("PUT", null, this.couchdb_url + "/de_id/_design/sortable", result, this.user_name, this.password);
                create_de_id_curl.execute();
            }
            catch (Exception ex)
            {
            }



            try
            {
                var create_report_curl = new cURL("PUT", null, this.couchdb_url + "/report", null, this.user_name, this.password);
                create_report_curl.execute();
            }
            catch (Exception ex)
            {
            }



            var    curl = new cURL("GET", null, this.couchdb_url + "/mmrds/_all_docs?include_docs=true", null, this.user_name, this.password);
            string res  = curl.execute();

/*
 * {
 * "total_rows": 3, "offset": 0, "rows": [
 *  {"id": "doc1", "key": "doc1", "value": {"rev": "4324BB"}},
 *  {"id": "doc2", "key": "doc2", "value": {"rev":"2441HF"}},
 *  {"id": "doc3", "key": "doc3", "value": {"rev":"74EC24"}}
 * ]
 * }
 */
            System.Dynamic.ExpandoObject all_docs = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject> (res);
            try
            {
                IDictionary <string, object> all_docs_dictionary = all_docs as IDictionary <string, object>;
                List <object> row_list = all_docs_dictionary ["rows"] as List <object>;
                foreach (object row_item in row_list)
                {
                    try
                    {
                        IDictionary <string, object> row_dictionary = row_item as IDictionary <string, object>;
                        IDictionary <string, object> doc_dictionary = row_dictionary ["doc"] as IDictionary <string, object>;
                        string document_id = doc_dictionary ["_id"].ToString();
                        if (document_id.IndexOf("_design/") < 0)
                        {
                            string document_json = Newtonsoft.Json.JsonConvert.SerializeObject(doc_dictionary);
                            mmria.server.util.c_sync_document sync_document = new c_sync_document(document_id, document_json);
                            sync_document.execute();
                        }
                    }
                    catch (Exception document_ex)
                    {
                        System.Console.Write($"error running c_docment_sync_all.document\n{document_ex}");
                    }
                }
            }
            catch (Exception ex)
            {
                System.Console.Write($"error running c_docment_sync_all\n{ex}");
            }
        }
Example #26
0
        public virtual Task Execute(IJobExecutionContext context)
        {
            //Common.Logging.ILog log = Common.Logging.LogManager.GetCurrentClassLogger();
            //log.Debug("IJob.Execute");

            JobKey jobKey = context.JobDetail.Key;


            //if (!Program.is_processing_export_queue)
            {
                System.Threading.Tasks.Task.Run
                (
                    new Action(() =>
                {
                    //System.Console.WriteLine ("{0} Beginning Export Queue Item Processing", System.DateTime.Now);
                    try
                    {
                        Process_Export_Queue_Item();
                    }
                    catch (Exception ex)
                    {
                        // to nothing for now
                        System.Console.WriteLine("{0} check_for_changes_job.Process_Export_Queue_Item: error\n{1}", System.DateTime.Now, ex);
                    }

                    try
                    {
                        Process_Export_Queue_Delete();
                    }
                    catch (Exception ex)
                    {
                        // to nothing for now
                        System.Console.WriteLine("{0} check_for_changes_job.Process_Export_Queue_Delete: error\n{1}", System.DateTime.Now, ex);
                    }

                    //System.Console.WriteLine ("{0} Ending Export Queue Item Processing", System.DateTime.Now);
                })
                );
            }


            //if (!Program.is_processing_syncronization)
            {
                //System.Console.WriteLine ("{0} Beginning Change Synchronization.", System.DateTime.Now);
                //log.DebugFormat("iCIMS_Data_Call_Job says: Starting {0} executing at {1}", jobKey, DateTime.Now.ToString("r"));
                mmria.server.model.couchdb.c_change_result latest_change_set = get_changes(Program.Last_Change_Sequence);

                Dictionary <string, KeyValuePair <string, bool> > response_results = new Dictionary <string, KeyValuePair <string, bool> > (StringComparer.OrdinalIgnoreCase);

                if (Program.Last_Change_Sequence != latest_change_set.last_seq)
                {
                    foreach (mmria.server.model.couchdb.c_seq seq in latest_change_set.results)
                    {
                        if (response_results.ContainsKey(seq.id))
                        {
                            if (
                                seq.changes.Count > 0 &&
                                response_results [seq.id].Key != seq.changes [0].rev)
                            {
                                if (seq.deleted == null)
                                {
                                    response_results [seq.id] = new KeyValuePair <string, bool> (seq.changes [0].rev, false);
                                }
                                else
                                {
                                    response_results [seq.id] = new KeyValuePair <string, bool> (seq.changes [0].rev, true);
                                }
                            }
                        }
                        else
                        {
                            if (seq.deleted == null)
                            {
                                response_results.Add(seq.id, new KeyValuePair <string, bool> (seq.changes [0].rev, false));
                            }
                            else
                            {
                                response_results.Add(seq.id, new KeyValuePair <string, bool> (seq.changes [0].rev, true));
                            }
                        }
                    }
                }


                if (Program.Change_Sequence_Call_Count < int.MaxValue)
                {
                    Program.Change_Sequence_Call_Count++;
                }

                if (Program.DateOfLastChange_Sequence_Call.Count > 9)
                {
                    Program.DateOfLastChange_Sequence_Call.Clear();
                }

                Program.DateOfLastChange_Sequence_Call.Add(DateTime.Now);

                Program.Last_Change_Sequence = latest_change_set.last_seq;

                //List<System.Threading.Tasks.Task> TaskList = new List<System.Threading.Tasks.Task> ();

                foreach (KeyValuePair <string, KeyValuePair <string, bool> > kvp in response_results)
                {
                    System.Threading.Tasks.Task.Run
                    (
                        new Action(async() =>
                    {
                        if (kvp.Value.Value)
                        {
                            try
                            {
                                mmria.server.util.c_sync_document sync_document = new mmria.server.util.c_sync_document(kvp.Key, null, "DELETE");
                                await sync_document.executeAsync();
                            }
                            catch (Exception ex)
                            {
                                //System.Console.WriteLine ("Sync Delete case");
                                //System.Console.WriteLine (ex);
                            }
                        }
                        else
                        {
                            string document_url  = Program.config_couchdb_url + "/mmrds/" + kvp.Key;
                            var document_curl    = new cURL("GET", null, document_url, null, Program.config_timer_user_name, Program.config_timer_password);
                            string document_json = null;

                            try
                            {
                                document_json = await document_curl.executeAsync();
                                if (!string.IsNullOrEmpty(document_json) && document_json.IndexOf("\"_id\":\"_design/") < 0)
                                {
                                    mmria.server.util.c_sync_document sync_document = new mmria.server.util.c_sync_document(kvp.Key, document_json);
                                    await sync_document.executeAsync();
                                }
                            }
                            catch (Exception ex)
                            {
                                //System.Console.WriteLine ("Sync PUT case");
                                //System.Console.WriteLine (ex);
                            }
                        }
                    })
                    );
                }
                //System.Threading.Tasks.Task.WhenAll (TaskList);

                try
                {
                    HashSet <string> mmrds_id_set   = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    HashSet <string> de_id_set      = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    HashSet <string> report_id_set  = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    HashSet <string> deleted_id_set = null;

                    string json = null;
                    mmria.server.model.couchdb.c_all_docs all_docs = null;
                    cURL curl = null;

                    // get all non deleted cases in mmrds
                    curl     = new cURL("GET", null, Program.config_couchdb_url + "/mmrds/_all_docs", null, Program.config_timer_user_name, Program.config_timer_password);
                    json     = curl.execute();
                    all_docs = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.server.model.couchdb.c_all_docs> (json);
                    foreach (mmria.server.model.couchdb.c_all_docs_row all_doc_row in all_docs.rows)
                    {
                        mmrds_id_set.Add(all_doc_row.id);
                    }


                    // get all non deleted cases in de_id
                    curl     = new cURL("GET", null, Program.config_couchdb_url + "/de_id/_all_docs", null, Program.config_timer_user_name, Program.config_timer_password);
                    json     = curl.execute();
                    all_docs = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.server.model.couchdb.c_all_docs> (json);
                    foreach (mmria.server.model.couchdb.c_all_docs_row all_doc_row in all_docs.rows)
                    {
                        de_id_set.Add(all_doc_row.id);
                    }

                    deleted_id_set = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    deleted_id_set.Union(de_id_set.Except(mmrds_id_set));
                    foreach (string id in deleted_id_set)
                    {
                        string rev = all_docs.rows.Where(r => r.id == id).FirstOrDefault().rev.rev;
                        curl = new cURL("DELETE", null, Program.config_couchdb_url + "/de_id/" + id + "?rev=" + rev, null, Program.config_timer_user_name, Program.config_timer_password);
                        json = curl.execute();
                    }

                    // get all non deleted cases in report
                    curl     = new cURL("GET", null, Program.config_couchdb_url + "/report/_all_docs", null, Program.config_timer_user_name, Program.config_timer_password);
                    json     = curl.execute();
                    all_docs = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.server.model.couchdb.c_all_docs> (json);
                    foreach (mmria.server.model.couchdb.c_all_docs_row all_doc_row in all_docs.rows)
                    {
                        report_id_set.Add(all_doc_row.id);
                    }
                    deleted_id_set = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
                    deleted_id_set.Union(report_id_set.Except(mmrds_id_set));
                    foreach (string id in deleted_id_set)
                    {
                        string rev = all_docs.rows.Where(r => r.id == id).FirstOrDefault().rev.rev;
                        curl = new cURL("DELETE", null, Program.config_couchdb_url + "/report/" + id + "?rev=" + rev, null, Program.config_timer_user_name, Program.config_timer_password);
                        json = curl.execute();
                    }
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine("Delete sync error:\n{0}", ex);
                }

                //System.Console.WriteLine ("{0}- Ending Change Synchronization.", System.DateTime.Now);
            }

            return(Task.CompletedTask);
        }
Example #27
0
        public void Execute(string[] args)
        {
            string import_directory = System.Configuration.ConfigurationManager.AppSettings["import_directory"];

            this.is_offline_mode = bool.Parse(System.Configuration.ConfigurationManager.AppSettings["is_offline_mode"]);

            if (!System.IO.Directory.Exists(import_directory))
            {
                System.IO.Directory.CreateDirectory(import_directory);
            }


            if (args.Length > 1)
            {
                for (var i = 1; i < args.Length; i++)
                {
                    string arg   = args[i];
                    int    index = arg.IndexOf(':');
                    string val   = arg.Substring(index + 1, arg.Length - (index + 1)).Trim(new char[] { '\"' });

                    if (arg.ToLower().StartsWith("auth_token"))
                    {
                        this.auth_token = val;
                    }
                    else if (arg.ToLower().StartsWith("user_name"))
                    {
                        this.user_name = val;
                    }
                    else if (arg.ToLower().StartsWith("password"))
                    {
                        this.password = val;
                    }
                    else if (arg.ToLower().StartsWith("database_file_path"))
                    {
                        this.database_path = val;
                    }
                    else if (arg.ToLower().StartsWith("url"))
                    {
                        this.mmria_url = val;
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(this.database_path))
            {
                System.Console.WriteLine("missing database_path");
                System.Console.WriteLine(" form database:[file path]");
                System.Console.WriteLine(" example 1 database_file_path:c:\\temp\\maternal_mortality.mdb");
                System.Console.WriteLine(" example 2 database_file_path:\"c:\\temp folder\\maternal_mortality.mdb\"");
                System.Console.WriteLine(" example 3 database_file_path:mapping-file-set\\maternal_mortality.mdb\"");
                System.Console.WriteLine(" mmria.exe import user_name:user1 password:secret url:http://localhost:12345 database_file_path:\"c:\\temp folder\\maternal_mortality.mdb\"");

                return;
            }

            if (string.IsNullOrWhiteSpace(this.mmria_url))
            {
                this.mmria_url = System.Configuration.ConfigurationManager.AppSettings["web_site_url"];


                if (string.IsNullOrWhiteSpace(this.mmria_url))
                {
                    System.Console.WriteLine("missing url");
                    System.Console.WriteLine(" form url:[website_url]");
                    System.Console.WriteLine(" example url:http://localhost:12345");

                    return;
                }
            }

            if (string.IsNullOrWhiteSpace(this.user_name))
            {
                System.Console.WriteLine("missing user_name");
                System.Console.WriteLine(" form user_name:[user_name]");
                System.Console.WriteLine(" example user_name:user1");
                return;
            }

            if (string.IsNullOrWhiteSpace(this.password))
            {
                System.Console.WriteLine("missing password");
                System.Console.WriteLine(" form password:[password]");
                System.Console.WriteLine(" example password:secret");
                return;
            }

            var mmria_server = new mmria_server_api_client(this.mmria_url);

            mmria_server.login(this.user_name, this.password);

            mmria.common.metadata.app metadata = mmria_server.get_metadata();

            var mmrds_data = new cData(get_mdb_connection_string(this.database_path));

            var directory_path         = @"mapping-file-set";
            var main_mapping_file_name = @"MMRDS-Mapping-NO-GRIDS-test.csv";
            var mapping_data           = new cData(get_csv_connection_string(directory_path));

            var grid_mapping_file_name = @"grid-mapping-merge.csv";


            var lookup_mapping_file_name = @"MMRDS-Mapping-NO-GRIDS-lookup-values.csv";
            var lookup_mapping_table     = get_look_up_mappings(mapping_data, lookup_mapping_file_name);


            System.Collections.Generic.Dictionary <string, Dictionary <string, string> > lookup_value1 = new Dictionary <string, Dictionary <string, string> >(StringComparer.InvariantCultureIgnoreCase);
            System.Collections.Generic.Dictionary <string, Dictionary <string, string> > lookup_value2 = new Dictionary <string, Dictionary <string, string> >(StringComparer.InvariantCultureIgnoreCase);


            var case_maker = new Case_Maker(import_directory, lookup_value1, lookup_value2);

            foreach (System.Data.DataRow row in lookup_mapping_table.Rows)
            {
                //mmria_path value1  value2 mmria_value
                //string mmria_path = row["mmria_path"].ToString().Trim();
                string mmria_path  = row["source_path"].ToString().Trim() + "|" + row["mmria_path"].ToString().Trim();
                string value1      = null;
                string value2      = null;
                string mmria_value = null;

                /*
                 * if (
                 *      //row["mmria_path"].ToString().Trim() == "home_record/state_of_death_record" ||
                 *      //row["source_path"].ToString().Trim() == "MaternalMortality1.MM_MBC" ||
                 *      //row["mmria_path"].ToString ().IndexOf("other significant") > -1 &&
                 *      //	row ["value1"] != DBNull.Value &&
                 *              row ["value1"].ToString ().IndexOf ("ther significant") > -1
                 * )
                 * {
                 *      System.Console.Write ("break");
                 *
                 * }*/

                if (row["value1"] != DBNull.Value)
                {
                    value1 = System.Text.RegularExpressions.Regex.Replace(row ["value1"].ToString().Trim(), @"[^\u0000-\u007F]+", string.Empty);
                }

                if (row["value2"] != DBNull.Value)
                {
                    value2 = System.Text.RegularExpressions.Regex.Replace(row["value2"].ToString().Trim(), @"[^\u0000-\u007F]+", string.Empty);
                }

                if (row["mmria_value"] != DBNull.Value)
                {
                    if (row["mmria_value"].ToString() == "(blank)")
                    {
                        mmria_value = "";
                    }
                    else
                    {
                        mmria_value = row["mmria_value"].ToString().Trim();
                    }
                }

                if (value1 == null && mmria_value != null && mmria_value == "")
                {
                    value1 = "";
                }


                if (value2 == null && mmria_value != null && mmria_value == "")
                {
                    value2 = "";
                }

                if (!lookup_value1.ContainsKey(mmria_path))
                {
                    lookup_value1[mmria_path] = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);
                }

                if (!lookup_value2.ContainsKey(mmria_path))
                {
                    lookup_value2[mmria_path] = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);
                }

                if (mmria_value != null && value1 != null && !lookup_value1[mmria_path].ContainsKey(value1))
                {
                    lookup_value1[mmria_path].Add(value1, mmria_value);
                }
                else if (mmria_value != null && value1 != null && mmria_value != "" && value1 != "")
                {
                    case_maker.add_bad_mapping(string.Format("duplicate lookup: {0} - {1}", mmria_path, value1));
                }

                if (mmria_value != null && value2 != null && !lookup_value2[mmria_path].ContainsKey(value2))
                {
                    lookup_value2[mmria_path].Add(value2, mmria_value);
                }
                else if (mmria_value != null && value2 != null && mmria_value != "" && value2 != "")
                {
                    case_maker.add_bad_mapping(string.Format("duplicate lookup: {0} - {1}", mmria_path, value2));
                }
            }


            var case_data_list = new List <dynamic>();


            var view_name_list = new string[] {
                "MaternalMortality",
                "DeathCertificate",
                "MaternalBirthCertificate",
                "ChildBirthCertificate",
                "AutopsyReport",
                "PrenatalCareRecord",
                "SocialServicesRecord",
                "Hospitalization",
                "OfficeVisits",
                "CommitteeReview",
                "Interviews"
            };


            var view_name_to_name_map = new Dictionary <string, string> {
                { "MaternalMortality", "home_record" },
                { "DeathCertificate", "death_certificate" },
                { "MaternalBirthCertificate", "birth_fetal_death_certificate_parent" },
                { "ChildBirthCertificate", "birth_certificate_infant_fetal_section" },
                { "AutopsyReport", "autopsy_report" },
                { "PrenatalCareRecord", "prenatal" },
                { "SocialServicesRecord", "social_and_environmental_profile" },
                { "Hospitalization", "er_visit_and_hospital_medical_records" },
                { "OfficeVisits", "other_medical_office_visits" },
                { "CommitteeReview", "committe_review" },
                { "Interviews", "informant_interviews" }
            };

            var view_name_cardinality_map = new Dictionary <string, bool> {
                { "MaternalMortality", false },
                { "DeathCertificate", false },
                { "MaternalBirthCertificate", false },
                { "ChildBirthCertificate", true },
                { "AutopsyReport", false },
                { "PrenatalCareRecord", false },
                { "SocialServicesRecord", false },
                { "Hospitalization", true },
                { "OfficeVisits", true },
                { "CommitteeReview", false },
                { "Interviews", true }
            };

            var           id_record_set = mmrds_data.GetDataTable("Select Distinct GlobalRecordId From MaternalMortality");
            string        json_string   = null;
            List <string> id_list       = new List <string>();

            foreach (System.Data.DataRow row in id_record_set.Rows)
            {
                /*
                 * if
                 * (
                 *      row[0].ToString() != "d0e08da8-d306-4a9a-a5ff-9f1d54702091" &&
                 *      row[0].ToString() != "244da20f-41cc-4300-ad94-618004a51917" &&
                 *      row[0].ToString() != "e98ce2be-4446-439a-bb63-d9b4e690e3c3" &&
                 *      row[0].ToString() != "b5003bc5-1ab3-4ba2-8aea-9f3717c9682a"
                 * )
                 * {
                 *      continue;
                 * }*/


                id_list.Add(row[0].ToString());
            }

            foreach (string global_record_id in id_list)
            {
                dynamic case_data = case_maker.create_default_object(metadata, new Dictionary <string, object>());

                json_string = Newtonsoft.Json.JsonConvert.SerializeObject(case_data, new Newtonsoft.Json.JsonSerializerSettings()
                {
                    Formatting           = Newtonsoft.Json.Formatting.Indented,
                    DateFormatHandling   = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
                    DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc
                });
                System.Console.WriteLine("json\n{0}", json_string);

                foreach (string view_name in view_name_list)
                {
                    System.Data.DataRow[] view_record_data = null;
                    System.Data.DataRow[] grid_record_data = null;
                    System.Data.DataTable view_data_table  = get_view_data_table(mmrds_data, view_name);

                    var mapping_view_table = get_view_mapping(mapping_data, view_name, main_mapping_file_name);

                    var grid_table_name_list = get_grid_table_name_list(mapping_data, view_name, grid_mapping_file_name);

                    if (view_name == "MaternalMortality")
                    {
                        view_record_data = view_data_table.Select(string.Format("MaternalMortality.GlobalRecordId='{0}'", global_record_id));

                        IDictionary <string, object> updater = case_data as IDictionary <string, object>;
                        updater["_id"]               = global_record_id;
                        updater["date_created"]      = view_record_data[0]["FirstSaveTime"] != DBNull.Value ? ((DateTime)view_record_data[0]["FirstSaveTime"]).ToString("s") + "Z" : null;
                        updater["created_by"]        = view_record_data[0]["FirstSaveLogonName"];
                        updater["date_last_updated"] = view_record_data[0]["LastSaveTime"] != DBNull.Value ? ((DateTime)view_record_data[0]["LastSaveTime"]).ToString("s") + "Z" : null;
                        updater["last_updated_by"]   = view_record_data[0]["LastSaveLogonName"];
                    }
                    else
                    {
                        view_record_data = view_data_table.Select(string.Format("FKEY='{0}'", global_record_id));
                    }


                    if (view_record_data.Length > 1)
                    {
                        System.Console.WriteLine("multi rows: {0}\t{1}", view_name, view_record_data.Length);
                    }
                    //mmria.common.metadata.node form_metadata = metadata.children.Where(c => c.type == "form" && c.name == view_name_to_name_map[view_name]).First();
                    if (view_name_cardinality_map[view_name] == true)
                    {
                        for (int i = 0; i < view_record_data.Length; i++)
                        {
                            System.Data.DataRow row = view_record_data[i];

                            process_view
                            (
                                metadata,
                                case_maker,
                                case_data,
                                row,
                                mapping_view_table,
                                i
                            );

                            int column_index = -1;
                            for (int column_index_i = 0; column_index_i < view_data_table.Columns.Count; column_index_i++)
                            {
                                if (view_data_table.Columns[column_index_i].ColumnName.ToLower() == (view_name + ".globalrecordid").ToLower())
                                {
                                    column_index = column_index_i;
                                }
                            }

                            foreach (string grid_name in grid_table_name_list)
                            {
                                System.Data.DataTable grid_data = mmrds_data.GetDataTable(string.Format("Select * From [{0}] Where FKey='{1}'", grid_name, row[column_index]));
                                var grid_mapping = get_grid_mapping(mapping_data, grid_name, grid_mapping_file_name);

                                if (grid_data.Rows.Count > 0)
                                {
                                }

                                for (int grid_row_index = 0; grid_row_index < grid_data.Rows.Count; grid_row_index++)
                                {
                                    System.Data.DataRow grid_row = grid_data.Rows[grid_row_index];

                                    process_grid
                                    (
                                        metadata,
                                        case_maker,
                                        case_data,
                                        grid_row,
                                        grid_mapping,
                                        i,
                                        grid_row_index
                                    );
                                }
                            }
                        }
                    }
                    else
                    {
                        foreach (System.Data.DataRow row in view_record_data)
                        {
                            process_view
                            (
                                metadata,
                                case_maker,
                                case_data,
                                row,
                                mapping_view_table
                            );


                            int column_index = -1;
                            for (int column_index_i = 0; column_index_i < view_data_table.Columns.Count; column_index_i++)
                            {
                                if (view_data_table.Columns[column_index_i].ColumnName.ToLower() == (view_name + ".globalrecordid").ToLower())
                                {
                                    column_index = column_index_i;
                                }
                            }

                            foreach (string grid_name in grid_table_name_list)
                            {
                                System.Data.DataTable grid_data = null;
                                int check_index = grid_name.IndexOf("/");
                                if (check_index > 0)
                                {
                                    grid_data = mmrds_data.GetDataTable(string.Format("Select * From [{0}] Where FKey='{1}'", grid_name.Substring(0, check_index), row[column_index]));
                                }
                                else
                                {
                                    grid_data = mmrds_data.GetDataTable(string.Format("Select * From [{0}] Where FKey='{1}'", grid_name, row[column_index]));
                                }

                                var grid_mapping = get_grid_mapping(mapping_data, grid_name, grid_mapping_file_name);

                                if (grid_data.Rows.Count > 0)
                                {
                                }

                                if (check_index > 0)
                                {
                                    int grid_row_index = int.Parse(grid_name.Substring(check_index + 1, grid_name.Length - (check_index + 1)));
                                    if (grid_data.Rows.Count > grid_row_index)
                                    {
                                        process_grid
                                        (
                                            metadata,
                                            case_maker,
                                            case_data,
                                            grid_data.Rows[grid_row_index],
                                            grid_mapping,
                                            null,
                                            null
                                        );
                                    }
                                }
                                else
                                {
                                    for (int grid_row_index = 0; grid_row_index < grid_data.Rows.Count; grid_row_index++)
                                    {
                                        System.Data.DataRow grid_row = grid_data.Rows[grid_row_index];

                                        process_grid
                                        (
                                            metadata,
                                            case_maker,
                                            case_data,
                                            grid_row,
                                            grid_mapping,
                                            null,
                                            grid_row_index
                                        );
                                    }
                                }
                            }
                        }
                    }
                }



                /*
                 * if (case_data_list.Count == 0)
                 * {
                 *      var result = mmria_server.set_case(json_string);
                 * }
                 */
                try
                {
                    // check if doc exists
                    string document_url  = System.Configuration.ConfigurationManager.AppSettings["couchdb_url"] + "/mmrds/" + global_record_id;
                    var    document_curl = new cURL("GET", null, document_url, null, this.user_name, this.password);
                    string document_json = null;

                    document_json = document_curl.execute();
                    var result = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Dynamic.ExpandoObject>(document_json);
                    IDictionary <string, object> updater           = case_data as IDictionary <string, object>;
                    IDictionary <string, object> result_dictionary = result as IDictionary <string, object>;
                    if (result_dictionary.ContainsKey("_rev"))
                    {
                        updater ["_rev"] = result_dictionary ["_rev"];


                        json_string = Newtonsoft.Json.JsonConvert.SerializeObject(case_data, new Newtonsoft.Json.JsonSerializerSettings()
                        {
                            Formatting           = Newtonsoft.Json.Formatting.Indented,
                            DateFormatHandling   = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
                            DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc
                        });
                        System.Console.WriteLine("json\n{0}", json_string);
                    }


                    IDictionary <string, object> home_record = result_dictionary["home_record"] as IDictionary <string, object>;

                    if (home_record.ContainsKey("jurisdiction_id"))
                    {
                        home_record["jurisdiction_id"] = "/";
                    }
                    else
                    {
                        home_record.Add("jurisdiction_id", "/");
                    }

                    var update_curl = new cURL("PUT", null, document_url, json_string, this.user_name, this.password);
                    try
                    {
                        string de_id_result = update_curl.execute();
                        System.Console.WriteLine("update id");
                        System.Console.WriteLine(de_id_result);
                    }
                    catch (Exception ex)
                    {
                        System.Console.WriteLine("sync de_id");
                        System.Console.WriteLine(ex);
                    }
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine("Get case");
                    System.Console.WriteLine(ex);

                    IDictionary <string, object> home_record = case_data["home_record"] as IDictionary <string, object>;

                    if (home_record.ContainsKey("jurisdiction_id"))
                    {
                        home_record["jurisdiction_id"] = "/";
                    }
                    else
                    {
                        home_record.Add("jurisdiction_id", "/");
                    }


                    json_string = Newtonsoft.Json.JsonConvert.SerializeObject(case_data, new Newtonsoft.Json.JsonSerializerSettings()
                    {
                        Formatting           = Newtonsoft.Json.Formatting.Indented,
                        DateFormatHandling   = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
                        DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc
                    });

                    string document_url = System.Configuration.ConfigurationManager.AppSettings["couchdb_url"] + "/mmrds/" + global_record_id;
                    var    update_curl  = new cURL("PUT", null, document_url, json_string, this.user_name, this.password);
                    try
                    {
                        string de_id_result = update_curl.execute();
                        System.Console.WriteLine("update id");
                        System.Console.WriteLine(de_id_result);
                    }
                    catch (Exception ex2)
                    {
                        System.Console.WriteLine("sync de_id");
                        System.Console.WriteLine(ex2);
                    }
                    System.Console.WriteLine("json\n{0}", json_string);
                }



                //return;
                System.IO.File.WriteAllText(import_directory + "/" + global_record_id + ".json", json_string);

                //break;
                case_data_list.Add(case_data);
            }
            case_maker.flush_bad_mapping();

            Console.WriteLine("Hello World!");

            System.IO.File.WriteAllText(import_directory + "/output.json", json_string);
        }
Example #28
0
        public async Task Setup()
        {
            string current_directory = AppContext.BaseDirectory;

            if (!System.IO.Directory.Exists(System.IO.Path.Combine(current_directory, "database-scripts")))
            {
                current_directory = System.IO.Directory.GetCurrentDirectory();
            }

            bool is_able_to_connect = false;

            try
            {
                if (await url_endpoint_exists(Program.config_couchdb_url, Program.config_timer_user_name, Program.config_timer_password, "GET"))
                {
                    is_able_to_connect = true;
                }
            }
            catch (Exception ex)
            {
            }

            if (!is_able_to_connect)
            {
                Log.Information("Starup pausing for 1 minute to give database a chance to start");
                int milliseconds_in_second = 1000;
                int number_of_seconds      = 60;
                int total_milliseconds     = number_of_seconds * milliseconds_in_second;

                System.Threading.Thread.Sleep(total_milliseconds);/**/
            }

            Log.Information("Starup/Install Check - start");
            if
            (
                await url_endpoint_exists(Program.config_couchdb_url, null, null, "GET") &&
                !Program.config_timer_user_name.Equals("couchdb_admin_user_name", StringComparison.OrdinalIgnoreCase) &&
                !Program.config_timer_password.Equals("couchdb_admin_password", StringComparison.OrdinalIgnoreCase) &&
                !await url_endpoint_exists(Program.config_couchdb_url, Program.config_timer_user_name, Program.config_timer_password, "GET")
            )
            {
                try
                {
                    await new cURL("PUT", null, Program.config_couchdb_url + $"/_node/nonode@nohost/_config/admins/{Program.config_timer_user_name}", $"\"{Program.config_timer_password}\"", null, null).executeAsync();

                    //await new cURL ("PUT", null, Program.config_couchdb_url + "/_node/nonode@nohost/_config/mmria_section/app_version", $"\"{Program.config_app_version}\"", Program.config_timer_user_name, Program.config_timer_password).executeAsync();


                    await new cURL("PUT", null, Program.config_couchdb_url + "/_node/nonode@nohost/_config/couch_httpd_auth/allow_persistent_cookies", $"\"true\"", Program.config_timer_user_name, Program.config_timer_password).executeAsync();


                    await new cURL("PUT", null, Program.config_couchdb_url + "/_node/nonode@nohost/_config/chttpd/bind_address", $"\"0.0.0.0\"", Program.config_timer_user_name, Program.config_timer_password).executeAsync();
                    await new cURL("PUT", null, Program.config_couchdb_url + "/_node/nonode@nohost/_config/chttpd/port", $"\"5984\"", Program.config_timer_user_name, Program.config_timer_password).executeAsync();


                    await new cURL("PUT", null, Program.config_couchdb_url + "/_node/nonode@nohost/_config/httpd/enable_cors", $"\"true\"", Program.config_timer_user_name, Program.config_timer_password).executeAsync();


                    await new cURL("PUT", null, Program.config_couchdb_url + "/_node/nonode@nohost/_config/cors/origins", $"\"*\"", Program.config_timer_user_name, Program.config_timer_password).executeAsync();

                    await new cURL("PUT", null, Program.config_couchdb_url + "/_node/nonode@nohost/_config/cors/credentials", $"\"true\"", Program.config_timer_user_name, Program.config_timer_password).executeAsync();

                    await new cURL("PUT", null, Program.config_couchdb_url + "/_node/nonode@nohost/_config/cors/headers", $"\"accept, authorization, content-type, origin, referer, cache-control, x-requested-with\"", Program.config_timer_user_name, Program.config_timer_password).executeAsync();

                    await new cURL("PUT", null, Program.config_couchdb_url + "/_node/nonode@nohost/_config/cors/methods", $"\"GET, PUT, POST, HEAD, DELETE\"", Program.config_timer_user_name, Program.config_timer_password).executeAsync();

                    await new cURL("PUT", null, Program.config_couchdb_url + "/_users", null, Program.config_timer_user_name, Program.config_timer_password).executeAsync();
                    await new cURL("PUT", null, Program.config_couchdb_url + "/_replicator", null, Program.config_timer_user_name, Program.config_timer_password).executeAsync();
                    await new cURL("PUT", null, Program.config_couchdb_url + "/_global_changes", null, Program.config_timer_user_name, Program.config_timer_password).executeAsync();
                }
                catch (Exception ex)
                {
                    Log.Information($"Failed configuration \n{ex}");
                }
            }
            Log.Information("Starup/Install Check - end");


            if (

                await url_endpoint_exists(Program.config_couchdb_url, Program.config_timer_user_name, Program.config_timer_password, "GET")  //&&
                //Verify_Password (Program.config_couchdb_url, Program.config_timer_user_name, Program.config_timer_password)
                )
            {
                Log.Information("DB Repair Check - start");

                await c_db_setup.UpdateMetadata(current_directory);

                await c_db_setup.UpdateJurisdiction(current_directory);

                if (!await url_endpoint_exists(Program.config_couchdb_url + "/mmrds", Program.config_timer_user_name, Program.config_timer_password))
                {
                    var mmrds_curl = new cURL("PUT", null, Program.config_couchdb_url + "/mmrds", null, Program.config_timer_user_name, Program.config_timer_password);
                    Log.Information("mmrds_curl\n{0}", await mmrds_curl.executeAsync());

                    await new cURL("PUT", null, Program.config_couchdb_url + "/mmrds/_security", "{\"admins\":{\"names\":[],\"roles\":[\"form_designer\"]},\"members\":{\"names\":[],\"roles\":[\"abstractor\",\"data_analyst\",\"timer\"]}}", Program.config_timer_user_name, Program.config_timer_password).executeAsync();
                    Log.Information("mmrds/_security completed successfully");


                    try
                    {
                        string case_design_sortable      = System.IO.File.OpenText(System.IO.Path.Combine(current_directory, "database-scripts/case_design_sortable.json")).ReadToEnd();
                        var    case_design_sortable_curl = new cURL("PUT", null, Program.config_couchdb_url + "/mmrds/_design/sortable", case_design_sortable, Program.config_timer_user_name, Program.config_timer_password);
                        await case_design_sortable_curl.executeAsync();

                        //await EnsureUpdate(case_design_sortable, Program.config_couchdb_url + "/mmrds/_design/sortable");

                        string case_store_design_auth = await System.IO.File.OpenText(System.IO.Path.Combine(current_directory, "database-scripts/case_store_design_auth.json")).ReadToEndAsync();

                        var case_store_design_auth_curl = new cURL("PUT", null, Program.config_couchdb_url + "/mmrds/_design/auth", case_store_design_auth, Program.config_timer_user_name, Program.config_timer_password);
                        await case_store_design_auth_curl.executeAsync();

                        //await EnsureUpdate(case_store_design_auth, Program.config_couchdb_url + "/mmrds/_design/auth");
                    }
                    catch (Exception ex)
                    {
                        Log.Information($"unable to configure mmrds database:\n{ex}");
                    }
                }



                if (!await url_endpoint_exists(Program.config_couchdb_url + "/session", Program.config_timer_user_name, Program.config_timer_password))
                {
                    var session_curl = new cURL("PUT", null, Program.config_couchdb_url + "/session", null, Program.config_timer_user_name, Program.config_timer_password);
                    Log.Information("session_curl\n{0}", await session_curl.executeAsync());

                    await new cURL("PUT", null, Program.config_couchdb_url + "/session/_security", "{\"admins\":{\"names\":[],\"roles\":[\"_admin\"]},\"members\":{\"names\":[],\"roles\":[\"_admin\"]}}", Program.config_timer_user_name, Program.config_timer_password).executeAsync();
                    Log.Information("session/_security completed successfully");


                    try
                    {
                        /*
                         * string session_design_profile_sortable = System.IO.File.OpenText (System.IO.Path.Combine (current_directory, "database-scripts/session_design_profile_sortable.json")).ReadToEnd ();
                         * var session_design_profile_sortable_curl = new cURL ("PUT", null, Program.config_couchdb_url + "/session/_design/profile_sortable", session_design_profile_sortable, Program.config_timer_user_name, Program.config_timer_password);
                         * await session_design_profile_sortable_curl.executeAsync ();
                         */
                        //await EnsureUpdate(case_design_sortable, Program.config_couchdb_url + "/mmrds/_design/sortable");

                        string session_design_session_event_sortable = await System.IO.File.OpenText(System.IO.Path.Combine(current_directory, "database-scripts/session_design_session_event_sortable.json")).ReadToEndAsync();

                        var session_design_session_event_sortable_curl = new cURL("PUT", null, Program.config_couchdb_url + "/session/_design/session_event_sortable", session_design_session_event_sortable, Program.config_timer_user_name, Program.config_timer_password);
                        await session_design_session_event_sortable_curl.executeAsync();


                        string session_design_session_sortable = await System.IO.File.OpenText(System.IO.Path.Combine(current_directory, "database-scripts/session_design_session_sortable.json")).ReadToEndAsync();

                        var session_design_session_sortable_curl = new cURL("PUT", null, Program.config_couchdb_url + "/session/_design/session_sortable", session_design_session_sortable, Program.config_timer_user_name, Program.config_timer_password);
                        await session_design_session_sortable_curl.executeAsync();

                        //await EnsureUpdate(case_store_design_auth, Program.config_couchdb_url + "/mmrds/_design/auth");
                    }
Example #29
0
        void IJob.Execute(IJobExecutionContext context)
        {
            //Common.Logging.ILog log = Common.Logging.LogManager.GetCurrentClassLogger();
            //log.Debug("IJob.Execute");

            JobKey jobKey = context.JobDetail.Key;

            //log.DebugFormat("iCIMS_Data_Call_Job says: Starting {0} executing at {1}", jobKey, DateTime.Now.ToString("r"));
            mmria.server.model.couchdb.c_change_result latest_change_set = GetJobInfo(Program.Last_Change_Sequence);

            Dictionary <string, KeyValuePair <string, bool> > response_results = new Dictionary <string, KeyValuePair <string, bool> > (StringComparer.OrdinalIgnoreCase);

            if (Program.Last_Change_Sequence != latest_change_set.last_seq)
            {
                foreach (mmria.server.model.couchdb.c_seq seq in latest_change_set.results)
                {
                    if (response_results.ContainsKey(seq.id))
                    {
                        if
                        (
                            seq.changes.Count > 0 &&
                            response_results [seq.id].Key != seq.changes [0].rev
                        )
                        {
                            if (seq.deleted == null)
                            {
                                response_results [seq.id] = new KeyValuePair <string, bool> (seq.changes [0].rev, false);
                            }
                            else
                            {
                                response_results [seq.id] = new KeyValuePair <string, bool> (seq.changes [0].rev, true);
                            }
                        }
                    }
                    else
                    {
                        if (seq.deleted == null)
                        {
                            response_results.Add(seq.id, new KeyValuePair <string, bool> (seq.changes [0].rev, false));
                        }
                        else
                        {
                            response_results.Add(seq.id, new KeyValuePair <string, bool> (seq.changes [0].rev, true));
                        }
                    }
                }
            }


            if (Program.Change_Sequence_Call_Count < int.MaxValue)
            {
                Program.Change_Sequence_Call_Count++;
            }

            if (Program.DateOfLastChange_Sequence_Call.Count > 9)
            {
                Program.DateOfLastChange_Sequence_Call.Clear();
            }

            Program.DateOfLastChange_Sequence_Call.Add(DateTime.Now);

            Program.Last_Change_Sequence = latest_change_set.last_seq;

            foreach (KeyValuePair <string, KeyValuePair <string, bool> > kvp in response_results)
            {
                System.Threading.Tasks.Task.Run
                (
                    new Action(() =>
                {
                    if (kvp.Value.Value)
                    {
                        try
                        {
                            mmria.server.util.c_sync_document sync_document = new mmria.server.util.c_sync_document(kvp.Key, null, "DELETE");
                            sync_document.execute();
                        }
                        catch (Exception ex)
                        {
                            System.Console.WriteLine("Sync Delete case");
                            System.Console.WriteLine(ex);
                        }
                    }
                    else
                    {
                        string document_url  = Program.config_couchdb_url + "/mmrds/" + kvp.Key;
                        var document_curl    = new cURL("GET", null, document_url, null, Program.config_timer_user_name, Program.config_timer_password);
                        string document_json = null;

                        try
                        {
                            document_json = document_curl.execute();
                            if (!string.IsNullOrEmpty(document_json) && document_json.IndexOf("\"_id\":\"_design/") < 0)
                            {
                                mmria.server.util.c_sync_document sync_document = new mmria.server.util.c_sync_document(kvp.Key, document_json);
                                sync_document.execute();
                            }
                        }
                        catch (Exception ex)
                        {
                            System.Console.WriteLine("Sync PUT case");
                            System.Console.WriteLine(ex);
                        }
                    }
                })
                );
            }



            //Program.JobInfoList = GetJobInfo();

            /*
             * if (Program.NumberOfJobInfoList_Call_Count < int.MaxValue)
             * {
             * Program.NumberOfJobInfoList_Call_Count++;
             * }
             *
             * if (Program.DateOfLastJobInfoList_Call.Count >10)
             * {
             * Program.DateOfLastJobInfoList_Call.Clear();
             * }
             *
             * Program.DateOfLastJobInfoList_Call.Add(DateTime.Now);
             */

            //log.DebugFormat("iCIMS_Data_Call_Job says: finishing {0} executing at {1}", jobKey, DateTime.Now.ToString("r"));
        }
Example #30
0
        public static HashSet <string> get_current_jurisdiction_id_set_for(System.Security.Claims.ClaimsPrincipal p_claims_principal)
        {
            HashSet <string> result = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            if (!p_claims_principal.HasClaim(c => c.Type == ClaimTypes.Name &&
                                             c.Issuer == "https://contoso.com"))
            {
                return(result);
            }

            if (p_claims_principal.HasClaim(c => c.Type == ClaimTypes.Role &&
                                            c.Value == "installation_admin"))
            {
                result.Add("/");
            }

            var user_name = p_claims_principal.Claims.Where(c => c.Type == ClaimTypes.Name).FirstOrDefault().Value;

            string jurisdicion_view_url      = $"{Program.config_couchdb_url}/jurisdiction/_design/sortable/_view/by_user_id?{user_name}";
            var    jurisdicion_curl          = new cURL("GET", null, jurisdicion_view_url, null, Program.config_timer_user_name, Program.config_timer_password);
            string jurisdicion_result_string = null;

            try
            {
                jurisdicion_result_string = jurisdicion_curl.execute();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex);
                return(result);
            }

            var jurisdiction_view_response = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.get_sortable_view_reponse_header <mmria.common.model.couchdb.user_role_jurisdiction> >(jurisdicion_result_string);

            var now = DateTime.Now;

            foreach (mmria.common.model.couchdb.get_sortable_view_response_item <mmria.common.model.couchdb.user_role_jurisdiction> jvi in jurisdiction_view_response.rows)
            {
                if (jvi.key != null && jvi.key == user_name)
                {
                    if (jvi.value.is_active != null && jvi.value.is_active.HasValue && jvi.value.is_active.Value)
                    {
                        bool add_item = true;

                        if (jvi.value.effective_start_date != null && jvi.value.effective_start_date.HasValue)
                        {
                            if (jvi.value.effective_start_date > now)
                            {
                                add_item = false;
                            }
                        }

                        if (jvi.value.effective_end_date != null && jvi.value.effective_end_date.HasValue)
                        {
                            if (jvi.value.effective_end_date.Value < now)
                            {
                                add_item = false;
                            }
                        }

                        if (add_item)
                        {
                            result.Add(jvi.value.jurisdiction_id);
                        }
                    }
                }
            }

            return(result);
        }