分类目录.NetCore

C#获取多个时间段的并集

        /// <summary>
        /// 获取时间段并集
        /// </summary>
        /// <param name="list">传入的时间(开始时间正序)</param>
        /// <returns></returns>
        private List<Time> GetListTime(List<Time> list)
        {
            for (int i = 0; i < list.Count; i++)
            {
                var dataI = list[i];
                for (int j = i + 1; j < list.Count; j++)
                {
                    var dataJ = list[j];
                    if (dataI.eTime.CompareTo(dataJ.bTime) >= 0 && dataI.eTime.CompareTo(dataJ.bTime) <= 0)
                    {
                        dataI.eTime = dataJ.eTime;
                        list.Remove(dataJ);
                        j--;
                    }
                    else if (dataI.eTime.CompareTo(dataJ.eTime) >= 0)
                    {
                        list.Remove(dataJ);
                        j--;
                    }
                    else
                    {
                        break;
                    }
                    i = j;
                }
            }
            return list;
        }
    public class Time
    {
        public DateTime bTime { get; set; }
        public DateTime eTime { get; set; }
    }

Quartz.netcore发布到linux未执行

在本地很够正常执行,发布到服务器上就不行,于是我打印日志发现错误信息是:The SSL connection could not be established, see inner exception.

好像是SLL连接被拒绝了,检查代码发现我是请求了接口的,源码如下

 public RESTResponseEntity RequestGet(string url)
        {
            RESTResponseEntity entity = new RESTResponseEntity();
            try
            {
               
                HttpClient httpClient = new HttpClient();
                if (timeout > 0)
                {
                    httpClient.Timeout = TimeSpan.FromMilliseconds(timeout);
                }
                //httpClient.DefaultRequestHeaders.Add(HEAD_KEY, TOKEN_KEY_PREFIX + " " + tokenKey);
                string strUrl = baseUrl + url;
                HttpResponseMessage hrm = httpClient.GetAsync(strUrl).Result;
                entity.StatusCode = Convert.ToInt32(hrm.StatusCode);
                entity.Data = hrm.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                throw;
            }
            return entity;
        }

后面查阅后,加如下代码可解决这个问题,改造后

 public RESTResponseEntity RequestGet(string url)
        {
            RESTResponseEntity entity = new RESTResponseEntity();
            try
            {
                var httpClientHandler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true
                };
                HttpClient httpClient = new HttpClient(httpClientHandler);
                if (timeout > 0)
                {
                    httpClient.Timeout = TimeSpan.FromMilliseconds(timeout);
                }
                //httpClient.DefaultRequestHeaders.Add(HEAD_KEY, TOKEN_KEY_PREFIX + " " + tokenKey);
                string strUrl = baseUrl + url;
                HttpResponseMessage hrm = httpClient.GetAsync(strUrl).Result;
                entity.StatusCode = Convert.ToInt32(hrm.StatusCode);
                entity.Data = hrm.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                throw;
            }
            return entity;
        }

Npoi动态导入

  public mResult Import(HttpPostedFileBase file, string tabName)
        {
            mResult ret = new mResult();
            ret.Code = "200";
            ret.Msg = "操作成功!";
            try
            {
                var strPath = @"~/up/" + DateTime.Now.ToString("yyyyMMdd");
                if (!Directory.Exists(strPath))
                {
                    //需要注意的是,需要对这个物理路径有足够的权限,否则会报错 
                    DirectoryInfo di = Directory.CreateDirectory(strPath);
                }
                var thisFileName = Guid.NewGuid().ToString().Replace("-", "") + "." + file.FileName.Split('.').LastOrDefault();
                var thisFilePath = Server.MapPath(strPath) + thisFileName;
                file.SaveAs(thisFilePath);
                using (var fileStream = System.IO.File.Open(thisFilePath, FileMode.Open))
                {
                    //把xls文件中的数据写入wk中,根据不同的文件格式实例化不同的对象去操作文件
                    IWorkbook wk;
                    string filePathChoice = thisFileName.Substring(thisFileName.LastIndexOf('.') + 1);
                    if (filePathChoice.Equals("xlsx"))
                    {
                        wk = new XSSFWorkbook(fileStream);
                    }
                    else
                    {
                        wk = new HSSFWorkbook(fileStream);
                    }
                    var sheet = wk.GetSheetAt(0); //读取当前表数据,直接去第一个Sheet
                                                  //判断是否有除去标题行的一行数据
                    if (sheet.LastRowNum < 1)
                    {
                        ret.Msg = "无数据";
                    }

                    AssemblyResult assInfo = ah.GetClassInfo("DataCenters.DAL.dll", "DataCenters.DAL." + tabName);

                    List<object> list = new List<object>();
                    // 去掉第一行
                    for (var j = 3; j <= sheet.LastRowNum; j++) //LastRowNum 是当前表的总行数
                    {
                        var row = sheet.GetRow(j); //读取当前行数据
                        var titles = sheet.GetRow(2);//标题列字段
                        if (row != null)
                        {
                            var obj = Activator.CreateInstance(assInfo.ClassType);
                            for (var k = 0; k <= row.LastCellNum; k++) //LastCellNum 是当前行的总列数
                            {
                                var title = titles.GetCell(k).ToString().ToLower().Trim();//对应字段
                                var cell = row.GetCell(k); //当前表格
                                var field = assInfo.Properties.Any(w => w.ToLower().Trim() == title) ? assInfo.Properties.FirstOrDefault(w => w.ToLower().Trim() == title) : "";
                                var fieldType = assInfo.PropertyType[assInfo.Properties.IndexOf(field)];
                                if (field != "" && cell != null)
                                {
                                    Debug.WriteLine("field", field);
                                    Debug.WriteLine("fieldType", fieldType);

                                    if (fieldType.ToLower().Contains("decimal"))
                                    {
                                        obj.GetType().GetProperty(field).SetValue(obj, Convert.ToDecimal(cell.ToString()));
                                    }
                                    else if (fieldType.ToLower().Contains("int16"))
                                    {
                                        obj.GetType().GetProperty(field).SetValue(obj, Convert.ToInt16(cell.ToString()));
                                    }
                                    else if (fieldType.ToLower().Contains("int32"))
                                    {
                                        obj.GetType().GetProperty(field).SetValue(obj, Convert.ToInt32(cell.ToString()));
                                    }
                                    else if (fieldType.ToLower().Contains("double"))
                                    {
                                        obj.GetType().GetProperty(field).SetValue(obj, Convert.ToDouble(cell.ToString()));
                                    }
                                    else if (fieldType.ToLower().Contains("datetime"))
                                    {
                                        obj.GetType().GetProperty(field).SetValue(obj, Convert.ToDateTime(cell.ToString()));
                                    }
                                    else
                                    {
                                        obj.GetType().GetProperty(field).SetValue(obj, cell.ToString());
                                    }
                                }
                            }
                            list.Add(obj);
                        }
                    }
                    ret.Data = list;
                }
            }
            catch (Exception e)
            {
                ret.Code = "500";
                ret.Msg = e.Message;
                throw;
            }
            return ret;
        }

        public class mResult
        {
            public string Code { get; set; }
            public string Msg { get; set; }
            public object Data { get; set; }
        }

AutoMapHelper帮助类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public static class AutoMapHelper
    {

        /// <summary>
        ///  类型映射,默认字段名字一一对应
        /// </summary>
        /// <typeparam name="TDestination"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static TDestination AutoMapTo<TDestination>(this object obj)
        {
            if (obj == null) return default(TDestination);
            var config = new AutoMapper.MapperConfiguration(cfg => cfg.CreateMap(obj.GetType(), typeof(TDestination)));
            return config.CreateMapper().Map<TDestination>(obj);
        }

        /// <summary>
        /// 类型映射,可指定映射字段的配置信息
        /// </summary>
        /// <typeparam name="TSource">源数据:要被转化的实体对象</typeparam>
        /// <typeparam name="TDestination">目标数据:转换后的实体对象</typeparam>
        /// <param name="source">任何引用类型对象</param>
        /// <param name="cfgExp">可为null,则自动一一映射</param>
        /// <returns></returns>
        public static TDestination AutoMapTo<TSource, TDestination>(this TSource source, Action<AutoMapper.IMapperConfigurationExpression> cfgExp)
            where TDestination : class
            where TSource : class
        {
            if (source == null) return default(TDestination);
            var config = new AutoMapper.MapperConfiguration(cfgExp != null ? cfgExp : cfg => cfg.CreateMap<TSource, TDestination>());
            var mapper = config.CreateMapper();
            return mapper.Map<TDestination>(source);
        }



        /// <summary>
        /// 类型映射,默认字段名字一一对应
        /// </summary>
        /// <typeparam name="TSource">源数据:要被转化的实体对象</typeparam>
        /// <typeparam name="TDestination">目标数据:转换后的实体对象</typeparam>
        /// <param name="source">任何引用类型对象</param>
        /// <returns>转化之后的实体</returns>
        public static TDestination AutoMapTo<TSource, TDestination>(this TSource source)
            where TDestination : class
            where TSource : class
        {
            if (source == null) return default(TDestination);
            var config = new AutoMapper.MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>());
            var mapper = config.CreateMapper();
            return mapper.Map<TDestination>(source);
        }


        /// <summary>
        /// 集合列表类型映射,默认字段名字一一对应
        /// </summary>
        /// <typeparam name="TDestination">转化之后的实体对象,可以理解为viewmodel</typeparam>
        /// <typeparam name="TSource">要被转化的实体对象,Entity</typeparam>
        /// <param name="source">通过泛型指定的这个扩展方法的类型,理论任何引用类型</param>
        /// <returns>转化之后的实体列表</returns>
        public static IEnumerable<TDestination> AutoMapTo<TSource, TDestination>(this IEnumerable<TSource> source)
            where TDestination : class
            where TSource : class
        {
            if (source == null) return new List<TDestination>();
            var config = new AutoMapper.MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>());
            var mapper = config.CreateMapper();
            return mapper.Map<List<TDestination>>(source);
        }



    }
}

C#异步编程

一.写法
先介绍一下写法,刚接触这两个关键字的时候,看别人写的代码总有些看不懂,后来发现原来是熟手们都喜欢简写,导致新手看不懂,如:

private static async Task TestFunction()
{
return await Task.Run(()=>”Test1″);
}
完整的写法应是:

private static async Task TestFunction()
{
Task task = new Task(() =>
{
return “Test1”;
});
task.Start();
var result = await task;
return result;
}
从完整的写法可以看出,await 等待的是 Task, 返回的是 Task Result 对应的具体类型值。

二.用法
下面以一些示例来说明具体用法和注意点:

1.示例,探究:只要是 async 方法里的操作,都不阻碍当前线程?

static void Main(string[] args)
{
Console.WriteLine(“Test Start”);
TestFunction();
Console.WriteLine(“Test End”);
Console.Read();
}

private static async Task TestFunction()
{
return await Task.Run(() =>
{
Thread.Sleep(2000);

    string result = "Test1";
    Console.WriteLine(result);
    return result;
});

}
结果:

把 TestFunction 方法改成:

private static async Task TestFunction()
{
Thread.Sleep(2000);

return await Task.Run(() =>
{
    string result = "Test1";
    Console.WriteLine(result);
    return result;
});

}
此时结果:

由此看出,Sleep 只有在 Task 或非主线程里,才不会阻碍当前UI线程,而不是只要放在 async 方法里就可以。

既然使用 Async Task,就不推荐使用 Sleep 了。一般使用 await Task.Delay, 既不影响当前主线程,也能达到延迟效果。

如:

private static async Task TestFunction()
{
await Task.Delay(5000);

string result = "Test1";
Console.WriteLine(result);
return result;

}
结果:

2.示例,探究:在 async 方法中使用多个 await

static async Task Main(string[] args)
{
await TestFunction();
Console.Read();
}

private static async Task TestFunction()
{
var task1Result = await TestFunction1();
var task2Result = await TestFunction2();
var result = $”{task1Result}+{task2Result}”;

await TestFunction3(result);

}

private static async Task TestFunction1()
{
await Task.Delay(2000);
return “TestFunction1”;
}

private static async Task TestFunction2()
{
await Task.Delay(3000);
return “TestFunction2”;
}

private static async Task TestFunction3(string str)
{
await Task.Delay(1000);
Console.WriteLine(str);
}
得到最后的结果共花了6秒:

更改 TestFunction 代码:

private static async Task TestFunction()
{
Task task1 = TestFunction1();
Task task2 = TestFunction2();
var result = await Task.WhenAll(task1, task2);

string output = string.Join("+", result);
await TestFunction3(output);

}
这样得到最后结果只花 4 秒。

总结,

1.不是遇到 async 方法就会不阻碍当前线程(因为里面可以会有Thread.Sleep…);

2.await 会阻碍当前Async Task 里面的代码执行,但不会阻塞调用 async 方法的线程;

3.如果一个任务依赖多个子任务得出结果,子任务之间又不互相依赖,可以考虑使用 WhenAll 节约时间。