RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-192029

tCode's questions

Martin Hope
tCode
Asked: 2020-04-01 21:07:14 +0000 UTC

C#。DLL 导入。DLLNotFoundException 错误

  • 1

问题是这样的:

  1. 我拿了 IP 摄像机模拟器的源代码(https://github.com/inspiredtechnologies/IP-Camera-Emulator)
  2. 我组装了一个解决方案,其中一个项目(相同的 dll)在 C++ 中

成功构建后,我收到了应用程序和 c++ dll。我启动应用程序,添加一个视频文件并单击开始 - 我得到一个 DLLNotFoundException 错误,虽然这个 DLL 位于 exe 文件旁边

在此处输入图像描述

在应用程序中,导入执行以下操作:

[DllImport("RtspStreamerLib.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern IntPtr CreateRtspStreamerLib();

    [DllImport("RtspStreamerLib.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern void DestroyRtspStreamerLib(IntPtr lib);

    [DllImport("RtspStreamerLib.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern Int32 StartStreamLib(IntPtr lib, byte[] streamName, byte[] mediaPath, Int32 portNumber);

    [DllImport("RtspStreamerLib.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern void StopStreamLib(IntPtr lib);

    [DllImport("RtspStreamerLib.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern bool GetStreamStatusLib(IntPtr lib);

    [DllImport("RtspStreamerLib.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern Int32 GetStreamRateLib(IntPtr lib);

    [DllImport("RtspStreamerLib.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern IntPtr GetVlcVersionLib(IntPtr lib);

实际上,如何解决问题?
我查看了 ProcMon,应用程序正在尝试加载 DLL,文件的路径是正确的,但是显示了一些调用,结果 FILE LOCKED WITH ONLY READERS 在此处输入图像描述

c#
  • 1 个回答
  • 10 Views
Martin Hope
tCode
Asked: 2020-07-05 20:38:25 +0000 UTC

C# 如何强制类库使用它的 App.config

  • 2

我有一个控制台应用程序,它通过反射从Class Library.

假设项目Class Library将使用自己的配置,但这不会发生,如果使用配置,则只有控制台应用程序。

我怎样才能做到这一点,以便我Class Library可以使用我自己的App.config?

c#
  • 1 个回答
  • 10 Views
Martin Hope
tCode
Asked: 2020-04-27 18:44:35 +0000 UTC

Web API 2. 从请求中获取参数值

  • 0

控制器

[HttpPost]
public HttpResponseMessage GetData(FormRequest formRequest)
{
    ...
}

表单请求

public class FormRequest
{
    public int Param1 { get; set; }
    public int Param2 { get; set; }
}

WebApi配置

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
                "DefaultApi",
                "api/{controller}/{action}/{id}",
                new { id = RouteParameter.Optional }
        );
    }
}

在 POST 请求中,具有名称$Param1和$Param2

如何将这些参数的值映射到对象的属性上FormRequest呢?

asp.net-web-api
  • 1 个回答
  • 10 Views
Martin Hope
tCode
Asked: 2020-03-09 22:54:27 +0000 UTC

是否可以使用 C# 获取有关集群的信息?

  • 0

是否可以使用 C# 获取有关集群的信息?
例如接收角色列表及其资源?

如果可能,请发布一个链接以阅读如何操作。

我试过了,但我明白了 System.Managment.ManagmentException: Invalid class

string clusterName = "app-server.local";
string custerGroupResource = "cluster.server.local";

ConnectionOptions options = new ConnectionOptions
{
    Authentication = AuthenticationLevel.PacketPrivacy
};

ManagementScope s = new ManagementScope("\\\\" + clusterName, options);

ManagementPath p = new ManagementPath("Mscluster_Clustergroup.Name='" + custerGroupResource + "'");

using (ManagementObject clrg = new ManagementObject(s, p, null))
{
    clrg.Get();
    Console.WriteLine(clrg["Status"]);
}
c#
  • 2 个回答
  • 10 Views
Martin Hope
tCode
Asked: 2020-03-03 17:54:47 +0000 UTC

ASP.NET 网络 API。将路由路由到具有权限的文件

  • 0

有一个网址:http://localhost/main/cat/sub/file.jsp

如何进行路由,以便在通过方法访问给定地址时POST,它将路由到Post()设置中指定的控制器中的方法?

我的尝试:

WebApiConfig.cs

config.Routes.MapHttpRoute(
    "Main",
    "main/cat/sub/{*src}",
    new { controller = "Main", id = RouteParameter.Optional },
    new { src = @"(.*?)\.(jsp)" }
);

主控制器.cs

public class MainController : ApiController
{
    [HttpPost]
    public HttpResponseMessage Post([FromUri]RequestModel values)
    {
        ...
    }
}

在这种情况下,我得到404

c#
  • 1 个回答
  • 10 Views
Martin Hope
tCode
Asked: 2020-02-18 22:06:36 +0000 UTC

ASP Web API + Android 改造。获取 JSON 时出错

  • 0

可用的:

  • 安卓应用
  • ASP.NET 上的 Web API

我创建一个对象Retrofit:

Retrofit service = new Retrofit.Builder()
    .baseUrl("http://192.168.0.3/") // адрес WebApi
    .addConverterFactory(GsonConverterFactory.create())
    .build();

在我调用我需要的 API 方法的代码中,数据正确地到达了 API。作为测试,我返回控制器中的模型json

行动

[HttpPost]
public JsonResult GetUser(UserModel model)
{
    return Json(JsonConvert.SerializeObject(model));
}

模型

public class UserModel
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("email")]
    public string Email { get; set; }

    [JsonProperty("password")]
    public string Password { get; set; }

    [JsonProperty("name")]
    public string name { get; set; }

    [JsonProperty("device_id")]
    public string DeviceId { get; set; }

    [JsonProperty("register_date")]
    public string RegisterDate { get; set; }

    [JsonProperty("updated_date")]
    public string UpdatedDate { get; set; }
}

通过 POSTMAN 我得到了正确的json.
但是,在 Android 中我得到Exception:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224)
     at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37)
     at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25)
     at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:117)
     at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:211)
     at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:106)
     at okhttp3.RealCall$AsyncCall.execute(RealCall.java:133)
     at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
     at java.lang.Thread.run(Thread.java:818)
 Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
     at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:385)
     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:213)
    ... 10 more

json为什么API自带的在 Android 上没有解析?

更新
API 响应:

{\"id\":1,\"email\":\"myemail@gmail.com\",\"password\":\"1234\",\"name\":null,\"device_id\":null,\"register_date\":null,\"updated_date\":null}

在 Android 中,在回调处理程序中,我掉在这里:

@Override
public void onFailure(Call<UserModel> call, Throwable t) {
    t.printStackTrace();
}
java
  • 1 个回答
  • 10 Views
Martin Hope
tCode
Asked: 2020-02-13 01:03:16 +0000 UTC

安卓。将 Set<String> 转换为 String[] 时出错

  • 0

我试图SharedPreference通过键从整个包中获取数据,但我无法将结果转换为String[]

java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Set


String[] codeValues;

我这样做:

private void loadCode() {
    preferences = getPreferences(MODE_PRIVATE);
    Set<String> codes = preferences.getStringSet("codes", new HashSet<String>());

    codeValues = codes.toArray(new String[codes.size()]);
    Toast.makeText(this, "Text loaded", Toast.LENGTH_SHORT).show();
}

我也试过这个:

private void loadCode() {
    preferences = getPreferences(MODE_PRIVATE);
    Set<String> codes = preferences.getStringSet("codes", new HashSet<String>() {
        @Override
        public int size() {
            return 0;
        }

        @Override
        public boolean isEmpty() {
            return false;
        }

        @Override
        public boolean contains(Object o) {
            return false;
        }

        @NonNull
        @Override
        public Iterator<String> iterator() {
            return null;
        }

        @NonNull
        @Override
        public Object[] toArray() {
            return new Object[0];
        }

        @NonNull
        @Override
        public <T> T[] toArray(T[] a) {
            return null;
        }

        @Override
        public boolean add(String s) {
            return false;
        }

        @Override
        public boolean remove(Object o) {
            return false;
        }

        @Override
        public boolean containsAll(Collection<?> c) {
            return false;
        }

        @Override
        public boolean addAll(Collection<? extends String> c) {
            return false;
        }

        @Override
        public boolean retainAll(Collection<?> c) {
            return false;
        }

        @Override
        public boolean removeAll(Collection<?> c) {
            return false;
        }

        @Override
        public void clear() {

        }
    });

    codeValues = codes.toArray(new String[codes.size()]);
    Toast.makeText(this, "Text loaded", Toast.LENGTH_SHORT).show();
}
java
  • 1 个回答
  • 10 Views
Martin Hope
tCode
Asked: 2020-02-13 00:31:50 +0000 UTC

安卓。自动完成文本视图。如何在关注某个字段时显示下拉列表?

  • 0

代码里面有AutoCompleteTextView值输入进去。
如何在单击/关注某个字段时一次显示包含所有附加值的列表?

AutoCompleteTextView textView = (AutoCompleteTextView)findViewById(R.id.editFriendCode);

String[] values = new String[]{"0f020", "ca35c"};

ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, values);
textView.setAdapter(adapter);

View.OnClickListener fdcClick = new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        view.showContextMenu(); // не работает так
    }
};

textView.setOnClickListener(fdcClick);

否则,如果你输入2个字符,它只显示值,但你想显示而不输入数据

请帮助或建议其他解决方案

更新程序

setOnTouchListener也不行...

java
  • 1 个回答
  • 10 Views
Martin Hope
tCode
Asked: 2020-02-09 20:43:11 +0000 UTC

Android 中的 POST 请求。如何?

  • 2

决定在Android下尿尿试试,于是出现了非常多的问题。谁不难回答请。

我正在尝试使应用程序使用特定的 API,使用 进行通信json,但我无法编写一个类,例如在 sharp 上,我向其传递地址、参数并执行POST请求,例如,像这里https://stackoverflow.com/questions/4015324/http-request-with-post。

据我了解,Android应用程序无法执行POST来自常规方法的请求,您需要使用它AsyncTask<>-我什么都不懂,从语法本身开始,即调用类型方法时是否枚举doInBackground(String... params)参数或者是什么? 总而言之String...doInBackground(str1, str2, str3)

我不是要你为我写现成的代码,我是要你帮助我理解如何POST在 Android 中处理请求的原理,至少一个具体的例子:POST (json)以相同的方式发送和接收响应json以及一点理论,请))。

java
  • 4 个回答
  • 10 Views
Martin Hope
tCode
Asked: 2020-01-14 07:23:13 +0000 UTC

为什么JS代码会阻塞提交

  • 0

ASP.NET MVC 上有一个表单。
模型显示在表单上,​​其属性具有标准验证的某些属性[Required]
当submit表单被触发时,标准库中的验证器:

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));

当您向页面添加脚本时,当您单击按钮submit时将其锁定,然后在 2 秒后将其激活,submit表单不会出现,锁定 \ 解锁脚本本身可以正常工作,这是什么问题?需要向该脚本中添加什么才能submit成功计算?

$(function() {
    $(".btn").each(function() {
        $(this).on("click", function () {
            var e = $(this);
            e.attr("disabled", "disabled");
            setTimeout(function() {
                e.removeAttr("disabled");
            }, 2000);
        });
    });
});
html
  • 1 个回答
  • 10 Views
Martin Hope
tCode
Asked: 2020-01-14 06:55:08 +0000 UTC

查询。如何将元素传递给 setTimeout [重复]

  • 2
这个问题已经在这里得到回答:
呼叫上下文丢失 (5 个答案)
5 年前关闭。

click我为该类的所有按钮订阅了一个事件btn。
有必要在单击按钮时使其变为非活动状态,并在 3 秒后再次变为活动状态。

$(function() {
    $(".btn").each(function() {
        $(this).on("click", function() {
            $(this).attr("disabled", "true");
            setTimeout(function() {
                $(this).removeAttr("disabled");
            }, 3000);
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" class="btn" value="Add"/>

因此按钮变为非活动状态,但 setTimeout 中的函数不起作用,或者更确切地说,它似乎起作用,但它不理解 $(this) 元素是什么。

虽然控制台中没有错误。

究竟如何是好?

它有效,但这个选项不适合

$(function() {
    $(".btn").each(function() {
        $(this).on("click", function() {
            $(this).attr("disabled", "true");
            setTimeout(function() {
                $(".btn").removeAttr("disabled");
            }, 3000);
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" class="btn" value="Add"/>

jquery
  • 2 个回答
  • 10 Views
Martin Hope
tCode
Asked: 2020-12-25 05:25:33 +0000 UTC

ASP.NET。MVC。模型属性的默认值

  • 2

有一个模型,模型的属性之一:

[Required(ErrorMessageResourceType = typeof(ServerLocale), ErrorMessageResourceName = "DateValidationMessage")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(ResourceType = typeof(ServerLocale), Name = "DateLabel")]
public DateTime Date { get; set; }

模型是从View填充的,这个属性在View上是这样显示的:

<div class="control-group">
    <div class="control-label">@Html.LabelFor(m => m.Date)</div>
    <div class="controls">@Html.EditorFor(m => m.Date)<br/>@Html.ValidationMessageFor(m => m.Date)</div>
</div>

但是第一次打开表单时,字段中的值是这样的:

01.01.0001

问题是如何创造价值DateTime.Now.AddMonth(1)???

24.01.2017

重要的是只有当模型为空(用户第一次打开表单,或刷新页面)时才将此值设置为属性,如果用户更改了此字段中的日期,则用户的值应该来到控制器

c#
  • 1 个回答
  • 10 Views
Martin Hope
tCode
Asked: 2020-12-10 17:11:28 +0000 UTC

ASP.NET。处理 _Layout.cshtml 时出现奇怪的错误

  • 0

Sat 规则css,沿途检查 IIS 中部署的站点上的更改。

在刷新页面的某个时候,我收到以下错误:

Ошибка сервера в приложении '/'.
Не удалось обработать следующий файл, так как его расширение ".cshtml" может не поддерживаться: "~/Views/Shared/_Layout.cshtml".

Описание: Необработанное исключение при выполнении текущего веб-запроса. Изучите трассировку стека для получения дополнительных сведений о данной ошибке и о вызвавшем ее фрагменте кода. 

Сведения об исключении: System.Web.HttpException: Не удалось обработать следующий файл, так как его расширение ".cshtml" может не поддерживаться: "~/Views/Shared/_Layout.cshtml".

Ошибка источника: Необработанное исключение при выполнении текущего веб-запроса. Информацию о происхождении и месте возникновения исключения можно получить, используя следующую трассировку стека исключений.

Трассировка стека: 

[HttpException (0x80004005): Не удалось обработать следующий файл, так как его расширение ".cshtml" может не поддерживаться: "~/Views/Shared/_Layout.cshtml".]
   System.Web.WebPages.BuildManagerExceptionUtil.ThrowIfUnsupportedExtension(String virtualPath, HttpException e) +297488
   System.Web.WebPages.WebPageBase.CreatePageFromVirtualPath(String virtualPath, HttpContextBase httpContext, Func`2 virtualPathExists, DisplayModeProvider displayModeProvider, IDisplayMode displayMode) +369
   System.Web.WebPages.<>c__DisplayClass7.<RenderPageCore>b__6(TextWriter writer) +258
   System.Web.WebPages.WebPageBase.Write(HelperResult result) +122
   System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) +88
   System.Web.WebPages.WebPageBase.PopContext() +371
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +375
   System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +31
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +437
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +185
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +27
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +22
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +22
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +22
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +399
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +157

Информация о версии: Платформа Microsoft .NET Framework, версия:4.0.30319; ASP.NET, версия:4.6.1586.0

它是从哪里来的,我完全无法理解,因为。我只是改变了css。而且我完全不明白如何修复它,我没有在谷歌中找到它

c#
  • 1 个回答
  • 10 Views
Martin Hope
tCode
Asked: 2020-11-27 03:17:37 +0000 UTC

C# LINQ 通过特定字段获取唯一值

  • 0

我从数据库中获取对象列表Server,Server其中一个字段称为Id.

public class Server 
{
    public int Id { get;set; }
    public string Name { get;set; }
    ....
}

有一张表ServerTags,分别存储标签Server.Id,Server.Id可以有多个标签

桌子:

|ServerId|TagId|TagName|

我需要:

  1. 拿到我需要的床单Server- 好的,我明白了
  2. 从表中ServerTags为每个选择所有标签Server.Id并分组,TagId而不会丢失其余字段及其值 - 粗略地说,只保留唯一值TagId

我目前正在使用此解决方案:

List<Server> servers;
using (ServerContext db = new ServerContext())
{
    servers = db.Servers.Where(e => e.Status == ServerStatus.Active).ToList();
}

using (TagContext db = new TagContext())
{
    List<ServerTag> tags = servers.Select(server => db.ServerTags
        .First(e => e.ServerId == server.Id)).ToList()
        .GroupBy(x => x.TagId).Select(x => x.First()).ToList();
}

好像可以,但是在选择的时候,每个服务器只选择了1个tag,其他的都不是傻选的,怎么弄对的?

c#
  • 2 个回答
  • 10 Views
Martin Hope
tCode
Asked: 2020-11-22 04:30:31 +0000 UTC

从类库项目调用方法时出现 C# ASP.NET 奇怪错误

  • 1

ASP.NET MVC / 我使用 VkNet 将记录发布到 VK 中的一个组

在某个时间,任务调度程序使用某个密钥Action( https://mydomain.com/Service/Vk?key=SECRET_KEY )发出 GET 请求

之后,执行逻辑Action并在最后调用负责使用 VkNet 的方法:

VkontakteService.WallPost(APPID, "LOGIN", "PWD", OWNERID, message);

方法:

public static void WallPost(ulong appId, string login, string password, long ownerId, string message)
{
    try
    {
        VkApi api = new VkApi();
        api.Authorize(new ApiAuthParams
        {
            ApplicationId = appId,
            Login = login,
            Password = password,
            Settings = Settings.All
        });

        api.Wall.Post(new WallPostParams
        {
            OwnerId = ownerId,
            FromGroup = true,
            Message = message,
            Signed = false,
        });
    }
    catch (Exception ex)
    {
        Log.Error($"Ошибка при добавлении записи в группу ВК: {ex}");
    }
}

结果,我得到了一个奇怪的Exception:

[2016-11-21 23:13:11.3353][Error]: Ошибка при добавлении записи в группу ВК: Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
System.IO.FileLoadException: Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
File name: 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'
   at VkNet.VkApi.Call(String methodName, VkParameters parameters, Boolean skipAuthorization)
   at VkNet.Categories.WallCategory.Post(WallPostParams params)
   at MyProject.Services.VkontakteService.WallPost(UInt64 appId, String login, String password, Int64 ownerId, String message) in D:\MyProject\trunk\Sources\MyProject.Services\VkontakteService.cs:line 27

=== Pre-bind state information ===
LOG: DisplayName = Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
 (Fully-specified)
LOG: Appbase = file:///D:/MyProject/trunk/Sources/MyProject.Host/
LOG: Initial PrivatePath = D:\MyProject\trunk\Sources\MyProject.Host\bin
Calling assembly : VkNet, Version=1.21.0.0, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: D:\MyProject\trunk\Sources\MyProject.Host\web.config
LOG: Using host configuration file: C:\Users\Home\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Post-policy reference: Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
LOG: Attempting download of new URL file:///C:/Users/Home/AppData/Local/Temp/Temporary ASP.NET Files/root/ee02bc37/45707ec2/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///C:/Users/Home/AppData/Local/Temp/Temporary ASP.NET Files/root/ee02bc37/45707ec2/Newtonsoft.Json/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///D:/MyProject/trunk/Sources/MyProject.Host/bin/Newtonsoft.Json.DLL.
WRN: Comparing the assembly name resulted in the mismatch: Major Version
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.

VkontakteService具有该方法的类本身WallPost位于具有连接的 VkNet 的相邻项目(类库)中

应用配置

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    </configSections>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="HtmlAgilityPack" publicKeyToken="bd319b19eaf3b43a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.4.9.5" newVersion="1.4.9.5" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

告诉我可能是什么问题,也许有人遇到过这样的错误,我第一次看到这么奇怪的日志?

c#
  • 3 个回答
  • 10 Views
Martin Hope
tCode
Asked: 2020-11-15 17:25:32 +0000 UTC

C#。窗口服务。内存泄漏

  • 3

请告诉我我在哪里犯了错误,该服务正在逐渐消耗内存

该服务在启动时的任务是逐行加载 Services.txt 文件中的地址,List<Uri>并在一定时间间隔后对文件中的每个 URL 发出 GET 请求

程序.cs

static class Program
{
    static void Main()
    {
        ServiceBase[] ServicesToRun = {
            new ServicePusher()
        };

        ServiceBase.Run(ServicesToRun);
    }
}

ServicePusher.cs

public partial class ServicePusher : ServiceBase
{
    private static readonly Logger Log = LogManager.GetCurrentClassLogger();
    private Timer ServiceTimer;
    private readonly List<Uri> ServiceUrl = new List<Uri>();

    public ServicePusher()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "/Services.txt"))
        {
            Log.Error("Не найден Services.txt");
            throw new FileNotFoundException("Не найден Services.txt");
        }

        using (StreamReader sr = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "/Services.txt"))
        {
            string line;

            while ((line = sr.ReadLine()) != null)
            {
                Uri serviceUri = null;

                try
                {
                    serviceUri = new Uri(line);
                }
                catch (Exception ex)
                {
                    Log.Error($"Ошибка при получении адреса сервиса ({line}): {ex}");
                }

                if (serviceUri != null)
                {
                    ServiceUrl.Add(serviceUri);
                }
                else
                {
                    Log.Error($"Некорректный адрес сервиса ({line}) в файле Services.txt");
                }
            }
        }

        ServiceTimer = new Timer
        {
            Interval = Config.Interval
        };

        ServiceTimer.Elapsed += Tick;
        ServiceTimer.AutoReset = true;
        ServiceTimer.Start();


        Log.Info("Сервис успешно запущен");
        Log.Info($"Загружено сервисов: {ServiceUrl.Count}");
    }

    protected override void OnStop()
    {
        ServiceTimer.Stop();
        ServiceTimer.Dispose();
        ServiceTimer = null;

        Log.Info("Сервис остановлен");
    }

    private void Tick(object sender, ElapsedEventArgs e)
    {
        try
        {
            foreach (Uri url in ServiceUrl)
            {
                ServicePointManager.ServerCertificateValidationCallback = (o, a, b, c) => true;

                WebRequest request = WebRequest.Create(url);
                request.Proxy = null;
                request.Method = "GET";
                request.Timeout = 360000;
                request.ContentType = "application/x-www-form-urlencoded";

                try
                {
                    using (WebResponse response = request.GetResponse())
                    {
                        using (Stream requestStream = response.GetResponseStream())
                        {
                            if (requestStream == null)
                            {
                                Log.Error($"Нет ответа от {url}");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error($"Ошибка ({ex.Message}) при запросе к сервису {url}");
                }
            }
        }
        catch (Exception ex)
        {
            Log.Error(ex.Message);
        }
    }
}

UPD:每小时消耗约 2 MB

UPD 2:更新问题中的代码,15分钟稳吃~350 kb ...

也许它在Program.cs中?

c#
  • 1 个回答
  • 10 Views
Martin Hope
tCode
Asked: 2020-10-12 18:24:00 +0000 UTC

C# REST API / 将请求参数映射到对象属性

  • 1

有一个 Web API应用程序。

有一个捕获请求的动作:

[HttpPost]
public HttpResponseMessage GetOrder(OrderRequest request)
{
    return ResponseHandler.GetResponse(Request, ActionHandler.Order(request));
}

有一个带有请求属性描述的模型:

public class OrderRequest
{
    public int OrderId { get; set; }
    public string Description { get; set; }
}

在发送POST请求的客户端中,分别将参数Description传为$Description,当请求落入字段时,Action只自动映射字段OrderId,参数为Description空。

如何指定应在请求中映射到OrderRequest的属性?Description$Description

是否可以将其作为属性的属性Description?

如果你能写一篇关于如何完成这种映射的理论的文章,​​我自己没找到

c#
  • 1 个回答
  • 10 Views
Martin Hope
tCode
Asked: 2020-08-23 02:10:38 +0000 UTC

Visual Studio 2013 丢失类和方法引用的显示

  • 0

大家好!

在 Visual Studio 2013 中,我不再看到类和方法中的引用...=\

在此处输入图像描述

用谷歌搜索,搜索,甚至尝试这样做,但在工作室设置中也没有CodeLens参数Code Information Indicators

在此处输入图像描述

我在某处遇到信息,这是由于缺少 TFS 包,并且还写道,该功能在工作室的 2013 年被一般开发人员删除

其实问题

如何返回参考文献的显示?Resharper 有这样的选项吗?

visual-studio
  • 1 个回答
  • 10 Views
Martin Hope
tCode
Asked: 2020-08-02 20:56:55 +0000 UTC

C# MVC 4. 将自定义字段传递给控制器

  • 0

大家好,我需要帮助

有一个页面可以添加字段(JQuery)

创建新字段时,它会创建一个唯一的名称。

其实问题是:如何在Controller中获取创建的自定义字段的值呢?

其实会有Key->Value类型的值

有人怀疑你可以以某种方式添加新字段作为模型对象,但我不知道如何

模型

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public Currency Currency { get; set; }
    public byte[] ImageData { get; set; }
    public string ImageMimeType { get; set; }
}

看法

@using (Html.BeginForm("CreateProduct", "Catalogue", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
    @Html.ValidationSummary(true)
    <div class="block-content collapse in">
        <table class="table table-striped" id="create-product">
            <tr>
                <td>@Html.LabelFor(m => m.Name)</td>
                <td>@Html.EditorFor(m => m.Name) <br/> @Html.ValidationMessageFor(m => m.Name)</td>
            </tr>
            <tr>
                <td>@Html.LabelFor(m => m.Price)</td>
                <td>@Html.EditorFor(m => m.Price) <br/> @Html.ValidationMessageFor(m => m.Price)</td>
            </tr>
            <tr>
                <td>@Html.LabelFor(m => m.Currency)</td>
                <td>@Html.EnumDropDownListFor(m => m.Currency) <br/> @Html.ValidationMessageFor(m => m.Currency)</td>
            </tr>
            <tr>
                <td>@Html.LabelFor(m => m.ImageData)</td>
                <td><input type="file" name="Image"/></td>
            </tr>
            <tr id="custom-params">
                <td>Универсальные параметры</td>
                <td><input type="checkbox" id="custom-parameters" onchange="showCustomForm(this)" /></td>
            </tr>

            <tr>
                <td></td>
                <td><input type="submit" class="btn btn-success" value="Сохранить"/></td>
            </tr>
        </table>
    </div>
}

JS

function createParam() {
    $('#custom-manager').after('<tr name="custom-' + fieldCount + '"><td><input type="text" name="key-' + fieldCount + '" /></td><td><input type="text" name="value-' + fieldCount + '" /></td></tr>');
    fieldCount++;
}

这一切到底是什么样子? 在此处输入图像描述

c#
  • 1 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5