public interface IHelloWorld
{
T SayHello<T>();
}
public class HelloWorld : IHelloWorld
{
public T SayHello<T>()
{
if (typeof(T) == typeof(string))
return (T)(object)"Hello, World!";
else
return default(T);
}
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
function(a, b)
{
return a + b;
}
add(1, 2)
public static string GetValueByKey(Dictionary<int, string> dic, int key){
if(dic.ContainsKey(key)){
return dic[key];
}else
{
return null;
}
}
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddHttpClient();
}
}
public static T CreateInstance<T>()
{
return default(T);
}
public class Startup : IWebJobsStartup
{
public void Configure(IWebJobsBuilder builder)
{
builder.Services.AddHttpClient();
builder.Services.AddMvc()
.AddNewtonsoftJson();
}
}
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.");
}
}
public static class GenericFactory
{
public static T Get<T>() where T : new()
{
return new T();
}
}
// Usage:
Person person = GenericFactory.Get<Person>();
using (Stream stream = new MemoryStream(File.ReadAllBytes("sample.xlsx")))
{
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
int[,] TwoDimArray = new int[3, 4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
Console.Write(TwoDimArray[i, j]);
}
}
g.Select(x => x.Sum(y => y.Quantity)).ToList()
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());
}
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();
}
}
public static Stream iformfiletoStream(IFormFile file){
Stream stream;
if (file.Length > 0)
{
using (stream = file.OpenReadStream())
{
return stream;
}
}
else
{
return null;
}
}
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
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
foreach (int element in array)
{
Console.WriteLine(element);
}
dic["GOL"] = "Golang"
dic.ContainsKey("GOL")
dic.TryGetValue("GOL", out var value)
dic.GetOrDefault("GOL", "")
int add(int a, int b)
{
return a + b;
}
add(1, 2);
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;
}
}
}
// 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());
}
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[
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);
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();
}
}
}
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());
}
}
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[
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);
}
Dictionary<string, int> numbers = new Dictionary<string, int>();
numbers["one"] = 1;
numbers["two"] = 2;
numbers["three"] = 3;
int value = numbers["one"];
// value is 1
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware<TokenValidatorMiddleware>();
app.UseMvc();
}
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);
}
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
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);
}
}
public static T Create<T>() where T : new()
{
return new T();
}
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}");
}
}
}
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}");
}
}
}
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();
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()
};
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((
public static bool HasAValue(string[] array, string value)
{
return array.Contains(value);
}
public static bool elemmatch(string[] arr, string str)
{
foreach (var item in arr)
if (item == str)
return true;
return false;
}
public class Startup : IWebJobsStartup
{
public void Configure(IWebJobsBuilder builder)
{
builder.Services.AddHttpClient();
}
}
public void ReadExcel(string filePath)
{
var fileExt = Path.GetExtension(filePath);
if (fileExt == ".xls")
{
//...
}
else if (fileExt == ".xlsx")
{
//...
}
else
{
throw new Exception("Wrong file type");
}
}
for (int i = 0, j = 10; i < j; i++, j--)
{
}
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;
}
public void Check(int x, int y)
{
if (x > y)
{
Console.WriteLine("x is greater than y");
}
else
{
Console.WriteLine("x is NOT greater than y");
}
}
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;
}
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);
}
public class MyObject {
public string someString;
public int someInt;
}
public class MyClass {
public T makeObject<T>(string a, int b) where T : MyObject, new() {
T t = new T();
t.someString = a;
t.someInt = b;
return t;
}
}
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
// 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,
public class Startup
{
public void Configure(IFunctionsHostBuilder builder)
{
builder.UseMiddleware<MyMiddleware>();
}
}
CreateMap<Source, Destination>();
public interface IRepository<T>
{
void Create(T obj);
void Edit(T obj);
void Delete(int id);
void Delete(T obj);
void GetById(T obj);
IEnumerable<T> GetAll();
}