write two list in file bin in C# - list

I have two list i want send them to bin file but with this method
i can send one of them ! is it possible use this method if yes please help
var mystudent=List<student>();
var mycourse=List<course>();
string dir = #"D:\";
string serializationFile = Path.Combine(dir, "Student.bin");
//serialize
using (Stream stream = File.Open(serializationFile, FileMode.Create))
{
var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bformatter.Serialize(stream, mystudentList);
}
// deserialize
using (Stream stream = File.Open(serializationFile, FileMode.Open))
{
var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
List<student> stud = (List<student>)bformatter.Deserialize(stream);
}

Related

AWS lambda function and s3 in Asp NetCore

I am new in AWS and Asp NetCore. Help me to find the solution.
I am using Asp NetCore, how should I use lambda function to upload clipped file in s3?
I have a IFormFile but I want to use s3 url instead of IFormFile and upload in s3 bucket. I have used ffmpeg library to cut the video and I want to send url of s3 using lambda function and upload the output of clipped video file again in s3 bucket directory that i created in s3 console.
using Abp.UI;
using FFmpeg.NET;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using Amazon.S3;
using System.Threading.Tasks;
using Amazon.S3.Transfer;
using Amazon.S3.Model;
using IdentityModel.Client;
using Amazon;
using System.Net.Http;
namespace VideoSlicer.About
{
public class AboutAppService : IAboutAppService
{
//Assigning readonly IHostingEnvironment
private readonly IHostingEnvironment _appEnvironment;
private readonly string bucketName = "videoslicerpuru";
private static readonly RegionEndpoint bucketRegion = RegionEndpoint.Region;
/*
private const string newFile = "QQ.mp4";
private const string newFile1 = "637156754716419260QQ.mp4";
private const string filePath = #"C:\Users\Purushottam\Downloads\VideoSlicer\5.1.1\aspnet-core\src\VideoSlicer.Web.Host\wwwroot\images\";*/
private static IAmazonS3 client;
//Making Constructor and passin IHostingEnvironment
public AboutAppService(IHostingEnvironment appEnvironment)
{
_appEnvironment = appEnvironment;
}
//Function which upload video and slice video accordingly start time and finish time given by the user
public async Task UploadImage(IFormFile file, string Start, string Finish)
{
HttpClient cli = new HttpClient();
cli.DefaultRequestHeaders.ExpectContinue = false;
try
{
//Taking out the extension of the file
var convertedExtension = file.FileName.Substring(file.FileName.LastIndexOf("."));
//Comparing the extension whether uploaded file is video or not
if (convertedExtension != ".mp4" && convertedExtension != ".flv" && convertedExtension != ".3GP" && convertedExtension != ".OGG" && convertedExtension != ".AVI" && convertedExtension != ".WMV ")
{
throw new UserFriendlyException("Please Select Valid Video file to clip!!");
}
//Checking if the file is null or has not been selected any file
if (file == null || file.Length == 0)
{
throw new UserFriendlyException("Please Select any file.");
}
//declaring web root path
string path_Root = _appEnvironment.WebRootPath;
//setting path root and saving video to the given path
string pathOfVideo = path_Root + "\\video\\";
string path_to_Video = path_Root + "\\images\\" + file.FileName;
using (var stream = new FileStream(path_to_Video, FileMode.Create))
{
await file.CopyToAsync(stream);
}
client = new AmazonS3Client("AccessKey", "SecretKey", bucketRegion);
TransferUtility utility = new TransferUtility(client);
TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();
string nameOfFile = file.FileName.ToString();
string videoPath = path_to_Video.ToString();
await utility.UploadAsync(videoPath, bucketName, nameOfFile);
Console.WriteLine("Upload 2 completed");
//To cut video, using ffmpeg media file where the video is saved
var input = new MediaFile(path_to_Video);
//The output of the clipped video and saving in a different folder
string nameFile = DateTime.Now.Ticks + file.FileName;
string nameBucket = bucketName + "/videoslice/";
var output = new MediaFile(path_Root + "/video/" + nameFile);
client = new AmazonS3Client(bucketRegion);
//making the object of Engine using ffmpeg application file
var ffmpeg = new Engine("C:\\ffmpeg\\bin\\ffmpeg.exe");
//making object of Conversion Option of ffmpeg
var options = new ConversionOptions();
//Converting string to double
var startTime = Convert.ToDouble($"{Start}");
var finishTime = Convert.ToDouble($"{Finish}");
//clipping video by given user input
options.CutMedia(TimeSpan.FromSeconds(startTime), TimeSpan.FromSeconds(finishTime - startTime));
await ffmpeg.ConvertAsync(input, output, options);
string clipPath = path_Root + "\\video\\" + nameFile;
//Checking if start time is greater then finish time
if (startTime > finishTime)
{
throw new UserFriendlyException("Please Enter Valid Second to proceed");
}
//Checking if start time is equal to finish time
if (startTime == finishTime)
{
throw new UserFriendlyException("Please Enter Valid Second to proceed");
}
var a = utility.UploadAsync(clipPath, nameBucket, nameFile);
Console.WriteLine("Upload 2 completed");
}
catch (AmazonS3Exception e)
{
string err = e.Message;
throw e;
}
catch (InternalBufferOverflowException a)
{
string me = a.Message;
throw a;
}
catch (HttpRequestException c)
{
string error = c.Message;
throw c;
}
catch (DriveNotFoundException e)
{
string mes = e.Message;
throw e;
}
catch(NullReferenceException e)
{
throw new UserFriendlyException (500, "Please Select a file to proceed",e.Message);
}
}
}
}

CSV File to Salesforce records

I have a custom object Employee with fields below. The employee data is maintained in an external system which is sending a base64 encoded string of the csv extract by calling a web service.
I am able to decode the string by using EncodingUtil.base64Decode(). My question is how can I prepare inserts from the decoded base64 string in Salesforce custom object.
String File = 'U25vLE5hbWUsTGFzdCBOYW1lLEVtcCBJZCxKb2IgRnVuY3Rpb24NCjEsU2FjaGluLENob3VyYXNpeWEsMzMwLEJ1c2luZXNzDQoyLFJhamF0ICxTYXhlbmEgLDMzNCxGdW5jdGlvbmFsDQo=';
String myFile = EncodingUtil.base64Decode(file).toString();
System.debug('Sachin'+'['+ myFile + ']');
Debug logs
I found an answer by myself. Please take a look and provide feedback.
String File = 'U25vLE5hbWUsTGFzdCBOYW1lLEVtcCBJZCxKb2IgRnVuY3Rpb24NCjEsU2FjaGluLENob3VyYXNpeWEsMzMwLEJ1c2luZXNzDQoyLFJhamF0ICxTYXhlbmEgLDMzNCxGdW5jdGlvbmFsDQo=';
String myFile = EncodingUtil.base64Decode(file).toString();
System.debug('Sachin'+'['+ myFile + ']');
List<String> EmployeeList = new List<String>();
EmployeeList = myFile.split('\n');
List<Employee__c> employeeInsertList = new List<Employee__c>();
for (String employee : EmployeeList)
{
List<String> fields = new List<String>();
fields = employee.split(',');
Employee__c empRecord = new Employee__c();
empRecord.LastName__c = fields[2];
empRecord.Name = fields[1];
empRecord.EmpId__c = fields[3];
empRecord.Job_Function__c = fields[4];
employeeInsertList.add(empRecord);
}
System.debug('Employee List is '+employeeInsertList);
insert employeeInsertList;

Serializing List<MemoryStream> to a file using a standard .NET class

Writing a WP8 Silverlight app. Is there a standard .NET technique available in this environment I can use to serialize an object like this
private static List<MemoryStream> MemoryStreamList = new List<MemoryStream>();
to save it to a file and restore it later?
I tried to use DataContractJsonSerializer for this which is good to serialize a List of simple custom objects, but it fails for List (I get System.Reflection.TargetInvocationException).
I would suggest converting your list to a list of byte arrays before persisting and then you should be able to serialize. Of course this comes with some overhead at deserialization as well.
Serialization part:
byte[] bytes = null;
var newList = MemoryStreamList.Select(x => x.ToArray()).ToList();
XmlSerializer ser = new XmlSerializer(newList.GetType());
using (var ms = new MemoryStream())
{
ser.Serialize(ms, newList);
//if you want your result as a string, then uncomment to lines below
//ms.Seek(0, SeekOrigin.Begin);
//using (var sr = new StreamReader(ms))
//{
//string serializedStuff = sr.ReadToEnd();
//}
//else you can call ms.ToArray() here and persist the byte[]
bytes = ms.ToArray();
}
Deserialization part:
using (var ms = new MemoryStream(bytes))
{
var result = ser.Deserialize(ms) as List<byte[]>;
}

How to set HtmlSaveOptions to save html and resources to stream using Aspose PDF

I am trying to use Aspose.PDF to load PDF from databases, convert it to HTML and render them to our web page.I want to know if we can save both the document and the resource to stream since current example in the document of Aspose.PDF saves css and images to a local path. I have tried this but the is and error that Aspose.Pdf.SaveFormat.Html is not supported.
Aspose.Pdf.Document PDFDocument = new Aspose.Pdf.Document(PDFStream);
MemoryStream HTMLStreamFromPDF = new MemoryStream();
PDFDocument.Save(HTMLStreamFromPDF, Aspose.Pdf.SaveFormat.Html);
If it can be done, how to write the parameters of CustomResourceSavingStrategy, CustomCssSavingStrategy, and CustomStrategyOfCssUrlCreation of HtmlSaveOptions. I am sorry that I am not quite familiar with delegate in C#
Thanks!
Finally found a way to save all files to stream.
MemoryStream HTMLStreamFromPDF = new MemoryStream();
List<MemoryStream> ResourseStreamList = new List<MemoryStream>();
List<string> ResourceNameList = new List<string>();
MemoryStream CSSStream = new MemoryStream();
Aspose.Pdf.HtmlSaveOptions saveOptions = new Aspose.Pdf.HtmlSaveOptions();
CustomResourcesProcessingBind customResourcesProcessingBind = new CustomResourcesProcessingBind((_1) => CustomResourcesProcessing(ResourseStreamList,ResourceNameList, RequestURL, _1));
saveOptions.CustomResourceSavingStrategy = new Aspose.Pdf.HtmlSaveOptions.ResourceSavingStrategy(customResourcesProcessingBind);
CssUrlCreationCustomStrategyBind cssUrlCreationCustomStrategyBind = new CssUrlCreationCustomStrategyBind((_1) => CssUrlCreationCustomStrategy(RequestURL, _1));
saveOptions.CustomStrategyOfCssUrlCreation = new Aspose.Pdf.HtmlSaveOptions.CssUrlMakingStrategy(cssUrlCreationCustomStrategyBind);
CustomCssSavingProcessingBind customCssSavingProcessingBind = new CustomCssSavingProcessingBind((_1) => CustomCssSavingProcessing(CSSStream, _1));
saveOptions.CustomCssSavingStrategy = new Aspose.Pdf.HtmlSaveOptions.CssSavingStrategy(customCssSavingProcessingBind);
saveOptions.HtmlMarkupGenerationMode = Aspose.Pdf.HtmlSaveOptions.HtmlMarkupGenerationModes.WriteOnlyBodyContent;
PDFDocument.Save(HTMLStreamFromPDF, saveOptions);
private delegate string CustomResourcesProcessingBind(Aspose.Pdf.SaveOptions.ResourceSavingInfo resourceSavingInfo);
private static string CustomResourcesProcessing(List<MemoryStream> ResourseStreamList, List<string> ResourceNameList, string RequestURL, Aspose.Pdf.SaveOptions.ResourceSavingInfo resourceSavingInfo)
{
MemoryStream newResource = new MemoryStream();
resourceSavingInfo.ContentStream.CopyTo(newResource);
ResourceNameList.Add(resourceSavingInfo.SupposedFileName);
ResourseStreamList.Add(newResource);
string urlThatWillBeUsedInHtml = RequestURL +"/"+ Path.GetFileName(resourceSavingInfo.SupposedFileName);
return urlThatWillBeUsedInHtml;
}
private delegate string CssUrlCreationCustomStrategyBind(Aspose.Pdf.HtmlSaveOptions.CssUrlRequestInfo requestInfo);
private static string CssUrlCreationCustomStrategy(string RequestURL,Aspose.Pdf.HtmlSaveOptions.CssUrlRequestInfo requestInfo)
{
return RequestURL + "/css_style.css";
}
private delegate void CustomCssSavingProcessingBind(Aspose.Pdf.HtmlSaveOptions.CssSavingInfo resourceInfo);
private static void CustomCssSavingProcessing(MemoryStream CSSStream, Aspose.Pdf.HtmlSaveOptions.CssSavingInfo resourceInfo)
{
resourceInfo.ContentStream.CopyTo(CSSStream);
}
Check the following sample code regarding how to use parameters CustomResourceSavingStrategy, CustomCssSavingStrategy and CustomStrategyOfCssUrlCreation of HtmlSaveOptions when converting from PDF to HTML.
static string _folderForReferencedResources;
static void Main(string[] args)
{
Document pdfDocument = new Document(#"F:\ExternalTestsData\input.pdf");
string outHtmlFile = #"F:\ExternalTestsData\output.html";
_folderForReferencedResources = #"F:\ExternalTestsData\resources\";
//-----------------------------------------------------
// 2)clean results if they already present
//-----------------------------------------------------
if (Directory.Exists(_folderForReferencedResources))
{
Directory.Delete(_folderForReferencedResources, true);
}
File.Delete(outHtmlFile);
//-----------------------------------------------------
// create HtmlSaveOption with tested feature
//-----------------------------------------------------
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
saveOptions.CustomResourceSavingStrategy = new HtmlSaveOptions.ResourceSavingStrategy(Strategy_11_CUSTOM_SAVE_OF_FONTS_AND_IMAGES);
saveOptions.CustomCssSavingStrategy = new HtmlSaveOptions.CssSavingStrategy(Strategy_11_CSS_WriteCssToPredefinedFolder);
saveOptions.CustomStrategyOfCssUrlCreation = new HtmlSaveOptions.CssUrlMakingStrategy(Strategy_11_CSS_ReturnResultPathInPredefinedTestFolder);
using (Stream outStream = File.OpenWrite(outHtmlFile))
{
pdfDocument.Save(outStream, saveOptions);
}
}
private static void Strategy_11_CSS_WriteCssToPredefinedFolder(HtmlSaveOptions.CssSavingInfo resourceInfo)
{
if (!Directory.Exists(_folderForReferencedResources))
{
Directory.CreateDirectory(_folderForReferencedResources);
}
string path = _folderForReferencedResources + Path.GetFileName(resourceInfo.SupposedURL);
System.IO.BinaryReader reader = new BinaryReader(resourceInfo.ContentStream);
System.IO.File.WriteAllBytes(path, reader.ReadBytes((int)resourceInfo.ContentStream.Length));
}
private static string Strategy_11_CSS_ReturnResultPathInPredefinedTestFolder(HtmlSaveOptions.CssUrlRequestInfo requestInfo)
{
return "file:///" + _folderForReferencedResources.Replace(#"\", "/") + "css_style{0}.css";
}
private static string Strategy_11_CUSTOM_SAVE_OF_FONTS_AND_IMAGES(SaveOptions.ResourceSavingInfo resourceSavingInfo)
{
if (!Directory.Exists(_folderForReferencedResources))
{
Directory.CreateDirectory(_folderForReferencedResources);
}
string path = _folderForReferencedResources + Path.GetFileName(resourceSavingInfo.SupposedFileName);
// first path of this method is for saving of font
System.IO.BinaryReader contentReader = new BinaryReader(resourceSavingInfo.ContentStream);
System.IO.File.WriteAllBytes(path, contentReader.ReadBytes((int)resourceSavingInfo.ContentStream.Length));
string urlThatWillBeUsedInHtml = "file:///" + _folderForReferencedResources.Replace(#"\", "/") + Path.GetFileName(resourceSavingInfo.SupposedFileName);
return urlThatWillBeUsedInHtml;
}
The details are available here.
P.S. I am Social Media Developer at Aspose.

DataSource attribute for unit test method

I try to use CSV data source in Device unit test (WinCE/Pocket PC2003 Emulator)
I have added source in using wizard in Data Connection String property:
using Microsoft.VisualStudio.TestTools.UnitTesting;
....
[TestMethod()]
[DeploymentItem("Options.txt")]
[DeploymentItem("Options_1.txt")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "C:\\...\\Tests\\Data\\LoadSettingsTest.csv", "LoadSettingsTest#csv", DataAccessMethod.Sequential)]
public void LoadSettingsTest()
{
...
}
I have following compiler error:
Error 1 The type or namespace name 'DataSource' could not be found
(are you missing a using directive or an assembly reference?)
Error 2 The type or namespace name 'DataSourceAttribute' could not be
found (are you missing a using directive or an assembly reference?)
What's? Where DataSource is defined? Is data DataSource attribute supported in device unit tests?
DataSource is not supported by Device Unit Testing Framework, see Unit Testing Framework (Devices).
It looks like you are trying to use a Comma Separated Values (CSV) file as a DataSource.
You should convert your CSV data into something a Data Control is familiar with first.
Here is an example:
private const string FIELD_SEP = "\t";
private const string LINE_BREAK = "\r\n";
private const int ONE_KB = 1024;
private System.Data.DataTable GenerateData(string csvDataFile) {
var sb = new System.Text.StringBuilder();
using (var file = File.Open(csvDataFile, FileMode.Open, FileAccess.Read)) {
byte[] buffer = new byte[ONE_KB];
int len = file.Read(buffer, 0, ONE_KB);
while (-1 < len) {
string oneK = Encoding.UTF8.GetString(buffer, 0, len);
sb.Append(oneK);
len = file.Read(buffer, 0, ONE_KB);
}
}
var table = new System.Data.DataTable();
var col1 = table.Columns.Add("ID", typeof(int));
var col2 = table.Columns.Add("Name", typeof(string));
var col3 = table.Columns.Add("Date", typeof(DateTime));
var col4 = table.Columns.Add("Cost", typeof(decimal));
var lines = sb.ToString().Split(LINE_BREAK.ToArray());
foreach (var line in lines) {
System.Data.DataRow row = table.NewRow();
var fields = line.Split(FIELD_SEP.ToArray());
row[col1] = int.Parse(fields[0]);
row[col2] = fields[1];
row[col3] = DateTime.Parse(fields[2]);
row[col4] = decimal.Parse(fields[3]);
table.Rows.Add(row);
}
return table;
}
Of course, I have no idea what kind of data you are trying to extract from this CSV file, and there is no error checking. If field[3] were an empty string, decimal.Parse(field[3]) would throw an exception.