Example #1
0
        /// <summary>
        /// Salva il file sul disco e lo include nel progetto
        /// </summary>
        /// <returns></returns>
        public async Task Save()
        {
            string udsNameSpacePath = string.Concat("Entities\\", _udsNamespace);

            _log.WriteInfo(new LogMessage(string.Format("Salvataggio file: {0}", udsNameSpacePath)), LogCategories);
            await WriteDocument.WriteToDiskAsync(_uds.WorkingProject, _uds.UnitSyntax, udsNameSpacePath, _udsClassName);

            _uds.Document = _uds.WorkingProject.AddDocument(string.Concat(_udsClassName, ".", Languages.cs.ToString()), _uds.UnitSyntax);
            await WriteDocument.WriteToProjectAsync(udsNameSpacePath, _udsClassName, _uds.WorkingProject, _workspace);
        }
        public async Task <HttpResponseMessage> CreateTag(WriteDocument template)
        {
            //model state nao funciona aqui porque não existe [Required] no tipo WriteDocument
            if (IsTemplateIncorrect(template.Template))
            {
                return(CollectionTemplateInvalidResponse());
            }

            var nameFromTemplate        = template.Template.Data[0].Value;
            var projectNameFromTemplate = template.Template.Data[1].Value;

            nameFromTemplate = nameFromTemplate.Replace(" ", "-");
            var isTagPresent = await Context.Tags.AnyAsync(t => t.Name.Equals(nameFromTemplate));

            if (!isTagPresent)
            {
                Context.Tags.Add(new TagModel()
                {
                    Name = nameFromTemplate
                });
            }
            var isTagRelatedToProject = await Context.ProjectTagSet.AnyAsync(p => p.TagName.Equals(nameFromTemplate));

            if (!isTagRelatedToProject)
            {
                Context.ProjectTagSet.Add(new ProjectTagSetModel
                {
                    ProjectName = projectNameFromTemplate,
                    TagName     = nameFromTemplate
                });
            }
            else
            {
                return(Request.BadRequestMessage(new List <ErrorResource.InvalidParams>
                {
                    new ErrorResource.InvalidParams
                    {
                        Name = template.Template.Data[0].Name,
                        Reason = $"A Tag with the name '{nameFromTemplate}' is already associated with the project '{projectNameFromTemplate}'."
                    }
                }));
            }

            await Context.SaveChangesAsync();

            //build siren resource's representation to include in the response
            var dbRecord = await Context.Tags.FindAsync(nameFromTemplate);

            var resource = await BuildResource(projectNameFromTemplate, dbRecord.Name);

            var locationUri = MakeUri <ProjectsController>(c => c.FindSingleProject(nameFromTemplate));

            return(Request.BuildCreatedResourceResponse(resource, locationUri));
        }
        private HttpResponseMessage ProcessNewProject(Template newProjTemplate)
        {
            var ctrler = new ProjectsController
            {
                Configuration = new HttpConfiguration(),
                Request       = new HttpRequestMessage()
            };
            var dataFromBody = new WriteDocument {
                Template = newProjTemplate
            };

            return(ctrler.CreateProject(dataFromBody).Result);
        }
        public CollectionJsonControllerTest()
        {
            reader = new Mock <ICollectionJsonDocumentReader <string> >();
            writer = new Mock <ICollectionJsonDocumentWriter <string> >();

            testReadDocument = new ReadDocument();
            testReadDocument.Collection.Href = new Uri("http://test.com");
            testWriteDocument = new WriteDocument();

            writer.Setup(w => w.Write(It.IsAny <IEnumerable <string> >())).Returns(testReadDocument);
            reader.Setup(r => r.Read(It.IsAny <WriteDocument>())).Returns("Test");
            controller = new TestController(writer.Object, reader.Object);
            controller.ConfigureForTesting(new HttpRequestMessage(HttpMethod.Get, "http://localhost/test/"));
        }
    public async Task <long> FindOrCreateLocationIdByName(string locationName, long teamId)
    {
        if (teamId <= 0)
        {
            throw new ArgumentOutOfRangeException(nameof(teamId));
        }

        string str = await _httpClient.GetStringAsync($"/locations/search?team_id={teamId}");

        ReadDocument rdoc = JsonConvert.DeserializeObject <ReadDocument>(str);


        var target = rdoc.Collection.Items
                     .Select(x => new { Id = long.Parse(x.Data.GetDataByName("id").Value.ToString()), Name = x.Data.GetDataByName("name").Value.ToString() })
                     .Where(x => x.Name.Equals(locationName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

        if (target != null)
        {
            return(target.Id);
        }
        else
        {
            WriteDocument doc = new WriteDocument
            {
                Template = new Template()
            };

            doc.Template.Data.Add(new Data()
            {
                Name = "name", Value = locationName
            });

            doc.Template.Data.Add(new Data()
            {
                Name = "team_id", Value = teamId
            });

            HttpResponseMessage resp = await _httpClient.PostAsJsonAsync("/locations", doc);

            string str2 = await resp.Content.ReadAsStringAsync();

            ReadDocument rdoc2 = JsonConvert.DeserializeObject <ReadDocument>(str2);

            resp.EnsureSuccessStatusCode();

            return(rdoc2.Collection.Items.Select(x => long.Parse(x.Data.GetDataByName("id").Value.ToString())).First());
        }
    }
        public async Task <HttpResponseMessage> CreateProject(WriteDocument template)
        {
            //model state nao funciona aqui porque não tenho [Required] no tipo WriteDocument
            if (IsTemplateIncorrect(template.Template))
            {
                return(CollectionTemplateInvalidResponse());
            }

            const int projectNameIdx = 0;

            var projectName = template.Template.Data[projectNameIdx].Value;

            if (projectName == null)
            {
                return(CollectionTemplateInvalidResponse());
            }
            projectName = projectName.Replace(" ", "-");

            var existsProject = await Context.Projects.AnyAsync(p => p.Name.Equals(projectName));

            if (existsProject)
            {
                return(Request.BadRequestMessage(new List <ErrorResource.InvalidParams>
                {
                    new ErrorResource.InvalidParams
                    {
                        Name = template.Template.Data[projectNameIdx].Name,
                        Reason = $"A project with the name '{projectName}' already exists."
                    }
                }));
            }

            if (!await SaveNewProject(template, projectName))
            {
                return(CollectionTemplateInvalidResponse());
            }

            //build siren resource's representation
            var dbRecord = await Context.Projects.FindAsync(projectName);

            var resource = await BuildProjectResource(dbRecord.Id.ToString(), dbRecord.Name);

            //send 201, representation and location of the new resource
            var locationUri = MakeUri <ProjectsController>(c => c.FindSingleProject(projectName));

            return(Request.BuildCreatedResourceResponse(resource, locationUri));
        }
    public async Task MakeTeamOwnerNonPlayer(long teamId)
    {
        long ownerMemberId = await GetTeamOwner(teamId);

        WriteDocument doc = new WriteDocument
        {
            Template = new Template()
        };

        doc.Template.Data.Add(new Data()
        {
            Name = "is_non_player", Value = true
        });

        HttpResponseMessage resp = await _httpClient.PutAsJsonAsync($"/members/{ownerMemberId}", doc);

        resp.EnsureSuccessStatusCode();
    }
    public async Task <long> CreateTeam(CreateTeamRequest team)
    {
        WriteDocument doc = new WriteDocument
        {
            Template = new Template()
        };

        doc.Template.Data.Add(new Data()
        {
            Name = "name", Value = team.Name
        });
        doc.Template.Data.Add(new Data()
        {
            Name = "sport_id", Value = team.SportId
        });
        doc.Template.Data.Add(new Data()
        {
            Name = "location_country", Value = team.LocationCountry
        });
        doc.Template.Data.Add(new Data()
        {
            Name = "time_zone", Value = team.IANATimeZone
        });
        doc.Template.Data.Add(new Data()
        {
            Name = "location_postal_code", Value = team.LocationPostalCode
        });

        HttpResponseMessage resp = await _httpClient.PostAsJsonAsync("/teams", doc);

        string str = await resp.Content.ReadAsStringAsync();

        ReadDocument rDoc = JsonConvert.DeserializeObject <ReadDocument>(str);

        if (resp.IsSuccessStatusCode)
        {
            return(rDoc.UnpackTeams().First().Id);
        }
        else
        {
            throw new HttpRequestException(rDoc.Collection.Error.Message);
        }
    }
    public async Task CancelEvent(long eventId, bool notifyTeam = true)
    {
        WriteDocument doc = new WriteDocument
        {
            Template = new Template()
        };

        doc.Template.Data.Add(new Data()
        {
            Name = "is_canceled", Value = true
        });

        doc.Template.Data.Add(new Data()
        {
            Name = "notify_team", Value = notifyTeam
        });

        HttpResponseMessage resp = await _httpClient.PutAsJsonAsync($"/events/{eventId}", doc);

        resp.EnsureSuccessStatusCode();
    }
    public async Task <long> CreateAndInviteTeamMember(CreateTeamMemberRequest req)
    {
        long?existingId = await FindTeamMemberIdByEmailAddress(req.TeamId, req.EmailAddress);

        if (existingId.HasValue)
        {
            return(existingId.Value);
        }

        WriteDocument doc = new WriteDocument
        {
            Template = new Template()
        };

        doc.Template.Data.Add(new Data()
        {
            Name = "first_name", Value = req.FirstName
        });
        doc.Template.Data.Add(new Data()
        {
            Name = "last_name", Value = req.LastName
        });
        doc.Template.Data.Add(new Data()
        {
            Name = "team_id", Value = req.TeamId
        });

        if (req.IsManager)
        {
            doc.Template.Data.Add(new Data()
            {
                Name = "is_manager", Value = true
            });
        }

        if (req.IsNonPlayer)
        {
            doc.Template.Data.Add(new Data()
            {
                Name = "is_non_player", Value = true
            });
        }

        HttpResponseMessage resp = await _httpClient.PostAsJsonAsync("/members", doc);

        string str = await resp.Content.ReadAsStringAsync();

        ReadDocument rDoc = JsonConvert.DeserializeObject <ReadDocument>(str);


        long member_id = 0;

        if (resp.IsSuccessStatusCode)
        {
            member_id = rDoc.Collection.Items.Select(x => long.Parse(x.Data.GetDataByName("id").Value.ToString())).First();

            if (!string.IsNullOrWhiteSpace(req.EmailAddress))
            {
                WriteDocument eDoc = new WriteDocument
                {
                    Template = new Template()
                };

                eDoc.Template.Data.Add(new Data()
                {
                    Name = "member_id", Value = member_id
                });
                eDoc.Template.Data.Add(new Data()
                {
                    Name = "email", Value = req.EmailAddress
                });
                eDoc.Template.Data.Add(new Data()
                {
                    Name = "receives_team_emails", Value = true
                });
                eDoc.Template.Data.Add(new Data()
                {
                    Name = "is_hidden", Value = true
                });


                HttpResponseMessage eResp = await _httpClient.PostAsJsonAsync("/member_email_addresses", eDoc);

                string eStr = await resp.Content.ReadAsStringAsync();

                ReadDocument erDoc = JsonConvert.DeserializeObject <ReadDocument>(eStr);

                if (eResp.IsSuccessStatusCode)
                {
                    long emailId = erDoc.Collection.Items.Select(x => long.Parse(x.Data.GetDataByName("id").Value.ToString())).First();

                    long teamOwnerId = await GetTeamOwner(req.TeamId);

                    var inviteCommand = new { team_id = req.TeamId, member_id, introduction = req.InvitationMessage, notify_as_member_id = teamOwnerId };

                    HttpResponseMessage eEviteResp = await _httpClient.PostAsJsonAsync("teams/invite", inviteCommand);

                    ReadDocument evrDoc = JsonConvert.DeserializeObject <ReadDocument>(await resp.Content.ReadAsStringAsync());

                    eEviteResp.EnsureSuccessStatusCode();

                    return(member_id);
                }
                else
                {
                    throw new HttpRequestException(erDoc.Collection.Error.Message);
                }
            }
            else
            {
                throw new HttpRequestException(rDoc.Collection.Error.Message);
            }
        }
        else
        {
            return(member_id);
        }
    }
    public async Task <long> CreateEvent(CreateEventRequest cer)
    {
        long locationId = await FindOrCreateLocationIdByName(cer.LocationName, cer.TeamId);

        WriteDocument doc = new WriteDocument
        {
            Template = new Template()
        };

        if (cer.NotifyTeam)
        {
            doc.Template.Data.Add(new Data()
            {
                Name = "notify_team", Value = cer.NotifyTeam
            });
            doc.Template.Data.Add(new Data()
            {
                Name = "notify_team_as_member_id", Value = await GetTeamOwner(cer.TeamId)
            });
        }

        doc.Template.Data.Add(new Data()
        {
            Name = "team_id", Value = cer.TeamId
        });

        doc.Template.Data.Add(new Data()
        {
            Name = "location_id", Value = locationId
        });

        doc.Template.Data.Add(new Data()
        {
            Name = "is_game", Value = cer.IsGame
        });

        if (cer.DurationMinutes > 0)
        {
            doc.Template.Data.Add(new Data()
            {
                Name = "duration_in_minutes", Value = cer.DurationMinutes
            });
        }

        if (cer.ArriveEarlyMinutes > 0)
        {
            doc.Template.Data.Add(new Data()
            {
                Name = "minutes_to_arrive_early", Value = cer.ArriveEarlyMinutes
            });
        }

        if (cer.IsGame)
        {
            long opponenentId = await FindOrCreateOpponentIdByName(cer.OpponentName, cer.TeamId);

            doc.Template.Data.Add(new Data()
            {
                Name = "opponent_id", Value = opponenentId
            });

            if (!string.IsNullOrWhiteSpace(cer.GameType))
            {
                doc.Template.Data.Add(new Data()
                {
                    Name = "game_type", Value = cer.GameType
                });
                doc.Template.Data.Add(new Data()
                {
                    Name = "game_type_code", Value = cer.GameType == "Home" ? 1 : 2
                });
            }
        }
        else
        {
            doc.Template.Data.Add(new Data()
            {
                Name = "name", Value = cer.Name
            });
        }

        if (!string.IsNullOrWhiteSpace(cer.Label))
        {
            doc.Template.Data.Add(new Data()
            {
                Name = "label", Value = cer.Label
            });
        }

        if (!string.IsNullOrWhiteSpace(cer.Notes))
        {
            doc.Template.Data.Add(new Data()
            {
                Name = "notes", Value = cer.Notes
            });
        }

        if (!string.IsNullOrWhiteSpace(cer.LocationDetails))
        {
            doc.Template.Data.Add(new Data()
            {
                Name = "additional_location_details", Value = cer.LocationDetails
            });
        }

        if (cer.IsTimeTBD)
        {
            doc.Template.Data.Add(new Data()
            {
                Name = "is_tbd", Value = true
            });
            doc.Template.Data.Add(new Data()
            {
                Name = "start_date", Value = cer.StartDate.Date
            });
        }
        else
        {
            doc.Template.Data.Add(new Data()
            {
                Name = "start_date", Value = ConvertToUtc(cer.StartDate)
            });
        }

        HttpResponseMessage resp = await _httpClient.PostAsJsonAsync("/events", doc);

        string str = await resp.Content.ReadAsStringAsync();

        ReadDocument rDoc = JsonConvert.DeserializeObject <ReadDocument>(str);

        if (resp.IsSuccessStatusCode)
        {
            return(rDoc.UnpackEvents().First().Id);
        }
        else
        {
            throw new HttpRequestException(rDoc.Collection.Error.Message);
        }
    }
        public async Task <HttpResponseMessage> CreateComment(string projectName, int issueId, WriteDocument template)
        {
            //assert template
            if (IsTemplateIncorrect(template.Template))
            {
                return(CollectionTemplateInvalidResponse());
            }
            //assert association between project and issue
            if (!await IsIssueRelatedToProject(projectName, issueId))
            {
                return(Request.ResourceNotFoundMessage());
            }
            //assert issue is not "closed"
            var issue =
                await Context.Issues.SingleOrDefaultAsync(i => i.ProjectModel.Name.Equals(projectName) && i.Id == issueId);

            if (issue.State.Equals(IssuesController.ClosedState))
            {
                var details = "A closed issue does not accept comments.";
                return(Request.BadRequestMessage(null, details));
            }

            var contentOfComment = template.Template.Data[0].Value;
            var project          = await Context.Projects.FindAsync(projectName);

            Context.Comments.Add(new CommentModel
            {
                Content      = contentOfComment,
                ProjectModel = project,
                IssueModel   = issue
            });
            await Context.SaveChangesAsync();

            // build the (siren) resource
            var lastIndex = Context.Comments.Where(c => c.IssueModel.Id == issueId).Max(i => (int?)i.Id);
            var model     = await Context
                            .Comments.SingleOrDefaultAsync(c => c.Id == lastIndex.Value &&
                                                           c.IssueModel.Id == issueId &&
                                                           c.ProjectModel.Name.Equals(projectName));

            var resource = BuildCommentResource(projectName, issueId, model);
            var selfLink = MakeUri <CommentsController>(c => c.GetSingleComment(projectName, issueId, model.Id));

            return(Request.BuildCreatedResourceResponse(resource, selfLink));
        }
        public async Task <HttpResponseMessage> CreateIssue(string projectName, WriteDocument template)
        {
            var body = template.Template;

            if (IsTemplateIncorrect(body))
            {
                return(CollectionTemplateInvalidResponse());
            }

            var projectRootEntity = await Context.Projects.FindAsync(projectName);

            if (projectRootEntity == null)
            {
                return(Request.ResourceNotFoundMessage());
            }

            //BadRequest if state is not 'open' or 'closed'
            const int titleIdx = 0, stateIdx = 1, descriptionIdx = 2, tagsIdx = 3;

            if (!IsIssueStateValid(body.Data[stateIdx]?.Value))
            {
                return(BadIssueStateErrorMessage(body, stateIdx));
            }

            int?lastElementIndex = Context.Issues.Max(i => (int?)i.Id);  //used in the making of the URI

            //Tags must belong to the project's set
            if (template.Template.Data.Count > GetTemplateParams())
            {
                var tags      = template.Template.Data[tagsIdx].Value.Split('+');
                var tagModels = tags.Select(tag => new TagModel {
                    Name = tag
                }).ToList();
                //check if each tag is present in the ProjectTag set. if not, returns Error else associate it with the issue
                foreach (var tagModel in tagModels)
                {
                    //verificar existencia no project relativo a este issue
                    if (!await IsTagRelatedToProject(projectName, tagModel))
                    {
                        return(TagNotRelatedToProjectError(body.Data[tagsIdx].Name));
                    }
                    //caso contrario, associa tag com issue
                    var elemIndex = (int)((lastElementIndex == null) ? 1 : lastElementIndex + 1);
                    AssociationBetweenTagAndIssue(tagModel, elemIndex);
                }
            }

            //what to save
            var newResource = new IssueModel
            {
                Title        = body.Data[titleIdx].Value,
                State        = body.Data[stateIdx].Value,
                Description  = body.Data[descriptionIdx].Value,
                ProjectModel = projectRootEntity
            };

            Context.Issues.Add(newResource);

            Context.SaveChanges();

            var issueCreated = await BuildIssueResource(projectName, newResource);

            var locationUri = MakeUri <IssuesController>(c => c.GetSingleIssue(projectName, lastElementIndex.Value));

            return(Request.BuildCreatedResourceResponse(issueCreated, locationUri));
        }