public object Any(RegisterAutoQueryService request)
        {
            var client   = new JsonServiceClient(request.BaseUrl);
            var response = client.Get(new AutoQueryMetadata());

            if (!response.Config.IsPublic)
            {
                throw HttpError.Conflict("This service does not permit publishing");
            }

            var service = response.Config.ConvertTo <AutoQueryService>();

            var existingService = Db.Single <AutoQueryService>(q => q.ServiceBaseUrl == request.BaseUrl);

            if (existingService != null)
            {
                existingService.PopulateWith(response.Config);
                existingService.LastModified = DateTime.UtcNow;
                Db.Update(existingService);
                service = existingService;
            }
            else
            {
                service.Created  = service.LastModified = DateTime.UtcNow;
                service.IsActive = true;
                Db.Save(service);
            }

            ContentCache.ClearAll();

            return(new RegisterAutoQueryServiceResponse
            {
                Result = service
            });
        }
        public CreateSubscriptionResponse Post(CreateSubscription request)
        {
            var now           = SystemTime.UtcNow.ToNearestSecond();
            var subscriptions = request.Events.Select(ev => new WebhookSubscription
            {
                Config              = request.Config,
                Name                = request.Name,
                IsActive            = true,
                CreatedDateUtc      = now,
                LastModifiedDateUtc = now,
                CreatedById         = Caller.UserId,
                Event               = ev
            }).ToList();

            subscriptions.ForEach(sub =>
            {
                if (Store.Get(sub.CreatedById, sub.Event) != null)
                {
                    throw HttpError.Conflict(Resources.SubscriptionService_DuplicateRegistration.Fmt(sub.Event));
                }

                var id = Store.Add(sub);
                sub.Id = id;

                logger.InfoFormat(@"[ServiceStack.Webhooks.ServiceInterface.SubscriptionService] Created subscription {0} to event {1} by user {2}", sub.Id, sub.Event, Caller.UserId);
            });

            return(new CreateSubscriptionResponse
            {
                Subscriptions = subscriptions
            });
        }
Beispiel #3
0
        public object Any(StoreRequest request)
        {
            CheckServerObject();

            if (SConfig.Server.AcceptingObjects)
            {
                //verify object
                if (request.Item != null)
                {
                    if (request.Item.Verify())
                    {
                        SConfig.Server.StoreCache.AddOrUpdate(request.Item.ComputedHash, request.Item, request.ExpireAt);
                        return(HttpResult.Status201Created("Stored", null));
                    }
                    else
                    {
                        return(HttpError.Conflict("Hash was invalid"));
                    }
                }
            }

            //didn't add the item
            return(new StoreResponse()
            {
                ItemAdded = false
            });
        }
Beispiel #4
0
        public override async Task <object> AuthenticateAsync(IServiceBase authService, IAuthSession session, Authenticate request, CancellationToken token = default)
        {
            var authRepo = HostContext.AppHost.GetAuthRepositoryAsync(authService.Request);

#if NET472 || NETCORE
            await using (authRepo as IAsyncDisposable)
#else
            using (authRepo as IDisposable)
#endif
            {
                var apiKey = GetApiKey(authService.Request, request.Password);
                ValidateApiKey(authService.Request, apiKey);

                if (string.IsNullOrEmpty(apiKey.UserAuthId))
                {
                    throw HttpError.Conflict(ErrorMessages.ApiKeyIsInvalid.Localize(authService.Request));
                }

                var userAuth = await authRepo.GetUserAuthAsync(apiKey.UserAuthId, token).ConfigAwait();

                if (userAuth == null)
                {
                    throw HttpError.Unauthorized(ErrorMessages.UserForApiKeyDoesNotExist.Localize(authService.Request));
                }

                if (await IsAccountLockedAsync(authRepo, userAuth, token: token).ConfigAwait())
                {
                    throw new AuthenticationException(ErrorMessages.UserAccountLocked.Localize(authService.Request));
                }

                await session.PopulateSessionAsync(userAuth, authRepo, token).ConfigAwait();

                if (session.UserAuthName == null)
                {
                    session.UserAuthName = userAuth.UserName ?? userAuth.Email;
                }

                var response = await OnAuthenticatedAsync(authService, session, null, null, token).ConfigAwait();

                if (response != null)
                {
                    return(response);
                }

                authService.Request.Items[Keywords.ApiKey] = apiKey;

                return(new AuthenticateResponse
                {
                    UserId = session.UserAuthId,
                    UserName = session.UserName,
                    SessionId = session.Id,
                    DisplayName = session.DisplayName
                                  ?? session.UserName
                                  ?? $"{session.FirstName} {session.LastName}".Trim(),
                    ReferrerUrl = authService.Request.GetReturnUrl(),
                });
            }
        }
Beispiel #5
0
        public async Task <CustomUserAuth> GetOrCreateUser(UserVoiceUser user)
        {
            if (user == null)
            {
                return(null);
            }

            var dbUser = await Db.SingleAsync <CustomUserAuth>(x => x.Email == user.Email ||
                                                               (x.RefSource == UserVoiceSource && x.RefId == user.Id));

            if (dbUser != null)
            {
                return(dbUser);
            }

            var userNameFromEmail  = user.Email.LeftPart('@');
            var potentialUserNames = new[] {
                userNameFromEmail,
                user.Name.Replace(" ", ""),
                user.Name.Replace(" ", "-"),
                userNameFromEmail + ".uv",
            };

            var takenUserNames = await Db.ColumnAsync <string>(Db.From <CustomUserAuth>()
                                                               .Where(x => potentialUserNames.Contains(x.UserName))
                                                               .Select(x => x.UserName));

            var bestUserName = potentialUserNames.FirstOrDefault(x => !takenUserNames.Contains(x));

            if (bestUserName == null)
            {
                throw HttpError.Conflict("Could not generate unique username, please specify one for UserVoice User: "******"uservoice",
                RefId             = user.Id,
                RefUrn            = $"urn:uservoice:user:{user.Id}",
                CreatedBy         = session.UserName,
                CreatedDate       = user.CreatedAt,
                ModifiedDate      = user.UpdatedAt,
            };

            newUser.Id = (int)await Db.InsertAsync(newUser, selectIdentity : true);

            return(newUser);
        }
Beispiel #6
0
        public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
        {
            var authRepo = HostContext.AppHost.GetAuthRepository(authService.Request);

            using (authRepo as IDisposable)
            {
                var apiKey = GetApiKey(authService.Request, request.Password);
                ValidateApiKey(authService.Request, apiKey);

                if (string.IsNullOrEmpty(apiKey.UserAuthId))
                {
                    throw HttpError.Conflict(ErrorMessages.ApiKeyIsInvalid.Localize(authService.Request));
                }

                var userAuth = authRepo.GetUserAuth(apiKey.UserAuthId);
                if (userAuth == null)
                {
                    throw HttpError.Unauthorized(ErrorMessages.UserForApiKeyDoesNotExist.Localize(authService.Request));
                }

                if (IsAccountLocked(authRepo, userAuth))
                {
                    throw new AuthenticationException(ErrorMessages.UserAccountLocked.Localize(authService.Request));
                }

                session.PopulateSession(userAuth, authRepo);

                if (session.UserAuthName == null)
                {
                    session.UserAuthName = userAuth.UserName ?? userAuth.Email;
                }

                var response = OnAuthenticated(authService, session, null, null);
                if (response != null)
                {
                    return(response);
                }

                authService.Request.Items[Keywords.ApiKey] = apiKey;

                return(new AuthenticateResponse
                {
                    UserId = session.UserAuthId,
                    UserName = session.UserName,
                    SessionId = session.Id,
                    DisplayName = session.DisplayName
                                  ?? session.UserName
                                  ?? $"{session.FirstName} {session.LastName}".Trim(),
                    ReferrerUrl = authService.Request.GetReturnUrl(),
                });
            }
        }
        public async Task<object> PostAsync(CreateProduct request)
        {
            var existingProduct = await _productsRepository.GetByIdsAsync(new int[] { request.CatalogNumber });
            if(existingProduct.FirstOrDefault() != null)
            {
                throw HttpError.Conflict($"Product with Catalog Number: {request.CatalogNumber} already exists.");
            }

            var product = request.ConvertTo<Product>();
            await _productsRepository.AddAsync(product);

            return new CreateProductResponse();
        }
Beispiel #8
0
        public AddCarResponse Post(AddCar request)
        {
            var car = _carService.Get(x => x.CarCode == request.CarCode);

            if (car != null)
            {
                throw HttpError.Conflict($"Duplicate CarCode");
            }
            var carDetails = _carService.Create(request.ConvertTo <Car>());

            return(new AddCarResponse {
                Id = carDetails.Id
            });
        }
        public HelloResponse Any(Hello request)
        {
            if (request.Name.Contains("ex"))
            {
                //                throw new ServiceResponseException("error 123");

                throw HttpError.Conflict("error 222");
            }

            //            return new HelloResponse { Result = $"Hello, {request.Name}" };

            return(new HelloResponse {
                Result = _helloBiz.Hello(request.Name)
            });
        }
Beispiel #10
0
        public static void FilterUpdateTechRequest(IRequest req, IResponse res, UpdateTechnology dto)
        {
            var dbFactory = req.TryResolve <IDbConnectionFactory>();

            if (req.Verb == "PUT")
            {
                using (var db = dbFactory.OpenDbConnection())
                {
                    //Check unqiue name
                    var exists = db.Single <Technology>(x => x.Name.ToLower() == dto.Name.ToLower());
                    if (exists != null && exists.Id != dto.Id)
                    {
                        throw HttpError.Conflict("A Technology with that name already exists");
                    }
                }
            }
        }
        private PlayerJoinGameResponse JoinGame(PlayerJoinGame request)
        {
            var result      = new PlayerJoinGameResponse();
            var game        = Cache.Get <CardGame>(request.GameId);
            var allGames    = Cache.Get <AllGames>(AllGamesSummaries);
            var gameSummary = allGames.Games.Single(x => x.GameId == request.GameId);

            if (game.PlayerOneId != null && game.PlayerTwoId != null)
            {
                throw HttpError.Conflict("Game full");
            }

            if (game.PlayerOneId == null)
            {
                game.PlayerOneId = request.PlayerId;
                game.PlayerOne   = new GamePlayer
                {
                    DisplayName = request.PlayerDisplayerName,
                    Hand        = game.Deck.Deal(2)
                };
                gameSummary.HasPlayerOne = true;
            }
            else
            {
                game.PlayerTwoId = request.PlayerId;
                game.PlayerTwo   = new GamePlayer
                {
                    DisplayName = request.PlayerDisplayerName,
                    Hand        = game.Deck.Deal(2)
                };
                gameSummary.HasPlayerTwo = true;
            }

            Cache.Set(AllGamesSummaries, allGames);

            game.Events.Add(new CardGameEvent
            {
                ClientId = request.PlayerId,
                GameId   = request.GameId,
                Message  = "Player {0} has entered the game.".Fmt(request.PlayerDisplayerName),
                Type     = "JOIN"
            });

            Cache.Set(request.GameId, game, TimeSpan.FromHours(1));
            return(result);
        }
Beispiel #12
0
    public void RequestFilter(IRequest req, IResponse res, object requestDto)
    {
        SomethingRequest somethingRequestDto = requestDto as SomethingRequest;

        if (somethingRequestDto == null)
        {
            return;
        }
        // Verify the code
        // Replace with suitable logic
        // If you need the database your wire it up from the IoC
        // i.e. HostContext.TryResolve<IDbConnectionFactory>();
        bool isUnique = ...
                        if (!isUnique)
        {
            throw HttpError.Conflict("This record already exists");
        }
    }
Beispiel #13
0
        public ExecOnceOnly(IRedisClientsManager redisManager, string hashKey, string correlationId)
        {
            redisManager.ThrowIfNull("redisManager");
            hashKey.ThrowIfNull("hashKey");

            this.hashKey       = hashKey;
            this.correlationId = correlationId;

            if (correlationId != null)
            {
                redis = redisManager.GetClient();
                var exists = !redis.SetEntryInHashIfNotExists(hashKey, correlationId, Flag);
                if (exists)
                {
                    throw HttpError.Conflict(ErrorMessages.RequestAlreadyProcessedFmt.Fmt(correlationId));
                }
            }
        }
Beispiel #14
0
        public async Task <object> Post(RequestOrganizationMemberInvite request)
        {
            if (request.OrganizationId <= 0)
            {
                throw new ArgumentNullException(nameof(request.OrganizationId));
            }

            var user   = GetUser();
            var userId = user.GetUserId();

            var memberExists = Db.Exists <OrganizationMember>(x =>
                                                              x.UserId == userId && x.OrganizationId == request.OrganizationId);

            if (memberExists)
            {
                throw HttpError.Conflict("Already a member");
            }

            var inviteExists = Db.Exists <OrganizationMemberInvite>(x =>
                                                                    x.UserId == userId && x.OrganizationId == request.OrganizationId);

            if (inviteExists)
            {
                throw HttpError.Conflict("Member Invite already requested");
            }

            await Db.InsertAsync(new OrganizationMemberInvite
            {
                UserId         = userId,
                UserName       = user.UserName,
                OrganizationId = request.OrganizationId,
                Created        = DateTime.Now,
            });

            SendSystemEmail(nameof(RequestOrganizationMemberInvite),
                            $"@{user.UserName} requested member invite for {request.OrganizationId}");

            ClearOrganizationCaches();

            return(new RequestOrganizationMemberInviteResponse
            {
                OrganizationId = request.OrganizationId,
            });
        }
Beispiel #15
0
        public object Any(ThrowType request)
        {
            switch (request.Type ?? "Exception")
            {
            case "Exception":
                throw new Exception(request.Message ?? "Server Error");

            case "NotFound":
                throw HttpError.NotFound(request.Message ?? "What you're looking for isn't here");

            case "Unauthorized":
                throw HttpError.Unauthorized(request.Message ?? "You shall not pass!");

            case "Conflict":
                throw HttpError.Conflict(request.Message ?? "We haz Conflict!");

            case "NotImplementedException":
                throw new NotImplementedException(request.Message ?? "Not implemented yet, try again later");

            case "ArgumentException":
                throw new ArgumentException(request.Message ?? "Client Argument Error");

            case "AuthenticationException":
                throw new AuthenticationException(request.Message ?? "We haz issue Authenticatting");

            case "UnauthorizedAccessException":
                throw new UnauthorizedAccessException(request.Message ?? "You shall not pass!");

            case "OptimisticConcurrencyExceptieon":
                throw new OptimisticConcurrencyException(request.Message ?? "Sorry too optimistic");

            case "UnhandledException":
                throw new FileNotFoundException(request.Message ?? "File was never here");

            case "RawResponse":
                Response.StatusCode        = 418;
                Response.StatusDescription = request.Message ?? "On a tea break";
                Response.Close();
                break;
            }

            return(request);
        }
Beispiel #16
0
        public async Task <ImportUserResponse> Any(ImportUser request)
        {
            if (string.IsNullOrEmpty(request.Email) && string.IsNullOrEmpty(request.UserName))
            {
                throw new ArgumentNullException(nameof(request.Email));
            }

            if (string.IsNullOrEmpty(request.RefSource))
            {
                throw new ArgumentNullException(nameof(request.RefSource));
            }

            if (string.IsNullOrEmpty(request.RefIdStr) && request.RefId == null)
            {
                throw new ArgumentNullException(nameof(request.RefId));
            }

            var existingUser =
                (string.IsNullOrEmpty(request.Email) ? null : AuthRepository.GetUserAuthByUserName(request.Email))
                ?? (string.IsNullOrEmpty(request.UserName) ? null : AuthRepository.GetUserAuthByUserName(request.UserName));

            if (existingUser != null)
            {
                throw HttpError.Conflict("Email and UserName must be unique");
            }

            var session = SessionAs <CustomUserSession>();

            var user = request.ConvertTo <CustomUserAuth>();

            user.CreatedDate = user.ModifiedDate = DateTime.Now;
            user.CreatedBy   = session.UserName;

            var userId = (int)await Db.InsertAsync(user, selectIdentity : true);

            return(new ImportUserResponse {
                Id = userId
            });
        }
Beispiel #17
0
 public static Exception CommandOptionAlreadyExists(string OptionName) =>
 HttpError.Conflict(ErrMsg.CommandOptionAlreadyExists(OptionName));
Beispiel #18
0
        public static Response <Pedido> Patch(this Pedido request,
                                              Factory factory,
                                              IHttpRequest httpRequest)
        {
            List <string> actions = new List <string>(new string[] { "ENVIAR", "ACEPTAR", "ANULAR" });

            var action = httpRequest.PathInfo.Substring(httpRequest.PathInfo.LastIndexOf("/") + 1).ToUpper();

            if (actions.IndexOf(action) < 0)
            {
                throw HttpError.Unauthorized(string.Format("Operacion: '{0}' no autorizada en Ofertas", action));
            }

            var session = httpRequest.GetSession();

            factory.Execute(proxy => {
                using (proxy.AcquireLock(request.GetLockKey(), BL.LockSeconds))
                {
                    var old = proxy.FirstOrDefaultById <Pedido>(request.Id);

                    var userSesssion = httpRequest.GetSession();

                    if (!(old.IdCreadoPor == int.Parse(userSesssion.UserAuthId) ||
                          userSesssion.HasRole(BL.RoleCoordinador)))
                    {
                        throw HttpError.Unauthorized(string.Format("Usuario '{0}' No puede  ejecutar '{1}' en las ofertas creadas por:'{2}' ",
                                                                   userSesssion.UserName, action, old.NombreCreadoPor));
                    }


                    if (old == default(Pedido))
                    {
                        throw HttpError.NotFound(string.Format("No existe Oferta con Id: '{0}'", request.Id));
                    }

                    if (old.FechaAnulado.HasValue)
                    {
                        throw HttpError.Unauthorized(string.Format("Operacion:'{0}' No permitida. Oferta '{1}' Id:'{2} se encuentra anulada", action, request.Consecutivo, request.Id));
                    }



                    request.PopulateWith(old);

                    if (action == "ENVIAR")
                    {
                        if (old.FechaEnvio.HasValue)
                        {
                            throw HttpError.Conflict("Oferta ya se encuentra en estado Enviada");
                        }
                        request.FechaEnvio   = DateTime.Today;
                        request.IdEnviadoPor = int.Parse(session.UserAuthId);
                    }
                    else if (action == "ACEPTAR")
                    {
                        if (old.FechaAceptacion.HasValue)
                        {
                            throw HttpError.Conflict("Oferta ya se encuentra en estado Aceptada");
                        }

                        if (!old.FechaEnvio.HasValue)
                        {
                            throw HttpError.Conflict("La Oferta primero debe ser enviada");
                        }

                        request.FechaAceptacion = DateTime.Today;
                        request.IdAceptadoPor   = int.Parse(session.UserAuthId);
                    }
                    else
                    {
                        request.FechaAnulado = DateTime.Today;
                        request.IdAnuladoPor = int.Parse(session.UserAuthId);
                    }

                    proxy.Update(request, ev => ev.Update(
                                     f => new {
                        f.FechaEnvio, f.FechaAceptacion, f.FechaAnulado, f.VigenteHasta,
                        f.IdAceptadoPor, f.IdAnuladoPor, f.IdEnviadoPor
                    }).Where(q => q.Id == request.Id));
                }
            });

            List <Pedido> data = new List <Pedido>();

            data.Add(request);

            return(new Response <Pedido>()
            {
                Data = data
            });
        }
Beispiel #19
0
 public static Exception BatchArtifactAlreadyExists(string ArtifactName) =>
 HttpError.Conflict(ErrMsg.BatchArtifactAlreadyExists(ArtifactName));
Beispiel #20
0
        public async Task <ImportUserVoiceSuggestionResponse> Any(ImportUserVoiceSuggestion request)
        {
            var user = GetUser();

            AssertOrganizationModerator(Db, request.OrganizationId, user, out var org, out var orgMember);

            var creator = await GetOrCreateUser(request.Creator);

            var existingPost = await Db.SingleAsync <Post>(x =>
                                                           (request.Url != null && x.Url == request.Url) ||
                                                           (x.RefSource == UserVoiceSource && x.RefId == request.Id));

            if (existingPost != null)
            {
                throw HttpError.Conflict($"Post already imported: /posts/{existingPost.Id}/{existingPost.Slug}");
            }

            var categoryId = await GetOrCreateCategory(request.OrganizationId, request.Category);

            var now    = DateTime.Now;
            var hidden = request.StatusKey == "declined" || request.StatusKey == "completed"
                ? now
                : (DateTime?)null;

            var statusBy = (await GetOrCreateUser(request.StatusChangedBy))?.UserName
                           ?? user.UserName;

            var labels = new List <string>();

            if (request.State != null && request.State != "closed")
            {
                labels.Add(request.State.GenerateSlug());
            }

            if (request.StatusKey != null)
            {
                labels.Add(request.StatusKey);

                var orgLabelExists = await Db.ExistsAsync <OrganizationLabel>(x =>
                                                                              x.OrganizationId == request.OrganizationId && x.Slug == request.StatusKey);

                if (!orgLabelExists)
                {
                    await Db.InsertAsync(new OrganizationLabel {
                        OrganizationId = request.OrganizationId,
                        Slug           = request.StatusKey,
                        Description    = $"UserVoice Suggestion",
                        Color          = request.StatusHexColor,
                    });
                }
            }

            Post newPost = null;

            using (var trans = Db.OpenTransaction())
            {
                newPost = new Post
                {
                    OrganizationId = request.OrganizationId,
                    UserId         = creator.Id,
                    Type           = PostType.Request,
                    Url            = request.Url,
                    Title          = request.Title,
                    Slug           = request.Slug ?? request.Title.GenerateSlug(),
                    RefSource      = "uservoice",
                    RefId          = request.Id,
                    RefUrn         = $"urn:uservoice:suggestion:{request.TopicId}:{request.Id}",
                    Created        = request.CreatedAt,
                    CreatedBy      = creator.UserName,
                    Modified       = request.UpdatedAt,
                    ModifiedBy     = creator.UserName,
                    CategoryId     = categoryId,
                    PointsModifier = request.VoteCount,
                    Hidden         = hidden,
                    HiddenBy       = statusBy,
                    Content        = request.Text,
                    ContentHtml    = request.FormattedText,
                    Labels         = labels.Count > 0 ? labels.ToArray() : null,
                };

                if (request.State == "closed")
                {
                    newPost.Status     = request.State;
                    newPost.StatusBy   = statusBy;
                    newPost.StatusDate = request.StatusChangedBy?.UpdatedAt;
                }

                newPost.Id = await Db.InsertAsync(newPost, selectIdentity : true);

                if (request.Response != null)
                {
                    var commentUser = await GetOrCreateUser(request.Response.Creator);

                    var newComment = new PostComment {
                        PostId      = newPost.Id,
                        Content     = request.Response.Text,
                        ContentHtml = request.Response.FormattedText,
                        Created     = request.Response.CreatedAt,
                        CreatedBy   = commentUser.UserName,
                        Modified    = request.Response.CreatedAt,
                        RefSource   = "uservoice",
                        RefId       = request.Id,
                        RefUrn      = $"urn:uservoice:response:{request.TopicId}:{request.Id}",
                    };

                    newComment.Id = await Db.InsertAsync(newComment, selectIdentity : true);

                    await Db.UpdateOnlyAsync(() => new Post { PinCommentId = newComment.Id },
                                             where : x => x.Id == newPost.Id && x.OrganizationId == request.OrganizationId);
                }

                trans.Commit();
            }

            return(new ImportUserVoiceSuggestionResponse {
                PostId = newPost.Id,
                PostSlug = newPost.Slug
            });
        }
Beispiel #21
0
        // [Authenticate]
        // public object Any(Session request) => SessionAs<AuthUserSession>();

        public object Any(Throw request) => HttpError.Conflict("Conflict message");
Beispiel #22
0
 public static Exception StepArtifactOptionAlreadyExists(string OptionName) =>
 HttpError.Conflict(ErrMsg.StepArtifactOptionAlreadyExists(OptionName));
Beispiel #23
0
        public async Task <CreateOrganizationForTechnologyResponse> Post(CreateOrganizationForTechnology request)
        {
            if (request.TechnologyId == null && request.TechStackId == null)
            {
                throw new ArgumentNullException(nameof(request.TechnologyId));
            }

            var user   = GetUser();
            var userId = user.GetUserId();

            var type = request.TechnologyId != null
                ? typeof(Technology)
                : typeof(TechnologyStack);

            var technology = request.TechnologyId != null
                ? Db.SingleById <Technology>(request.TechnologyId.Value)
                : null;

            var techstack = request.TechStackId != null
                ? Db.SingleById <TechnologyStack>(request.TechStackId.Value)
                : null;

            if (technology == null && techstack == null)
            {
                throw HttpError.NotFound(type.Name + " does not exist");
            }

            var name = technology?.Name ?? techstack?.Name;

            var alreadyLinked = technology?.CommentsPostId != null || techstack?.CommentsPostId != null;

            if (alreadyLinked)
            {
                throw HttpError.Conflict($"{name} {type.Name} Post has already been linked");
            }

            var id        = technology?.Id ?? techstack.Id;
            var techOrgId = technology?.OrganizationId ?? techstack?.OrganizationId;
            var techSlug  = technology?.Slug ?? techstack?.Slug;
            var techRoute = techstack != null
                ? "stacks"
                : "tech";
            var organization = techOrgId == null
                ? Db.Single <Organization>(x => x.Slug == techSlug)
                : Db.SingleById <Organization>(techOrgId);

            using (var trans = Db.OpenTransaction())
            {
                var postTitle   = $"{name} Page Comments";
                var postContent = $"### Comments for [{name} {type.Name}](/{techRoute}/{techSlug}) page";
                var now         = DateTime.Now;

                if (organization == null)
                {
                    var description = technology?.Description ?? techstack?.Description;
                    organization = new Organization
                    {
                        Name            = name,
                        Slug            = techSlug,
                        Description     = description,
                        DescriptionHtml = MarkdownConfig.Transform(description),
                        PostTypes       = new []
                        {
                            PostType.Announcement.ToString(),
                                PostType.Post.ToString(),
                                PostType.Showcase.ToString(),
                        },
                        RefId      = id,
                        RefSource  = type.Name,
                        RefUrn     = $"urn:{type.Name}:{id}",
                        Created    = now,
                        CreatedBy  = user.UserName,
                        Modified   = now,
                        ModifiedBy = user.UserName,
                    };

                    organization.Id = (int)await Db.InsertAsync(organization, selectIdentity : true);
                }

                var post = new Post
                {
                    OrganizationId = organization.Id,
                    Type           = PostType.Post,
                    Title          = postTitle,
                    Slug           = postTitle.GenerateSlug(),
                    Content        = postContent,
                    ContentHtml    = $"<div class='gfm ssfm'>{MarkdownConfig.Transform(postContent)}</div>",
                    RefId          = organization.RefId,
                    RefSource      = organization.RefSource,
                    RefUrn         = organization.RefUrn,
                    Created        = now,
                    CreatedBy      = user.UserName,
                    Modified       = now,
                    ModifiedBy     = user.UserName,
                    Hidden         = now,
                    HiddenBy       = "webstacks",
                    UserId         = userId,
                    UpVotes        = 0,
                    Rank           = 0,
                    TechnologyIds  = technology != null ? new[] { (int)technology.Id } : null,
                };
                post.Id = await Db.InsertAsync(post, selectIdentity : true);

                if (technology != null)
                {
                    await Db.UpdateOnlyAsync(() => new Technology {
                        OrganizationId = organization.Id,
                        CommentsPostId = post.Id,
                    }, where : x => x.Id == technology.Id);
                }
                else
                {
                    await Db.UpdateOnlyAsync(() => new TechnologyStack {
                        OrganizationId = organization.Id,
                        CommentsPostId = post.Id,
                    }, where : x => x.Id == techstack.Id);
                }

                trans.Commit();

                SendSystemEmail(nameof(CreateOrganizationForTechnology),
                                $"New {name} {type.Name} Organization was created by {user.UserName} at /{techSlug}");

                ClearOrganizationCaches();
                ClearPostCaches();

                return(new CreateOrganizationForTechnologyResponse
                {
                    OrganizationId = organization.Id,
                    OrganizationSlug = organization.Slug,
                    CommentsPostId = post.Id,
                    CommentsPostSlug = post.Slug,
                });
            }
        }
Beispiel #24
0
 public static Exception StepAlreadyExists(string StepName) =>
 HttpError.Conflict(ErrMsg.StepAlreadyExists(StepName));
Beispiel #25
0
 public static Exception BatchVariableAlreadyExists(string VariableName) =>
 HttpError.Conflict(ErrMsg.BatchVariableAlreadyExists(VariableName));