Julian Gonzalez

All generations.

generate functionThu, 04 May 2023

example create middleware in web api .Net 6 and show register in Program.cs and use from controller

public class LoggingMiddleware { private readonly RequestDelegate _next; public LoggingMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context, ILogger<LoggingMiddleware> logger) { logger.LogInformation("Handling request: " + context.Request.Path); await _next(context); logger.LogInformation("Finished handling request."); } }

generate functionTue, 25 Apr 2023

How to generate api keys in .net 6

public static string CreateApiKey() { var random = new Random(); const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return new string(Enumerable.Repeat(chars, 32) .Select(s => s[random.Next(s.Length)]).ToArray()); }

generate functionThu, 30 Mar 2023

How to return a generic object in c# create objects and implement interface

interface IAnimal { void Breathe(); } class Dog : IAnimal { public void Breathe() { Console.WriteLine("I'm breathing"); } } class Cat : IAnimal { public void Breathe() { Console.WriteLine("I'm breathing"); } } class Program { static void Main(string[] args) { IAnimal dog = GetAnimal(args[0]); dog.Breathe(); IAnimal cat = GetAnimal(args[0]); cat.Breathe(); Console.ReadLine(); } private static IAnimal GetAnimal(string animal) { if (animal == "dog") { return new Dog(); } return new Cat(); } }

generate functionFri, 31 Mar 2023

iformfile to stream c#

public static Stream iformfiletoStream(IFormFile file){ Stream stream; if (file.Length > 0) { using (stream = file.OpenReadStream()) { return stream; } } else { return null; } }

generate functionTue, 04 Apr 2023

$elemmatch mongdb string array

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Driver; using MongoDB.Driver.Builders; using MongoDB.Driver.GridFS; using MongoDB.Driver.Linq; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.IdGenerators; using MongoDB.Bson.Serialization.Options; using MongoDB.Bson.Serialization.Serializers; namespace MongoDB { class Program { static void Main(string[] args) { try { Console.WriteLine("Connecting to MongoDB..."); var connectionString = "mongodb://localhost"; var client = new MongoClient(connectionString); var server = client.GetServer(); var database = server.GetDatabase("DbName"); // get our

generate functionTue, 25 Apr 2023

Simple and secure custom API Keys using ASP.NET Core

public class ApiKeyFilter : IAuthorizationFilter { private const string ApiKeyName = "api_key"; private const string ApiKeyValue = "abcdefghijklmnopqrstuvwxyz"; public void OnAuthorization(AuthorizationFilterContext context) { if (!context.HttpContext.Request.Headers.TryGetValue(ApiKeyName, out var potentialApiKey)) { context.Result = new UnauthorizedResult(); return; } if (!ApiKeyValue.Equals(potentialApiKey)) { context.Result = new UnauthorizedResult(); return; } } }

generate functionFri, 07 Apr 2023

Group next class by field CompanyId and add all CampaignId in a list Linq lambda public class ReportWeeklyDTO { public string CampaignId { get; set; } public string CampaignName { get; set; } public int NumberMessages { get; set; } public string User { get; set; } public int SentMessages { get; set; } public int ErrorMessages { get; set; } public string ErrorDescription { get; set; } public string CompanyId { get; set; } }

// function name -> GroupByCampaignId // input parameter -> ReportWeeklyDTO // return => ??? private ??? GroupByCampaignId(ReportWeeklyDTO[] reportWeeklyDTOs) { return reportWeeklyDTOs.GroupBy(x => x.CompanyId).ToDictionary(x => x.Key, x => x.Select(s => s.CampaignId).ToList()); }

generate functionWed, 29 Mar 2023

Read excel file in .Net 6

using Microsoft.Office.Interop.Excel; var xlApp = new Application(); var xlWorkbook = xlApp.Workbooks.Open(fileName); var xlWorksheet = xlWorkbook.Sheets[1]; var xlRange = xlWorksheet.UsedRange; int rowCount = xlRange.Rows.Count; int colCount = xlRange.Columns.Count; //iterate over the rows and columns and print to the console as it appears in the file //excel is not zero based!! for (int i = 1; i <= rowCount; i++) { for (int j = 1; j <= colCount; j++) { //new line if (j == 1) Console.Write("\r\n"); //write the value to the console if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null) Console.Write(xlRange.Cells[

generate functionSat, 01 Apr 2023

map objects c# with automapper library

public class Customer { public string Name { get; set; } public string Address { get; set; } } public class CustomerDto { public string Name { get; set; } public string Address { get; set; } } // mapper config var config = new MapperConfiguration(cfg => { cfg.CreateMap<Customer, CustomerDto>(); }); var mapper = config.CreateMapper(); // do your mapping return mapper.Map<CustomerDto>(customer);

generate functionSat, 01 Apr 2023

using dictionarys in c#

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp8 { class Program { static void Main(string[] args) { Dictionary<string, int> students = new Dictionary<string, int>(); students.Add("Brian", 23); students.Add("Dillon", 22); students.Add("Matt", 23); students.Add("Colin", 22); students.Add("Barry", 25); students.Add("Sean", 25); students.Add("Kevin", 25); foreach (KeyValuePair<string, int> student in students) { Console.WriteLine(student.Value); } Console.ReadLine(); } } }

generate functionThu, 30 Mar 2023

create interface with method that return generic object and where clausule

public interface IGeneric<T> { T Get(); } public class GenericClass<T> : IGeneric<T> { public T Get() { throw new NotImplementedException(); } } public static class Run { public static void Main() { var igen = new GenericClass<int>(); var sgen = new GenericClass<string>(); DoSomething(igen); DoSomething(sgen); } private static void DoSomething<T>(IGeneric<T> arg) where T : class { Console.WriteLine(arg.Get()); } }

generate functionThu, 30 Mar 2023

How to return a generic object in c# create objects

public static Object create(String className, String[] params) { Object o = null; Assembly asm = Assembly.GetExecutingAssembly(); Type t = asm.GetType(className); int l = params.Length; switch (l) { case 0: o = Activator.CreateInstance(t); break; case 1: o = Activator.CreateInstance(t, params[0]); break; case 2: o = Activator.CreateInstance(t, params[0], params[1]); break; case 3: o = Activator.CreateInstance(t, params[0], params[1], params[2]); break; case 4: o = Activator.CreateInstance(t, params[0], params[1], params[2], params[3]); break; case 5: o = Activator.CreateInstance(t, params[0], params[1], params[2], params[3], params[

generate functionFri, 07 Apr 2023

Add fileds in a list after groupby linq

public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector) { return source.GroupBy(keySelector, elementSelector, EqualityComparer<TKey>.Default); } public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer) { return new GroupedEnumerable<TSource, TKey, TElement>(source, keySelector, elementSelector, comparer); }

generate functionSat, 01 Apr 2023

using dictionarys in c#

Dictionary<string, int> numbers = new Dictionary<string, int>(); numbers["one"] = 1; numbers["two"] = 2; numbers["three"] = 3; int value = numbers["one"]; // value is 1

generate functionSat, 01 Apr 2023

map objects c# with automapper

static void AutoMapper() { Mapper.Initialize(cfg => { cfg.CreateMap<int, string>().ConvertUsing(i => i.ToString()); cfg.CreateMap<int, DateTime>().ConvertUsing(i => DateTime.Now); }); Mapper.AssertConfigurationIsValid(); var str1 = Mapper.Map<string>(3); var str2 = Mapper.Map<DateTime>(3); Console.WriteLine(str1); Console.WriteLine(str2); }

generate functionFri, 31 Mar 2023

Read excel file in .NEt 6 using EPPlus library

public static void Main(string[] args) { //nuget package manager or dotnet cli //install-package EPPlus //https://www.nuget.org/packages/EPPlus/ //https://github.com/JanKallman/EPPlus FileInfo file = new FileInfo(@"C:\Test\" + "ExcelSample.xlsx"); ExcelPackage.LicenseContext = LicenseContext.NonCommercial; using (ExcelPackage package = new ExcelPackage(file)) { //Get the work book in the file ExcelWorkbook workBook = package.Workbook; if (workBook != null) { if (workBook.Worksheets.Count > 0) { //Get the first worksheet ExcelWorksheet currentWorksheet = workBook.Worksheets.First(); //Read some data Console.WriteLine(currentWorksheet.Cells["B1"].Value); Console.WriteLine(currentWorksheet.Cells["B2"].Value

generate functionThu, 04 May 2023

example create middleware in web api .Net 6

public class MyMiddleware { private readonly RequestDelegate _next; public MyMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { var a = 1; var b = 2; var c = a + b; // do something with c await _next(context); } }

generate functionFri, 31 Mar 2023

Read excel file in .NEt 6 using OfficeOpenXml

using System; using System.Diagnostics; using System.IO; using OfficeOpenXml; public class Program { public static void Main() { FileInfo file = new FileInfo("data.xlsx"); ExcelPackage.LicenseContext = LicenseContext.NonCommercial; using (ExcelPackage package = new ExcelPackage(file)) { ExcelWorksheet worksheet = package.Workbook.Worksheets[0]; string name = worksheet.Cells[2, 1].Value.ToString(); string email = worksheet.Cells[2, 2].Value.ToString(); string phone = worksheet.Cells[2, 3].Value.ToString(); string state = worksheet.Cells[2, 4].Value.ToString(); int age = int.Parse(worksheet.Cells[2, 5].Value.ToString()); Debug.WriteLine($"Name: {name}, email: {email}"); } } }

generate functionFri, 31 Mar 2023

Read excel file in .NEt 6 using EPPlus library

public static void ReadExcel(string filePath) { FileInfo file = new FileInfo(filePath); using (ExcelPackage package = new ExcelPackage(file)) { ExcelWorksheet worksheet = package.Workbook.Worksheets[1]; var rowCount = worksheet.Dimension.Rows; for (int row = 1; row <= rowCount; row++) { var name = worksheet.Cells[row, 1].Value; var age = worksheet.Cells[row, 2].Value; Console.WriteLine( $"Name: {name} - Age: {age}"); } } }

generate functionFri, 07 Apr 2023

Group next class by field CompanyId and add all CampaignId in a list Linq lambda public class ReportWeeklyDTO { public string CampaignId { get; set; } public string CampaignName { get; set; } public int NumberMessages { get; set; } public string User { get; set; } public int SentMessages { get; set; } public int ErrorMessages { get; set; } public string ErrorDescription { get; set; } public string CompanyId { get; set; } }

return reports.GroupBy(x => x.CompanyId).Select(x => new ReportWeeklyDTO { CampaignId = string.Join(",", x.Select(y => y.CampaignId).ToList()), CampaignName = string.Join(",", x.Select(y => y.CampaignName).ToList()), NumberMessages = x.Sum(y => y.NumberMessages), User = x.First().User, SentMessages = x.Sum(y => y.SentMessages), ErrorMessages = x.Sum(y => y.ErrorMessages), CompanyId = x.First().CompanyId, ErrorDescription = x.Sum(y => y.ErrorMessages) > 0 ? string.Join(",", x.Where(y => !string.IsNullOrEmpty(y.ErrorDescription)).Select(y => y.ErrorDescription).ToList()) : null }).ToList();

generate functionFri, 07 Apr 2023

Group next class by field CompanyId and add all CampaignId in a list public class ReportWeeklyDTO { public string CampaignId { get; set; } public string CampaignName { get; set; } public int NumberMessages { get; set; } public string User { get; set; } public int SentMessages { get; set; } public int ErrorMessages { get; set; } public string ErrorDescription { get; set; } public string CompanyId { get; set; } }

public class ReportWeeklyDTO { public string CampaignId { get; set; } public string CampaignName { get; set; } public int NumberMessages { get; set; } public string User { get; set; } public int SentMessages { get; set; } public int ErrorMessages { get; set; } public string ErrorDescription { get; set; } public string CompanyId { get; set; } } var query = from e in reportWeeklyDTOs group e by e.CompanyId into companyGroup select new { CompanyId = companyGroup.Key, CampaignIds = companyGroup.Select(x => x.CampaignId).ToList() };

generate functionSat, 01 Apr 2023

travel array with two dimensions c#

public class VisitedArray { bool[,] visited; List<(int, int)> path = new List<(int, int)>(); public List<(int, int)> GetPath(bool[,] visited) { this.visited = visited; GetPath(0, 0); return path; } public bool GetPath(int i, int j) { if (i == visited.GetLength(0) - 1 && j == visited.GetLength(1) - 1) { path.Add((i, j)); return true; } if (i >= visited.GetLength(0) || j >= visited.GetLength(1) || visited[i, j]) { return false; } visited[i, j] = true; if (GetPath(i + 1, j)) { path.Add((i, j)); return true; } if (GetPath(i, j + 1)) { path.Add((

generate functionWed, 29 Mar 2023

Read excel file in .Net 6

public void ReadExcel(string filePath) { var fileExt = Path.GetExtension(filePath); if (fileExt == ".xls") { //... } else if (fileExt == ".xlsx") { //... } else { throw new Exception("Wrong file type"); } }

generate functionThu, 30 Mar 2023

Read excel file in .Net 6 using EPPlus library

using OfficeOpenXml; public DataTable ReadExcelFile(string path, string sheetName) { DataTable dt = new DataTable(); using (ExcelPackage package = new ExcelPackage(new System.IO.FileInfo(path))) { ExcelWorksheet workSheet = package.Workbook.Worksheets[sheetName]; foreach (ExcelRangeBase cell in workSheet.Cells) { if (cell.Start.Column == 1 && cell.Start.Row != 1) { dt.Rows.Add(); } if (cell.Start.Row == 1) { dt.Columns.Add(cell.Text); } else { dt.Rows[cell.Start.Row - 2][cell.Start.Column - 1] = cell.Text; } } } return dt; }

generate functionFri, 31 Mar 2023

iformfile to fileinfo c#

public static FileInfo GetFileInfo(this IFormFile formFile) { var fileName = ContentDispositionHeaderValue.Parse(formFile.ContentDisposition).FileName.Trim('"'); var myUniqueFileName = Convert.ToString(Guid.NewGuid()); var FileExtension = Path.GetExtension(fileName); var newFileName = myUniqueFileName + FileExtension; var file = new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads", newFileName)); return file; }

generate functionThu, 30 Mar 2023

create interface with method that return generic object with where clausule

public interface IGenericObject { // add properties to object void Add(string name, object value); //return object with property name object Get(string name); // return object object Get(); // return collection of property names IEnumerable<string> GetProperties(); // return where sql clausule with property name = value string Where(); } // return generic object with where clausule public interface IWhere { // return object that implement IGenericObject IGenericObject Where(string name, object value); }

generate functionSat, 01 Apr 2023

using dictionarys in c#

public void add(string a, string b) { var dict = new Dictionary<string, int>(); dict.Add("one", 1); dict.Add("two", 2); dict.Add("three", 3); dict.Add("four", 4); dict.Add("five", 5); dict.Add("six", 6); dict.Add("seven", 7); dict.Add("eight", 8); dict.Add("nine", 9); dict.Add("ten", 10); dict.Add("eleven", 11); dict.Add("twelve", 12); dict.Add("thirteen", 13); dict.Add("fourteen", 14); dict.Add("fifteen", 15); dict.Add("sixteen", 16); dict.Add("seventeen", 17); dict.Add("eighteen", 18); dict.Add("nineteen", 19); dict.Add("twenty", 20); dict.Add("thirty", 30); dict.Add("forty", 40); dict.Add("fifty", 50); dict

generate functionSat, 01 Apr 2023

map objects c# with mapper

// map two objects var a = new {a = 1, b = 2}; var b = new {a = 3, b = 4}; var c = a.MapWith(b); // map array of objects var a = new[] { new {a = 1, b = 2}, new {a = 3, b = 4} }; var b = new[] { new {a = 5, b = 6}, new {a = 7, b = 8} }; var c = a.MapWith(b); // map list of objects var a = new List<{a = 1, b = 2}> { new {a = 1, b = 2}, new {a = 3, b = 4} }; var b = new List<{a = 1, b = 2}> { new {a = 5, b = 6}, new {a = 7, b = 8} }; var c = a.MapWith(b); // map any IEnumerable of objects var a = new List<{a = 1, b = 2}> { new {a = 1,

Questions about programming?Chat with your personal AI assistant