小编Ste*_*rdi的帖子

传递具有两个参数的委托作为参数函数

我有一系列看起来非常相似的函数,但对于一行,如下面两行(但我还有更多):

private static int HowManyHoursInTheFirstYear(IList<T> samples)
{
    DateTime firstDate = samples[0].Date;
    int count = 0;

    while (count < samples.Count && 
          samples[count].Date.Year == firstDate.Year)
    {
        count++;
    }

    return count;
}


private static int HowManyDaysInTheFirstMonth(IList<T> samples)
{
    DateTime firstDate = samples[0].Date;
    int count = 0;

    while (count < samples.Count && 
           samples[count].Date.Month == firstDate.Month) // <--- only change!
        count++;
    }

    return count;
}
Run Code Online (Sandbox Code Playgroud)

我正在考虑使用委托以一种优雅的方式删除代码中的重复,这将允许我调用类似的东西:

HowManyDaysInTheFirstPeriod(
    samples,
    delegate(DateTime d1, DateTime d2) { return d1.Month == d2.Month; });
Run Code Online (Sandbox Code Playgroud)

从而宣布代表如下:

delegate bool DateComparer(DateTime first, DateTime second); …
Run Code Online (Sandbox Code Playgroud)

c# delegates

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

WCF:使用流式传输与消息合同

我正在尝试使用带有消息合同的WCF流,因为我需要在流本身旁边添加其他参数.

基本上我正在创建一个文件上传和下载服务,顶部还有一些额外的逻辑.

不幸的是,当我尝试从浏览器点击服务以检查一切正常时,我收到以下错误:

'/'应用程序中的服务器错误.合同'IFileTransferService'中的"UploadFile"操作使用具有SOAP头的MessageContract.None MessageVersion不支持SOAP标头.

不幸的是谷歌搜索它并没有产生任何帮助我的重要结果.你们能帮助我吗?这里是服务的细节(我已经删除了下载部分,因为空间的原因).

[ServiceContract(Namespace = "http://www.acme.org/2009/04")]
public interface IFileTransferService
{
    [OperationContract(Action = "UploadFile")]
    void UploadFile(FileUploadMessage request);
}

[MessageContract]
public class FileUploadMessage
{
    [MessageHeader(MustUnderstand = true)]
    public FileMetaData Metadata { get; set; }

    [MessageBodyMember(Order = 1)]
    public Stream FileByteStream { get; set; }
}

[DataContract(Namespace = "http://schemas.acme.org/2009/04")]
public class FileMetaData
{
    [DataMember(Name="FileType", Order=0, IsRequired=true)]
    public FileTypeEnum fileType;

    [DataMember(Name="localFilename", Order=1, IsRequired=false)]
    public string localFileName;

    [DataMember(Name = "remoteFilename", Order = 2, IsRequired = false)]
    public string remoteFileName;
}
Run Code Online (Sandbox Code Playgroud)

我试图使用basichttpbinding和customhttp绑定,但效果不佳:

<customBinding> …
Run Code Online (Sandbox Code Playgroud)

.net c# wcf wcf-binding wcf-configuration

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

如何通过反射获取集合中包含的类型

在我的代码的某些部分,我传递了一组类型的对象T.我不知道我将通过哪个具体的收集,除了它的要求IEnumerable.

在运行时,我需要找出哪些类型T(例如System.Double,System.String等...).

有什么方法可以找到它吗?

更新:我应该澄清一下我正在工作的背景(一个Linq提供者).

我的函数有如下的签名,我将集合的类型作为参数:

string GetSymbolForType(Type collectionType)
{

}
Run Code Online (Sandbox Code Playgroud)

是否有任何方法collectionType来获取包含的对象类型?

c# reflection collections

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

将mongo集合导出到SQL Server的最佳实践

我们使用MongoDB(在Linux上)作为我们的主数据库.但是,我们需要定期(例如每晚)将Mongo中的一些集合导出到MS SQL服务器以运行分析.

我正在考虑以下方法:

  1. 使用mongodump备份Mongo数据库(可能来自副本)
  2. 将数据库还原到配置了Mongo的Windows计算机
  3. 编写一个自定义应用程序,将Mongo中的集合导入SQL(可能需要处理任何所需的规范化).
  4. 在Windows SQL Server安装上运行分析.

还有其他"经过验证的"替代方案吗?

谢谢,斯特凡诺

编辑:对于第4点,分析将在SQL Server上运行,而不是在Mongo上运行.

sql-server mongodb

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

通过使用不同属性类型的反射设置对象的属性

我使用反射来填充对象的属性.

这些属性有不同的类型:String,Nullable(double)和Nullable(long)(不知道如何在这里转义尖括号......).这些属性的值来自(字符串,对象)对的字典.

因此,例如我的类具有以下属性:

string Description { get; set; } 
Nullable<long> Id { get; set; }
Nullable<double> MaxPower { get; set; }
Run Code Online (Sandbox Code Playgroud)

(实际上有大约十几个属性),字典将有<"描述","描述">,<"Id",123456>,<"MaxPower",20000>等条目

现在我使用类似以下内容来设置值:

foreach (PropertyInfo info in this.GetType().GetProperties())
{
    if (info.CanRead)
    {
         object thisPropertyValue = dictionary[info.Name];

         if (thisPropertyValue != null && info.CanWrite)
         {
             Type propertyType = info.PropertyType;

             if (propertyType == typeof(String))
             {
                 info.SetValue(this, Convert.ToString(thisPropertyValue), null);
             }
             else if (propertyType == typeof(Nullable<double>))
             {
                 info.SetValue(this, Convert.ToDouble(thisPropertyValue), null);
             }
             else if (propertyType == typeof(Nullable<long>))
             {
                 info.SetValue(this, Convert.ToInt64(thisPropertyValue), null);
             }
             else
             {
                 throw new …
Run Code Online (Sandbox Code Playgroud)

c# reflection runtime properties

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

将自定义类型的Safearray从C++传递到C#

如何使用a Safearray将一组自定义类型(一个只包含属性的类)从C++传递给C#?使用该VT_RECORD类型的方法是正确的吗?

我正在尝试以下方式,但SafeArrayPutElement在尝试填充safearray时返回错误,对类数组的引用以NULL形式获取托管代码.

我在托管世界中有以下内容:

[ComVisible(true)]
public interface IStatistics
{
    double Mean { get; set; } 
    double StdDev { get; set; } 
}

[Serializable]
[ComVisible(true)]
public class Statistics : IStatistics
{
    public Mean { get; set; }
    public double StdDev { get; set; } 
}
Run Code Online (Sandbox Code Playgroud)

未管理的世界:

HRESULT hr = CoInitialize(NULL);
...
SAFEARRAY *pEquationsStatistics;

// common dimensions for all arrays
SAFEARRAYBOUND dimensions[1];  
dimensions[0].cElements = 2;   
dimensions[0].lLbound = 0;    

pEquationsStatistics = SafeArrayCreate(VT_RECORD, 1, dimensions);
... …
Run Code Online (Sandbox Code Playgroud)

c# c++ com serialization safearray

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

Mongo聚合框架:按年龄分组用户

我有一个用户库存储在mongo中.用户可以记录他们的出生日期.我需要运行按年龄汇总用户的报告.

我现在有一个管道,按出生年份对用户进行分组.然而,这不够精确,因为大多数人不是1月1日出生的; 因此,即使他们出生于1970年,他们也可能还不到43岁.

db.Users.aggregate([
    { $match : { "DateOfBirth" : { $exists : true} } },
    { $project : {"YearOfBirth" : {$year : "$DateOfBirth"} } }, 
    { $group : { _id : "$YearOfBirth", Total : { $sum : 1} } },
    { $sort : { "Total" : -1 } }
])
Run Code Online (Sandbox Code Playgroud)

您是否知道在聚合框架内是否可以执行某种算法来精确计算用户的年龄?或者只有MapReduce可以实现吗?

mongodb

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

托管代码是否应该返回错误或将异常抛给非托管代码?

我将使用COM将使用C#编写的服务公开给传统的C++应用程序.向非托管客户端报告错误的最佳方法是什么?抛出异常或只返回错误值?

谢谢,斯特凡诺

c# c++ com exception

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

是否可以通过COM公开DateTime字段?

看起来我无法通过COM将类暴露给非托管客户端,如果该类的一个属性具有类型DateTime.

例:

[ComVisible(true)]
public interface ITest
{
   string Name { get; }
   DateTime Date { get; }
}

[Serializable]
[ComVisible(true)]
public class Test : ITest
{
    public string Name { get; private set; }
    public DateTime Date { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

只有当我Date在接口和实现上注释掉属性时,.tlh文件才会包含Test结构(显然没有Date).

任何的想法?有没有办法表示通过COM可见的日期?我是否真的需要传递Date作为a string然后解析它?

感谢您的时间!

c# com serialization

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

函数返回一个泛型类型,其值仅在运行时已知

我需要使用如下通用接口:

public interface IContainer<T>
{
    IEnumerable<IContent<T>> Contents { get; }
}
Run Code Online (Sandbox Code Playgroud)

实现此接口的对象由以下通用方法返回:

IContainer<T> GetContainer<T>(IProperty property);
Run Code Online (Sandbox Code Playgroud)

T在运行时之前,类型是未知的.

使用反射我可以调用GetContainer<T>方法并获得结果.

我的问题是我不知道如何枚举具有类型的结果Object(因此我无法将其强制转换IEnumerable).

我也试过如下铸造,但它不起作用(它说"预期类型"):

var myContainer = genericMethodInfo.Invoke(
                           myService, 
                           new object[] { property })
    as typeof(IContainer<>).MakeGenericType(type);
Run Code Online (Sandbox Code Playgroud)

type运行时类型在哪里,myService是暴露GetContainer<T>方法的服务,并且propertyIProperty根据需要的类型.

更新:在我的博客中查看我的完整解决方案:http://stefanoricciardi.com/2010/02/18/generics-with-type-uknown-at-compile-time/

c# generics reflection

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

以编程方式配置WCF流服务的错误响应(400)

这个,如果我第一次尝试使用流式传输WCF,我正在努力与可怕的"远程服务器返回一个意外的响应:(400)错误请求"响应.

跟踪查看器说这是一个System.ServiceModel.ProtocolException,并显示消息" 从网络收到的XML存在问题.有关更多详细信息,请参阅内部异常." 内部异常类型显示" 消息正文无法读取,因为它是空的. "

让其他一切都相等,如果我在客户端切换到缓冲模式,我可以调试到服务器代码!

出于某种原因,我必须以编程方式配置我的服务,如下所示:

    public IUniverseFileService OpenProxy(string serviceUrl)
    {
        Debug.Assert(!string.IsNullOrEmpty(serviceUrl));

        var binding = new BasicHttpBinding();
        binding.Name = "basicHttpStream";
        binding.MaxReceivedMessageSize = 1000000;
        binding.TransferMode = TransferMode.Streamed;

        var channelFactory = 
           new ChannelFactory<localhost.IUniverseFileService>(
              binding, 
              new EndpointAddress(serviceUrl));

        return channelFactory.CreateChannel();
    }
Run Code Online (Sandbox Code Playgroud)

服务器配置如下:

 <system.serviceModel>
    <!-- BEHAVIORS -->
    <behaviors>
      <serviceBehaviors>
        <behavior name="serviceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true" httpHelpPageEnabled="true"/>
          <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <!-- SERVICES -->
    <services>
      <service behaviorConfiguration="serviceBehavior" name="Org.Acme.UniverseFileService">
        <endpoint address="" 
                  binding="basicHttpBinding" 
                  name="basicHttpStream" 
                  bindingConfiguration="httpLargeMessageStream"
                  contract="Org.Acme.RemoteCommand.Service.IUniverseFileService" /> 
        <endpoint address="mex" 
                  binding="mexHttpBinding" 
                  bindingConfiguration="" name="mexStream" …
Run Code Online (Sandbox Code Playgroud)

c# streaming wcf soap

4
推荐指数
2
解决办法
6904
查看次数

通过COM将对象从C++传递到C#

您好在C#中有一个COM可见API,如下所示:

public void DoSomething(string par1, string par2, object additionalParameter)
Run Code Online (Sandbox Code Playgroud)

我的想法是,基于字符串参数的值,我希望将不同的类作为第三个参数,并在实现中适当地投射它(我知道这个设计不是最优的,但我在这里没有太大的灵活性).

假设对于字符串参数的某些组合,附加参数的类型如下:

[ComVisible(true)]
[Serializable]
public class TestObject    
{
    public string String{ get; set; }

    public long Long { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我需要从一些非托管代码中获取我的API方法; 但是我在创建variant第三个参数所需的合适时遇到了困难.

我正在使用CComVariant(...)传递IDispatch指向我刚刚构建的TestObject.

假设这pTestObject是一个指向我的TestObject的IDispatch指针,我有以下内容:

CComVariant pObjectVariant(pTestObject);
DoSomething(BSTR(L"first"), BSTR(L"second"), pObjectVariant);
Run Code Online (Sandbox Code Playgroud)

但是,当最终调用C#函数时,我看到该对象具有类型bool而不是TestObject我期望的类型.

任何的想法?

斯特凡诺

c# interop variant

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

Ruby:如何匹配正则表达式中的双引号

我试图使用Ruby one liner从文本文件中删除一些双引号(")字符,但收效甚微.

我尝试了以下和一些变化,但没有成功.

ruby -pe 'gsub(/\"/,"")' < myfile.txt
Run Code Online (Sandbox Code Playgroud)

这给了我以下错误:

-e:1: Invalid argument - < (Errno::EINVAL)
Run Code Online (Sandbox Code Playgroud)

我在Win机器上运行Ruby:

ruby 1.8.6(2007-09-24 patchlevel 111)[i386-mswin32]

任何的想法?

ruby regex escaping gsub

2
推荐指数
1
解决办法
2522
查看次数