Exemplo n.º 1
0
        public static AppReturn SendEmailForForgottenPassword(User user)
        {
            AppReturn result = new AppReturn();

            bool isSent = Helpers.SendEmail.SendEmailSmtp(user.Email,
                                                          "Shifter and Worker User Informations",
                                                          string.Format(
                                                              $"<p>Dear {user.FirstName + " " + user.LastName},</p>" +
                                                              "<p>You can see your user information details below.</p>" +
                                                              $"<p>Email: {user.Email}</p>" +
                                                              $"<p>Password: {user.Password}</p>" +
                                                              "<p>Regards,</p>" +
                                                              "<p>Shifter and Worker</p>"),
                                                          new List <string>()
            {
                user.Email
            });

            if (!isSent)
            {
                result.Success = false;
                result.Message = "An error has occured when mail sending.";
                return(result);
            }

            result.Success = true;
            result.Message = "Password sent successfuly! Please check your inbox.";
            return(result);
        }
Exemplo n.º 2
0
        /**********************************************************************************************************
         *  Client-Side Called Methods
         *********************************************************************************************************/



        public List <AppReturn> get()
        {
            bool isWithQParam = AppArgs.ContainsKey(_g.KEY_QPARAM_JSON);

            if (isWithQParam)
            {
                return(ProcessQParam());
            }

            if (isAppDebug)
            {
                return new List <AppReturn>()
                       {
                           DebugData
                       }
            }
            ;

            AppReturn appReturn = new AppReturn();

            // populate props with AppSettings
            foreach (KeyValuePair <string, dynamic> tk in _g.AppSetings)
            {
                appReturn.props.Add(tk.Key, tk.Value);
            }

            return(new List <AppReturn>()
            {
                appReturn
            });
        }
Exemplo n.º 3
0
        }   /** End of POST method **/

        private List <AppReturn> nullget(string table, string key = "", string keyField = "")
        {
            List <AppReturn> retVal = new List <AppReturn> {
            };
            AppReturn ret           = new AppReturn();

            retVal.Add(ret);
            return(retVal);
        }
        public ActionResult SendAnswerEmail(int mailId, string body)
        {
            User loggedUser = Session["LoggedUser"] as User;

            Mail mail = _uow.MailManager.Get(x => x.MailId == mailId);

            Mail newMail;

            if (mail.SenderId == loggedUser.UserId) // En son cevap veren giriş yapmış olan kullanıcı ise (kendi kendine cevaplamasın diye).
            {
                newMail = new Mail
                {
                    Subject           = mail.Subject,
                    Body              = body,
                    CreateDate        = DateTime.Now,
                    IsRead            = false,
                    IsActive          = true,
                    IsPermanentDelete = false,
                    SenderId          = loggedUser.UserId,
                    ReceiverId        = mail.ReceiverId,
                    ParentMailId      = mail.MailId
                };
            }
            else // En son cevap veren karşı taraf ise.
            {
                newMail = new Mail
                {
                    Subject           = mail.Subject,
                    Body              = body,
                    CreateDate        = DateTime.Now,
                    IsRead            = false,
                    IsActive          = true,
                    IsPermanentDelete = false,
                    SenderId          = loggedUser.UserId,
                    ReceiverId        = mail.SenderId,
                    ParentMailId      = mail.MailId
                };
            }

            AppReturn result = _uow.MailManager.Add(newMail);

            if (_uow.SaveChanges())
            {
                TempData["ProcessResult"] = "Mail sent successfuly.";
                TempData["AlertType"]     = "success";
                return(RedirectToAction("Inbox"));
            }
            else
            {
                TempData["ProcessResult"] = "An error has occured when sending mail.";
                TempData["AlertType"]     = "danger";
                return(RedirectToAction("Inbox"));
            }
        }
Exemplo n.º 5
0
 public AppReturn PermanentDelete(int id)
 {
     try
     {
         Mail mail = _context.Mails.Find(id);
         mail.IsPermanentDelete = true;
         return(AppReturn.Successful("Successfully deleted mail permanently"));
     }
     catch (Exception)
     {
         // TODO : Logger has to add here.
         return(AppReturn.InvalidOperation("An error has occured when deleting email."));
     }
 }
Exemplo n.º 6
0
        public AppReturn Add(TEntity entity)
        {
            try
            {
                DbSet.Add(entity);

                Log.Info("Successfully added model.");
                return(AppReturn.Successful());
            }
            catch (Exception e)
            {
                Log.Error("An unexpected error has occured while adding model.", e);
                return(AppReturn.InvalidOperation(e.Message));
            }
        }
Exemplo n.º 7
0
        public AppReturn Delete(int id)
        {
            try
            {
                User user = _context.Users.Find(id);
                user.IsActive = false;

                Log.Info("Successfully deleted user.");
                return(AppReturn.Successful("User deleted successfully."));
            }
            catch (Exception e)
            {
                Log.Error("An unexpected error has occured while deleting user.", e);
                return(AppReturn.InvalidOperation("An error has occured when deleting user."));
            }
        }
Exemplo n.º 8
0
        public AppReturn Update(TEntity entity)
        {
            try
            {
                DbSet.Attach(entity);
                _context.Entry(entity).State = EntityState.Modified;

                Log.Info($"{ entity.GetType() } updated successfuly.");
                return(AppReturn.Successful());
            }
            catch (Exception e)
            {
                Log.Error($"An unexpected error has occured while updating { entity.GetType() }.", e);
                return(AppReturn.InvalidOperation(e.Message));
            }
        }
Exemplo n.º 9
0
        public AppReturn Delete(int id)
        {
            try
            {
                Note note = _context.Notes.Find(id);
                note.IsActive = false;
                Log.Info("Successfully deleted note.");

                return(AppReturn.Successful("Note deleted successfully."));
            }
            catch (Exception e)
            {
                Log.Error("An unexpected error has occured while deleting note.", e);
                return(AppReturn.InvalidOperation("An error has occured when deleting note."));
            }
        }
        public AppReturn Delete(int id)
        {
            try
            {
                Announcement announcement = _context.Announcements.Find(id);
                announcement.IsActive = false;

                Log.Info("Successfully deleted announcement.");
                return(AppReturn.Successful("Announcement deleted successfully."));
            }
            catch (Exception e)
            {
                Log.Error("An unexpected error has occured while deleting announcement.", e);
                return(AppReturn.InvalidOperation("An error has occured when deleting announcement."));
            }
        }
        public JsonResult SendPassword(string email)
        {
            JsonResult jsonResult = new JsonResult
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };

            #region User control

            User user = _uow.UserManager.Get(x => x.Email == email);

            if (user == null)
            {
                jsonResult.Data = new
                {
                    success = false,
                    message = "You are not registered in our system or have used a faulty email. Please check and try again."
                };
                return(jsonResult);
            }

            #endregion

            #region Send email and return result

            AppReturn result = EmailTemplateManager.SendEmailForForgottenPassword(user);
            if (result.Success)
            {
                jsonResult.Data = new
                {
                    success = true,
                    message = result.Message
                };
                return(jsonResult);
            }
            else
            {
                jsonResult.Data = new
                {
                    success = false,
                    message = result.Message
                };
                return(jsonResult);
            }

            #endregion
        }
Exemplo n.º 12
0
        public AppReturn Delete(int id)
        {
            try
            {
                Mail mail = _context.Mails.Find(id);
                mail.IsActive   = false;
                mail.DeleteDate = DateTime.Now;

                Log.Info("Successfully deleted email.");
                return(AppReturn.Successful("Mail deleted successfully."));
            }
            catch (Exception e)
            {
                Log.Error("An unexpected error has occured while deleting email.", e);
                return(AppReturn.InvalidOperation("An error has occured when deleting email."));
            }
        }
Exemplo n.º 13
0
        public ActionResult MoveDeletedMailToInbox(int id)
        {
            var mail = _uow.MailManager.Get(x => x.MailId == id);

            mail.IsActive = true;

            AppReturn result = _uow.MailManager.Update(mail);

            if (_uow.SaveChanges())
            {
                TempData["ProcessResult"] = "Mail moved to inbox.";
                TempData["AlertType"]     = "success";
            }
            else
            {
                TempData["ProcessResult"] = "An error has occured when moving email to inbox.";
                TempData["AlertType"]     = "danger";
            }

            return(RedirectToAction("Trash"));
        }
Exemplo n.º 14
0
        public ActionResult Send(string email, string subject, string body)
        {
            User loggedUser = Session["LoggedUser"] as User;

            var receiverUser = _uow.UserManager.Get(x => x.Email == email); // bringing for receiverId property when creating a new mail.

            if (receiverUser == null)
            {
                TempData["ProcessResult"] = "There is no such a user in the system.";
                TempData["AlertType"]     = "danger";
                return(View());
            }

            AppReturn result = _uow.MailManager.Add(new Mail
            {
                Subject           = subject,
                Body              = body,
                CreateDate        = DateTime.Now,
                SenderId          = loggedUser.UserId,
                IsActive          = true,
                ReceiverId        = receiverUser.UserId,
                IsPermanentDelete = false,
                IsRead            = false
            });

            if (_uow.SaveChanges())
            {
                TempData["ProcessResult"] = "Mail sent successfully.";
                TempData["AlertType"]     = "success";
                return(RedirectToAction("Inbox"));
            }
            else
            {
                TempData["ProcessResult"] = "An error has occured when sending mail.";
                TempData["AlertType"]     = "danger";
                return(RedirectToAction("Inbox"));
            }
        }
Exemplo n.º 15
0
        public ActionResult Create(VMUserCreate model)
        //[Bind(Include = "FirstName, LastName, Phone, DateOfBirth, Email, About, ImageUrl, DepartmentId, RoleId, WorkingTypeId")]
        {
            User loggedUser = Session["LoggedUser"] as User;

            AppReturn result = _uow.UserManager.Add(
                new User
            {
                About         = model.About,
                CreateDate    = DateTime.Now,
                DateOfBirth   = model.DateOfBirth,
                DepartmentId  = model.DepartmentId,
                Email         = model.Email,
                IsActive      = true,
                ImageUrl      = model.ImageUrl,
                FirstName     = model.FirstName,
                LastName      = model.LastName,
                Phone         = model.Phone,
                Password      = "******", // Default Password.
                RoleId        = model.RoleId,
                StoreId       = loggedUser.StoreId,
                SupervisorId  = model.SupervisorId,
                WorkingTypeId = model.WorkingTypeId
            });

            if (!_uow.SaveChanges())
            {
                TempData["ProcessResult"] = "An unexpected error occured while creating user.";
                TempData["AlertType"]     = "danger";
                return(RedirectToAction("List"));
            }

            TempData["ProcessResult"] = "User created successfully.";
            TempData["AlertType"]     = "success";
            return(RedirectToAction("List"));
        }
Exemplo n.º 16
0
        public List <AppReturn> post([FromBody] JObject values)
        {
            /************************************************************************************
            * 20 Dec 2019 - alv
            * values:
            * {
            *  "<tableCode>":[{data row object 1},...,{data row object n}]
            * }
            ************************************************************************************/

            /************************************************************************************
            * 15 April 2020 - alv
            *
            * public static string KEY_REQUEST_HEADER_CODE = "__header__";
            *
            * public static string KEY_REQUEST_STAMP = "_req_stamp_";
            * public static string KEY_USER_ID = "__uid__";
            * public static string KEY_USER_RIGHTS = "__rights__";
            * public static string KEY_ACTION = "__action__";
            *
            * JSON
            *
            *  "__header__" :
            *  {
            *       "_req_stamp_":"",
            *       "__uid__":"alv",
            *       "__rights__":"",
            *       "__action__":""
            *  }
            *  "__header__" :{"_req_stamp_":"","__uid__":"alv","__rights__":"","__action__":""}
            *
            *  https://www.base64encode.org/
            *  Equivalent base64: eyJfcmVxX3N0YW1wXyI6IiIsIl9fdWlkX18iOiJhbHYiLCJfX3JpZ2h0c19fIjoiIiwiX19hY3Rpb25fXyI6IiJ9
            *
            * Converted to Base64 text
            ************************************************************************************/

            DateTime startProcess = DateTime.Now;


            //dGhpcyBpcyBhIHRlc3Q=
            byte[] bytes = Convert.FromBase64String("dGhpcyBpcyBhIHRlc3Q=");
            string text  = System.Text.Encoding.Default.GetString(bytes);

            byte[] bytes2  = System.Text.Encoding.Default.GetBytes(text);
            string textB64 = Convert.ToBase64String(bytes2);

            JObject args = AppArgs;

            if (values.ContainsKey(_g.KEY_REQUEST_HEADER_CODE))
            {
                string  header    = (String)values[_g.KEY_REQUEST_HEADER_CODE];        // extract header Base64
                byte[]  jsonBytes = Convert.FromBase64String(header);                  // convert to byte array
                string  jsonText  = System.Text.Encoding.Default.GetString(jsonBytes); // convert to JSON string
                JObject json      = JObject.Parse(jsonText);                           // convert to JSON object

                // loop through header information and add token to AppArgs if not yet existing
                foreach (JProperty jph in (JToken)json)
                {
                    if (!args.ContainsKey(jph.Name))
                    {
                        args.Add(jph.Name, jph.Value);
                    }
                }
            }

            List <AppReturn> retVal  = new List <AppReturn> {
            };
            List <CommandParam> cmds = new List <CommandParam>();

            // generate collection of commands to execute
            foreach (JProperty jp in (JToken)values)
            {
                // iterate through all tables to generate CommandParams collection
                if (jp.Name != _g.KEY_REQUEST_HEADER_CODE)
                {
                    // get table object from the collection
                    DALTable tbl = AppDataset.AppTables[jp.Name];

                    // get collection of CommandParams per table
                    List <CommandParam> cmdsTemp = tbl.GetCommandParamsForPosting((JArray)jp.Value, args);
                    if (DALData.DAL.globalError.Length != 0)
                    {
                        // error has occured, therefore empty list is returned. handle error here
                        break;
                    }

                    // append commands to the general collection for execution in bulk
                    foreach (CommandParam cmd in cmdsTemp)
                    {
                        cmds.Add(cmd);
                    }
                }

                // execute commands
            }

            // execute all commands in the collection
            List <ReturnObject> cmdResults = DALData.DAL.Excute(cmds, true);

            DateTime endProcess = DateTime.Now;

            AppReturn ret = new AppReturn();
            long      dur = ((endProcess.Millisecond +
                              endProcess.Second * 1000 +
                              endProcess.Minute * 60 * 1000 +
                              endProcess.Hour * 60 * 60 * 1000) -
                             (startProcess.Millisecond +
                              startProcess.Second * 1000 +
                              startProcess.Minute * 60 * 1000 +
                              startProcess.Hour * 60 * 60 * 1000));

            //ret.returnStrings.Add("Process Duration in milliseconds: " + dur.ToString() + "(ms)");
            //if (errMessage.Length!=0) ret.returnStrings.Add("Error:" + errMessage);

            //ret.stamps = new DALStamps(cmds[0].table.columns, "@alv");
            ret.stamps = null;

            //AppReturn ar = new AppReturn();
            //ar.stamps = new DALStamps(cmds[0].table.columns, "@alv");
            //retVal.Add(ar);

            ret.errorMessage = DALData.DAL.globalError;

            retVal.Add(ret);

            foreach (ReturnObject rObj in cmdResults)
            {
                ret = new AppReturn();
                ret.errorMessage = rObj.result.exceptionMessage;
                retVal.Add(ret);
            }

            return(retVal);
            //return new List<AppReturn> { new AppReturn() };
        }
Exemplo n.º 17
0
        public List <AppReturn> get(string table, string key = "",
                                    string keyField          = "", string includedFields = "",
                                    string filter            = "", string sortFields     = "",
                                    string pageNumber        = "0", string pageSize      = "0",
                                    string requestConfig     = "", string fieldMap       = "")
        //string keyField = "")
        {
            //_g.CONFIG_FILE = "ngarbi.settings.json";
            // process request where all parameters are embedded in the Base64 querystring parameter "_p"

            // Add all parameters to the AppArgs object

            List <AppReturn> retVal = new List <AppReturn> {
            };

            if (isAppDebug)
            {
                return new List <AppReturn> {
                           DebugPath
                }
            }
            ;

            AppReturn appReturn = new AppReturn();

            if (table == "@gents")
            {
                // Generate client-side typescript files
                AppDataset.Initialize();

                appReturn.props.Add("Tables", AppDataset.AppTables.Count());
                appReturn.subsKey = "Hello Test Me!";

                appReturn.props.Add("Views", AppDataset.AppViews.Count());
                appReturn.props.Add("StoredProcedures", AppDataset.AppProcedures.Count());

                foreach (string tblCode in AppDataset.AppTables.Keys)
                {
                    DALTable tbl = AppDataset.AppTables[tblCode];
                    appReturn.processLogs.Add(tblCode, tbl.tableName);
                    appReturn.processLogs.Add(tblCode + "_relation", tbl.tableRelations == null ? "0" : tbl.tableRelations.Count.ToString());
                    foreach (string pv in tbl.tableProcessLogs.Keys)
                    {
                        appReturn.processLogs.Add(tblCode + "_proc_" + pv, tbl.tableProcessLogs[pv]);
                    }
                }

                //retVal.Add(appReturn); return retVal;
                return(new List <AppReturn> {
                    appReturn
                });
            }

            if (table == "@locs")
            {
                Stopwatch st = new Stopwatch();
                st.Start();
                string[] keyArr = key.Split('`');
                string   pCode  = "";

                if (keyArr.Length >= 2)
                {
                    pCode = keyArr[1];
                }

                DALData.DAL.BuildNodeLocation(Convert.ToInt32(keyArr[0]), pCode);
                appReturn.returnCode = table;
                st.Stop();
                appReturn.requestDuration = st.ElapsedMilliseconds;

                return(new List <AppReturn> {
                    appReturn
                });
            }
            if (table == "@mtbl")
            {
                // multi table query, accepts json formatted parameters supplied as
                // Base64 encoded querystring parameters named ?p=
                // api call <protocol>://<domain>[/application]/api/app/@mtbl?p=<base64 encoded parameters>
                return(new List <AppReturn> {
                    appReturn
                });
            }

            if (isAppDebugPaths)
            {
                return new List <AppReturn> {
                           DebugPath
                }
            }
            ;


            JObject jArgs = new JObject()
            {
            };

            // split "table" parameter to get the parent table code (first element) and from clause join codes (second element)
            string[] tableArr = table.Split('|');

            jArgs.Add("code", tableArr[0]);
            if (tableArr.Length > 1)
            {
                jArgs.Add("fromClauseExpr", tableArr[1]);
            }

            jArgs.Add("key", (key == "-" ? "" : key));
            jArgs.Add("keyField", (keyField == "-" ? "" : keyField));
            jArgs.Add("includedFields", (includedFields == "-" ? "" : includedFields));
            jArgs.Add("filter", (filter == "-" ? "" : filter));
            jArgs.Add("fieldMap", (filter == "-" ? "" : fieldMap));
            jArgs.Add("sortFields", (sortFields == "-" ? "" : sortFields));
            jArgs.Add("pageNumber", (!pageNumber.All(char.IsDigit) ? 0 : Convert.ToInt64(pageNumber)));
            jArgs.Add("pageSize", (!pageSize.All(char.IsDigit) ? 0 : Convert.ToInt64(pageSize)));
            jArgs.Add("requestConfig", (requestConfig == "-" ? "" : requestConfig));
            jArgs.Add("snapshot", _g.TKVBln(AppArgs, "snapshot"));
            jArgs.Add("distinct", _g.TKVBln(AppArgs, "distinct"));

            AppArgs.Add(_g.KEY_REQ_ARGS_ARR, new JArray()
            {
                jArgs
            });

            return(ExecuteGetRequest());
        }

        //public ReturnObjectExternal xxxxpostX(string table, [FromBody]JObject values)
        //{
        //    ReturnObject retVal = AppDataset.Post(table, values, AppArgs);
        //    return retVal.result;
        //}


        /**********************************************************************************************************
         *  Private Methods
         *********************************************************************************************************/

        //private JObject AppArgs()
        //{
        //    // Collect query string arguments and some headers ...

        //    JObject ret = new JObject();

        //    List<KeyValuePair<string, string>> retList = ControllerContext.Request.GetQueryNameValuePairs().ToList();

        //    // add request data/time stamp
        //    retList.Add(new KeyValuePair<string, string>(AppGlobals.KEY_REQUEST_STAMP, DateTime.Now.ToString()));

        //    //add content type
        //    if (this.Request.Content.Headers.Contains("Content-Type"))
        //    {
        //        ret.Add(new KeyValuePair<string, string>(AppGlobals.KEY_CONTENT_TYPE, this.Request.Content.Headers.ContentType.ToString().ToLower()));
        //    }

        //    foreach (KeyValuePair<string, string> arg in retList)
        //    {
        //        ret.Add(arg.Key, arg.Value);
        //    }
        //    return ret;
        //}
    }
}
Exemplo n.º 18
0
        private List <AppReturn> ExecuteGetRequest()
        {
            List <AppReturn> retVal = new List <AppReturn> {
            };
            JObject reqConfig       = null;

            foreach (JObject jParam in _g.TKVJArr(AppArgs, _g.KEY_REQ_ARGS_ARR))
            {
                string[] tableCodeArr = _g.TKVStr(jParam, "code").Split('|');
                string   tableCode    = tableCodeArr[0];

                if (tableCodeArr.Length > 1)
                {
                    // table code was supplied with fromClause expression code to be parsed during
                    // creation of SQL statement.
                    jParam["code"] = tableCode;
                    jParam.Add("fromClauseExpr", tableCodeArr[1]);
                }

                if (tableCode == "")
                {
                    continue;                   // table code not found
                }
                //http://soga-alv/NgArbi/api/app?_p=W3siY29kZSI6IkBtaXNjIn0seyJjb2RlIjoidXNlciIsInBhZ2VOdW1iZXIiOjEsInBhZ2VTaXplIjozNX1d
                if (tableCode == "@config")
                {
                    // miscellaneous parameters passed from the client
                    reqConfig = new JObject();

                    AppReturn misc = new AppReturn();
                    misc.returnType = "config";
                    misc.subsKey    = _g.TKVStr(jParam, "subsKey");

                    retVal.Insert(0, misc);

                    continue;
                }

                //if (tableCodeArr.Length > 1)
                //{
                //    // fromClauseExpr is specified, add entry to AppArgs object
                //    AppArgs.Add("fromClauseExpr", tableCodeArr[1]);
                //}


                //List<ReturnObject> ret = AppDataset.AppTables[tableCode].Get(AppArgs, jParam);
                List <ReturnObject> ret = AppDataset.AppTables[tableCode].GetData(AppArgs, jParam);

                // iterate through the results of table Get method to build the final return collection
                int retCount = 0;
                foreach (ReturnObject retObj in ret)
                {
                    AppReturn appRet = new AppReturn()
                    {
                        // used as handle of list in the client-side data capture reoutine
                        returnCode = retObj.returnCode,
                        returnType = retObj.returnType,

                        // date and time stamp ( by default this parameter is set in the constructor
                        // requestDateTime = DateTime.Now,

                        recordCount      = retObj.result.recordCount,
                        records          = retObj.result.jsonReturnData,
                        returnDataParams = retObj.result.returnDataParams,
                        recordsList      = retObj.result.returnData,
                        recordsProps     = retObj.result.recordsProps,
                        //columns = retObj.result.columns
                        //columnsArr = retObj.result.jsonReturnData
                        fieldNames   = retObj.result.fieldsNames,
                        errorMessage = retObj.result.error,

                        requestDateTime = retObj.result.requestDateTime,
                        requestDuration = retObj.result.requestDuration,

                        subsKey = _g.TKVStr(AppArgs, _g.QS_SUBSCRIPTION_KEY),
                    };

                    retCount++;
                    if (retCount == 1)
                    {
                        appRet.globalMesages = DALData.DAL.globalMessages;
                    }
                    retVal.Add(appRet);
                }
            }


            return(retVal);
        }
Exemplo n.º 19
0
        public List <AppReturn> post([FromBody] JObject values)
        {
            //_g.CONFIG_FILE = "ngarbi.settings.json";

            DateTime startProcess = DateTime.Now;

            if (values[_g.KEY_QPARAM_JSON] != null)
            {
                // get request with complex parameters initiated
                return(RequestData(values));
            }


            //dGhpcyBpcyBhIHRlc3Q=
            byte[] bytes = Convert.FromBase64String("dGhpcyBpcyBhIHRlc3Q=");
            string text  = System.Text.Encoding.Default.GetString(bytes);

            byte[] bytes2  = System.Text.Encoding.Default.GetBytes(text);
            string textB64 = Convert.ToBase64String(bytes2);

            JObject args = AppArgs;

            // initialize return object
            AppReturn ret = new AppReturn();



            if (values.ContainsKey(_g.KEY_REQUEST_HEADER_CODE))
            {
                try
                {
                    string  header    = (String)values[_g.KEY_REQUEST_HEADER_CODE];        // extract header Base64
                    byte[]  jsonBytes = Convert.FromBase64String(header);                  // convert to byte array
                    string  jsonText  = System.Text.Encoding.Default.GetString(jsonBytes); // convert to JSON string
                    JObject json      = JObject.Parse(jsonText);                           // convert to JSON object

                    // loop through header information and add token to AppArgs if not yet existing
                    foreach (JProperty jph in (JToken)json)
                    {
                        if (!args.ContainsKey(jph.Name))
                        {
                            args.Add(jph.Name, jph.Value);
                        }
                    }

                    ret.headerProcessResult.Add("result", "Success");
                }
                catch (Exception e)
                {
                    ret.headerProcessResult.Add("ErrorDetails", e.ToString());
                    ret.headerProcessResult.Add("result", "Error");
                }
            }

            List <AppReturn> retVal        = new List <AppReturn> {
            };
            List <CommandParam> cmds       = new List <CommandParam>();
            JObject             postConfig = null;
            bool         useCommonNewKey   = false;
            bool         firstTable        = true;
            List <Int64> tblCommonId       = new List <Int64>();

            // generate collection of commands to execute
            foreach (JProperty jp in (JToken)values)
            {
                // iterate through all tables to generate CommandParams collection
                if (jp.Name == _g.KEY_PROCESS_HEADER_CODE)
                {
                    DALData.DAL.LogGlobalMessage("proces header code is supplied!", "invoke_process");
                    // this section is where application-specific process will be invoked
                    ret.invokeResult = RunModels.Invoke(jp);
                }
                else if (jp.Name == _g.KEY_REQUEST_HEADER_CODE)
                {
                    ;
                }
                else if (jp.Name == _g.KEY_PROCESS_CONFIG_CODE)
                // config code value contains instruction/parameters which
                // will determine specific process when posting
                // eg. on creation of new record with sub table, use common id
                // for both
                {
                    postConfig = (JObject)jp.Value;
                    if (postConfig["useCommonNewKey"] != null)
                    {
                        useCommonNewKey = (bool)postConfig["useCommonNewKey"];
                    }
                }

                else
                {
                    // PROCESS TABLE CREATE, UPDATE, DELETE

                    // get table object from the collection
                    DALTable tbl = AppDataset.AppTables[jp.Name];
                    // if(!firstTable && tblCommonId)
                    //
                    Int64 newRecordKeyId = -1;


                    // get collection of CommandParams per table
                    List <CommandParam> cmdsTemp = tbl.GetCommandParamsForPosting((JArray)jp.Value, args);
                    CommandParam        cmd1     = cmdsTemp[0];
                    if (firstTable)
                    {
                        // record first table record ids.
                        // iterate through the records' parameters

                        if (cmd1.newKey != -1)
                        {
                            // new record. populate tblCommonId with key id's of all commands
                            cmdsTemp.ForEach(cmd => tblCommonId.Add(cmd.paramKeyValue));
                        }

                        firstTable = false; // set first table flag to false after processing it
                    }
                    else
                    {
                        // if use common id,
                        if (useCommonNewKey && cmd1.newKey != -1 && tblCommonId.Count != 0)
                        {
                            int ctr = 0;
                            cmdsTemp.ForEach(cmd =>
                            {
                                cmd.cmdParams[DALData.PARAM_PREFIX + "p" + (int)cmd.paramKeyValuePosition] = tblCommonId[ctr];
                                ctr++;
                            });
                        }
                    }
                    if (DALData.DAL.globalError.Length != 0)
                    {
                        // error has occured, therefore empty list is returned. handle error here
                        break;
                    }



                    // append commands to the general collection for execution in bulk
                    foreach (CommandParam cmd in cmdsTemp)
                    {
                        cmds.Add(cmd);
                    }
                }

                // execute commands
            }

            List <ReturnObject> cmdResults = new List <ReturnObject>();

            // execute all commands in the collection (if any) - debug bypass by alv 2020/12/04 5:40am
            cmdResults = DALData.DAL.Excute(cmds, true);

            DateTime endProcess = DateTime.Now;

            long dur = ((endProcess.Millisecond +
                         endProcess.Second * 1000 +
                         endProcess.Minute * 60 * 1000 +
                         endProcess.Hour * 60 * 60 * 1000) -
                        (startProcess.Millisecond +
                         startProcess.Second * 1000 +
                         startProcess.Minute * 60 * 1000 +
                         startProcess.Hour * 60 * 60 * 1000));

            //ret.returnStrings.Add("Process Duration in milliseconds: " + dur.ToString() + "(ms)");
            //if (errMessage.Length!=0) ret.returnStrings.Add("Error:" + errMessage);

            //ret.stamps = new DALStamps(cmds[0].table.columns, "@alv");
            ret.stamps = null;

            ret.errorMessage = DALData.DAL.globalError;

            if (DALData.DAL.globalMessages.Count() != 0)
            {
                ret.globalMesages = DALData.DAL.globalMessages;
            }

            retVal.Add(ret);

            // ***** Generate result summary for client-side processing ******
            foreach (ReturnObject rObj in cmdResults)
            {
                string retCode = rObj.returnCode;
                if (retCode == "chgTrack" || retCode == "")
                {
                    continue;
                }

                ret = new AppReturn();

                ret.returnCode       = rObj.returnCode;
                ret.errorMessage     = rObj.result.exceptionMessage;
                ret.returnDataParams = rObj.result.returnDataParams;
                ret.result           = rObj.result.result;

                retVal.Add(ret);
            }

            return(retVal);
            //return new List<AppReturn>();
            //return new List<AppReturn> { new AppReturn() };
        }   /** End of POST method **/
Exemplo n.º 20
0
        public List <AppReturn> get(string table, string key = "",
                                    string keyField          = "", string includedFields = "",
                                    string filter            = "", string sortFields     = "",
                                    string pageNumber        = "0", string pageSize      = "0",
                                    string requestConfig     = "", string fieldMap       = "")
        //string keyField = "")
        {
            //_g.CONFIG_FILE = "ngarbi.settings.json";
            // process request where all parameters are embedded in the Base64 querystring parameter "_p"

            // Add all parameters to the AppArgs object

            List <AppReturn> retVal = new List <AppReturn> {
            };

            if (isAppDebug)
            {
                return new List <AppReturn> {
                           DebugPath
                }
            }
            ;

            AppReturn appReturn = new AppReturn();

            if (table == "@gents")
            {
                // Generate client-side typescript files
                AppDataset.Initialize();

                appReturn.props.Add("Tables", AppDataset.AppTables.Count());
                appReturn.subsKey = "Hello Test Me!";

                appReturn.props.Add("Views", AppDataset.AppViews.Count());
                appReturn.props.Add("StoredProcedures", AppDataset.AppProcedures.Count());

                foreach (string tblCode in AppDataset.AppTables.Keys)
                {
                    DALTable tbl = AppDataset.AppTables[tblCode];
                    appReturn.processLogs.Add(tblCode, tbl.tableName);
                    appReturn.processLogs.Add(tblCode + "_relation", tbl.tableRelations == null ? "0" : tbl.tableRelations.Count.ToString());
                    foreach (string pv in tbl.tableProcessLogs.Keys)
                    {
                        appReturn.processLogs.Add(tblCode + "_proc_" + pv, tbl.tableProcessLogs[pv]);
                    }
                }

                //retVal.Add(appReturn); return retVal;
                return(new List <AppReturn> {
                    appReturn
                });
            }

            if (table == "@locs")
            {
                Stopwatch st = new Stopwatch();
                st.Start();
                string[] keyArr = key.Split('`');
                string   pCode  = "";

                if (keyArr.Length >= 2)
                {
                    pCode = keyArr[1];
                }

                DALData.DAL.BuildNodeLocation(Convert.ToInt32(keyArr[0]), pCode);
                appReturn.returnCode = table;
                st.Stop();
                appReturn.requestDuration = st.ElapsedMilliseconds;

                return(new List <AppReturn> {
                    appReturn
                });
            }
            if (table == "@mtbl")
            {
                // multi table query, accepts json formatted parameters supplied as
                // Base64 encoded querystring parameters named ?p=
                // api call <protocol>://<domain>[/application]/api/app/@mtbl?p=<base64 encoded parameters>
                return(new List <AppReturn> {
                    appReturn
                });
            }

            if (isAppDebugPaths)
            {
                return new List <AppReturn> {
                           DebugPath
                }
            }
            ;


            JObject jArgs = new JObject()
            {
            };

            // split "table" parameter to get the parent table code (first element) and from clause join codes (second element)
            string[] tableArr = table.Split('|');

            jArgs.Add("code", tableArr[0]);
            if (tableArr.Length > 1)
            {
                jArgs.Add("fromClauseExpr", tableArr[1]);
            }

            jArgs.Add("key", (key == "-" ? "" : key));
            jArgs.Add("keyField", (keyField == "-" ? "" : keyField));
            jArgs.Add("includedFields", (includedFields == "-" ? "" : includedFields));
            jArgs.Add("filter", (filter == "-" ? "" : filter));
            jArgs.Add("fieldMap", (filter == "-" ? "" : fieldMap));
            jArgs.Add("sortFields", (sortFields == "-" ? "" : sortFields));
            jArgs.Add("pageNumber", (!pageNumber.All(char.IsDigit) ? 0 : Convert.ToInt64(pageNumber)));
            jArgs.Add("pageSize", (!pageSize.All(char.IsDigit) ? 0 : Convert.ToInt64(pageSize)));
            jArgs.Add("requestConfig", (requestConfig == "-" ? "" : requestConfig));
            jArgs.Add("snapshot", _g.TKVBln(AppArgs, "snapshot"));
            jArgs.Add("distinct", _g.TKVBln(AppArgs, "distinct"));

            AppArgs.Add(_g.KEY_REQ_ARGS_ARR, new JArray()
            {
                jArgs
            });

            return(ExecuteGetRequest());
        }