小编Com*_*ity的帖子

MVC:自定义,流利的Html助手

我正在编写一个自定义的HTML帮助器来显示一个Grid,我正专注于Telerik和其他各方,我想使用的语法.

我有一个具有3个属性(Name,DateUpdated和DateCreted)的模型,并将一个IEnumerable传递给我的视图:

@model IEnumerable<GridPageFolderViewModel>
Run Code Online (Sandbox Code Playgroud)

然后我有我的静态HtmlHelperExtensions类:

public static class HtmlHelperExtensions
{
    #region Grid

    public static GridBuilder<TModelEntry> GridFor<TModel, TModelEntry>(this HtmlHelper<TModel> htmlHelper, TModelEntry model)
    {
        return new GridBuilder<TModelEntry>();
    }

    #endregion
}
Run Code Online (Sandbox Code Playgroud)

这个类确实返回一个GridBuilder,如下所示:

public class GridBuilder<TModel> : IGridBuilder
{
    #region Properties

    private string name { get; set; }

    #endregion

    #region Methods

    public GridBuilder<TModel> WithColumns(Action<ColumnBuilder<TModel>> function)
    {
        return this;
    } 

    internal MvcHtmlString Render()
    {
        return new MvcHtmlString("This is a value.");
    }

    #endregion

    #region IGridBuilder Members

    public GridBuilder<TModel> Name(string name)
    {
        this.name = name;

        return this; …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc html-helper

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

单击项目时,在React中更改列表中的项目

我对ReactJS很陌生,我很难理解不同的组件如何相互通信.

我有一个组件将呈现一个列表,每个列表项是一个不同的组件.我想保持组件尽可能小.

现在,每个列表项都可以具有一个名为property的属性active,如果该属性设置为true,则会添加一个附加类.

这是在组件中定义单个项的类.

请参阅以下代码,以了解定义单个列表项的组件:

export default class OfficeRibbonTab extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      active: props.active ? props.active : false
    }

    // Assign all the correct event handlers.
    this.setActive = this.setActive.bind(this);
  }


  setActive() {
    this.setState({active: true});
  }

  render() {
    // When the tab is defined as active, add the "active" class on it.
    if (this.state.active)
    { var tabClassName = "active"; }

    return <li onClick={this.setActive} className={tabClassName}>{this.props.tabName}</li>;
  }
}
Run Code Online (Sandbox Code Playgroud)

所以,我有active传递给这个组件的propery ,我存储在组件状态中.当我单击列表项时,我将当前项的状态设置为活动状态.问题是我希望所有其他列表项变为非活动状态,从而将active的状态设置为false.

下面的代码是我的列表的概述:

export default …
Run Code Online (Sandbox Code Playgroud)

reactjs

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

C#Generic Repository - 工作单元 - 线程安全

我目前正在编写一个依赖于数据库的应用程序,而我正在使用Entity Framework(根据Nuget版本为6.1.1).

现在我编写了一个Repository模式,如下所示:

public class RepositoryBase<TEntity> where TEntity : class
{
    #region Constructors

    protected RepositoryBase(IDbContext context, IUnitOfWork unitOfWork)
    {
        Context = context;
        DbSet = Context.Set<TEntity>();
        UnitOfWork = unitOfWork;
    }

    #endregion

    #region Properties

    protected IDbSet<TEntity> DbSet;

    protected readonly IDbContext Context;

    protected readonly IUnitOfWork UnitOfWork;

    #endregion

    #region Methods

    protected TEntity Get(Expression<Func<TEntity, bool>> filter)
    {
        DbSet.ThrowIfNull("DbSet");

        IQueryable<TEntity> query = DbSet;

        return !query.Any() ? null : !query.Where(filter).Any() ? null : query.First(filter);
    }

    protected TEntity Get(Expression<Func<TEntity, bool>> filter, string[] includeProperties)
    {
        DbSet.ThrowIfNull("DbSet");

        IQueryable<TEntity> query = …
Run Code Online (Sandbox Code Playgroud)

c# multithreading entity-framework

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

这是编写异步方法的正确方法吗?

我目前正在尝试编写异步代码,我觉得我的代码根本不太正确.

我有以下方法:

public void Commit()
{
    _context.SaveChangesToDatabase();
}
Run Code Online (Sandbox Code Playgroud)

不要在这里判断代码,因为这只是样本.此外,不要说如果我使用实体框架,它们已经与Async方法打包在一起.我只是想了解这里的异步概念.

假设该方法SaveChangesToDatabase确实需要几秒钟才能完成.现在,我不想等待它,所以我创建了一个异步方法:

public async Task CommitAsync()
{
    await Task.Run(() => Commit());
}
Run Code Online (Sandbox Code Playgroud)

这是否意味着如果我有一个方法:

public void Method()
{
    // Operation One:

    CommitAsync();

    // Operation Two.
}
Run Code Online (Sandbox Code Playgroud)

这是否意味着我的操作二代码将在CommitAsync()完成之前执行?

如果没有,请指导我正确的方向.

更新

根据这里的评论,我忽略了我的异步方法结果,这个实现更好吗?

public Task<TaskResult> CommitAsync()
{
    var task = new Task<TaskResult>(() =>
    {
        try { Commit(); }
        catch (Exception ex)
        {
            return new TaskResult
            {
                Result = TaskExceutionResult.Failed,
                Message = ex.Message
            };
        }

        return new TaskResult { Result = TaskExceutionResult.Succeeded }; …
Run Code Online (Sandbox Code Playgroud)

c# asynchronous async-await c#-5.0

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

如何单元测试FileStream的File.Open

首先,我熟悉单元测试模拟的概念,我正在根据TDD编写应用程序.

我有一个方法,我需要读取一个文件.读入文件:

 using (var webshopXmlFileStream = StreamFactory.Create(importFile))
 {
     // Opens a reader that will read the Xml file.
     using (var reader = XmlReader.Create(webshopXmlFileStream))
     {
         // Read the nodes "Node" and "ArticleGroup" recursively.
         var nodes = XmlReaderUtils.EnumerateAxis(reader, new[] { "Node", "ArticleGroup" });
     }
 }
Run Code Online (Sandbox Code Playgroud)

当然,这不是单元可测试的.

所以,我创建了一个名为的接口IStreamFactory,它只有一个方法:

Stream Create(string filePath);
Run Code Online (Sandbox Code Playgroud)

此接口的实现如下所示:

public Stream Create(string filePath)
{ 
  return File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None); 
}
Run Code Online (Sandbox Code Playgroud)

所以,现在我可以模拟界面返回a MemoryStream,如下所示:

const string webshopXmlData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                "<Node>" +
                                  "<Name></Name>" +
                                "</Node>";
var streamFactoryMock …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing

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

如何使用MongoDB C#Driver 2.0创建流畅的聚合

我是MongoDB的新手,我在Web Api中使用它来为移动应用程序提供服务.

现在,我需要运行一个聚合,因为我正在使用C#,我想通过使用Aggregate一个返回我的集合上的命令来流利地完成它IAggregateFluent.

但是,我被困住了,我在SO上找到的信息对我没有帮助,因此是一个新问题.

我已经建立了一个小型集合,其中包含具有一些基本属性的智能手机,智能手机集合中的单个项目看起来像:

{
    "name" : "LG Nexus 5",
    "description" : "A Nexus 5 device, created by Google.",
    "typenr" : "LG-NEX-5/WHITE",
    "props" : [ 
        {
            "type" : "os",
            "value" : "Android"
        }, 
        {
            "type" : "storage",
            "value" : "8"
        }, 
        {
            "type" : "storage",
            "value" : "16"
        }, 
        {
            "type" : "storage",
            "value" : "32"
        }, 
        {
            "type" : "storage",
            "value" : "64"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

现在,我在shell中创建了一个聚合,如下所示:

// Get all the amount of filters …
Run Code Online (Sandbox Code Playgroud)

c# mongodb mongodb-csharp-2.0 mongodb-.net-driver

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

将aa href设置为按钮

我正在创建一组可在每个浏览器中运行的大量HTML组件(无论如何,这个想法始于:-))

现在,我想要一个按钮,根据StackOverflow 上的这篇文章,我不应该使用按钮,因为那个按钮具有3D推送效果.为了删除那个,建议是使用a a href和样式到我喜欢的按钮.

所以这是HTML:

<a href="#" class="button">
    <span>Yes</span>
</a>
Run Code Online (Sandbox Code Playgroud)

当然,这是HTML:

a.button {
  color: #444;
  border: 1px solid #ababab;
  cursor: default;
  padding: 0 5px 0 5px;
  text-decoration: none;
}
a.button:hover {
  background-color: #cde6f7;
  border: 1px solid #92c0e0;
}
a:active.button {
  background-color: #92c0e0;
  border: 1px solid #2a8dd4;
}
Run Code Online (Sandbox Code Playgroud)

没有什么真的很复杂

现在,这可以在谷歌Chrome和Firefox中运行,就像这个JsFiddle演示的那样.

该按钮有3种不同的状态:

  • 一个普通的"默认"按钮.
  • 悬停在它上面的一种风格.
  • 点击它时的样式.

现在,当您单击按钮时,Internet Explorer不会应用新样式,它与悬停时的样式相同.除非您单击边框(如果您设法单击边框,则应用正确的样式).

现在,为什么我有这种行为并且可以解决,因为它对我的Control Suite的开发至关重要.

我知道可以通过在点击它时添加删除类来解决jQuery,但这似乎是一个非常难看的解决方案,如果有一个'CSS-Friendly'解决方案,我想使用那个.

html javascript css jquery css3

3
推荐指数
1
解决办法
148
查看次数

如何仅选择 OData 子元素

我正在构建一个 OData 应用程序,我正在努力研究如何检索结果并且只包含某些(子属性)。

首先,让我向您展示在我的构建器中的注册:

builder.EntitySet<AggregatedArticlesSearchModel>("Search").EntityType.HasKey(x => x.Name);
Run Code Online (Sandbox Code Playgroud)

现在,转到我从查询返回的模型:

<EntityType Name="AggregatedArticlesSearchModel">
    <Key>
        <PropertyRef Name="Name"/>
    </Key>
    <Property Name="Name" Nullable="false" Type="Edm.String"/>
    <Property Name="Values" Type="Collection(Zevij_Necomij.Mobile.App.Api.Models.OccurenceViewModel)"/>
</EntityType>
<ComplexType Name="OccurenceViewModel">
    <Property Name="Value" Type="Edm.String"/>
    <Property Name="Count" Nullable="false" Type="Edm.Double"/>
    <Property Name="Articles" Type="Collection(Zevij_Necomij.Mobile.App.Api.Models.AggregatedArticleDescriptionViewModel)"/>
</ComplexType>
<ComplexType Name="AggregatedArticleDescriptionViewModel">
    <Property Name="Name" Type="Edm.String"/>
    <Property Name="Specification" Type="Edm.String"/>
    <Property Name="Brand" Type="Edm.String"/>
</ComplexType>
Run Code Online (Sandbox Code Playgroud)

当我执行获取数据的请求时,我没有做任何花哨的事情,只是从数据库中返回结果:

public async Task<IHttpActionResult> Get()
{
    // Create all the managers for the platform context that are required by the application.
    var classificationManager = Context.CreateManager(typeof(AggregatedArticleManager<>)) as AggregatedArticleManager<IAggregatedArticleStore<AggregatedArticle>>;

    var classifications = await classificationManager.GetAllAsync();

    var …
Run Code Online (Sandbox Code Playgroud)

c# odata

3
推荐指数
1
解决办法
4713
查看次数

无法在 Vue 中渲染多个组件

我刚开始使用 Vue,我已经定义了 2 个组件,但是,我无法在同一个“Vue”实例中呈现它们。

这是我的两个组件:

Vue.component('mat-example', {
  data: function () {
    return {
      count: 0
    }
  },
  template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})

Vue.component('button-counter', {
  data: function () {
    return {
      count: 0
    }
  },
  template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
Run Code Online (Sandbox Code Playgroud)

接下来,我确实定义了“Vue”入口点:

var app = new Vue({
  el: '#app'
});
Run Code Online (Sandbox Code Playgroud)

在我的 HTML 中,我确实有以下代码:

<div id="app">
    <button-counter />
    <mat-example />
</div>
Run Code Online (Sandbox Code Playgroud)

“Vue”开发工具只显示“button-counter”组件:

在此处输入图片说明

如果我删除了“button-counter”,“mat-example”就会出现在 Vue 开发者工具中。

为什么我无法在我的 Vue 入口点渲染这两个组件?

javascript vue.js vuejs2

3
推荐指数
1
解决办法
2327
查看次数

通过Ninject内核是一个好习惯吗?

我正在编写一个执行几项任务的小框架.有些任务需要通过Ninject注入的特定属性.

假设我的基类中有以下构造函数,它代表一个Task:

protected DDPSchedulerTask(ILogger logger, List<string> platforms, IBackOfficeDataStore backOfficeDataStore, ICommonDataStore commonDataStore)
{
    _logger = logger;
    _platforms = platforms;
    _backOfficeDataStore = backOfficeDataStore;
    _commonDataStore = commonDataStore;
}
Run Code Online (Sandbox Code Playgroud)

所有任务都需要这些属性,因此我使用Ninject使用以下Ninject模块注入它们.

public class DDPDependencyInjectionBindingConfiguration : NinjectModule
{
    #region NinjectModule Members

    /// <summary>
    ///     Loads the module into the kernel.
    /// </summary>
    public override void Load()
    {
        Bind<Scheduler>().ToSelf(); // Make sure that the 'Scheduler' is resolved to itself.
        Bind<ILogger>().ToMethod(context => LogFactory.Create()); // Make sure that an instance of an ILogger is created through the LogFactory.

        // …
Run Code Online (Sandbox Code Playgroud)

c# ninject

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

CA2000和我没有看到原因

我正在编写一个项目,我使用Microsoft Code Analysis,但确实收到以下错误:

CA2000:在丢失范围之前处置对象.

这是我在实体框架周围编写的代码.

public bool IsInstalled(InstallationContext context)
{
    var dbContext = new ScheduleFrameworkDataContext();
    var repository = new TaskRepository(dbContext);

    try
    {
        // Check if there is already a task with the same name.
        if (repository.Get().Select(x => x.Name == context.InstallationParameters.Name).Any())
        { return true; }
    }
    finally { dbContext.Dispose(); }

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

现在,我认为我的上下文被处理掉了,因为它在finally块中.(上下文是EF Code First DB Context).但是,我仍然收到这个错误.

我在这里错过了什么吗?

.net c# dispose entity-framework

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

更改值后反应组件未更新

在 ReactJS 中,我正在编写一个无状态组件;
因为我读过避免不必要的状态是最佳实践。

该组件代表一个输入字段,当输入框包含一个值时,它会执行一个函数。

    export const InputField = (props) => {
      
      const InputFieldContentsChanged = (event) => {
        props.onChange(event.target.value);
      };

      return (
        <div data-component="input-field"
          className={(props.value !== "" ? "value": "")}>
          <input type={props.type} value={props.value} onChange={InputFieldContentsChanged} />
          <span className="bar"></span>
          <label>{props.label}</label>
        </div>
      );
    };

    InputField.PropTypes = {
      type: PropTypes.oneOf([ "text", "password" ]).isRequired,
      label: PropTypes.string.isRequired,
      value: PropTypes.string,
      onChange: PropTypes.func.isRequired
    }
Run Code Online (Sandbox Code Playgroud)

现在,我创建了另一个组件,它只是测试上述组件的示例。如下所示:

    export const SampleComponent = (props) => {
      
      let componentUsername = "";
      
      const onUsernameChanged = (username) => {
        componentUsername = username;
      };
      
      return ( …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks react-state react-functional-component react-class-based-component

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