Wednesday, December 23, 2020

Save a file in s3 Bucket with ASP.net Core and lambda

 First create a bucket and get the config  and for lambda please consider this post for setting otherwise your image or video  get corrupted on S3 bucket 



 "Bucket": {
    "AWSAccessKey": "",
    "AWSSecretKey": "",
    "BucketName": "BucketName",
    "FilePathImages": "MobileAPI/email_images",
    "FilePathVideo": "MobileAPI/email_videos"
  },

 In bucket I create a sub folder with MobileAPI that contains two folder email_images and email_videos because I want to save video and images in a separate folder

 

Lets jump in to the code make a new controller name what ever you want use this name as to hit this method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Amazon.S3;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System.IO;
namespace MobileAPILambda.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class send_contact_messageController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        public static IWebHostEnvironment _environment;
        public send_contact_messageController(IWebHostEnvironment environment,
            IConfiguration configuration)
        {
            _environment = environment;
            _configuration = configuration;
        }
        public class FileUploadAPI
        {
            public IFormFile image { get; set; }
        }
        public class FileUploadvideoAPI
        {
            public IFormFile video { get; set; }
        }
        [HttpPost]
        public async Task<string> Post([FromForm] FileUploadvideoAPI objVideoFile, [FromForm] FileUploadAPI objFile)
        {
            string jsonString = "";
            try
            {
                        string AWS_bucketName = Convert.ToString(_configuration["Bucket:BucketName"]);
                        string AWS_accessKey = Convert.ToString(_configuration["Bucket:AWSAccessKey"]);
                        string AWS_secretKey = Convert.ToString(_configuration["Bucket:AWSSecretKey"]);
                        string FilePathImages = Convert.ToString(_configuration["Bucket:FilePathImages"]);
                        string FilePathVideo = Convert.ToString(_configuration["Bucket:FilePathVideo"]);
                        #region local save
                        /* FileStream fileStream = System.IO.File.Create(objFile.image.FileName);
                         using (FileStream fileStream1 = System.IO.File.Create(_environment.ContentRootPath + "\\Uploads\\" + objFile.image.FileName))
                         {
                             objFile.image.CopyTo(fileStream);
                             fileStream.Flush();
                         }
                         using (FileStream fileStream2 = System.IO.File.Create(_environment.ContentRootPath + "\\Uploads\\" + objVideoFile.video.FileName))
                         {
                             objVideoFile.video.CopyTo(fileStream);
                             fileStream.Flush();
                         } */
                        #endregion
                        string email_images = await UploadFileToAWSAsync(AWS_accessKey, AWS_secretKey, AWS_bucketName, FilePathImages, objFile.image);
                        string email_video = await UploadFileToAWSAsync(AWS_accessKey, AWS_secretKey, AWS_bucketName, FilePathVideo, objVideoFile.video);

// This is the return Json i want to send as response
                        Result.message = "Upload!";
                        Result.success = true;
                        var options = new JsonSerializerOptions
                        {
                            WriteIndented = true,
                        };
                        jsonString = System.Text.Json.JsonSerializer.Serialize(Result, options);
                   
                }
            }
            catch (Exception ex)
            {
                return ex.Message.ToString();
            }
            return jsonString;
        }
        protected async Task<string> UploadFileToAWSAsync(string AWS_accessKey, string AWS_secretKey, string AWS_bucketName, string AWS_defaultFolder, IFormFile myfile)
        {
            var result = "";
            try
            {
                var s3Client = new AmazonS3Client(AWS_accessKey, AWS_secretKey, Amazon.RegionEndpoint.APNortheast2);
                var bucketName = AWS_bucketName;
                var keyName = AWS_defaultFolder;
                keyName = keyName + "/" + myfile.FileName;
                var fs = myfile.OpenReadStream();
                var request = new Amazon.S3.Model.PutObjectRequest
                {
                    BucketName = bucketName,
                    Key = keyName,
                    InputStream = fs,
                    ContentType = myfile.ContentType,
                    CannedACL = S3CannedACL.Private
                };
                await s3Client.PutObjectAsync(request);
                result = string.Format("https://{0}.s3.ap-northeast-2.amazonaws.com/{1}", bucketName, keyName);
            }
            catch (AmazonS3Exception exception)
            {
                result = exception.Message;
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }

    }
}

Wednesday, September 30, 2020

Dropdown Select Value by Using Linq

You can select the dropdown value by based of text. Contains works ' like ' in SQL

 DropDownList1.Items.Cast<ListItem>() .Where(x => x.Value.Contains("three")) .LastOrDefault().Selected = true;

Wednesday, June 24, 2020

Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back

For this issue you can try this code.

   protected override PageStatePersister PageStatePersister
    {
        get
        {
            return new SessionPageStatePersister(this);
        }
    }

This overrides the normal page state persister and provides one that persists the page data to the Session instead of the ViewState and please make sure that if the property of any control by force is true make it false otherwise issue will still remain same.

enableviewstate=false


Links:
Refer link

Sunday, February 9, 2020

Google API Translation on Asp.net Controls (Lables,Butttons)

I have a task in which i have to translate a whole page. In this page most are labels and buttons So I used google translator API here is the reference.

You will only be allowed to translate about 100 words per hour using the free API. If you abuse this, Google API will return a 429 (Too many requests) error.

Google Translator API Implementation

Now the second task how i can search labels and button of my page so i need to translate so here is the function i made for labels and button.



For Button Translation :
public void UpdateButtonsforTranslation()
{
    foreach (Control c in Page.Form.Controls)
    {
        if (c is Button)
        {
            Button btn = ((Button)c);
            string text = btn.Text;
            if (!string.IsNullOrEmpty(text))
            {
                try
                {
// make a function of that and passing paramters in which language i want to translate
                    string translatedText = objtranslate.TranslateText(text, "en", "es");
                    btn.Text = translatedText;
                }
                catch (Exception ex)
                {
                }
            }
        }
    }
}


For Labels Translation :
public void UpdateLabelsforTranslation()
{
    foreach (Control c in Page.Form.Controls)
    {
        if (c is Label)
        {
            Label lbl = ((Label)c);
            string text = lbl.Text;
            if (!string.IsNullOrEmpty(text))
            {
                try
                {
// make a function of that and passing paramters in which language i want to translate
                    string translatedText = objtranslate.TranslateText(text, "en", "es");
                    lbl.Text = translatedText;
                }
                catch (Exception ex)
                {
                }
            }
        }
    }
}