C# - How to Upload large size video ( in GB ) to Amazon S3 bucket - amazon-s3

I need to upload a large size video to Amazon S3 bucket.
I have a large size video and it
here is my class that i am using
public class CustomAmazon
{
public string tourName { get; set; }
public string driveName { get; set; }
public string tourID { get; set; }
public string driveID { get; set; }
public string key { get; set; }
public string bucketName { get; set; }
public string cloudFrontVideoUrl { get; set; }
public string amazonS3VideoUrl { get; set; }
public string filePath { get; set; }
}
and here is the Amazon Code for writing an object
static string WritingAnObject(CustomAmazon customAmazon)
{
try
{
var videoStream = new FileStream(customAmazon.filePath, FileMode.Open, FileAccess.Read);
// put a more complex object with some metadata and http headers.
string fileName = customAmazon.tourID + "/" + customAmazon.driveID + "/" + Guid.NewGuid() + "__" + Path.GetFileName(customAmazon.filePath);
PutObjectRequest titledRequest = new PutObjectRequest()
{
BucketName = customAmazon.bucketName,
Key = fileName,
InputStream = videoStream,
Timeout = new TimeSpan(4, 30, 30),
ContentType = "video/mov",
CannedACL = S3CannedACL.PublicRead
};
titledRequest.Metadata.Add("title", fileName);
titledRequest.Metadata.Add("drive", customAmazon.driveName);
client.PutObject(titledRequest);
Thread.Sleep(4000);
// Retrieve ACL for object
customAmazon.cloudFrontVideoUrl = customAmazon.cloudFrontVideoUrl + fileName;
customAmazon.key = fileName;
customAmazon.amazonS3VideoUrl = ReadConfig.AWSStorageUrl + fileName;
}
catch (AmazonS3Exception amazonS3Exception)
{
Logger.Write(amazonS3Exception.Message);
if (amazonS3Exception.ErrorCode != null &&
(amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") ||
amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
{
Console.WriteLine("Please check the provided AWS Credentials.");
Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
}
else
{
Logger.Write(string.Format("An error occurred with the message '{0}' when writing an object", amazonS3Exception.Message));
}
}
return customAmazon.amazonS3VideoUrl;
}
I am getting error while uploading large size video, while in small size videos it is working fine.

Yes, I got the answer, I tried it using multicast and it is working fine, here is my solution
Here is my class
public class CustomAmazon
{
public string tourName { get; set; }
public string driveName { get; set; }
public string tourID { get; set; }
public string driveID { get; set; }
public string key { get; set; }
public string bucketName { get; set; }
public string cloudFrontVideoUrl { get; set; }
public string amazonS3VideoUrl { get; set; }
public string filePath { get; set; }
}
and here is my solution
I just call below method to upload large video file after connecting credentials
/// <summary>
/// Method used for DFI (website or API) users to upload a file on Amazon S3 storage
/// </summary>
/// <param name="customAmazon"></param>
/// <returns>CustomAmazon class object </returns>
public CustomAmazon UploadFiletoAmazonS3Storage(CustomAmazon customAmazon)
{
using (client = new AmazonS3Client(ReadConfig.AWSAccessKeyId, ReadConfig.AWSSecretKey, RegionEndpoint.USEast1))
{
Console.WriteLine("Writing an object");
WritingAnLargeObject(customAmazon);
}
return customAmazon;
}
public static string WritingAnLargeObject(CustomAmazon customAmazon)
{
// List to store upload part responses.
List<UploadPartResponse> uploadResponses = new List<UploadPartResponse>();
string fileName = string.Empty;
// Giving custom filename to original file
if (!string.IsNullOrEmpty(customAmazon.tourID) && (!string.IsNullOrEmpty(customAmazon.driveID)))
{
fileName = customAmazon.tourID + "/" + customAmazon.driveID + "/" + Guid.NewGuid() + "___" + Regex.Replace(Path.GetFileName(customAmazon.filePath), #"\s", "");
}
else
{
fileName = Guid.NewGuid() + "___" + Regex.Replace(Path.GetFileName(customAmazon.filePath), #"\s", "");
}
// 1. Initialize MultipartUploadRequest.
InitiateMultipartUploadRequest initiateRequest = new InitiateMultipartUploadRequest
{
BucketName = customAmazon.bucketName,
Key = fileName,
ContentType = "video/mov",
CannedACL = S3CannedACL.PublicRead
};
InitiateMultipartUploadResponse initResponse =
client.InitiateMultipartUpload(initiateRequest);
// 2. Upload video in small Parts of 5 MB.
long contentLength = new FileInfo(customAmazon.filePath).Length;
long partSize = 5 * (long)Math.Pow(2, 20); // 5 MB
try
{
long filePosition = 0;
for (int index = 1; filePosition < contentLength; index++)
{
UploadPartRequest uploadRequest = new UploadPartRequest
{
BucketName = customAmazon.bucketName,
Key = fileName,
UploadId = initResponse.UploadId,
PartNumber = index,
PartSize = partSize,
FilePosition = filePosition,
FilePath = customAmazon.filePath
};
// Upload part and add response to our list.
uploadResponses.Add(client.UploadPart(uploadRequest));
filePosition += partSize;
}
// Step 3: complete.
CompleteMultipartUploadRequest completeRequest = new CompleteMultipartUploadRequest
{
BucketName = customAmazon.bucketName,
Key = fileName,
UploadId = initResponse.UploadId,
//PartETags = new List<PartETag>(uploadResponses)
};
completeRequest.AddPartETags(uploadResponses);
customAmazon.key = fileName;
CompleteMultipartUploadResponse completeUploadResponse = client.CompleteMultipartUpload(completeRequest);
customAmazon.cloudFrontVideoUrl = customAmazon.cloudFrontVideoUrl + fileName;
customAmazon.amazonS3VideoUrl = ReadConfig.AWSStorageUrl + fileName;
}
catch (Exception exception)
{
Logger.Write(exception.Message);
Console.WriteLine("Exception occurred: {0}", exception.Message);
AbortMultipartUploadRequest abortMPURequest = new AbortMultipartUploadRequest
{
BucketName = customAmazon.bucketName,
Key = fileName,
UploadId = initResponse.UploadId
};
client.AbortMultipartUpload(abortMPURequest);
}
return fileName;
}
and Finally I uploaded the video into S3 bucket

Related

is there a reason to serialize and then deserialize an object?

I have a SOAP web service that someone developed at my work place and i try to learn it and i came across a move in the code that i can't get my head around. can someone explain to me the logic behind it? why would someone want to serialize an object and a line after to deserialize it?
**this is the whole code: if someone has a way to improve the code it will be appreciated: **
using IRail.BLL.SAP;
using IRail.Entities.SAP.Report;
using IRail.WebAPI.Heplers;
using Logger;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Script.Serialization;
using System.Web.Services;
namespace IRail.WebAPI
{
public class EventInfo
{
public string QMNUM { get; set; }
public string QMART { get; set; }
public string STATUS { get; set; }
public string MAHUT_CODE { get; set; }
public string MAHUT_TXT { get; set; }
public string START_DATE { get; set; }
public string START_TIME { get; set; }
public string END_DATE { get; set; }
public string END_TIME { get; set; }
public string ZQMNUM { get; set; }
public string QMTXT { get; set; }
public string IKUN { get; set; }
public string ZLONG { get; set; }
public string LAT { get; set; }
public string TPLNR { get; set; }
public string ZZKM_NUM { get; set; }
public string ZZTOKM_NUM { get; set; }
}
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class Events : System.Web.Services.WebService
{
public static readonly ILogger _logger = LogManager.GetLogger();
[WebMethod]
public string UpdateEvent(EventInfo eventInfo)
{
// create an instance of SapClient object an fill it with the input parameters,
// that passes by the url to the function using the eventInfo class.
SapClient SapArgs = new SapClient()
{
params_input = "",
QNUM = eventInfo.QMNUM,
QMART = eventInfo.QMART,
STATUS = eventInfo.STATUS,
MAHUT_CODE = eventInfo.MAHUT_CODE,
MAHUT_TXT = eventInfo.MAHUT_TXT,
START_DATE = eventInfo.START_DATE,
START_TIME = eventInfo.START_TIME,
END_DATE = eventInfo.END_DATE,
END_TIME = eventInfo.END_TIME,
ZQMNUM = eventInfo.ZQMNUM,
QMTXT = eventInfo.QMTXT,
IKUN = eventInfo.IKUN,
ZLONG = eventInfo.ZLONG,
LAT = eventInfo.LAT,
TPLNR = eventInfo.TPLNR,
ZZKM_NUM = eventInfo.ZZKM_NUM,
ZZTOKM_NUM = eventInfo.ZZTOKM_NUM,
ikunx = "",
ikuny = "",
operation_type = "",
returnZ = "",
returnM = "",
returnTrueCurves = "",
f = ""
};
string errorMsg = String.Empty;
string outputJson = String.Empty;
ApiHelper apiHelper = new ApiHelper();
try
{
// create an instance of JS Serializer.
var jss = new JavaScriptSerializer();
// serialize the object to convert it to json format.
JObject sapArgs = JObject.Parse(jss.Serialize(SapArgs));
// decerialize the object back from json format to pass the JSON string representation
// of the sapArgs object as the input to the callGPAsync method.
var dict = jss.Deserialize<Dictionary<string, string>>(sapArgs.ToString());
// create an instance of EventsEngine.
EventsEngine eventsEngine = new EventsEngine();
// assign the type of the event to the events object:
// check the event type.
SapArgs.operation_type = eventsEngine.CheckEventType(dict, ref errorMsg);
// assign the event type that has returned to the sapArgs object's operation_type parameter.
sapArgs["operation_type"] = SapArgs.operation_type; // "1";// set operation_type for test;
// if encountered an error return the content of it.
if (errorMsg != "") return "UpdateEvent ERROR: " + errorMsg;
_logger.Info($"Username: {Utils.GetUserName()}, UpdateEvent : {sapArgs.ToString()}, eventType :{SapArgs.operation_type}");
if (!string.IsNullOrWhiteSpace(apiHelper.getValueFromDict(dict, "IKUN")) && dict["IKUN"].ToString() == "Y")
{
var res = apiHelper.convertCoordiateWGSToITM(sapArgs).GetAwaiter().GetResult();
}
outputJson = apiHelper.callGPAsync(sapArgs).GetAwaiter().GetResult();
try
{
// if there is result from submitted job add operation_type
outputJson = outputJson.Replace("}", ", \"operation_type\" = \"" + SapArgs.operation_type + "\" }");
}
catch (Exception outputEx)
{
return "outputJson ERROR: " + outputEx;
}
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent(outputJson, System.Text.Encoding.UTF8, "application/json");
return outputJson;
}
catch (Exception ex)
{
_logger.Error(" UpdateEvent ERROR : " + SapArgs.ToString() + ", eventType :" + SapArgs.operation_type + ", errorMsg :" + errorMsg);
_logger.Error(ex);
return "UpdateEvent ERROR: update failed on exception. please check logs.";
}
//0. check with documentation - what are the parameters - in sap document
//0. log -> input call
//1. properties input validation -
// A. all inputs are correct //2.4 in documents ---> function in BLL that does the validation
//2. if all ok - -- delete prev event
//3. call GP service to update new event
//4. return success + log reult
}
}
}
I did not try anything i just want to understand the logic.

tron.net.client: How to Get Account Balance

I am try to get the balance from a random account (I think the most valuable account) in the mainnet. But it always return 0.
May I know what is wrong with my code?
internal class MainCfg : IChannelConfiguration
{
public int Port { get; set; } = 50051;
public string Host { get; set; } = "3.225.171.164"; // Correct?
public int? MaxConcurrentStreams { get; set; } = 2;
public TimeSpan? TimeOutMs { get; set; } = TimeSpan.FromSeconds(5);
}
var configuration = new MainCfg();
var grpcChanngelFactory = new GrpcChannelFactory(configuration);
var walletClientFactory = new WalletClientFactory(grpcChanngelFactory);
var wallet = new Wallet(walletClientFactory, new AllClientsDefaultCallConfiguration());
var bytes = Base58.Decode("TNUC9Qb1rRpS5CbWLmNMxXBjyFoydXjWFR"); // An account with lots of balance
var account = await w.GetAccountAsync(new Tron.Net.Protocol.Account{
Address = ByteString.CopyFrom(bytes)
});
Console.Write("Balance=" + account.Balance); // output = 0

getting 400 error on webapi call blazorserver

i am trying to setup a blazor server app, calling a webapi.
I keep getting a 400 error returned, when I call the API.
I have 3 Projects, projectserver and projectapi. projectserver is where the Blazor app sits and Project API is where the API sits.
I don't know if the apicall can find the API as it does not hit any breakpoints in the API section, I am totally confused, as if it cannot find the API then it should return a 404 or other error and not 400 ?
thank you for your efforts.
this is my code,
Projectserver, this is where I post the Register Model to the API
public string message { get; set; }
public RegisterModel r = new RegisterModel();
private async Task Create(MouseEventArgs e)
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject(r);
var client = clientfactory.CreateClient("ServerApi");
var result = await client.PostAsJsonAsync("/Account/Register",json); // check the Startup file and check base address for the Full route.
message = result.StatusCode.ToString();
}
}
the ClientFactory returns the base address of what is defined in startup.cs
services.AddHttpClient("ServerApi", client => client.BaseAddress = new Uri("https://localhost:44302/"));
the API is Projectserver and defined as follows.
[Route("[controller]")]
[ApiController]
public class AccountContoller : ControllerBase
{
private readonly ApplicationDbContext _context;
private readonly SecurityOptions _securityOptions;
private readonly JwtIssuerOptions _jwtOptions;
// GET: api/<Account>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<Account>/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/<Account>
[HttpPost]
public void Post([FromBody] string value)
{
}
// POST api/<Account>
[HttpPost("Register")]
public async Task<ActionResult<RegisterResult>> Register(RegisterModel model)
{
RegisterResult r = new RegisterResult();
var Exisits = await _context.Users.Where(r => r.EmailAddress == model.Email).FirstOrDefaultAsync();
if(Exisits != null)
{
r.Sucsess = false;
r.ErrorMessage = "Email - Already Exisits";
return r;
}
else
{
try
{
User newuser = new User();
newuser.CreatedDateTime = DateTime.UtcNow;
newuser.UserID = Guid.NewGuid();
newuser.MobileNumber = model.MobileNumber;
newuser.Password = model.Password;
newuser.FirstName = model.FirstName;
newuser.Surname = model.LastName;
_context.Users.Add(newuser);
await _context.SaveChangesAsync();
r.Sucsess = true;
return r;
}
catch(Exception e)
{
r.Sucsess = false;
r.ErrorMessage = e.ToString();
return r;
}
}
}
the Model classes are defined as Serializable
[Serializable]
public class RegisterResult
{
public bool Sucsess { get; set; }
public string ErrorMessage { get; set; }
}
[Serializable]
public class RegisterModel
{
public string UserName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string RoleID { get; set; }
public string EntityID { get; set; }
public string MobileNumber { get; set; }
}
Can you please modify your code as below and give it a try:-
var serializedBody = JsonConvert.SerializeObject(r);
var jsonRequestBodyContent = new StringContent(serializedBody, Encoding.UTF8,"application/json");
var client = clientfactory.CreateClient("ServerApi");
var result = await client.PostAsync("/Account/Register",jsonRequestBodyContent);

Problems with converting FixedLength format to to csv using same class definition

I defined both FixedLength and Delimited attributes on a single class. It reads the fixed length file fine but fails when i try to write out a csv.
[FixedLengthRecord]
[DelimitedRecord(",")]
public class PCFFileHeader
{
[FieldFixedLength(2)] public string RecordType { get; set; }
[FieldFixedLength(25)] public string FileDescription { get; set; }
}
var engine = new MultiRecordEngine(typeof(PCFFileHeader), typeof(SecondHeader));
engine.RecordSelector = RecordSelector;
var output = engine.ReadFile(filePath);
// code to extract PCFHeader from output and create a list
var headerEngine = new DelimitedFileEngine<PCFFileHeader>();
headerEngine.WriteFile("header_" + DateTime.Now.ToString("yyyyMMddhhmmss"), pcfFileHeaderList);
You can't add both [FixedLengthRecord] and [DelimitedRecord] to the same class. FileHelpers will just treat it as [FixedLengthRecord]. With your current class, it will error if you do:
// This causes an exception because the class is not a delimited record definition
var delimitedHeaderEngine = new DelimitedFileEngine<PCFFileHeader>();
Instead, you should have two PCFFileHeader definitions, FixedPCFFileHeader and DelimitedPCFFileHeader.
[FixedLengthRecord]
public class FixedPCFFileHeader
{
[FieldFixedLength(2)] public string RecordType { get; set; }
[FieldFixedLength(25)] public string FileDescription { get; set; }
}
[DelimitedRecord(",")]
public class DelimitedPCFFileHeader
{
public string RecordType { get; set; }
public string FileDescription { get; set; }
}
class Program
{
static void Main(string[] args)
{
var fixedHeaderEngine = new FileHelperEngine<FixedPCFFileHeader>();
var recordsFixed = fixedHeaderEngine.ReadString("AADescription ");
Debug.Assert(recordsFixed.Count() == 1);
Debug.Assert(recordsFixed[0].RecordType == "AA");
Debug.Assert(recordsFixed[0].FileDescription == "Description ");
var delimitedHeaderEngine = new FileHelperEngine<DelimitedPCFFileHeader>();
var recordsDelimited = delimitedHeaderEngine.ReadString("AA,Description");
Debug.Assert(recordsDelimited.Count() == 1);
Debug.Assert(recordsDelimited[0].RecordType == "AA");
Debug.Assert(recordsDelimited[0].FileDescription == "Description");
var pcfFileHeaderList = new FixedPCFFileHeader[] { new FixedPCFFileHeader() { RecordType = "AA", FileDescription = "Description" } };
// If you want to output a header when exporting uncomment the following
//headerEngine.HeaderText = "header_" + DateTime.Now.ToString("yyyyMMddhhmmss");
var output = fixedHeaderEngine.WriteString(pcfFileHeaderList);
Debug.Assert(output == "AADescription \r\n");
Console.WriteLine("All OK");
Console.ReadLine();
}
}
If you want to automatically detect the correct format during import, you can use the FileHelpers Smart Format Detector.

Google Cell Tower Location API: Changed?

For the last few months I've been finding the locations of cell towers as we use their cellid and areaid, based on the following code:
public class GoogleService
{
public GoogleCell GetCellInfo(string lac, string mnc, string mcc, string cellID)
{
try
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("https://www.google.com/loc/json");
myReq.Method = "POST";
myReq.ContentType = "application/jsonrequest";
string postData = "{\"cell_towers\": [{\"location_area_code\": \"" + lac + "\", \"mobile_network_code\": \"" + mnc + "\", \"cell_id\": \"" + cellID + "\", \"mobile_country_code\": \"" + mcc + "\"}], \"version\": \"1.1.0\", \"request_address\": \"true\"}";
myReq.ContentLength = postData.Length;
StreamWriter stOut = new StreamWriter(myReq.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(postData);
stOut.Close();
HttpWebResponse webresponse;
webresponse = (HttpWebResponse)myReq.GetResponse();
Encoding enc = System.Text.Encoding.UTF8;
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);
string Response = loResponseStream.ReadToEnd();
loResponseStream.Close();
webresponse.Close();
GoogleCell Mycell = JsonConvert.DeserializeObject<GoogleCell>(Response);
return Mycell;
}
catch (Exception ex)
{
string strErr = ex.Message;
if (ex.InnerException != null)
{
strErr += ": " + ex.InnerException.Message;
}
MessageBox.Show(strErr);
return new GoogleCell();
}
}
}
public class GoogleCell
{
public GoogleCell() { }
public GoogleCell(string mnc, string mcc, string lac)
{
this.Mnc = mnc;
this.Mcc = mcc;
this.Lac = lac;
}
public string Mnc { get; set; }
public string Mcc { get; set; }
public string Lac { get; set; }
public string CellID { get; set; }
public Location location { get; set; }
public class Location
{
public Location() { }
public Location(string latitude, string longitude)
{
this.latitude = latitude;
this.longitude = longitude;
}
public string latitude { get; set; }
public string longitude { get; set; }
public Address address { get; set; }
public class Address
{
public Address() { }
public string country { get; set; }
public string country_code { get; set; }
public string city { get; set; }
public string region { get; set; }
public string street { get; set; }
public string street_number { get; set; }
public string postal_code { get; set; }
}
}
The code worked flawlessly until sometime between one and two weeks ago, when it started returning error 400: Bad Request when it does the GetRequestStream().
My code hasn't changed.
I can't find any record of the API's parameters changing.
What else could be going on? This uses Google Gears, which has been deprecated for a while now, but I can't find any doco on a replacement that finds cell towers.
any ideas?
I ended up kicking Google to the curb and using OpenCellID:
public CellTowerPOCO GetCellInfo_OpenCellID(string lac, string mnc, string mcc, string cellID)
{
try
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(string.Format("http://www.opencellid.org/cell/get?mcc={0}&mnc={1}&cellid={2}&lac={3}",mcc,mnc,cellID,lac));
HttpWebResponse webresponse;
webresponse = (HttpWebResponse)myReq.GetResponse();
//Encoding enc = System.Text.Encoding.UTF8;
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream());
string Response = loResponseStream.ReadToEnd();
loResponseStream.Close();
webresponse.Close();
CellTowerPOCO Mycell = new CellTowerPOCO();
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(Response);
Mycell.location.latitude = xdoc.ChildNodes[1].FirstChild.Attributes["lat"].Value;
Mycell.location.longitude = xdoc.ChildNodes[1].FirstChild.Attributes["lon"].Value;
Mycell.Mcc = mcc;
Mycell.CellID = cellID;
Mycell.Mnc = mnc;
//MessageBox.Show(xdoc.ChildNodes[0].InnerText);
return Mycell;
}
catch (Exception ex)
{
string strErr = ex.Message;
if (ex.InnerException != null)
{
strErr += ": " + ex.InnerException.Message;
}
MessageBox.Show(strErr);
return new CellTowerPOCO();
}
}