コード例 #1
0
        protected async Task <SaveResult <TDto> > SaveImplementation(TDto dto, string includes = null, string dataSource = null, bool returnObject = true)
        {
            ListParameters listParams = new ListParameters(includes: includes, listDataSource: dataSource);

            var result = new SaveResult <TDto>();

            // See if this is new or an update using the key.
            T item = null;

            object idValue = IdValue(dto);

            if (idValue is int && (int)idValue != 0 || idValue is string && (string)idValue != "")
            {
                item = await DataSource.FindItemAsync(idValue);

                if (item == null)
                {
                    result.WasSuccessful = false;
                    result.Message       =
                        string.Format("Item with {0} = {1} not found.", ClassViewModel.PrimaryKey.Name, IdValue(dto));
                    Response.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
                    return(result);
                }
            }

            // See if we found it.
            if (item == null)
            {
                item = new T();  // This does not work with Lazy Loading because it gives the POCO not the proxy object.
                DataSource.Add(item);
            }

            // Convert all DateTimeOffsets to the correct Time Zone.
            foreach (var prop in DtoViewModel.Properties.Where(f => f.Type.IsDateTimeOffset))
            {
                var typeProperty = dto.GetType().GetProperty(prop.Name);
                // Make sure the property exists. TODO: Check this out for base classes.
                if (typeProperty != null)
                {
                    DateTimeOffset?value = (DateTimeOffset?)typeProperty.GetValue(dto);
                    if (value != null)
                    {
                        dto.GetType().InvokeMember(prop.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
                                                   Type.DefaultBinder, dto, new object[] { TimeZoneInfo.ConvertTime(value.Value, CurrentTimeZone) });
                    }
                }
            }

            // Create a shallow copy.
            var origItem = item.Copy();

            // Allow the user to stop things from saving.
            try
            {
                if (BeforeSave(dto, item))
                {
                    IncludeTree includeTree = null;

                    var original = item.Copy <T>();
                    MapDtoToObj(dto, item, includes);
                    try
                    {
                        SetFingerprint(item);
                        // Run validation in this controller
                        var validateResult = Validate(original, dto, item);
                        // Run validation from the POCO if it implements IValidatable
                        if (typeof(IBeforeSave <T, TContext>).IsAssignableFrom(typeof(T)))
                        {
                            var itemAsBeforeSave = item as IBeforeSave <T, TContext>;
                            validateResult.Merge(itemAsBeforeSave.BeforeSave(original, Db, User, includes));
                        }

                        if (validateResult.WasSuccessful)
                        {
                            await Db.SaveChangesAsync();

                            // Pull the object to get any changes.
                            var idString = IdValue(item).ToString();
                            listParams.AddFilter("id", idString);
                            var itemResult = await GetUnmapped(idString, listParams);

                            item        = itemResult.Item1;
                            includeTree = itemResult.Item2;

                            // Call the AfterSave method to support special cases.
                            var reloadItem = AfterSave(dto, item, origItem, Db);

                            // Call PostSave if the object has that.
                            if (typeof(IAfterSave <T, TContext>).IsAssignableFrom(typeof(T)))
                            {
                                var itemAsAfterSave = item as IAfterSave <T, TContext>;
                                itemAsAfterSave.AfterSave(original, Db, User, includes);
                            }

                            if (reloadItem && returnObject)
                            {
                                itemResult = await GetUnmapped(idString, listParams);

                                item        = itemResult.Item1;
                                includeTree = itemResult.Item2;
                            }

                            result.WasSuccessful = true;
                        }
                        else
                        {
                            result.WasSuccessful = false;
                            result.Message       = validateResult.Message;
                            if (validateResult.ReturnObject != null)
                            {
                                result.Object = MapObjToDto(validateResult.ReturnObject, includes);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        //Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                        result = new SaveResult <TDto>(ex);
                        //Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
                    }
                    // Get the key back.
                    if (item != null)
                    {
                        result.Object = MapObjToDto(item, includes, includeTree);
                    }
                }
                else
                {
                    result.WasSuccessful = false;
                    result.Message       = "Canceled";
                    //Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
                }
            }
            catch (Exception ex)
            {
                result.WasSuccessful = false;
                result.Message       = ex.Message;
            }

            return(result);
        }
コード例 #2
0
ファイル: CaseController.g.cs プロジェクト: upta/Coalesce
 public virtual Task <ListResult <CaseDtoGen> > List(
     ListParameters parameters,
     IDataSource <Coalesce.Domain.Case> dataSource)
 => ListImplementation(parameters, dataSource);
コード例 #3
0
ファイル: CaseController.g.cs プロジェクト: upta/Coalesce
 public virtual Task <string> CsvText(
     ListParameters parameters,
     IDataSource <Coalesce.Domain.Case> dataSource)
 => CsvTextImplementation(parameters, dataSource);
コード例 #4
0
 // Returns records of all extension calls that are in progress, ordered by start time in descending order.
 public Task <ActiveCallsResponse> List(ListParameters parameters)
 {
     return(List(parameters as object));
 }
コード例 #5
0
 protected override IQueryable <Coalesce.Domain.CaseProduct> GetListDataSource(ListParameters parameters)
 {
     return(base.GetListDataSource(parameters));
 }
コード例 #6
0
 public virtual Task <ListResult <Coalesce.Domain.CaseDto> > List(
     ListParameters parameters,
     [DeclaredFor(typeof(Coalesce.Domain.CaseDto))] IDataSource <Coalesce.Domain.Case> dataSource)
 => ListImplementation(parameters, dataSource);
コード例 #7
0
 public virtual Task <string> CsvText(
     ListParameters parameters,
     [DeclaredFor(typeof(Coalesce.Domain.CaseDto))] IDataSource <Coalesce.Domain.Case> dataSource)
 => CsvTextImplementation(parameters, dataSource);
コード例 #8
0
 public virtual Task <ListResult <ApplicationUserDtoGen> > List(
     ListParameters parameters,
     IDataSource <CoalescePlayground.Data.Models.ApplicationUser> dataSource)
 => ListImplementation(parameters, dataSource);
コード例 #9
0
 public virtual Task <FileResult> CsvDownload(
     ListParameters parameters,
     IDataSource <CoalescePlayground.Data.Models.ApplicationUser> dataSource)
 => CsvDownloadImplementation(parameters, dataSource);
コード例 #10
0
 protected override IQueryable <Coalesce.TaskListSample.Data.Models.Blog> GetListDataSource(ListParameters parameters)
 {
     return(base.GetListDataSource(parameters));
 }
コード例 #11
0
 // Returns list of chats where user is a participant.
 public Task <GlipChatsList> List(ListParameters parameters)
 {
     return(List(parameters as object));
 }
コード例 #12
0
 // <p style='font-style:italic;'></p><p></p><h4>Required Permissions</h4><table class='fullwidth'><thead><tr><th>Permission</th><th>Description</th></tr></thead><tbody><tr><td class='code'>ReadAccounts</td><td>Viewing user account info (including name, business name, address and phone number/account number)</td></tr></tbody></table><h4>Usage Plan Group</h4><p>Light</p>
 public Task <DepartmentMemberList> List(ListParameters parameters)
 {
     return(List(parameters as object));
 }
コード例 #13
0
 // Synchronizes call log records
 public Task <CallLogSync> List(ListParameters parameters)
 {
     return(List(parameters as object));
 }
コード例 #14
0
 // Returns list of licenses for a specific user.
 public Task <LicenseList> List(ListParameters parameters)
 {
     return(List(parameters as object));
 }
コード例 #15
0
 // Get Extension Phone Numbers
 public Task <ListResponse> List(ListParameters parameters)
 {
     return(List(parameters as object));
 }
コード例 #16
0
 public virtual Task <string> CsvText(
     ListParameters parameters,
     IDataSource <CoalescePlayground.Data.Models.ApplicationUser> dataSource)
 => CsvTextImplementation(parameters, dataSource);
コード例 #17
0
 // Returns user personal contacts.
 public Task <ContactList> List(ListParameters parameters)
 {
     return(List(parameters as object));
 }
コード例 #18
0
 // <p style='font-style:italic;'>Since 1.0.0</p><p>Returns the list of extensions created for a particular account. All types of extensions are included in this list.</p><h4>Required Permissions</h4><table class='fullwidth'><thead><tr><th>Permission</th><th>Description</th></tr></thead><tbody><tr><td class='code'>ReadAccounts</td><td>Viewing user account info (including name, business name, address and phone number/account number)</td></tr></tbody></table><h4>API Group</h4><p>Medium</p>
 public Task <GetExtensionListResponse> List(ListParameters parameters)
 {
     return(List(parameters as object));
 }
コード例 #19
0
 public virtual Task <FileResult> CsvDownload(
     ListParameters parameters,
     [DeclaredFor(typeof(Coalesce.Domain.CaseDto))] IDataSource <Coalesce.Domain.Case> dataSource)
 => CsvDownloadImplementation(parameters, dataSource);
コード例 #20
0
 public virtual Task <ListResult <StreamDtoGen> > List(
     ListParameters parameters,
     IDataSource <MMDash.Data.Models.Stream> dataSource)
 => ListImplementation(parameters, dataSource);
コード例 #21
0
 // <p style='font-style:italic;'>Since 1.0.4 (Release 5.13)</p><p>Provides facilities to synchronize mailbox content stored externally with server state.</p><h4>Required Permissions</h4><table class='fullwidth'><thead><tr><th>Permission</th><th>Description</th></tr></thead><tbody><tr><td class='code'>ReadMessages</td><td>Viewing user messages</td></tr></tbody></table><h4>Usage Plan Group</h4><p>Light</p>
 public Task <GetMessageSyncResponse> List(ListParameters parameters)
 {
     return(List(parameters as object));
 }
コード例 #22
0
 public virtual Task <FileResult> CsvDownload(
     ListParameters parameters,
     IDataSource <MMDash.Data.Models.Stream> dataSource)
 => CsvDownloadImplementation(parameters, dataSource);
コード例 #23
0
        public async Task <ActionResult <ExchangeRateInformation> > GetHistoricalExchangeRates([FromQuery] ListParameters parameters)
        {
            var result = await _mediator.Send(new GetHistoricalData.Query(parameters.Dates, parameters.BaseCurrency, parameters.TargetCurrency));

            if (result.IsEmpty)
            {
                return(NotFound());
            }

            return(result.ExchangeRateInformation);
        }
コード例 #24
0
 public virtual Task <string> CsvText(
     ListParameters parameters,
     IDataSource <MMDash.Data.Models.Stream> dataSource)
 => CsvTextImplementation(parameters, dataSource);
コード例 #25
0
 // Returns call queue group list
 public Task <CallQueues> List(ListParameters parameters)
 {
     return(List(parameters as object));
 }
コード例 #26
0
 // <p style='font-style:italic;'>Since 1.0.7 (Release 5.16)</p><p>Returns the list of extension phone numbers used for call forwarding and call flip. The returned list contains all the extension phone numbers that are used for call forwarding and call flip.</p><h4>Required Permissions</h4><table class='fullwidth'><thead><tr><th>Permission</th><th>Description</th></tr></thead><tbody><tr><td class='code'>ReadAccounts</td><td>Viewing user account info (including name, business name, address and phone number/account number)</td></tr></tbody></table><h4>Usage Plan Group</h4><p>Light</p>
 public Task <GetExtensionForwardingNumberListResponse> List(ListParameters parameters)
 {
     return(List(parameters as object));
 }
コード例 #27
0
ファイル: CaseController.g.cs プロジェクト: upta/Coalesce
 public virtual Task <FileResult> CsvDownload(
     ListParameters parameters,
     IDataSource <Coalesce.Domain.Case> dataSource)
 => CsvDownloadImplementation(parameters, dataSource);
コード例 #28
0
 // <p style='font-style:italic;'>Since 1.0.28 (Release 8.4)</p><p>Returns list of posts.</p><h4>Required Permissions</h4><table class='fullwidth'><thead><tr><th>Permission</th><th>Description</th></tr></thead><tbody><tr><td class='code'>Glip</td><td>Availability of Glip</td></tr></tbody></table><h4>API Group</h4><p>Light</p>
 public Task <GlipPosts> List(ListParameters parameters)
 {
     return(List(parameters as object));
 }
コード例 #29
0
 public virtual Task <ListResult <TriviaBoardDtoGen> > List(
     ListParameters parameters,
     IDataSource <TriviaGame.Data.Models.TriviaBoard> dataSource)
 => ListImplementation(parameters, dataSource);
コード例 #30
0
        protected IQueryable <T> AddFilters(IQueryable <T> result, ListParameters listParameters)
        {
            // Add key value pairs where = is used.
            // TODO: Fix for SQL Injection
            foreach (var clause in listParameters.Filters)
            {
                var prop = ClassViewModel.PropertyByName(clause.Key);
                if (prop != null)
                {
                    result = DatabaseCompareExpression(result, prop, clause.Value, CurrentTimeZone);
                }
                else
                {
                    // This property was not recognized as a valid property name for this object.
                    // TODO: Do something about this.
                }
            }
            // Add more free form filters.
            // TODO: Fix for SQL Injection
            if (!string.IsNullOrWhiteSpace(listParameters.Where))
            {
                result = result.Where(listParameters.Where);
            }

            // Add general search filters.
            // These search specified fields in the class
            if (!string.IsNullOrWhiteSpace(listParameters.Search))
            {
                // See if the user has specified a field with a colon and search on that first
                bool termFound = false;
                if (listParameters.Search.Contains(":"))
                {
                    var field = listParameters.Search.Split(new string[] { ":" }, StringSplitOptions.None)[0];
                    var prop  = ClassViewModel.Properties.FirstOrDefault(f => string.Compare(f.Name, field, true) == 0 || string.Compare(f.DisplayName, field, true) == 0);
                    var value = listParameters.Search.Split(new string[] { ":" }, StringSplitOptions.None)[1].Trim();
                    if (prop != null && !string.IsNullOrWhiteSpace(value) && !prop.Type.IsEnum) // Search not supported on enum.
                    {
                        value = value.EscapeStringLiteralForLinqDynamic();
                        var expressions = new List <string>();
                        foreach (var kvp in prop.SearchTerms(1))
                        {
                            // Only strings work reliably
                            if (kvp.Value.Type.IsString)
                            {
                                if (kvp.Key.Contains("[]."))
                                {
                                    var parts = kvp.Key.Split(new[] { "[]." }, StringSplitOptions.RemoveEmptyEntries);
                                    var expr  = $@"{parts[0]}.Count({parts[1]}.ToString().{string.Format(kvp.Value.SearchMethodName, value)}";
                                    expressions.Add(expr);
                                }
                                else if (prop.Type.IsString)
                                {
                                    var expr = $@"({kvp.Key} != null && {kvp.Key}.{string.Format(kvp.Value.SearchMethodName, value)})";
                                    expressions.Add(expr);
                                }
                                else
                                {
                                    var expr = $@"{kvp.Key}.ToString().{string.Format(kvp.Value.SearchMethodName, value)}";
                                    expressions.Add(expr);
                                }
                            }
                        }
                        // Join these together with an 'or'
                        if (expressions.Any())
                        {
                            string finalSearchClause = string.Join(" || ", expressions);
                            result    = result.Where(finalSearchClause);
                            termFound = true;
                        }
                    }
                }

                // This uses the default search properties based on the attributes and defaults (name and ID for example).
                if (!termFound)
                {
                    var completeSearchClauses = new List <string>();
                    // Handle the split on spaces first because it will be done differently with ands and ors.
                    if (ClassViewModel.SearchProperties().Any(f => f.Value.SearchIsSplitOnSpaces))
                    {
                        var splitSearchClauses = new List <string>();

                        var clauses = listParameters.Search
                                      .Split(new string[] { " ", ", ", " ," }, StringSplitOptions.RemoveEmptyEntries)
                                      .Select(c => c.EscapeStringLiteralForLinqDynamic());

                        foreach (var clause in clauses)
                        {
                            var searchClauses = new List <string>();
                            foreach (var prop in ClassViewModel.SearchProperties().Where(f => f.Value.SearchIsSplitOnSpaces))
                            {
                                string expr;
                                if (prop.Value.PureType.IsString)
                                {
                                    if (prop.Key.Contains("[]."))
                                    {
                                        var parts = prop.Key.Split(new[] { "[]." }, StringSplitOptions.RemoveEmptyEntries);
                                        expr = $@"{parts[0]}.Count({parts[1]}.{string.Format(prop.Value.SearchMethodName, clause)}) > 0";
                                    }
                                    else
                                    {
                                        expr = $"({prop.Key} != null && {prop.Key}.{string.Format(prop.Value.SearchMethodName, clause)})";
                                    }
                                }
                                else
                                {
                                    if (prop.Key.Contains("[]."))
                                    {
                                        var parts = prop.Key.Split(new[] { "[]." }, StringSplitOptions.RemoveEmptyEntries);
                                        expr = $@"{parts[0]}.Count({parts[1]}.ToString().{string.Format(prop.Value.SearchMethodName, clause)}) > 0";
                                    }
                                    else
                                    {
                                        expr = $@"{prop.Key}.ToString().{string.Format(prop.Value.SearchMethodName, clause)}";
                                    }
                                }
                                searchClauses.Add(expr);
                            }
                            if (searchClauses.Count > 0)
                            {
                                splitSearchClauses.Add("( " + string.Join(" || ", searchClauses) + " )");
                            }
                        }
                        completeSearchClauses.Add("( " + string.Join(" && ", splitSearchClauses) + " )");
                    }

                    // Handle not split on spaces with simple ors.
                    if (ClassViewModel.SearchProperties().Any(f => !f.Value.SearchIsSplitOnSpaces))
                    {
                        var clause = listParameters.Search.EscapeStringLiteralForLinqDynamic();
                        foreach (var prop in ClassViewModel.SearchProperties().Where(f => !f.Value.SearchIsSplitOnSpaces))
                        {
                            int temp;
                            if (prop.Value.PureType.IsString)
                            {
                                string expr;
                                if (prop.Key.Contains("[]."))
                                {
                                    var parts = prop.Key.Split(new[] { "[]." }, StringSplitOptions.RemoveEmptyEntries);
                                    expr = $@"{parts[0]}.Count({parts[1]}.{string.Format(prop.Value.SearchMethodName, clause)}) > 0";
                                }
                                else
                                {
                                    expr = $"({prop.Key} != null && {prop.Key}.{string.Format(prop.Value.SearchMethodName, clause)})";
                                }
                                completeSearchClauses.Add(expr);
                            }
                            else if (int.TryParse(clause, NumberStyles.Integer, CultureInfo.CurrentCulture, out temp))
                            {
                                string expr;
                                if (prop.Key.Contains("[]."))
                                {
                                    var parts = prop.Key.Split(new[] { "[]." }, StringSplitOptions.RemoveEmptyEntries);
                                    expr = $@"{parts[0]}.Count({parts[1]} = {clause}) > 0";
                                }
                                else
                                {
                                    expr = $"{prop.Key} = {clause}";
                                }
                                completeSearchClauses.Add(expr);
                            }
                        }
                    }

                    if (completeSearchClauses.Any())
                    {
                        string finalSearchClause = string.Join(" || ", completeSearchClauses);
                        result = result.Where(finalSearchClause);
                    }
                }
            }
            return(result);
        }