/// <summary> /// Inserts the data into the database. /// </summary> /// <param name="db">The database connection to be used</param> /// <param name="item">Data which need to be inserted</param> /// <returns>Returns null if insert fails else returns data in DynamicDictionary</returns> public virtual ResponseModel Insert(DbConnect con, DynamicDictionary item) { ResponseModel resp = new ResponseModel(false, string.Empty); TModel model = new TModel(); try { //validate data before saving if (!IsValid((DynamicDictionary)item.Clone(), false, con)) { resp.message = "Validation failed."; resp.PushValidationErrors(ValidationErrors); return(resp); } //save if (CrudRepo.Insert(con, item)) { if (LoadItemAfterSave) { //PropertyInfo key = Models.ModelService.GetKeyPropertyInfo(item); //TKey id = Models.ModelService.ChangeType<TKey>(key.GetValue(item)); //CrudSrvc.get //item = CrudSrvc.GetItemAsModel(id); resp.data = item; } resp.success = true; resp.message = "Data added successfully."; } else { resp.message = "System Error :: DB"; } } catch (Exception ex) { Errors.Add(ex.Message); } if (resp.success == false) { resp.PushErrors(CrudRepo.Errors); resp.PushErrors(Errors); resp.PushValidationErrors(ValidationErrors); } return(resp); }
/// <summary> /// Grid filter items /// </summary> /// <param name="data_param"></param> /// <param name="page"></param> /// <param name="pageSize"></param> /// <param name="sort_by"></param> /// <returns>Returns null if fails else object with or without data.</returns> public virtual ResponseCollection GetSearchItems(DynamicDictionary data_param, int page = -1, int pageSize = 20, string sort_by = null) { IEnumerable <dynamic> items = null; int total = 0; DynamicDictionary copy = (DynamicDictionary)data_param.Clone(); ResponseCollection resp = new ResponseCollection(false, string.Empty); using (DbConnect con = new DbConnect()) { //pulling the count; total = SearchRepo.GetSearchItemsCount(con, copy, page, pageSize); if (total > 0) { items = SearchRepo.GetSearchItems(con, data_param, page, pageSize, sort_by); } } if (Errors.Count > 0) { resp.message = "Grid filter data load failed."; resp.PushErrors(Errors); } else { resp.success = true; if (total > 0 && items != null && items.Count() > 0) { resp = ServiceUtility.CaculatePaging(resp, total, page, pageSize); resp.data = items; resp.message = "Search Items loaded successfully."; } else { resp.message = "Grid filter data not found as per search condition"; } } return(resp); }
public virtual async Task <IResponseReport> GetListExportPdf(DynamicDictionary data_param, string reportType, string reportName, string sort_by, IReportBase report = null) { ReponseReport resp = new ReponseReport(false, string.Empty); try { IEnumerable <dynamic> items = null; int total = 0; DynamicDictionary copy = (DynamicDictionary)data_param.Clone(); Dictionary <string, object> officeInfo; string JsonData, JsonOfficeInfo; officeInfo = report.GetOfficeInfo(); officeInfo.Add("current_user", SessionData.user_name); foreach (KeyValuePair <string, object> item in data_param) { string k = item.Key; object v = item.Value; officeInfo.Add(k, v); } using (DbConnect con = new DbConnect()) { total = SearchRepo.GetSearchItemsCount(con, copy, -1, 1); if (total > 0) { items = SearchRepo.GetSearchItems(con, data_param, -1, 1, sort_by); IList <dynamic> list = (IList <dynamic>)items; if (list == null) { resp.isData = false; } } } if (Errors.Count > 0) { resp.message = "Grid filter data load failed."; resp.PushErrors(Errors); } else { resp.success = true; if (total > 0 && items != null && items.Count() > 0) { JsonData = Newtonsoft.Json.JsonConvert.SerializeObject(items); if (report == null) { report = GetReportObject(); } JsonOfficeInfo = Newtonsoft.Json.JsonConvert.SerializeObject(officeInfo); string reportTitle = data_param.GetValueAsString("reportTitle"); report.ReportData = "{\"items\":" + JsonData + ",\"info\":" + JsonOfficeInfo + ",\"title\":" + "\"" + reportTitle + "\"" + "}"; bool status = await report.GenerateReport(reportType, reportName); if (status) { resp.success = true; resp.report_url = report.GeneratedFileUrl; resp.report_name = report.GeneratedFileName; } else { resp.message = report.Error; } } else { resp.message = "Grid filter data not found as per search condition"; } } } catch (Exception ex) { } return(resp); }
/// <summary> /// Performs validation of unique-constraints. Detail on the failure are stored in UniqueErrors Property /// It will use the help of TModel for performing the unique-constraint check. /// </summary> /// <param name="item"></param> /// <returns>Returns the status of the validation.</returns> public virtual bool ValidateUniqueValue(DbConnect con, DynamicDictionary item, IModel validatorModel, bool skipFieldsNotProvided = false) { /** * TODO * 1) disable null check or check if unique constraint is not composite constraint * 2) check unique constraint in edit mode, load all data **/ PropertyInfo key = validatorModel.GetKeyPropertyInfo(); TKey id = item.GetValue <TKey>(key.Name); //if (Conversion.ToInt32(id.ToString()) > 0) // skipFieldsNotProvided = false; //if edit mode checke if (validatorModel.GetType().GetProperty("deleted_uq_code") != null) //tod not equal.. { item["deleted_uq_code"] = 1; } BangoCommand cmd = new BangoCommand(commandType: MyroCommandTypes.StringBuilder); string union = string.Empty; //List<PropertyInfo> uniqueFields = new List<PropertyInfo>(); DictionaryFx <string, PropertyInfo> uniqueFields = new DictionaryFx <string, PropertyInfo>(); //preparing sql DynamicDictionary data_param = null; Bango.Models.Attributes.TableDetailAttribute tabelDetail = validatorModel.GetTableDetail(); foreach (KeyValuePair <string, UniqueConstraint> unique in validatorModel.UniqueFields) { if (unique.Value.Fields.Count == 0) { continue; } bool value_not_provided = false; foreach (string fld in unique.Value.Fields) { if (!item.ContainsKey(fld)) { //1) disable null check or check if unique constraint is not composite constraint ///if (unique.Value.Fields.Count <= 1) if (unique.Value.Fields.Count <= 1) //TODO:Shivashwor modify... for client duplicate data insert OFF... { value_not_provided = true; break; } if (!skipFieldsNotProvided) { //If fld name not exists in validatorModel then if (validatorModel.GetValue(fld) == null) { ///item.Add(fld, null); value_not_provided = true; } else { Type t = validatorModel.GetType().GetProperty(fld).PropertyType; if (t.IsValueType) { item.Add(fld, Activator.CreateInstance(t)); } else { item.Add(fld, null); } } } else { //TODO:Shivashwor modify... for client duplicate data insert OFF... value_not_provided = true; } break; } } if (value_not_provided) { continue; } data_param = (DynamicDictionary)item.Clone(); ///TODO:SHIVASHWOR 15 nov 2015 for Unique value is empty or not... object data_val = data_param.GetValue(unique.Key); if (data_val != null) { if (data_val.ToString().Trim().Length == 0) { continue; } } if (union.Length > 0) { cmd.SqlString.AppendLine(union); } string and = string.Empty; cmd.SqlString.AppendLine(String.Format("SELECT distinct '{0}' unique_constraint, '{2}' error_message FROM {1} {3} WHERE 1=1 " , DbServiceUtility.SafeDBString(unique.Value.Name), tabelDetail.Name , DbServiceUtility.SafeDBString(unique.Value.ErrorMessage) , tabelDetail.Alias)); //CHECKING In if client_id exists in the model for adding the client_id in unique contraint check if the developer has forgot to added PropertyInfo prop_client_id = validatorModel.GetType().GetProperty("client_id"); if (prop_client_id != null) { if (!unique.Value.Fields.Contains("client_id")) { unique.Value.Fields.Add("client_id"); } } foreach (string fld in unique.Value.Fields) { if (validatorModel.GetType().GetProperty(fld) != null) { DbServiceUtility.BindParameter(cmd, fld, data_param, validatorModel.GetType().GetProperty(fld).PropertyType, tabelDetail.Alias, SearchTypes.Equal | SearchTypes.CaseSensetive, string.Empty, true, validatorModel.GetType().GetProperty(fld)); } //cmd.SqlString.AppendFormat(" {1} {0} = @{0}", fld, and);//uniqueFields[fld] = validatorModel.GetType().GetProperty(fld); } if (key.Name.Trim().Length > 0)//PRIMARY KEY Check if n { if (id != null) { //var obj_updateBy = data_param.GetValue("updated_by"); //if (obj_updateBy!= null) DbServiceUtility.BindParameter(cmd, key.Name, data_param, System.Data.DbType.Int32, tabelDetail.Alias, SearchTypes.NotEqual, string.Empty, true, key); } } union = " UNION ALL"; } string finalSql = cmd.FinalSql; IEnumerable <dynamic> lst = null; if (finalSql.Length > 0) { try { lst = con.DB.Query <dynamic>(finalSql, cmd.FinalParameters); } catch (NpgsqlException ex) { Errors.Add(ex.ToString()); LogTrace.WriteErrorLog(ex.ToString()); LogTrace.WriteDebugLog(string.Format("sql which gave exception:\r{0}", ex.Routine)); return(false); } catch (Exception ex) { } //checking for the unique constraint if (lst.Count() > 0) { foreach (DapperRow dr in lst) { DynamicDictionary dic = Conversion.ToDynamicDictionary(dr); DynamicDictionary err = new DynamicDictionary(); err.Add(dic.GetValueAsString("unique_constraint"), dic.GetValue("error_message")); ModelService.PushValidationErros(err, ValidationErrors); } return(false); } } else { //TODO:Shivashwor 01 Nov 2015/ //if edit mode nothing changed after save data occurs // throw new NoSqlStringProvidedException(); } return(true); }
public virtual bool Update(DbConnect con, TKey id, DynamicDictionary data) { //pull old data TModel oldData = new TModel(); ITable <TModel, TKey> tbl = con.GetModelTable <TModel, TKey>(); oldData = tbl.Get(id); //checking if the data is editable by current login or not if (CheckClientID) { if (ValidateForClientData(oldData) == false) { return(false); } } ChangeHistoryHelper <TModel> chngHlpr = null; chngHlpr = new ChangeHistoryHelper <TModel>(AuditActivityTypes.UPDATE); //if CREATED_BY, CREATED_on field exists then update those fields PropertyInfo by = oldData.GetType().GetProperty("updated_by"); if (by != null) { data.SetValue("updated_by", SessionData.user_id); } PropertyInfo on = oldData.GetType().GetProperty("updated_on"); if (on != null) { data.SetValue("updated_on", DateTime.Now); } dynamic cloned = data.Clone(); chngHlpr.CheckChangeChanges(oldData, data); //if no changes then return true if (chngHlpr.Diff.ParameterNames.Count() == 0) { return(true); } int?savedId = null; //chngHlpr.Diff.Add("id", id, DbType.Int32, ParameterDirection.Input); DynamicParameters where = new DynamicParameters(); where.Add("id", id, DbServiceUtility.GetDbType(typeof(TKey))); if (CheckClientID) { PropertyInfo client_id = oldData.GetType().GetProperty("client_id"); if (client_id != null) { where.Add("client_id", SessionData.client_id, DbServiceUtility.GetDbType(client_id.PropertyType)); } } try { savedId = tbl.Update(where, chngHlpr.Diff); if (TrackChanges) { //save the changes chngHlpr.LogChanges(con); } } catch (Npgsql.NpgsqlException ex) { LogTrace.WriteErrorLog(ex.ToString()); LogTrace.WriteDebugLog(string.Format("SQL which gave exception:\r{0}", ex.Routine)); throw ex; } if (savedId > 0) { return(true); } else { return(false); } }