小编ims*_*me1的帖子

将数据写入Excel时如何制作正确的日期格式

我使用office interop将DataTable导出到Excel文件.问题是,Excel不会识别日期,而是显示数字.在另一种情况下,我传递一个字符串,然后将其识别为日期.在这两种情况下,数据都搞砸了.

我尝试过NumberFormat @,它应该以文本格式存储单元格,但它也不起作用.

Application app = new Application();
app.Visible = false;
app.ScreenUpdating = false;
app.DisplayAlerts = false;
app.EnableAnimations = false;
app.EnableAutoComplete = false;
app.EnableSound = false;
app.EnableTipWizard = false;
app.ErrorCheckingOptions.BackgroundChecking = false; 

Workbook wb = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet ws = (Worksheet)wb.Worksheets[1];

for (int j = 0; j < dt.Rows.Count; j++)
{
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        Range rng = ws.Cells[j+2, i+1]as Range;
        rng.Value2 = dt.Rows[j][i].ToString();
        rng.NumberFormat = "@";
    }   
}           

wb.SaveAs(filename, Missing.Value, Missing.Value, Missing.Value, Missing.Value, …
Run Code Online (Sandbox Code Playgroud)

.net c# excel office-interop

35
推荐指数
3
解决办法
9万
查看次数

KeyVaultClient.AuthenticationCallback Delegate 的参数从何而来?

我正在尝试调用订阅中的所有保险库。我使用的方法是这样的 -

控制器

var myClient = new Microsoft.Azure.KeyVault.KeyVaultClient(new KeyVaultClient.AuthenticationCallback(Helper.GetToken));
Microsoft.Azure.KeyVault.KeyVaultCredential test = new KeyVaultCredential(new KeyVaultClient.AuthenticationCallback(Helper.GetToken));

TokenCloudCredentials tokenCredentials = new TokenCloudCredentials("xxx", test.Token);

KeyVaultManagementClient client = new KeyVaultManagementClient(tokenCredentials);
VaultListResponse response = new VaultListResponse();
Run Code Online (Sandbox Code Playgroud)

帮手

public static async Task<string> GetToken(string authority, string resource, string scope)
{

  var clientId = ConfigurationManager.AppSettings["AuthClientId"];
  var clientRedirectURI = ConfigurationManager.AppSettings["AuthClientRedirectURI"];

  var context = new AuthenticationContext(authority, TokenCache.DefaultShared);

  result = await context.AcquireTokenAsync(resource, clientId, new Uri(clientRedirectURI), new PlatformParameters(PromptBehavior.Always)); 
 return result.AccessToken; 
}
Run Code Online (Sandbox Code Playgroud)

对于我的控制器“test.Token”总是返回 null,但我不禁认为这可能是因为我没有在测试中将任何东西传递给 Helper.Token。我知道 Helper.Token 基本上匹配回调想要的内容:

public delegate Task<string> AuthenticationCallback(
string authority, …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc active-directory azure azure-keyvault

8
推荐指数
1
解决办法
9233
查看次数

在使用外部WCF服务时,在docker中运行的Dotnet核心web api无法进行身份验证

我正在使用dotnet core 1.1.2构建RESTful API.

这个api的很大一部分需要向外部WCF服务发出请求.这些请求使用基于Windows的身份验证与用户名,密码和域进行身份验证.

我目前正在准备api生产,我想尝试将它停靠.

我遇到的问题是,一旦从docker容器中调用它,就会对第三方WCF服务进行身份验证失败.使用dotnet运行时运行API可以从windows和mac运行,并且服务将按照应有的方式进行身份验证.

我使用Visual Studio 2017的Connect wcf服务功能使用WCF服务,然后使用正确的身份验证模式修改端点绑定.

public ServiceSoapClient(EndpointConfiguration endpointConfiguration, string username, string password, string domain) :
base(ServiceSoapClient.GetBindingForEndpoint(endpointConfiguration), ServiceSoapClient.GetEndpointAddress(endpointConfiguration))
{
    this.ChannelFactory.Credentials.Windows.ClientCredential.UserName = username;
    this.ChannelFactory.Credentials.Windows.ClientCredential.Password = password;
    this.ChannelFactory.Credentials.Windows.ClientCredential.Domain = domain;

    this.Endpoint.Name = endpointConfiguration.ToString();
    ConfigureEndpoint(this.Endpoint, this.ClientCredentials);
}

private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(EndpointConfiguration endpointConfiguration)
{
    if ((endpointConfiguration == EndpointConfiguration.ServiceSoap))
    {
        System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding();
        result.MaxBufferSize = int.MaxValue;
        result.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max;
        result.MaxReceivedMessageSize = int.MaxValue;
        result.AllowCookies = true;
        result.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.Transport;
        result.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
        return result;
    }
    throw new System.InvalidOperationException(string.Format("Could not …
Run Code Online (Sandbox Code Playgroud)

c# authentication wcf docker .net-core

7
推荐指数
1
解决办法
462
查看次数

RestSharp超时无法正常工作

我有一个restsharp客户端和请求设置如下:

var request = new RestRequest();
request.Method = Method.POST;
request.AddParameter("application/json", jsonBody, ParameterType.RequestBody);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
request.Timeout = -1;
request.ReadWriteTimeout = -1;
var url = $"http://{ipAddress}/api/calculate";
var client = new RestClient();
client.BaseUrl = new Uri(url);
client.Timeout = -1;
client.ReadWriteTimeout = -1;
var response = client.Execute(request);
Run Code Online (Sandbox Code Playgroud)

这个请求需要一段时间才能完成,大约需要30分钟.现在,我知道有更优雅的方法可以做到这一点,但是,对于这个请求,我需要这样做.

此RestSharp客户端和请求在Windows服务中执行.当服务执行请求时,它会抛出TimoutException并且请求最大超时大约为40秒.

出于某种原因,我设置的超时对于这种情况不起作用.

有人有解决方案吗?

.net c# windows-services timeout restsharp

7
推荐指数
3
解决办法
2万
查看次数

未设置 ASP.NET Core 2.0 身份验证 Cookie

我按照Microsoft 的这篇文章 ( https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x ) 在我的 .NET Core 2.0 MVC 应用程序中迁移了我的身份验证程序。

Startup.cs(配置服务)

services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

services.AddAuthentication("MyCookieAuthenticationScheme")
        .AddCookie("MyCookieAuthenticationScheme", options => {
            options.AccessDeniedPath = "/Account/Forbidden/";
            options.LoginPath = "/Account/Login/";
        });
Run Code Online (Sandbox Code Playgroud)

Startup.cs(配置)

app.UseAuthentication();
Run Code Online (Sandbox Code Playgroud)

账户控制器.cs

List<Claim> claims = new List<Claim> {
                        new Claim(ClaimTypes.Name, "testUser"),
                        new Claim(ClaimTypes.Email, model.Email),
                        //new Claim("ID", user.ID.ToString(), ClaimValueTypes.Integer),
                        new Claim(ClaimTypes.Role, "Admin")
                    };

ClaimsIdentity identity = new ClaimsIdentity(claims, "MyCookieAuthenticationScheme");

ClaimsPrincipal principal = new ClaimsPrincipal(identity);

await HttpContext.SignInAsync("MyCookieAuthenticationScheme", principal, new AuthenticationProperties
{
    IsPersistent = false
});
Run Code Online (Sandbox Code Playgroud)

不幸的是,我的 .NET Cookie 从未设置过。这意味着 User.Identity.IsAuthenticated 始终为 false。我尝试了许多 cookie …

c# cookies asp.net-mvc asp.net-core asp.net-core-2.0

6
推荐指数
1
解决办法
8047
查看次数

如何在DataGridViewComboBoxColumn中设置SelectedIndex?

我正在使用datagridview,因为我正在使用datagridviewcomboboxcolumn,comboboxcolumn正在显示文本,但问题是我想默认选择第一项comboboxcolumn如何才能这样做

DataGridViewComboBoxColumn dgvcb = (DataGridViewComboBoxColumn)grvPackingList.Columns["PackingUnits"];
Globals.G_ProductUtility G_Utility = new Globals.G_ProductUtility();
G_Utility.addUnittoComboDGV(dgvcb);
DataSet _ds = iRawMaterialsRequest.SelectBMR(bmr_ID, branch_ID, "PACKING");
grvPackingList.DataSource = _ds.Tables[0];
int i = 0;
foreach (DataRow dgvr in _ds.Tables[0].Rows)
{
    grvPackingList.Rows[i].Cells["Units"].Value = dgvr["Units"].ToString();
    i++;
}
Run Code Online (Sandbox Code Playgroud)

c# windows

5
推荐指数
1
解决办法
5万
查看次数

C#中的Google图片搜索

我在github上找到了这段代码.当你输入某些东西它会搜索谷歌并在picturebox1中显示第一个图像 - 现在我想添加3-4其他图片框,我希望它也显示其他图片(如第二和第三 - 而不仅仅是第一个).我的问题是我无法理解如何做到这一点.

try {
        this.Cursor = Cursors.WaitCursor;
        this._lblStatus.Text = "Searching...";
        this._lblStatus.Update();
        List<String> images_urls = t.SearchForImages (this._editImageText.Text.Trim());
        if (t.Error == null && images_urls.Count > 0) {
           //Show first image only
           foreach (String image_url in images_urls) {
              Bitmap bitmap = ImageUtil.LoadPicture(image_url);
              if (bitmap != null) { //sometime the server refuses getting the image directly
                 Image image = ImageUtil.ResizeImage(bitmap, pictureBox1, true);
                 pictureBox1.Image = image;
                 if (bitmap != null) bitmap.Dispose();
                 break;   //show only one image
Run Code Online (Sandbox Code Playgroud)

我试过的:我删除了休息时间; 但它只是继续搜索,它永远不会停止.我希望它像其他网站一样(例如:每页显示5-10张图片).我应该改变什么?我究竟做错了什么 ?

c#

5
推荐指数
1
解决办法
1100
查看次数

使用UWP DatagramSocket和Socket API的UDP吞吐量性能较差

我有一个基本的C#.NET UDP服务器和客户端代码,我正在尝试将其移植到UWP.对于UWP,我尝试使用DatagramSocket和常规Socket类.我看到使用DatagramSocket类在UWP服务器上传入的UDP数据包上有近40%的数据包丢失.如果我使用UWP套接字,我看到丢包率约为70%.旧的.NET代码显示0%的数据包丢失.

我想也许我没有正确使用UWP API,因此我的性能很差.有人可以指导我如何提高UWP服务器性能吗?

现在,所有测试都是使用环回完成的.UWP默认情况下不允许环回,因此我按照此处提到的说明启用环回.

服务器在50000端口上侦听数据包,客户端代码从50001向服务器发送大约60字节的数据包.

C#.NET客户端代码如下:

try
{
    byte[] buffer = new byte[1024];

    IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 50001);
    IPAddress remoteIp = System.Net.IPAddress.Parse("127.0.0.1");
    IPEndPoint remoteEP = new IPEndPoint(remoteIp, 50000);

    Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

    try
    {
        sender.Bind(localEP);

        for(int i = 0; i < 10000; i++)
        {
            //Thread.Sleep(1);
            // Encode the data string into a byte array. 
            string ClientReq =  "Client Request:: " + i.ToString() + " "+ Guid.NewGuid().ToString();
            byte[] msg = Encoding.ASCII.GetBytes(ClientReq);

            // Send the …
Run Code Online (Sandbox Code Playgroud)

c# sockets networking udp uwp

5
推荐指数
0
解决办法
315
查看次数

Oracle中如何按字符串和数字混合的字段排序?

这些是要排序的字段 (crane_no) 值
QC11
QC10
QC9

我尝试了以下查询:

select * from table order by crane_no DESC
Run Code Online (Sandbox Code Playgroud)

但查询结果没有按顺序给出,因为该字段混合了星号和数字(例如:QC12)。我得到上述查询的以下结果:
QC9
QC11
QC10

我希望结果按顺序排列(QC9、QC10、QC11)。谢谢

oracle

4
推荐指数
1
解决办法
6221
查看次数

Oracle从字符串中提取字母字符

我只想分别提取字母字符。
例如,“ NIC132DA.1 ”的输出应分别为“ NIC ”和“ DA ”,没有任何数字。
我尝试了以下查询:

select regexp_replace('NIC132DA.1','[^A-Za-z]') from dual;
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:NICDA
预期输出分别是“ NIC”和“ DA”。
注意:输入字符串中的字母字符数不是固定的。

sql oracle oracle11g

4
推荐指数
1
解决办法
3750
查看次数