我有一个 web api 控制器,我想在其中使用事件处理程序。更具体地说,我有一个MessagesController,当执行 action 方法时,WriteMessage我想触发一个SignalR Hub method将订阅a 的事件,该方法将向所有必要的接收者广播消息。看看下面的简化代码:
这是控制器:
public class MessagesController : ApiController
{
private readonly IMessageService _messageService;
public EventHandler<MessageEventArgs> MessageSent;
public MessagesController(IMessageService messageService)
{
_messageService = messageService;
}
public IHttpActionResult WriteMessage(Message message)
{
try
{
//here I'm using MessageService to write the message to the data base
_messageService.WriteMessage(message);
//after the message was saved successfully I would like to trigger the event that will fire a signalR hub's method
OnMessageSent(message);
return Content(HttpStatusCode.Created, …Run Code Online (Sandbox Code Playgroud) 我知道当我们在C#中使用属性时,编译器总是在CIL中为它们生成getter和setter(例如,get_PropertyName和set_PropertyName),例如,考虑以下代码:
class Program
{
class Test
{
public string Name { get; set; }
}
static void Main(string[] args)
{
//Here I'm using reflection to inspect methods of Test class
Type type = typeof(Test);
foreach (var item in type.GetMethods())
{
Console.WriteLine(item.Name);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这一计划将产生的输出与方法Test,其中还会有get_Name和set_Name-我说的是getter和setter方法.根据我的理解,如果getters和setter是在"幕后"创建的,那么应该创建一个支持字段,getter和setter获取/设置值.因此,从前面的示例中,我可以使用反射来检查Test类的字段,如下所示:
static void Main(string[] args)
{
Type type = typeof(Test);
foreach (var item in type.GetFields())
{
Console.WriteLine(item.Name);
}
}
Run Code Online (Sandbox Code Playgroud)
这个程序的输出是空的,我认为这是因为创建的支持字段具有private访问权限,因此我们无法看到它.但由于我不知道如何检查它,你能告诉我是否总是创建一个支持字段(即使我们只有一个简单的属性get;和set;)?
我对服务定位器和依赖注入的概念非常熟悉,但有一件事让我感到困惑,即为应用程序实现依赖注入,我们必须在开始时使用某种服务定位器.请考虑以下代码,假设我们有一些简单的DAL类:
public class UserProviderSimple : IUserProvider
{
public void CreateUser(User user)
{
//some code to user here
}
}
Run Code Online (Sandbox Code Playgroud)
然后在Business Logig Layer中,我们有一些IUserProvider使用构造函数注入注入的简单类:
public class UserServiceSimple : IUserService
{
public IUserProvider UserProvider { get; set; }
public UserServiceSimple(IUserProvider userProvider)
{
UserProvider = userProvider;
}
public void CreateUser(User user)
{
UserProvider.CreateUser(user);
}
}
Run Code Online (Sandbox Code Playgroud)
现在我们可能有几个这样的类,并且在任何地方都使用构造函数注入,但是在应用程序启动的主类中,所有这些类型都必须得到解决,因此我们必须使用服务定位器来解析所有这些类型,例如,在这里,我将创建一个单件服务定位器类来解决控制台应用程序启动时的所有依赖关系,如下所示:
public class ServiceLocator
{
private readonly UnityContainer _container;
private static ServiceLocator _instance;
public static ServiceLocator Instance()
{
if (_instance == null)
{
_instance = new ServiceLocator(); …Run Code Online (Sandbox Code Playgroud) c# dependency-injection inversion-of-control service-locator
FtpWebRequest在 C# 中使用类时遇到问题。
当我第一次尝试使用正确的凭据将文件上传到 FTP 服务器,然后第二次使用错误的凭据(用户名相同但密码错误)时,没有抛出异常,文件仍然上传到 FTP服务器。请考虑以下代码:
using System;
using System.Net;
internal class Program
{
private static void Main(string[] args)
{
var uri = new Uri("ftp://ftp.dlptest.com/TestFile.txt");
var method = WebRequestMethods.Ftp.UploadFile;
//Here I'm uploading the test file using correct credentials
var correctCredentials =
new NetworkCredential("dlpuser@dlptest.com", "fwRhzAnR1vgig8s");
DoFtpRequest(uri, correctCredentials, method);
//Here I'm uploading the test file using wrong credentials.
//I expect some exception to be thrown and the file not being
//uploaded to the server, neither is the case.
var wrongCredentials …Run Code Online (Sandbox Code Playgroud) 我正在使用 Firebase Cloud Messaging 向 IOS 和 Android 设备发送推送通知。我想在邮件正文中发送一些文本,其中一部分是粗体的。这就是我的 Android 推送通知的 JSON 现在的样子:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"body":"Some plain text THIS TEXT SHOULD BE BOLD some plain text"
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想在推送通知中看到这样的消息:“一些纯文本此文本应该是粗体一些纯文本”
可以这样做吗?
push-notification firebase pushsharp firebase-cloud-messaging
我用来XmlSerializer将 C# 对象序列化为 XML。我有DefaultValueAttribute一些我尝试序列化的类的属性,当我尝试序列化它们时,XmlSerializer如果它等于默认值,则似乎不包含 xml 中的值。看这个例子:
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace Test
{
public class Person
{
[System.Xml.Serialization.XmlAttribute()]
[System.ComponentModel.DefaultValue("John")]
public string Name { get; set; }
}
public static class Test
{
public static void Main()
{
var serializer = new XmlSerializer(typeof(Person));
var person = new Person { Name = "John" };
using (var sw = new StringWriter())
{
using (var writer = XmlWriter.Create(sw))
{
serializer.Serialize(writer, person);
var xml = sw.ToString();
} …Run Code Online (Sandbox Code Playgroud) 我正在使用TimedRotatingFileHandler创建我的日志。我希望我的日志文件每分钟创建一次,最多保留 2 个日志文件并删除旧的。这是示例代码:
import logging
import logging.handlers
import datetime
logger = logging.getLogger('MyLogger')
logger.setLevel(logging.DEBUG)
handler = logging.handlers.TimedRotatingFileHandler(
"logs/{:%H-%M}.log".format(datetime.datetime.now()),
when="M",
backupCount=2)
logger.addHandler(handler)
logger.debug("PLEASE DELETE PREVIOUS FILES")
Run Code Online (Sandbox Code Playgroud)
如果我多次运行此代码(间隔一分钟),我会在我的日志目录中得到多个文件,如下所示:
21-01.log
21-02.log
21-03.log
...
Run Code Online (Sandbox Code Playgroud)
这对我来说似乎很奇怪,因为我设置了backupCount=2它表示最多应该保存 2 个文件,并且应该删除旧文件。但是,当我在日志文件夹中使用 2 个或更多文件启动我的应用程序时,不会删除旧文件。
为什么 TimedRotatingFileHandler 不删除旧文件?有什么办法可以设置 TimedRotatingFileHandler 来删除旧文件?
我知道,当您想在 HTML body 部分中调用 JavaScript 函数时,您可以通过放入 body 标记中来实现<script> someFunction(); </script>,这是一个示例,我有这样的 HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript"
src="/Script.js"></script>
</head>
<body>
<script>
showAlert();
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
javascript 文件如下:
function showAlert(){
alert("This is an alert!");
}
Run Code Online (Sandbox Code Playgroud)
这工作正常,但如果我将 JavaScript 文件引用放在正文的末尾,如下所示:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<script>
showAlert();
</script>
<script type="text/javascript"
src="/Script.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
该函数showAlert()不再被调用。您能回答以下2个问题吗:
showAlert()在第二种情况下没有被调用?我之所以问这个问题,是因为我知道在正文末尾而不是头部引用 JavaScript 文件是一个很好的做法,这样页面将在加载所有 JavaScript 代码之前首先呈现。
我有一个习惯AuthorizeAttribute,在授予用户查看资源的权限之前,需要使用其中一个业务层服务来验证数据库中的某些数据。为了能够在我内部分配此服务,我AuthorizeAttribute决定使用服务位置“反模式”,这是代码:
internal class AuthorizeGetGroupByIdAttribute : AuthorizeAttribute
{
private readonly IUserGroupService _userGroupService;
public AuthorizeGetGroupByIdAttribute()
{
_userGroupService = ServiceLocator.Instance.Resolve<IUserGroupService>();
}
//In this method I'm validating whether the user is a member of a group.
//If they are not they won't get a permission to view the resource, which is decorated with this attribute.
protected override bool IsAuthorized(HttpActionContext actionContext)
{
Dictionary<string, string> parameters = actionContext.Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);
int groupId = int.Parse(parameters["groupId"]);
int currentUserId = HttpContext.Current.User.Identity.GetUserId();
return …Run Code Online (Sandbox Code Playgroud) asp.net authorize-attribute asp.net-web-api iauthorizationfilter asp.net-web-api-filters
我正在开发一个可以发送fttp请求的类,它有一个可以执行不同类型的ftp方法的实用工具方法:
private FtpWebResponse DoFttpRequest(Uri uri, NetworkCredential credentials, string method, string file = null)
{
var request = (FtpWebRequest)WebRequest.Create(uri);
request.Credentials = credentials;
request.Method = method;
if (!string.IsNullOrEmpty(file))
{
using (var stream = request.GetRequestStream())
using (var writer = new StreamWriter(stream))
{
writer.Write(file);
}
}
return (FtpWebResponse)request.GetResponse();
}
Run Code Online (Sandbox Code Playgroud)
如您所见,此方法执行ftp方法并将响应流返回给调用者.以下是使用此方法通过ftp将字符串内容写入文件的客户端方法:
public void WriteToFile(string path, string contents)
{
var uri = new Uri(path);
using (var ftpResponse = DoFttpRequest(uri, _credentials, Ftp.UploadFile, contents)) { }
}
Run Code Online (Sandbox Code Playgroud)
如您所见,这里我使用空的using语句using (var ftpResponse = DoFttpRequest(uri, _credentials, Ftp.UploadFile, contents)) { } …
如何通过 XAML 设置窗口的所有者Application.Current.MainWindow?到目前为止我已经尝试过这个:
<Window x:Class="ModalWindow.CustomModalWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Owner="System.Windows.Application.Current.MainWindow">
<!--Some XAML code-->
</Window>
Run Code Online (Sandbox Code Playgroud)
那行不通。
在我的WIX项目中,我有一个像这样的目录结构:
<Directory Id="TARGETDIR" Name="SourceDir">
<Directory Id="INSTALLLOCATION" Name="FolderName">
...
</Directory>
<Directory Id="MYDIRECTORY" Name="SomeDifferentDirectory">
...
</Directory>
</Directory>
Run Code Online (Sandbox Code Playgroud)
这里INSTALLLOCATION代表我程序的安装文件夹,但是我想另外创建另一个安装目录之外的目录,例如D:\MyFolder1\MyFolder2,从上面的例子中我如何分配这个值,MYDIRECTORY以便在安装完成后创建它?
c# ×6
asp.net ×2
ftp ×2
webrequest ×2
.net ×1
amazon ×1
amazon-mws ×1
attributes ×1
cil ×1
controller ×1
dispose ×1
firebase ×1
html ×1
javascript ×1
logging ×1
owner ×1
properties ×1
pushsharp ×1
python ×1
python-3.x ×1
signalr ×1
signalr-hub ×1
using ×1
wix ×1
wix3.11 ×1
wpf ×1
xaml ×1
xml ×1
xmlwriter ×1