关于Azure Function找不到dll程序集的问题

大致现象

静态编译没问题,运行报错内容如下:

Could not load file or assembly 'Microsoft.xxxx.xxxx.xxxx, Version=6.15.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified.

或:

无法加载文件或程序集 'Microsoft.xxxx.xxxx.xxxx, Version=6.15.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'。系统找不到指定的文件。

- 阅读剩余部分 -

错误信息

System.ServiceModel.Security.MessageSecurityException: 从另一方收到未进行安全处理或安全处理不正确的错误。有关错误代码和详细信息,请参见内部 FaultException。 
---> System.ServiceModel.FaultException: An error occurred when verifying security for the message. 验证报文安全性时发生错误。

Invalid Login Information : 
从另一方收到未进行安全处理或安全处理不正确的错误。有关错误代码和详细信息,请参见内部 FaultException。 
=> An error occurred when verifying security for the message.
Unable to Login to Dynamics CRM
Unable to Login to Dynamics CRM************ NullReferenceException - WhoAmI : Execute (WhoAmI) request to CRM from IOrganizationService |
=> 未将对象引用设置到对象的实例。
未将对象引用设置到对象的实例。
[TerminalFailure] Failed to Execute Command - WhoAmI : 
RequestID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx : Execute (WhoAmI) request to CRM from IOrganizationService duration=00:00:00.0032364 ExceptionMessage = 未将对象引用设置到对象的实例。
未将对象引用设置到对象的实例。

Error    : OrganizationWebProxyClient is null

- 阅读剩余部分 -

C# JObject 初始化构造器 的两种写法

优点:

  1. 简化对象属性的赋值过程
  2. 属性中可以包含特殊字符
  3. 赋值语句右侧可以写其他表达式(三元表达式、运算表达式等)
  4. 提高代码可读性
var ent = new JObject
{
    ["guid"] = a["new_guid"].ToString(),
    ["newid"] = newid,
    ["new_name"] = a["new_name"].ToString(),
    ["name"] = name,
    ["age"] = student[0]["age"]?.ToString(),
    ["type"] = 8
};
var _account = new JObject()
{
    {"new_isOk",true},
    {"code_1",1},
    {"code_2",2},
    {"guid",guid},
};

风格大变、不回消息、男生服装、周游世界,种种迹象都在暗示,又何必再等呢。

她明白,爱情不过是一场华丽的游戏,而她已经选择了另一种玩法。
心中的失望渐渐被理智所取代,她决定放手,让自己重新振作起来。
在这个充满可能的世界里,她相信总会有一个人能够懂得珍惜她的一切,而那个人,绝对不会让她再次感到迷茫和不安。

C# HttpClient PostAsync 卡死/假死/死锁 详解

注意:为了避免阅读本文产生误解,本文在撰写过程中,部分使用了PostAsync,部分使用了GetAsync,均视为一个表述

例子

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Method().GetAwaiter().GetResult();// 这里为同步等待
            button1.Text = "End";
        }

        private async Task<string> Method()
        {
            HttpClient client = new HttpClient();

            // 发送 GET 请求
            HttpResponseMessage response = await client.PostAsync("https://baidu.com/");

            // 读取响应内容
            string responseBody = await response.Content.ReadAsStringAsync();

            return responseBody;
        }
    }

产生的场景

在Winform或Asp.net这类使用主线程的应用程序中,并且在主线程使用了同步等待(除了await Method()这类方式以外都是同步等待)的情况下,子方法调用HttpClientawait PostAsync方法时会导致死锁。(控制台程序没这个问题,控制台是单线程)

- 阅读剩余部分 -

备注:需要保证outlook是打开且登录状态

using Microsoft.Office.Interop.Outlook;

    // 核心代码
    Application app = new Application();
    NameSpace ns = app.GetNamespace("MAPI");

    // 查看有哪些Folder
    foreach (MAPIFolder folder in ns.Folders)
    {
        Console.WriteLine(folder.Name); 
    }

    // 获取指定文件夹
    MAPIFolder folder = ns.Folders["一级目录"];
    folder = folder.Folders["二级目录"];

    // 对邮件列表进行排序,按接收时间降序排列
    Items items = folder.Items;
    items.Sort("[ReceivedTime]", true);

    Console.WriteLine($@"邮件总数: {items.Count}");

    // 遍历邮件
    foreach (object item in items)
    {
        if (item is MailItem)
        {
            MailItem mailItem = item as MailItem;

            Console.WriteLine($@"
                创建时间: {mailItem.CreationTime}
                接收时间: {mailItem.ReceivedTime}
                主    题: {mailItem.Subject}
                正    文: {mailItem.Body}"
            );

            // 将邮件设置为已读(设置未读状态)
            if (mailItem.UnRead == true)
            {
                // 已读
                mailItem.UnRead = false;
                mailItem.Save();
            }
        }
    }

接收(同步)最新邮件,这段代码好像没什么用

            #region 接收邮件
            // 创建Outlook应用程序对象
            Application outlookApp = new Application();

            for (int i = 1; i < outlookApp.Session.SyncObjects.Count + 1; i++)
            {
                var syncObject = outlookApp.Session.SyncObjects[i];

                #region 绑定事件
                syncObject.SyncStart += () =>
                {
                    Console.WriteLine("SyncStart");
                };
                syncObject.Progress += (OlSyncState State, string Description, int Value, int Max) =>
                {
                    Console.WriteLine($@"
Progress
State: {State}
Description: {Description}
Value: {Value}
Max: {Max}");
                };
                syncObject.OnError += (int Code, string Description) =>
                {
                    Console.WriteLine($@"
OnError
Code: {Code}
Description: {Description}");
                };
                syncObject.SyncEnd += () =>
                {
                    Console.WriteLine("SyncEnd");
                };
                #endregion

                syncObject.Start();
            }

            Console.WriteLine("【接收完成】");
            #endregion

定义一个转换器,继承自:System.Text.Json.Serialization.JsonConverter<DateTime>

    public class CustomDateTimeConverter : JsonConverter<DateTime>
    {
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.Number)
            {
                // Assume Unix timestamp (seconds since 1970-01-01T00:00:00Z)
                return DateTimeOffset.FromUnixTimeSeconds(reader.GetInt64()).LocalDateTime;
            }

            return reader.GetDateTime().ToLocalTime();
        }

        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToUniversalTime());
        }
    }

在Flurl中设置上述的转换器

            // 设置 Flurl 的全局 JSON 序列化器
            FlurlHttp.Clients.WithDefaults(settings =>
            {
                settings.Settings.JsonSerializer = new DefaultJsonSerializer(new JsonSerializerOptions
                {
                    //PropertyNameCaseInsensitive = true,
                    //IgnoreReadOnlyProperties = true,
                    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
                    Converters = { new CustomDateTimeConverter() },
                });
            });

    var StringUtils = {
        strLen: function (str) {
            var len = 0;
            for (var i = 0; i < str.length; i++) {
                if (str.charCodeAt(i) > 255 || str.charCodeAt(i) < 0) len += 2;
                else len++;
            }
            return len;
        },

        strToChars: function (str) {
            var chars = new Array();
            for (var i = 0; i < str.length; i++) {
                chars[i] = [str.substr(i, 1), this.isCHS(str, i)];
            }
            return chars;
        },

        isCHS: function (str, i) {
            if (str.charCodeAt(i) > 255 || str.charCodeAt(i) < 0) return true;
            else return false;
        },

        subCHString: function (str, start, end) {
            var len = 0;
            var result = "";
            var charsArray = this.strToChars(str);
            for (var i = 0; i < str.length; i++) {
                if (charsArray[i][1]) len += 2;
                else len++;
                if (end < len) return result;
                else if (start < len) result += charsArray[i][0];
            }
            return result;
        },

        subCHStr: function (str, start, length) {
            return this.subCHString(str, start, start + length);
        }
    };
// Usage example:
var str = "你好,世界!Hello, World!";
console.log(StringUtils.strLen(str)); // Output: 27
console.log(StringUtils.subCHStr(str, 0, 5)); // Output: "你好,"

参考:
JavaScript截取中英文字符串