Ejemplo n.º 1
0
        public async Task <int> AddPost(PostEntity post)
        {
            Guard.ArgumentNotNull(post, nameof(post));

            using (var context = new InstaContext())
            {
                var postRecord = new PostRecord
                {
                    Description = new DescriptionRecord
                    {
                        Text = post.Description
                    },
                    Geolocation = post.Location,
                    UserId      = post.UserId,
                    CreatedAt   = DateTimeOffset.Now,
                };

                await context.PostRecords.AddAsync(postRecord);

                await context.SaveChangesAsync();

                var entityRecord = new EntityRecord
                {
                    ExternalEntityId = postRecord.PostId,
                    EntityTypeId     = (int)EntityType.Post
                };

                await context.EntityRecords.AddAsync(entityRecord);

                await context.SaveChangesAsync();

                return(postRecord.PostId);
            }
        }
Ejemplo n.º 2
0
        private async Task <ActionResult> AddOrEdit(PostEditViewModel model)
        {
            try
            {
                var record = await _postService.Get(model.Id);

                var isAdd = record == null;
                if (record == null)
                {
                    record = PostRecord.Create(await _userService.GetUserById(_authenticationService.GetAuthenticatedUser().Identity));
                }

                model.UpdateRecord(record, _categoryService);

                if (isAdd)
                {
                    await _postService.Add(record);
                }

                return(this.Success());
            }
            catch (ValidationException validationException)
            {
                return(this.Error(validationException.Message));
            }
        }
        public List <PostRecord> getAllPostRecords(int userId)
        {
            string            connectionString = config.GetConnectionString("DefaultConnection");
            MySqlConnection   conn             = new MySqlConnection(connectionString);
            MySqlCommand      mySqlCommand     = new MySqlCommand();
            List <PostRecord> postRecords      = new List <PostRecord>();

            try
            {
                conn.Open();    //opening DB connection
                mySqlCommand.Connection  = conn;
                mySqlCommand.CommandText = "get_all_post_records";
                mySqlCommand.CommandType = CommandType.StoredProcedure;
                mySqlCommand.Parameters.Add(new MySqlParameter("_user_id", userId));
                MySqlDataReader reader = mySqlCommand.ExecuteReader();
                while (reader.Read())
                {
                    PostRecord postRecord = getPostRecordFromReader(reader);
                    postRecords.Add(postRecord);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            finally
            {
                conn.Close();           //closing DB connection
            }
            return(postRecords);
        }
Ejemplo n.º 4
0
        public async Task Add(PostRecord record)
        {
            if (await _routeService.ExistByPath(record.Route.Path))
            {
                throw new ValidationException($"路由路径 '{record.Route.Path}' 已经存在!");
            }

            _repository.Value.Create(record);
        }
        private PostRecord getPostRecordFromReader(MySqlDataReader reader)
        {
            PostRecord postRecord = new PostRecord();

            postRecord.postRecordId = Int32.Parse(reader["post_record_id"].ToString());
            postRecord.userId       = Int32.Parse(reader["user_id"].ToString());
            postRecord.postId       = Int32.Parse(reader["post_id"].ToString());
            postRecord.datePosted   = reader["date_posted"].ToString();
            return(postRecord);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <IEnumerable <PostRecord> > FunctionHandler(PostRequestEvent input, ILambdaContext context)
        {
            var recordId = input.RecordId;

            var tableName = Environment.GetEnvironmentVariable("DB_TABLE_NAME");

            using (var dynamoDb = new AmazonDynamoDBClient())
            {
                var fieldsToRetrieve = new List <string> {
                    "id", "text", "voice", "status", "url"
                };

                if (recordId == "*")
                {
                    var results = await dynamoDb.ScanAsync(tableName, fieldsToRetrieve);

                    return(results.Items.Select(d =>
                    {
                        var record = new PostRecord
                        {
                            Id = d["id"].S,
                            Text = d["text"].S,
                            Voice = d["voice"].S,
                            Status = d["status"].S,
                            Url = d["url"].S
                        };

                        return record;
                    }).ToList());
                }
                else
                {
                    var result = await dynamoDb.GetItemAsync(tableName,
                                                             new Dictionary <string, AttributeValue>
                    {
                        { "id", new AttributeValue {
                              S = recordId
                          } }
                    }
                                                             );

                    var record = new PostRecord
                    {
                        Id     = result.Item["id"].S,
                        Text   = result.Item["text"].S,
                        Voice  = result.Item["voice"].S,
                        Status = result.Item["status"].S,
                        Url    = result.Item["url"].S
                    };

                    return(new[] { record });
                }
            }
        }
Ejemplo n.º 7
0
        public JsonResult createPostRecord([FromBody] PostRecord postRecord)
        {
            Response response = new Response();
            PostRecordDataHandler postRecordDataHandler = new PostRecordDataHandler(config);

            postRecordDataHandler.postId       = postRecord.postId;
            postRecordDataHandler.postRecordId = postRecord.postRecordId;
            postRecordDataHandler.userId       = postRecord.userId;
            postRecordDataHandler.datePosted   = postRecord.datePosted;
            response.status = postRecordDataHandler.createPostRecord();
            return(Json(response));
        }
Ejemplo n.º 8
0
 public static PostEntity ToEntity(this PostRecord record)
 {
     return(new PostEntity
     {
         Id = record.PostId,
         CreatedAt = record.CreatedAt,
         UserId = record.UserId,
         UserName = record.User.Profile.UserName,
         Description = record.Description.Text,
         Location = record.Geolocation,
         Tags = record.Tags.Select(x => x.UniqueTag).Select(x => x.Text).ToArray()
     });
 }
Ejemplo n.º 9
0
        private static void MakePostListener(CombinedSubreddit subreddit, ConcurrentQueue <PostRecord> concurrentQueue)
        {
            try
            {
                var sub   = subreddit;
                var queue = concurrentQueue;

                foreach (var post in sub.Posts.GetListingStream())
                {
                    var postRecord = new PostRecord
                    {
                        Subreddit = post.SubredditName.ToLower(),
                        Username  = post.AuthorName.ToLower(),
                        Url       = post.Shortlink.Substring(15)
                    };
                    queue.Enqueue(postRecord);
                }
            }
            catch { }
        }
Ejemplo n.º 10
0
        private async Task <PostEntity> ToPostEntity(PostRecord post)
        {
            using (var context = new InstaContext())
            {
                var entity = await context.EntityRecords
                             .AsNoTracking()
                             .Include(x => x.Photos)
                             .Include(x => x.Likes)
                             .FirstAsync(x => x.ExternalEntityId == post.PostId);

                var photos = entity.Photos
                             .Select(x => x.ToEntity())
                             .ToArray();

                var postEntity = post.ToEntity();
                postEntity.Photos = photos;
                postEntity.Likes  = entity.Likes.Count;

                return(postEntity);
            }
        }
Ejemplo n.º 11
0
        public async void createPost(object sender, EventArgs e) // creation of a new post with required fields
        {
            try
            {
                string todayDate   = DateTime.Now.ToString("yyyy-MM-dd");
                string imageString = imageToBase64();
                Cloth  cloth       = new Cloth(user.userId, pickerCLothType.SelectedItem.ToString(), imageString, entryColor.Text, entryMaterial.Text, pickerSeason.SelectedItem.ToString());
                Cloth  newCloth    = await clothController.createCloth(cloth);

                if (newCloth != null)
                {
                    Post post    = new Post(user.userId, newCloth.clothId, Double.Parse(entryPrice.Text), entryUrl.Text, switchModel.IsToggled);
                    Post newPost = await postController.createPost(post);

                    if (newPost != null)
                    {
                        PostRecord postRecord = new PostRecord(user.userId, newPost.postId, todayDate);

                        bool flag = await postRecordController.createModel(postRecord);

                        if (flag)
                        {
                            await DisplayAlert("Message", "Post Create Successfully!", "Okay");

                            App.Current.MainPage = new NavPage(user);
                        }

                        else
                        {
                            await DisplayAlert("Message", "Error Occured!", "Okay");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
        public async Task <IActionResult> AddRecord([FromBody] PostRecord record)
        {
            _logger.Info("posting record : " + record);
            if (record == null)
            {
                _logger.Info("Record is null (not created).");
                return(BadRequest());
            }

            using (var dal = new WeatherStationDal(_context))
            {
                try
                {
                    await dal.AddRecordAsync(record.DateTime, record.Temperature, record.Humidity, record.BroadcasterName);

                    _logger.Info("Record created.");
                    return(Created(String.Empty, null));
                }
                catch (ApiException ex)
                {
                    string exMessage = ex.Message + Environment.NewLine;
                    _logger.Error("Error creating record : " + exMessage);
                    return(BadRequest());
                }
                catch (Exception ex)
                {
                    string exMessage = ex.Message + Environment.NewLine;
                    while (ex.InnerException != null)
                    {
                        exMessage += $"InnerException : {ex.InnerException.Message}{Environment.NewLine}";
                        ex         = ex.InnerException;
                    }
                    _logger.Error("Error creating record : " + exMessage);
                    return(StatusCode(500));
                }
            }
        }
Ejemplo n.º 13
0
        public PostRecord UpdateRecord(PostRecord record, ICategoryService categoryService)
        {
            record.Status              = IsPublish ? PostStatus.Publish : PostStatus.UnPublished;
            record.Content             = Content;
            record.OppositionCount     = OppositionCount;
            record.ReadingCount        = ReadingCount;
            record.RecommendationCount = RecommendationCount;
            record.ShowInIndex         = ShowInIndex;
            record.Summary             = Summary;
            record.Tags         = Tags;
            record.Title        = Title;
            record.AllowComment = AllowComment;
            record.Seo          = Seo;
            if (record.Route == null)
            {
                record.Route = RouteRecord.Create();
            }
            record.Route.Path = RoutePath;

            var newCategorys = Categorys == null ? null :
                               categoryService.GetList(Categorys.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));

            if (record.Categorys.Any())
            {
                record.Categorys.Clear();
            }

            if (newCategorys != null)
            {
                foreach (var category in newCategorys)
                {
                    record.Categorys.Add(category);
                }
            }

            return(record);
        }
Ejemplo n.º 14
0
 public Task <PostRecord> GetAfterPost(PostRecord post)
 {
     return(Table().OrderBy(i => i.CreateTime).FirstOrDefaultAsync(i => i.CreateTime > post.CreateTime));
 }
Ejemplo n.º 15
0
 public JsonResult createPostRecord(PostRecord postRecord)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 16
0
        public object AddRecord(PostRecord record)
        {
            if (record == null || string.IsNullOrEmpty(record.QuestionId) ||
                string.IsNullOrEmpty(record.UserId))
            {
                return(new ReturnResult <bool>(-2, "参数传入错误!"));
            }
            Record saveTemp = _QuestionService.GetRecord(record.QuestionId, record.UserId);
            bool   isNew    = false;

            if (saveTemp == null)
            {
                saveTemp = record.ToModel();
                isNew    = true;
            }
            switch (record.Type)
            {
            default:
            case 0:
                break;

            case 1:    //点赞
                if (!isNew && saveTemp.ispraise)
                {
                    //此种情况,正常返回,后台不做处理
                    return(new ReturnResult <bool>(1, true, "此文已经赞过!"));
                }
                saveTemp.ispraise = true;
                break;

            case 2:    //收藏
                if (!isNew && saveTemp.iscollect)
                {
                    return(new ReturnResult <bool>(1, true, "此文已经收藏过!"));
                }
                saveTemp.iscollect = true;
                break;

            case -1:    //取消点赞
                if (!isNew && !saveTemp.ispraise)
                {
                    return(new ReturnResult <bool>(1, true, "此文未赞过!"));
                }
                saveTemp.ispraise = false;
                break;

            case -2:    //取消收藏
                if (!isNew && !saveTemp.iscollect)
                {
                    return(new ReturnResult <bool>(1, true, "此文未收藏过!"));
                }
                saveTemp.iscollect = false;
                break;
            }
            ReturnResult <bool> res = new ReturnResult <bool>();

            if (isNew)
            {
                res = _QuestionService.AddRecord(saveTemp);
            }
            else
            {
                res = _QuestionService.UpdateRecord(saveTemp);
            }
            if (res.code > 0)
            {
                switch (record.Type)
                {
                default:
                case 0:
                    _QuestionService.UpdateReadCount(record.QuestionId);
                    break;

                case 1:    //点赞
                    _QuestionService.UpdatePraiseCount(record.QuestionId, 1);
                    _IUsersService.UpdatePraiseCount(record.QuestionId, 1);
                    break;

                case 2:    //收藏
                    _QuestionService.UpdateCollectCount(record.UserId, 1);
                    break;

                case -1:    //取消点赞
                    _QuestionService.UpdatePraiseCount(record.QuestionId, -1);
                    _IUsersService.UpdatePraiseCount(record.QuestionId, -1);
                    break;

                case -2:    //取消收藏
                    _QuestionService.UpdateCollectCount(record.UserId, -1);
                    break;
                }
            }
            return(res);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <string> FunctionHandler(SNSEvent snsEvent, ILambdaContext context)
        {
            var postId = snsEvent.Records[0].Sns.Message;

            Console.WriteLine($"Text to Speech function. Post ID in DynamoDB: {postId}");

            //Retrieving information about the post from DynamoDB table
            PostRecord record;

            using (var dynamoDb = new AmazonDynamoDBClient())
            {
                var fieldsToRetrieve = new List <string> {
                    "id", "text", "voice", "status"
                };

                var tableName = Environment.GetEnvironmentVariable("DB_TABLE_NAME");

                var result = await dynamoDb.GetItemAsync(tableName,
                                                         new Dictionary <string, AttributeValue>
                {
                    { "id", new AttributeValue {
                          S = postId
                      } }
                }
                                                         );

                record = new PostRecord
                {
                    Id     = result.Item["id"].S,
                    Text   = result.Item["text"].S,
                    Voice  = result.Item["voice"].S,
                    Status = result.Item["status"].S
                };
            }

            var outputPath = String.Format("{0}tmp{0}{1}.mp3", Path.DirectorySeparatorChar, record.Id);

            var rest = record.Text;

            // Because single invocation of the polly synthesize_speech api can
            // transform text with about 1,500 characters, we are dividing the
            // post into blocks of approximately 1,000 characters.
            var textBlocks = new List <string>();

            while (rest.Length > 1100)
            {
                var end = rest.IndexOf(".", 0, 1000);

                if (end < 0)
                {
                    end = rest.IndexOf(" ", 0, 1000);
                }

                textBlocks.Add(rest.Substring(0, end + 1));

                if (end + 1 < rest.Length)
                {
                    rest = rest.Substring(end + 1);
                }
            }

            if (!String.IsNullOrEmpty(rest))
            {
                textBlocks.Add(rest);
            }

            //For each block, invoke Polly API, which will transform text into audio
            using (var polly = new AmazonPollyClient())
            {
                foreach (var textBlock in textBlocks)
                {
                    var request = new SynthesizeSpeechRequest
                    {
                        OutputFormat = "mp3",
                        Text         = textBlock,
                        VoiceId      = record.Voice //TODO error prone
                    };

                    var pollyResponse = await polly.SynthesizeSpeechAsync(request);

                    if (pollyResponse.AudioStream != null &&
                        pollyResponse.AudioStream.CanRead)
                    {
                        using (var tempFile = File.Open(outputPath, FileMode.Append))
                        {
                            await pollyResponse.AudioStream.CopyToAsync(tempFile);
                        }
                    }
                }
            }

            var bucketName = Environment.GetEnvironmentVariable("BUCKET_NAME");

            string url;

            using (var s3Client = new AmazonS3Client())
            {
                var key = Path.GetFileName(outputPath);

                var s3Request = new PutObjectRequest
                {
                    BucketName = bucketName,
                    FilePath   = outputPath,
                    CannedACL  = S3CannedACL.PublicRead,
                    Key        = key
                };

                var s3Result = await s3Client.PutObjectAsync(s3Request);

                var location = await s3Client.GetBucketLocationAsync(bucketName);

                var region = location.Location;

                url = "https://s3";

                if (!String.IsNullOrEmpty(region))
                {
                    url = url + "-" + region;
                }

                url = url + ".amazonaws.com/"
                      + bucketName
                      + "/"
                      + key;
            }

            //Updating the item in DynamoDB
            using (var dynamoDb = new AmazonDynamoDBClient())
            {
                var tableName = Environment.GetEnvironmentVariable("DB_TABLE_NAME");

                var result = await dynamoDb.UpdateItemAsync(tableName,
                                                            new Dictionary <string, AttributeValue>
                {
                    { "id", new AttributeValue {
                          S = postId
                      } }
                },
                                                            new Dictionary <string, AttributeValueUpdate>
                {
                    { "status", new AttributeValueUpdate(new AttributeValue {
                            S = "UPDATED"
                        }, AttributeAction.PUT) },
                    { "url", new AttributeValueUpdate(new AttributeValue {
                            S = url
                        }, AttributeAction.PUT) }
                }
                                                            );
            }

            return("success");
        }
Ejemplo n.º 18
0
 public Task <PostRecord> GetBeforePost(PostRecord post)
 {
     return(Table().OrderByDescending(i => i.CreateTime).FirstOrDefaultAsync(i => i.CreateTime < post.CreateTime));
 }
Ejemplo n.º 19
0
 public PostWindow()
 {
     InitializeComponent();
     mypostrecord     = new PostRecord(this);
     this.DataContext = this;
 }