content stringlengths 23 1.05M |
|---|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Core.Domain.Security
{
[Table("SecurityGroup", Schema = "dbo")]
public class SecurityGroup : BaseEntity
{
//[Key]
//public int SecurityGroupId { get; set; }
public string Name { get; set; }
public string DisplayName { get; set; }
public virtual ICollection<SecurityPermission> Permissions { get; set; }
public SecurityGroup()
{
Permissions = new HashSet<SecurityPermission>();
}
}
}
|
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
#pragma warning disable IDE1006 // Naming Styles
namespace KerbDump
{
public class LSASecret : IDisposable
{
private const string ADVAPI32 = "advapi32.dll";
private const uint POLICY_GET_PRIVATE_INFORMATION = 0x00000004;
[StructLayout(LayoutKind.Sequential)]
private struct LSA_UNICODE_STRING
{
public UInt16 Length;
public UInt16 MaximumLength;
public IntPtr Buffer;
}
[StructLayout(LayoutKind.Sequential)]
private struct LSA_OBJECT_ATTRIBUTES
{
public int Length;
public IntPtr RootDirectory;
public LSA_UNICODE_STRING ObjectName;
public uint Attributes;
public IntPtr SecurityDescriptor;
public IntPtr SecurityQualityOfService;
}
[DllImport(ADVAPI32, SetLastError = true, PreserveSig = true)]
private static extern uint LsaRetrievePrivateData(
IntPtr PolicyHandle,
ref LSA_UNICODE_STRING KeyName,
out IntPtr PrivateData
);
[DllImport(ADVAPI32, SetLastError = true, PreserveSig = true)]
private static extern uint LsaOpenPolicy(
ref LSA_UNICODE_STRING SystemName,
ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
uint DesiredAccess,
out IntPtr PolicyHandle
);
[DllImport(ADVAPI32, SetLastError = true, PreserveSig = true)]
private static extern int LsaNtStatusToWinError(uint status);
[DllImport(ADVAPI32, SetLastError = true, PreserveSig = true)]
private static extern uint LsaClose(IntPtr policyHandle);
[DllImport(ADVAPI32, SetLastError = true, PreserveSig = true)]
private static extern uint LsaFreeMemory(IntPtr buffer);
private LSA_UNICODE_STRING secretName;
private readonly IntPtr lsaPolicyHandle;
public LSASecret(string key)
{
this.secretName = new LSA_UNICODE_STRING()
{
Buffer = Marshal.StringToHGlobalUni(key),
Length = (ushort)(key.Length * 2),
MaximumLength = (ushort)((key.Length + 1) * 2)
};
var localsystem = default(LSA_UNICODE_STRING);
var objectAttributes = default(LSA_OBJECT_ATTRIBUTES);
var winErrorCode = LsaNtStatusToWinError(
LsaOpenPolicy(
ref localsystem,
ref objectAttributes,
POLICY_GET_PRIVATE_INFORMATION,
out this.lsaPolicyHandle
)
);
if (winErrorCode != 0)
{
throw new Win32Exception(winErrorCode);
}
}
private static void FreeMemory(IntPtr Buffer)
{
var winErrorCode = LsaNtStatusToWinError(LsaFreeMemory(Buffer));
if (winErrorCode != 0)
{
throw new Win32Exception(winErrorCode);
}
}
public string GetSecret(out byte[] data)
{
var winErrorCode = LsaNtStatusToWinError(
LsaRetrievePrivateData(this.lsaPolicyHandle, ref this.secretName, out IntPtr privateData)
);
if (winErrorCode != 0)
{
throw new Win32Exception(winErrorCode);
}
var lusSecretData = (LSA_UNICODE_STRING)Marshal.PtrToStructure(privateData, typeof(LSA_UNICODE_STRING));
data = new byte[lusSecretData.Length];
Marshal.Copy(lusSecretData.Buffer, data, 0, lusSecretData.Length);
FreeMemory(privateData);
return Encoding.Unicode.GetString(data);
}
public void Dispose()
{
var winErrorCode = LsaNtStatusToWinError(LsaClose(this.lsaPolicyHandle));
if (winErrorCode != 0)
{
throw new Win32Exception(winErrorCode);
}
}
}
}
|
namespace AtomicusChart.Demo.Views
{
internal partial class StatusbarView
{
public StatusbarView()
{
InitializeComponent();
}
}
}
|
#region License
// Copyright (c) 2011, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This software is licensed under the Open Software License v3.0.
// For the complete license, see http://www.clearcanvas.ca/OSLv3.0
#endregion
namespace ClearCanvas.ImageViewer.Graphics
{
/// <summary>
/// Defines an <see cref="IVectorGraphic"/> that can be described as an ordered list of independent points.
/// </summary>
public interface IPointsGraphic : IVectorGraphic
{
/// <summary>
/// Gets the ordered list of points that defines the graphic.
/// </summary>
IPointsList Points { get; }
}
} |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// 事件的代理
/// </summary>
public delegate void SceneHook(IScene scene);
/// <summary>
/// 场景管理器
/// </summary>
/// <author>zhulin</author>
public class SceneM
{
/// <summary>
/// Unload事件
/// </summary>
public static event SceneHook eventUnload;
/// <summary>
/// loaded事件
/// </summary>
public static event SceneHook eventLoaded;
// 前一个场景
private static IScene s_preScene = null;
// 准备载入的场景
private static IScene s_loadingIScene = null;
// 当前是否正在载入场景
private static bool bLoading = false;
// 当前场景
private static IScene s_CurIScene = null;
// 场景载入器映射表
private static Dictionary<string, IScene> sceneLoadControl = new Dictionary<string, IScene>();
private static Dictionary<string, ILoading> sceneLoadingAnim = new Dictionary<string, ILoading>();
public static GameObject Schedulergo = null;
// 待载入场景的结构
private class SceneNode
{
public string name;
public ILoading loading;
public SceneNode(string name, ILoading loading)
{
this.name = name;
this.loading = loading;
}
}
public static IScene GetISceneByName(string sceneName)
{
IScene scene;
sceneLoadControl.TryGetValue(sceneName, out scene);
return scene;
}
//获取当前场景
public static IScene GetCurIScene()
{
return s_CurIScene;
}
/// <summary>
/// 当期那是否正在载入场景
/// </summary>
public static bool IsLoading { get { return bLoading; } }
public static IScene GetLoadingIScene()
{
return s_loadingIScene;
}
/// <summary>
/// 登记场景处理器
/// </summary>
public static void LinkScheduler(GameObject go)
{
Schedulergo = go;
}
/// <summary>
/// 登记场景处理器
/// </summary>
public static void RegisterScene(string name, IScene scene)
{
sceneLoadControl[name] = scene;
}
public static void RegisterLoadingAnim(string name, ILoading lodingAnimaiton)
{
sceneLoadingAnim[name] = lodingAnimaiton;
}
/// <summary>
/// 载入场景
/// </summary>
/// <param name="sceneName">待载入的场景名称</param>
/// <param name="sync">通过异步(false)方式还是同步(true)方式载入</param>
/// <param name="loading">载入动画的实例<see cref="ILoading"/></param>
/// <param name="force">是否需要保证载入成功(如果当前正在载入某个场景中,会仍到队列而不是直接失败)</param>
/// <returns>成功处理则返回true</returns>
public static bool Load(string sceneName, bool sync, ILoading loading, bool force)
{
if (!force && bLoading)
{
App.log.Trace("SceneM.cs", "当前正在载入场景中,无法重复加载。");
return false;
}
if (bLoading && sync)
{
App.log.Trace("SceneM.cs", "当前正在载入场景中,无法再同步加载场景了。");
return false;
}
if (bLoading)
{
// 添加到列表中,等待处理
return true;
}
// 如果当前正处于目标场景,无视
// 任务副本需要做特殊处理
IScene scene = sceneLoadControl[sceneName];
// 标记正在载入场景
s_loadingIScene = scene;
bLoading = false;
if (scene == s_CurIScene)
return true;
bLoading = true;
// 异步载入方式
if (!sync)
{
App.log.Trace("SceneM.cs", "开始异步载入场景{0}", sceneName);
Coroutine.DispatchService(NonsyncLoad(sceneName, loading), Schedulergo, null);
return true;
}
// 取得载入器
IScene preScene = s_CurIScene;
s_CurIScene = scene;
// 同步载入(不会播放任何动画)
App.log.Trace("SceneM.cs", "开始同步载入场景{0}", sceneName);
try
{
// 1 产生事件并清理旧的场景
if (eventUnload != null)
eventUnload(preScene);
if (null != preScene)
preScene.Clear();
// 2 载入新的场景
scene.Load();
// 3 数据切换回来
s_preScene = preScene;
scene.BuildScene();
scene.Start();
// 4 发出载入完毕的事件
if (eventLoaded != null)
eventLoaded(scene);
}
catch (Exception e)
{
App.log.Error("SceneM.cs", e.ToString());
}
// 载入完毕,进行垃圾回收
App.log.Trace("SceneM.cs", "同步载入场景{0}完成", sceneName);
bLoading = false;
Resources.UnloadUnusedAssets();
System.GC.Collect();
Load(sceneName, sync, force);
return true;
}
/// <summary>
/// 载入场景
/// </summary>
/// <param name="sceneName">待载入的场景名称</param>
/// <param name="sync">通过异步(false)方式还是同步(true)方式载入</param>
/// <param name="loading">载入动画的实例<see cref="ILoading"/></param>
/// <param name="force">是否需要保证载入成功(如果当前正在载入某个场景中,会仍到队列而不是直接失败)</param>
/// <returns>成功处理则返回true</returns>
public static bool Load(string sceneName, bool sync, bool force)
{
if (!force && bLoading)
{
App.log.Trace("SceneM.cs", "当前正在载入场景中,无法重复加载。");
return false;
}
if (bLoading && sync)
{
App.log.Trace("SceneM.cs", "当前正在载入场景中,无法再同步加载场景了。");
return false;
}
if (bLoading)
{
// 添加到列表中,等待处理
return true;
}
// 如果当前正处于目标场景,无视
// 任务副本需要做特殊处理
IScene scene = sceneLoadControl[sceneName];
ILoading loading = sceneLoadingAnim[sceneName];
// 标记正在载入场景
s_loadingIScene = scene;
bLoading = false;
if (scene == s_CurIScene)
return true;
bLoading = true;
// 异步载入方式
if (!sync)
{
App.log.Trace("SceneM.cs", "开始异步载入场景{0}", sceneName);
Coroutine.DispatchService(NonsyncLoad(sceneName, loading), Schedulergo, null);
return true;
}
// 取得载入器
IScene preScene = s_CurIScene;
s_CurIScene = scene;
// 同步载入(不会播放任何动画)
App.log.Trace("SceneM.cs", "开始同步载入场景{0}", sceneName);
try
{
// 1 产生事件并清理旧的场景
if (eventUnload != null)
eventUnload(preScene);
if (null != preScene)
preScene.Clear();
// 2 载入新的场景
scene.Load();
// 3 数据切换回来
s_preScene = preScene;
scene.BuildScene();
scene.Start();
// 4 发出载入完毕的事件
if (eventLoaded != null)
eventLoaded(scene);
}
catch (Exception e)
{
App.log.Error("SceneM.cs", e.ToString());
}
// 载入完毕,进行垃圾回收
App.log.Trace("SceneM.cs", "同步载入场景{0}完成", sceneName);
bLoading = false;
Resources.UnloadUnusedAssets();
System.GC.Collect();
return true;
}
// 异步载入场景
private static IEnumerator NonsyncLoad(string sceneName, ILoading loading)
{
App.log.Trace("SceneM.cs", "开始异步载入场景{0}", sceneName);
// 取得载入器
IScene scene = sceneLoadControl[sceneName];
s_preScene= s_CurIScene;
s_loadingIScene = scene;
// 1 播放开始载入的动画,并等待其播放完毕
if (loading != null)
{
App.log.Trace("SceneM.cs", "播放载入开始动画");
loading.FadeIn();
while (loading.IsFadingIn())
yield return null;
}
// 欲载入的处理
scene.PrepareLoad();
// 2 产生事件并清理旧的场景
if (eventUnload != null)
eventUnload(s_preScene);
if(s_preScene!=null)
s_preScene.Clear();
// 3 载入新的场景
scene.Load();
if (sceneLoadingAnim.ContainsKey(sceneName))
{
sceneLoadingAnim[sceneName].SetAsyncLoading(scene.AsyncLoading);
}
if (sceneLoadControl.ContainsKey (CombatScene.GetSceneName ()))
{
IScene sceneCombat = sceneLoadControl[CombatScene.GetSceneName()];
// 清理内存资源
if (scene != sceneCombat && s_preScene != sceneCombat)
{
Resources.UnloadUnusedAssets();
System.GC.Collect();
}
}
// 1 播放开始载入的动画,并等待其播放完毕
if (loading != null)
{
App.log.Trace("SceneM.cs", "播放载入开始动画");
loading.Load();
while (loading.IsLoading())
yield return null;
}
yield return new WaitForMSeconds(100f);
// 等待载入完成
while (! scene.IsEnd())
yield return null;
// 场景载入完成(一定要在load完毕后才能替换,此时的环境才能称得上载入完成)
s_CurIScene = scene;
bLoading = false;
// 6 发出载入完毕的事件
if (eventLoaded != null)
eventLoaded(scene);
//载入完成。
scene.BuildScene();
scene.Start();
// 4 播放载入完成的动画,并等待其播放完毕
if (loading != null)
{
App.log.Trace("SceneM.cs", "播放载入完成动画");
loading.FadeOut();
while (loading.IsFadingOut())
yield return null;
loading.TryDestroy();
}
// 载入完成
App.log.Trace("SceneM.cs", "异步载入场景{0}完成", sceneName);
}
// 当前场景Update
public static void Update(float deltaTime)
{
if(s_CurIScene != null && s_CurIScene.IsEnd() == true)
{
s_CurIScene.Update(deltaTime);
}
}
// 当前场景LateUpdate
public static void LateUpdate(float deltaTime)
{
if(s_CurIScene != null && s_CurIScene.IsEnd() == true)
{
s_CurIScene.LateUpdate(deltaTime);
}
}
// 当前场景LateUpdate
public static void FixedUpdate(float deltaTime)
{
if(s_CurIScene != null && s_CurIScene.IsEnd() == true)
{
s_CurIScene.FixedUpdate(deltaTime);
}
}
}
/// <summary>
/// Loading动画接口
/// </summary>
/// <author>weism</author>
public interface ILoading
{
/// <summary>
/// 播放准备加载的动画
/// </summary>
void FadeIn();
/// <summary>
/// 是否在播放准备加载的动画
/// </summary>
bool IsFadingIn();
/// <summary>
/// 播放加载中的动画
/// </summary>
void Load();
/// <summary>
/// 是否在播加载中的动画
/// </summary>
bool IsLoading();
/// <summary>
/// 播放加载完毕的动画
/// </summary>
void FadeOut();
/// <summary>
/// 是否在播加载入完毕的动画
/// </summary>
bool IsFadingOut();
/// <summary>
/// 播放结束后尝试回收loading资源
/// </summary>
void TryDestroy();
void SetAsyncLoading(AsyncOperation async);
}
|
using CarDiaryX.Domain.Vehicles;
namespace CarDiaryX.Application.Common.Helpers
{
public static class PermissionsHelper
{
public static bool IsPaidUser(Permission userPermission)
=> userPermission?.PermissionType == PermissionType.Premium
|| userPermission?.PermissionType == PermissionType.Professional;
}
}
|
using System;
using Data.Infrastructure;
namespace Data.Entity.SystemSecurity
{
public class LogEntity : IEntity
{
/// <summary>
/// 日期
/// </summary>
public DateTime? Date { get; set; }
/// <summary>
/// 用户名
/// </summary>
public string UserName { get; set; } = null!;
/// <summary>
/// 操作类型
/// </summary>
public string Type { get; set; } = null!;
/// <summary>
/// IP地址
/// </summary>
public string IPAddress { get; set; } = null!;
/// <summary>
/// 操作结果
/// </summary>
public bool? Result { get; set; }
/// <summary>
/// 操作描述
/// </summary>
public string Description { get; set; } = null!;
}
class LogMap : EntityTypeConfiguration<LogEntity> { }
}
|
using System;
using Xunit;
namespace service.test
{
public class MockTests
{
public MockTests()
{
}
[Fact]
public void TestStockItemsAreThere()
{
Assert.Equal(4, service.Mock.StockItems.Count);
}
[Fact]
public void TestDiscountsAreThere()
{
Assert.Equal(2, service.Mock.Discounts.Count);
}
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using NHibernate;
using NLog;
using Shoko.Commons.Extensions;
using Shoko.Models.Enums;
using Shoko.Server.Databases;
using Shoko.Server.Extensions;
using Shoko.Server.Models;
using Shoko.Server.Repositories;
using Shoko.Server.Repositories.Cached;
using Shoko.Server.Repositories.NHibernate;
using Shoko.Server.Server;
using Shoko.Server.Settings;
namespace Shoko.Server.Tasks
{
internal class AnimeGroupCreator
{
private static readonly Logger _log = LogManager.GetCurrentClassLogger();
private const int DefaultBatchSize = 50;
public const string TempGroupName = "AAA Migrating Groups AAA";
private static readonly Regex _truncateYearRegex = new Regex(@"\s*\(\d{4}\)$");
private readonly AniDB_AnimeRepository _aniDbAnimeRepo = RepoFactory.AniDB_Anime;
private readonly AnimeSeriesRepository _animeSeriesRepo = RepoFactory.AnimeSeries;
private readonly AnimeGroupRepository _animeGroupRepo = RepoFactory.AnimeGroup;
private readonly AnimeGroup_UserRepository _animeGroupUserRepo = RepoFactory.AnimeGroup_User;
private readonly GroupFilterRepository _groupFilterRepo = RepoFactory.GroupFilter;
private readonly JMMUserRepository _userRepo = RepoFactory.JMMUser;
private readonly bool _autoGroupSeries;
/// <summary>
/// Initializes a new instance of the <see cref="AnimeGroupCreator"/> class.
/// </summary>
/// <param name="autoGroupSeries"><c>true</c> to automatically assign to groups based on aniDB relations;
/// otherwise, <c>false</c> to assign each series to its own group.</param>
public AnimeGroupCreator(bool autoGroupSeries)
{
_autoGroupSeries = autoGroupSeries;
}
/// <summary>
/// Initializes a new instance of the <see cref="AnimeGroupCreator"/> class.
/// </summary>
/// <remarks>
/// Uses the current server configuration to determine if auto grouping series is enabled.
/// </remarks>
public AnimeGroupCreator()
: this(ServerSettings.Instance.AutoGroupSeries)
{
}
/// <summary>
/// Creates a new group that series will be put in during group re-calculation.
/// </summary>
/// <param name="session">The NHibernate session.</param>
/// <returns>The temporary <see cref="SVR_AnimeGroup"/>.</returns>
private SVR_AnimeGroup CreateTempAnimeGroup(ISessionWrapper session)
{
DateTime now = DateTime.Now;
var tempGroup = new SVR_AnimeGroup
{
GroupName = TempGroupName,
Description = TempGroupName,
SortName = TempGroupName,
DateTimeUpdated = now,
DateTimeCreated = now
};
// We won't use AnimeGroupRepository.Save because we don't need to perform all the extra stuff since this is for temporary use only
session.Insert(tempGroup);
lock (RepoFactory.AnimeGroup.Cache)
{
RepoFactory.AnimeGroup.Cache.Update(tempGroup);
}
return tempGroup;
}
/// <summary>
/// Deletes the anime groups and user mappings as well as resetting group filters and moves all anime series into the specified group.
/// </summary>
/// <param name="session">The NHibernate session.</param>
/// <param name="tempGroupId">The ID of the temporary anime group to use for migration.</param>
private void ClearGroupsAndDependencies(ISessionWrapper session, int tempGroupId)
{
ServerState.Instance.DatabaseBlocked = new ServerState.DatabaseBlockedInfo {Blocked = true, Status = "Removing existing AnimeGroups and resetting GroupFilters"};
_log.Info("Removing existing AnimeGroups and resetting GroupFilters");
_animeGroupUserRepo.DeleteAll(session);
_animeGroupRepo.DeleteAll(session, tempGroupId);
session.CreateSQLQuery(@"
UPDATE AnimeSeries SET AnimeGroupID = :tempGroupId;
UPDATE GroupFilter SET GroupsIdsString = '{}';")
.SetInt32("tempGroupId", tempGroupId)
.ExecuteUpdate();
// We've deleted/modified all AnimeSeries/GroupFilter records, so update caches to reflect that
_animeSeriesRepo.ClearCache();
_groupFilterRepo.ClearCache();
_log.Info("AnimeGroups have been removed and GroupFilters have been reset");
}
private void UpdateAnimeSeriesContractsAndSave(ISessionWrapper session,
IReadOnlyCollection<SVR_AnimeSeries> series)
{
ServerState.Instance.DatabaseBlocked = new ServerState.DatabaseBlockedInfo {Blocked = true, Status = "Updating contracts for AnimeSeries"};
_log.Info("Updating contracts for AnimeSeries");
// Update batches of AnimeSeries contracts in parallel. Each parallel branch requires it's own session since NHibernate sessions aren't thread safe.
// The reason we're doing this in parallel is because updating contacts does a reasonable amount of work (including LZ4 compression)
Parallel.ForEach(series.Batch(DefaultBatchSize), new ParallelOptions {MaxDegreeOfParallelism = 4},
localInit: () => DatabaseFactory.SessionFactory.OpenStatelessSession(),
body: (seriesBatch, state, localSession) =>
{
SVR_AnimeSeries.BatchUpdateContracts(localSession.Wrap(), seriesBatch);
return localSession;
},
localFinally: localSession => { localSession.Dispose(); });
_animeSeriesRepo.UpdateBatch(session, series);
_log.Info("AnimeSeries contracts have been updated");
}
private void UpdateAnimeGroupsAndTheirContracts(ISessionWrapper session,
IReadOnlyCollection<SVR_AnimeGroup> groups)
{
ServerState.Instance.DatabaseBlocked = new ServerState.DatabaseBlockedInfo {Blocked = true, Status = "Updating statistics and contracts for AnimeGroups"};
_log.Info("Updating statistics and contracts for AnimeGroups");
var allCreatedGroupUsers = new ConcurrentBag<List<SVR_AnimeGroup_User>>();
// Update batches of AnimeGroup contracts in parallel. Each parallel branch requires it's own session since NHibernate sessions aren't thread safe.
// The reason we're doing this in parallel is because updating contacts does a reasonable amount of work (including LZ4 compression)
Parallel.ForEach(groups.Batch(DefaultBatchSize), new ParallelOptions {MaxDegreeOfParallelism = 4},
localInit: () => DatabaseFactory.SessionFactory.OpenStatelessSession(),
body: (groupBatch, state, localSession) =>
{
var createdGroupUsers = new List<SVR_AnimeGroup_User>(groupBatch.Length);
// We shouldn't need to keep track of updates to AnimeGroup_Users in the below call, because they should have all been deleted,
// therefore they should all be new
SVR_AnimeGroup.BatchUpdateStats(groupBatch, watchedStats: true, missingEpsStats: true,
createdGroupUsers: createdGroupUsers);
allCreatedGroupUsers.Add(createdGroupUsers);
SVR_AnimeGroup.BatchUpdateContracts(localSession.Wrap(), groupBatch, updateStats: true);
return localSession;
},
localFinally: localSession => { localSession.Dispose(); });
_animeGroupRepo.UpdateBatch(session, groups);
_log.Info("AnimeGroup statistics and contracts have been updated");
ServerState.Instance.DatabaseBlocked = new ServerState.DatabaseBlockedInfo {Blocked = true, Status = "Creating AnimeGroup_Users and updating plex/kodi contracts"};
_log.Info("Creating AnimeGroup_Users and updating plex/kodi contracts");
List<SVR_AnimeGroup_User> animeGroupUsers = allCreatedGroupUsers.SelectMany(groupUsers => groupUsers)
.ToList();
// Insert the AnimeGroup_Users so that they get assigned a primary key before we update plex/kodi contracts
_animeGroupUserRepo.InsertBatch(session, animeGroupUsers);
// We need to repopulate caches for AnimeGroup_User and AnimeGroup because we've updated/inserted them
// and they need to be up to date for the plex/kodi contract updating to work correctly
_animeGroupUserRepo.Populate(session, displayname: false);
_animeGroupRepo.Populate(session, displayname: false);
// NOTE: There are situations in which UpdatePlexKodiContracts will cause database database writes to occur, so we can't
// use Parallel.ForEach for the time being (If it was guaranteed to only read then we'd be ok)
foreach (SVR_AnimeGroup_User groupUser in animeGroupUsers)
{
groupUser.UpdatePlexKodiContracts(session);
}
_animeGroupUserRepo.UpdateBatch(session, animeGroupUsers);
_log.Info("AnimeGroup_Users have been created");
}
/// <summary>
/// Updates all Group Filters. This should be done as the last step.
/// </summary>
/// <remarks>
/// Assumes that all caches are up to date.
/// </remarks>
private void UpdateGroupFilters(ISessionWrapper session)
{
_log.Info("Updating Group Filters");
_log.Info("Calculating Tag Filters");
ServerState.Instance.DatabaseBlocked = new ServerState.DatabaseBlockedInfo {Blocked = true, Status = "Calculating Tag Filters"};
_groupFilterRepo.CalculateAnimeSeriesPerTagGroupFilter(session);
_log.Info("Calculating All Other Filters");
ServerState.Instance.DatabaseBlocked = new ServerState.DatabaseBlockedInfo {Blocked = true, Status = "Calculating Non-Tag Filters"};
IEnumerable<SVR_GroupFilter> grpFilters = _groupFilterRepo.GetAll(session).Where(a =>
a.FilterType != (int) GroupFilterType.Tag &&
((GroupFilterType) a.FilterType & GroupFilterType.Directory) == 0).ToList();
// The main reason for doing this in parallel is because UpdateEntityReferenceStrings does JSON encoding
// and is enough work that it can benefit from running in parallel
Parallel.ForEach(
grpFilters, filter =>
{
filter.SeriesIds.Clear();
filter.CalculateGroupsAndSeries();
filter.UpdateEntityReferenceStrings();
});
using (ITransaction trans = session.BeginTransaction())
{
_groupFilterRepo.BatchUpdate(session, grpFilters);
trans.Commit();
}
_log.Info("Group Filters updated");
}
/// <summary>
/// Creates a single <see cref="SVR_AnimeGroup"/> for each <see cref="SVR_AnimeSeries"/> in <paramref name="seriesList"/>.
/// </summary>
/// <remarks>
/// This method assumes that there are no active transactions on the specified <paramref name="session"/>.
/// </remarks>
/// <param name="session">The NHibernate session.</param>
/// <param name="seriesList">The list of <see cref="SVR_AnimeSeries"/> to create groups for.</param>
/// <returns>A sequence of the created <see cref="SVR_AnimeGroup"/>s.</returns>
private IEnumerable<SVR_AnimeGroup> CreateGroupPerSeries(ISessionWrapper session,
IReadOnlyList<SVR_AnimeSeries> seriesList)
{
ServerState.Instance.DatabaseBlocked = new ServerState.DatabaseBlockedInfo {Blocked = true, Status = "Auto-generating Groups with 1 group per series"};
_log.Info("Generating AnimeGroups for {0} AnimeSeries", seriesList.Count);
DateTime now = DateTime.Now;
var newGroupsToSeries = new Tuple<SVR_AnimeGroup, SVR_AnimeSeries>[seriesList.Count];
// Create one group per series
for (int grp = 0; grp < seriesList.Count; grp++)
{
SVR_AnimeGroup group = new SVR_AnimeGroup();
SVR_AnimeSeries series = seriesList[grp];
group.Populate(series, now);
newGroupsToSeries[grp] = new Tuple<SVR_AnimeGroup, SVR_AnimeSeries>(group, series);
}
using (ITransaction trans = session.BeginTransaction())
{
_animeGroupRepo.InsertBatch(session, newGroupsToSeries.Select(gts => gts.Item1).AsReadOnlyCollection());
trans.Commit();
}
// Anime groups should have IDs now they've been inserted. Now assign the group ID's to their respective series
// (The caller of this method will be responsible for saving the AnimeSeries)
foreach (Tuple<SVR_AnimeGroup, SVR_AnimeSeries> groupAndSeries in newGroupsToSeries)
{
groupAndSeries.Item2.AnimeGroupID = groupAndSeries.Item1.AnimeGroupID;
}
_log.Info("Generated {0} AnimeGroups", newGroupsToSeries.Length);
return newGroupsToSeries.Select(gts => gts.Item1);
}
/// <summary>
/// Creates <see cref="SVR_AnimeGroup"/> that contain <see cref="SVR_AnimeSeries"/> that appear to be related.
/// </summary>
/// <remarks>
/// This method assumes that there are no active transactions on the specified <paramref name="session"/>.
/// </remarks>
/// <param name="session">The NHibernate session.</param>
/// <param name="seriesList">The list of <see cref="SVR_AnimeSeries"/> to create groups for.</param>
/// <returns>A sequence of the created <see cref="SVR_AnimeGroup"/>s.</returns>
private IEnumerable<SVR_AnimeGroup> AutoCreateGroupsWithRelatedSeries(ISessionWrapper session,
IReadOnlyCollection<SVR_AnimeSeries> seriesList)
{
ServerState.Instance.DatabaseBlocked = new ServerState.DatabaseBlockedInfo {Blocked = true, Status = "Auto-generating Groups based on Relation Trees"};
_log.Info("Auto-generating AnimeGroups for {0} AnimeSeries based on aniDB relationships", seriesList.Count);
DateTime now = DateTime.Now;
var grpCalculator = AutoAnimeGroupCalculator.CreateFromServerSettings(session);
_log.Info(
"The following exclusions will be applied when generating the groups: " + grpCalculator.Exclusions);
// Group all of the specified series into their respective groups (keyed by the groups main anime ID)
var seriesByGroup = seriesList.ToLookup(s => grpCalculator.GetGroupAnimeId(s.AniDB_ID));
var newGroupsToSeries =
new List<Tuple<SVR_AnimeGroup, IReadOnlyCollection<SVR_AnimeSeries>>>(seriesList.Count);
foreach (var groupAndSeries in seriesByGroup)
{
int mainAnimeId = groupAndSeries.Key;
SVR_AnimeSeries mainSeries = groupAndSeries.FirstOrDefault(series => series.AniDB_ID == mainAnimeId);
SVR_AnimeGroup animeGroup = CreateAnimeGroup(mainSeries, mainAnimeId, now);
newGroupsToSeries.Add(
new Tuple<SVR_AnimeGroup, IReadOnlyCollection<SVR_AnimeSeries>>(animeGroup,
groupAndSeries.AsReadOnlyCollection()));
}
using (ITransaction trans = session.BeginTransaction())
{
_animeGroupRepo.InsertBatch(session, newGroupsToSeries.Select(gts => gts.Item1).AsReadOnlyCollection());
trans.Commit();
}
// Anime groups should have IDs now they've been inserted. Now assign the group ID's to their respective series
// (The caller of this method will be responsible for saving the AnimeSeries)
foreach (var groupAndSeries in newGroupsToSeries)
{
foreach (SVR_AnimeSeries series in groupAndSeries.Item2)
{
series.AnimeGroupID = groupAndSeries.Item1.AnimeGroupID;
}
}
_log.Info("Generated {0} AnimeGroups", newGroupsToSeries.Count);
return newGroupsToSeries.Select(gts => gts.Item1);
}
/// <summary>
/// Creates an <see cref="SVR_AnimeGroup"/> instance.
/// </summary>
/// <remarks>
/// This method only creates an <see cref="SVR_AnimeGroup"/> instance. It does NOT save it to the database.
/// </remarks>
/// <param name="session">The NHibernate session.</param>
/// <param name="mainSeries">The <see cref="SVR_AnimeSeries"/> whose name will represent the group (Optional. Pass <c>null</c> if not available).</param>
/// <param name="mainAnimeId">The ID of the anime whose name will represent the group if <paramref name="mainSeries"/> is <c>null</c>.</param>
/// <param name="now">The current date/time.</param>
/// <returns>The created <see cref="SVR_AnimeGroup"/>.</returns>
private SVR_AnimeGroup CreateAnimeGroup(SVR_AnimeSeries mainSeries, int mainAnimeId,
DateTime now)
{
SVR_AnimeGroup animeGroup = new SVR_AnimeGroup();
string groupName;
if (mainSeries != null)
{
animeGroup.Populate(mainSeries, now);
groupName = animeGroup.GroupName;
}
else // The anime chosen as the group's main anime doesn't actually have a series
{
SVR_AniDB_Anime mainAnime = _aniDbAnimeRepo.GetByAnimeID(mainAnimeId);
animeGroup.Populate(mainAnime, now);
groupName = animeGroup.GroupName;
}
// If the title appears to end with a year suffix, then remove it
groupName = _truncateYearRegex.Replace(groupName, string.Empty);
animeGroup.GroupName = groupName;
animeGroup.SortName = groupName;
return animeGroup;
}
/// <summary>
/// Gets or creates an <see cref="SVR_AnimeGroup"/> for the specified series.
/// </summary>
/// <param name="session">The NHibernate session.</param>
/// <param name="series">The series for which the group is to be created/retrieved (Must be initialised first).</param>
/// <returns>The <see cref="SVR_AnimeGroup"/> to use for the specified series.</returns>
/// <exception cref="ArgumentNullException"><paramref name="session"/> or <paramref name="series"/> is <c>null</c>.</exception>
public SVR_AnimeGroup GetOrCreateSingleGroupForSeries(ISessionWrapper session, SVR_AnimeSeries series)
{
if (session == null)
throw new ArgumentNullException(nameof(session));
if (series == null)
throw new ArgumentNullException(nameof(series));
SVR_AnimeGroup animeGroup;
if (_autoGroupSeries)
{
var grpCalculator = AutoAnimeGroupCalculator.CreateFromServerSettings(session);
IReadOnlyList<int> grpAnimeIds = grpCalculator.GetIdsOfAnimeInSameGroup(series.AniDB_ID);
// Try to find an existing AnimeGroup to add the series to
// We basically pick the first group that any of the related series belongs to already
animeGroup = grpAnimeIds.Where(id => id != series.AniDB_ID)
.Select(id => RepoFactory.AnimeSeries.GetByAnimeID(id))
.Where(s => s != null)
.Select(s => RepoFactory.AnimeGroup.GetByID(s.AnimeGroupID))
.FirstOrDefault(s => s != null);
if (animeGroup == null)
{
// No existing group was found, so create a new one
int mainAnimeId = grpCalculator.GetGroupAnimeId(series.AniDB_ID);
SVR_AnimeSeries mainSeries = _animeSeriesRepo.GetByAnimeID(mainAnimeId);
animeGroup = CreateAnimeGroup(mainSeries, mainAnimeId, DateTime.Now);
RepoFactory.AnimeGroup.Save(animeGroup, true, true);
}
}
else // We're not auto grouping (e.g. we're doing group per series)
{
animeGroup = new SVR_AnimeGroup();
animeGroup.Populate(series, DateTime.Now);
RepoFactory.AnimeGroup.Save(animeGroup, true, true);
}
return animeGroup;
}
/// <summary>
/// Re-creates all AnimeGroups based on the existing AnimeSeries.
/// </summary>
/// <param name="session">The NHibernate session.</param>
/// <exception cref="ArgumentNullException"><paramref name="session"/> is <c>null</c>.</exception>
public void RecreateAllGroups(ISessionWrapper session)
{
if (session == null)
throw new ArgumentNullException(nameof(session));
bool cmdProcGeneralPaused = ShokoService.CmdProcessorGeneral.Paused;
bool cmdProcHasherPaused = ShokoService.CmdProcessorHasher.Paused;
bool cmdProcImagesPaused = ShokoService.CmdProcessorImages.Paused;
try
{
// Pause queues
ShokoService.CmdProcessorGeneral.Paused = true;
ShokoService.CmdProcessorHasher.Paused = true;
ShokoService.CmdProcessorImages.Paused = true;
ServerState.Instance.DatabaseBlocked = new ServerState.DatabaseBlockedInfo {Blocked = true, Status = "Beginning re-creation of all groups"};
_log.Info("Beginning re-creation of all groups");
IReadOnlyList<SVR_AnimeSeries> animeSeries = RepoFactory.AnimeSeries.GetAll();
IReadOnlyCollection<SVR_AnimeGroup> createdGroups = null;
SVR_AnimeGroup tempGroup = null;
using (ITransaction trans = session.BeginTransaction())
{
tempGroup = CreateTempAnimeGroup(session);
ClearGroupsAndDependencies(session, tempGroup.AnimeGroupID);
trans.Commit();
}
if (_autoGroupSeries)
{
createdGroups = AutoCreateGroupsWithRelatedSeries(session, animeSeries)
.AsReadOnlyCollection();
}
else // Standard group re-create
{
createdGroups = CreateGroupPerSeries(session, animeSeries)
.AsReadOnlyCollection();
}
using (ITransaction trans = session.BeginTransaction())
{
UpdateAnimeSeriesContractsAndSave(session, animeSeries);
session.Delete(tempGroup); // We should no longer need the temporary group we created earlier
trans.Commit();
}
// We need groups and series cached for updating of AnimeGroup contracts to work
_animeGroupRepo.Populate(session, displayname: false);
_animeSeriesRepo.Populate(session, displayname: false);
using (ITransaction trans = session.BeginTransaction())
{
UpdateAnimeGroupsAndTheirContracts(session, createdGroups);
trans.Commit();
}
// We need to update the AnimeGroups cache again now that the contracts have been saved
// (Otherwise updating Group Filters won't get the correct results)
_animeGroupRepo.Populate(session, displayname: false);
_animeGroupUserRepo.Populate(session, displayname: false);
_groupFilterRepo.Populate(session, displayname: false);
UpdateGroupFilters(session);
_log.Info("Successfuly completed re-creating all groups");
}
catch (Exception e)
{
_log.Error(e, "An error occurred while re-creating all groups");
try
{
// If an error occurs then chances are the caches are in an inconsistent state. So re-populate them
_animeSeriesRepo.Populate();
_animeGroupRepo.Populate();
_groupFilterRepo.Populate();
_animeGroupUserRepo.Populate();
}
catch (Exception ie)
{
_log.Warn(ie, "Failed to re-populate caches");
}
throw;
}
finally
{
ServerState.Instance.DatabaseBlocked = new ServerState.DatabaseBlockedInfo();
// Un-pause queues (if they were previously running)
ShokoService.CmdProcessorGeneral.Paused = cmdProcGeneralPaused;
ShokoService.CmdProcessorHasher.Paused = cmdProcHasherPaused;
ShokoService.CmdProcessorImages.Paused = cmdProcImagesPaused;
}
}
public void RecreateAllGroups()
{
using (IStatelessSession session = DatabaseFactory.SessionFactory.OpenStatelessSession())
{
RecreateAllGroups(session.Wrap());
}
}
public void RecalculateStatsContractsForGroup(SVR_AnimeGroup group)
{
using (ISession sessionNotWrapped = DatabaseFactory.SessionFactory.OpenSession())
{
var groups = new List<SVR_AnimeGroup> {group};
var session = sessionNotWrapped.Wrap();
var series = group.GetAllSeries(true);
// recalculate series
_log.Info($"Recalculating Series Stats and Contracts for Group: {group.GroupName} ({group.AnimeGroupID})");
using (ITransaction trans = session.BeginTransaction())
{
UpdateAnimeSeriesContractsAndSave(session, series);
trans.Commit();
}
// Update Cache so that group can recalculate
series.ForEach(a => _animeSeriesRepo.Cache.Update(a));
// Recalculate group
_log.Info($"Recalculating Group Stats and Contracts for Group: {group.GroupName} ({group.AnimeGroupID})");
using (ITransaction trans = session.BeginTransaction())
{
UpdateAnimeGroupsAndTheirContracts(session, groups);
trans.Commit();
}
// update cache
_animeGroupRepo.Cache.Update(group);
var groupsUsers = _animeGroupUserRepo.GetByGroupID(group.AnimeGroupID);
groupsUsers.ForEach(a => _animeGroupUserRepo.Cache.Update(a));
// update filters
_log.Info($"Recalculating Filters for Group: {group.GroupName} ({group.AnimeGroupID})");
UpdateGroupFilters(session);
_log.Info($"Done Recalculating Stats and Contracts for Group: {group.GroupName} ({group.AnimeGroupID})");
}
}
}
}
|
using System;
using FubuCore;
using FubuCore.Conversion;
using FubuMVC.Core.Json;
using Shouldly;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using NUnit.Framework;
namespace FubuMVC.Tests.Json
{
[TestFixture]
public class respects_the_injected_settings_in_serialization
{
[Test]
public void round_trip_with_camel_casing()
{
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var serializer = new NewtonSoftJsonSerializer(settings, new JsonConverter[0]);
var json = serializer.Serialize(new Target {Name = "Jeremy"});
json.ShouldBe("{\"name\":\"Jeremy\"}");
var target2 = serializer.Deserialize<Target>(json);
target2.Name.ShouldBe("Jeremy");
}
}
public class Target
{
public string Name { get; set; }
}
[TestFixture]
public class when_deserializing_an_object
{
private NewtonSoftJsonSerializer theSerializer;
private string theInput;
private ParentType theObject;
[SetUp]
public void SetUp()
{
var locator = new InMemoryServiceLocator();
var objectConverter = new ObjectConverter(locator, new ConverterLibrary(new[] {new StatelessComplexTypeConverter()}));
locator.Add<IObjectConverter>(objectConverter);
var converter = new ComplexTypeConverter(objectConverter);
theInput = "{\"Name\":\"Test\",\"Child\":\"x:123\"}";
theSerializer = new NewtonSoftJsonSerializer(new JsonSerializerSettings(), new[] { converter });
theObject = theSerializer.Deserialize<ParentType>(theInput);
}
[Test]
public void uses_the_object_converter()
{
theObject.Name.ShouldBe("Test");
theObject.Child.ShouldBe(new ComplexType {Key = "x", Value = "123"});
}
}
public class StatelessComplexTypeConverter : StatelessConverter<ComplexType>
{
protected override ComplexType convert(string text)
{
var values = text.Split(new[] { ":" }, StringSplitOptions.None);
return new ComplexType {Key = values[0], Value = values[1]};
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SuperSpeed
{
class UserData
{
//{"CommitGcid":"","Message":"文件名中包含违规内容,无法添加到高速通道","Result":509,"SubId":5}
public const string COMMIT_GCID = "CommitGcid";
public const string MESSAGE = "Message";
public const string RESULT = "Result";
public const string SUB_ID = "SubId";
public string CommitGcid { get; set; }
public string Message { get; set; }
public int Result { get; set; }
public string SubId { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Threading.Tasks;
namespace CS_lazy
{
class Order
{
public override string ToString()
{
return "Order";
}
}
class Orders
{
public Orders(int numOrders) { }
public Orders(string custID) { }
public Order[] OrderData;
}
class IntroSnippets
{
static bool displayOrders = true;
public static void Test()
{
//<snippet1>
// Initialize by using default Lazy<T> constructor. The
// Orders array itself is not created yet.
Lazy<Orders> _orders = new Lazy<Orders>();
//</snippet1>
}
//dummy method for snippet3
public static void DisplayOrders(Order[] orders) { }
public static void Test2()
{
//<snippet2>
// Initialize by invoking a specific constructor on Order when Value
// property is accessed
Lazy<Orders> _orders = new Lazy<Orders>(() => new Orders(100));
//</snippet2>
//<snippet3>
// We need to create the array only if displayOrders is true
if (displayOrders == true)
{
DisplayOrders(_orders.Value.OrderData);
}
else
{
// Don't waste resources getting order data.
}
//</snippet3>
//<snippet4>
_orders = new Lazy<Orders>(() => new Orders(10));
//</snippet4>
}
//<snippet5>
class Customer
{
private Lazy<Orders> _orders;
public string CustomerID {get; private set;}
public Customer(string id)
{
CustomerID = id;
_orders = new Lazy<Orders>(() =>
{
// You can specify any additional
// initialization steps here.
return new Orders(this.CustomerID);
});
}
public Orders MyOrders
{
get
{
// Orders is created on first access here.
return _orders.Value;
}
}
}
//</snippet5>
//<snippet6>
[ThreadStatic]
static int counter = 1;
//</snippet6>
//<snippet7>
ThreadLocal<int> betterCounter = new ThreadLocal<int>(() => 1);
//</snippet7>
}
class DataInitializedFromDb
{
public DataInitializedFromDb(SqlDataReader reader) { }
public int Count { get; private set; }
}
class MyClass3
{
static void Main()
{
string connectionString = "";
Lazy<DataInitializedFromDb> _data =
new Lazy<DataInitializedFromDb>(delegate
{
using(SqlConnection conn = new SqlConnection(connectionString))
using(SqlCommand comm = new SqlCommand())
{
SqlDataReader reader = comm.ExecuteReader();
DataInitializedFromDb data =
new DataInitializedFromDb(reader);
return data;
}
});
//…
// use the data
if (_data.Value.Count > 10) ProcessData(_data.Value);
}
static void ProcessData(DataInitializedFromDb data) { }
}
class LazyProgram
{
static void Main(string[] args)
{
// LazyAndThreadLocal();
TestEnsureInitialized();
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
private static void LazyAndThreadLocal()
{
//<snippet8>
// Initialize the integer to the managed thread id of the
// first thread that accesses the Value property.
Lazy<int> number = new Lazy<int>(() => Thread.CurrentThread.ManagedThreadId);
Thread t1 = new Thread(() => Console.WriteLine("number on t1 = {0} ThreadID = {1}",
number.Value, Thread.CurrentThread.ManagedThreadId));
t1.Start();
Thread t2 = new Thread(() => Console.WriteLine("number on t2 = {0} ThreadID = {1}",
number.Value, Thread.CurrentThread.ManagedThreadId));
t2.Start();
Thread t3 = new Thread(() => Console.WriteLine("number on t3 = {0} ThreadID = {1}", number.Value,
Thread.CurrentThread.ManagedThreadId));
t3.Start();
// Ensure that thread IDs are not recycled if the
// first thread completes before the last one starts.
t1.Join();
t2.Join();
t3.Join();
/* Sample Output:
number on t1 = 11 ThreadID = 11
number on t3 = 11 ThreadID = 13
number on t2 = 11 ThreadID = 12
Press any key to exit.
*/
//</snippet8>
//<snippet9>
// Initialize the integer to the managed thread id on a per-thread basis.
ThreadLocal<int> threadLocalNumber = new ThreadLocal<int>(() => Thread.CurrentThread.ManagedThreadId);
Thread t4 = new Thread(() => Console.WriteLine("threadLocalNumber on t4 = {0} ThreadID = {1}",
threadLocalNumber.Value, Thread.CurrentThread.ManagedThreadId));
t4.Start();
Thread t5 = new Thread(() => Console.WriteLine("threadLocalNumber on t5 = {0} ThreadID = {1}",
threadLocalNumber.Value, Thread.CurrentThread.ManagedThreadId));
t5.Start();
Thread t6 = new Thread(() => Console.WriteLine("threadLocalNumber on t6 = {0} ThreadID = {1}",
threadLocalNumber.Value, Thread.CurrentThread.ManagedThreadId));
t6.Start();
// Ensure that thread IDs are not recycled if the
// first thread completes before the last one starts.
t4.Join();
t5.Join();
t6.Join();
/* Sample Output:
threadLocalNumber on t4 = 14 ThreadID = 14
threadLocalNumber on t5 = 15 ThreadID = 15
threadLocalNumber on t6 = 16 ThreadID = 16
*/
//</snippet9>
}
static void TestEnsureInitialized()
{
Order[] _orders = new Order[100];
bool displayOrderInfo = true;
//<snippet10>
// Assume that _orders contains null values, and
// we only need to initialize them if displayOrderInfo is true
if(displayOrderInfo == true)
{
for (int i = 0; i < _orders.Length; i++)
{
// Lazily initialize the orders without wrapping them in a Lazy<T>
LazyInitializer.EnsureInitialized(ref _orders[i], () =>
{
// Returns the value that will be placed in the ref parameter.
return GetOrderForIndex(i);
});
}
}
//</snippet10>
foreach(var v in _orders)
Console.WriteLine(v.ToString());
}
static Order GetOrderForIndex(int slot)
{ return new Order(); }
static void InitializeDBConnection()
{
}
static void InitializeBigComputation(long bigNum)
{
Lazy<int[]> primeFactors = new Lazy<int[]>(() => GetPrimeFactors(bigNum), true);
}
static int[] GetPrimeFactors(long bigNum)
{ return new int[1]; }
}
}
namespace HowToSnippets
{
using System;
using System.Net;
class Number
{
public int Num {get; private set;}
public Lazy<int[]> primeFactors;
public Number(int i)
{
Num = i;
primeFactors = new Lazy<int[]>(() => GetPrimeFactors(Num));
}
private static int[] GetPrimeFactors(int i)
{
return new int[100];
}
class WebPage
{
private Lazy<String> _text;
public WebPage(string url, string title)
{
this.URL = url;
this.Title = Title;
this._text = new Lazy<string>(() =>
{
return new WebClient().DownloadString(URL);
});
}
public string URL { get; private set; }
public string Title { get; private set; }
public string Text {
get
{
return _text.Value;
}
}
}
static void Main()
{
WebPage[] catalog = new WebPage[5]
{
new WebPage("", ""),
new WebPage("", ""),
new WebPage("", ""),
new WebPage("", ""),
new WebPage("", ""),
};
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace com.DaHuotu
{
public partial class frmSetting : Form
{
public frmSetting()
{
InitializeComponent();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
Properties.Settings.Default.showPath = this.checkBoxShowPath.Checked;
Properties.Settings.Default.showAlert = this.checkBoxShowAlert.Checked;
Properties.Settings.Default.addHead = this.checkBoxImgHead.Checked;
SetRadioButton();
Properties.Settings.Default.Save();
MessageBox.Show("设置成功", "提示", MessageBoxButtons.OK);
}
private void Setting_Load(object sender, EventArgs e)
{
this.checkBoxShowPath.Checked = Properties.Settings.Default.showPath;
this.checkBoxShowAlert.Checked = Properties.Settings.Default.showAlert;
this.checkBoxImgHead.Checked = Properties.Settings.Default.addHead;
string code = Properties.Settings.Default.codeType;
switch (code)
{
case "h5":
this.rdb2.Checked = true;
break;
case "css":
this.rdb3.Checked = true;
break;
case "mini":
this.rdb4.Checked = true;
break;
default:
this.rdb1.Checked = true;
break;
}
}
#region 常用函数
private void SetRadioButton()
{
if (this.rdb1.Checked == true)
{
Properties.Settings.Default.codeType = "";
}
if (this.rdb2.Checked == true)
{
Properties.Settings.Default.codeType = "h5";
}
if (this.rdb3.Checked == true)
{
Properties.Settings.Default.codeType = "css";
}
if (this.rdb4.Checked == true)
{
Properties.Settings.Default.codeType = "mini";
}
}
#endregion
}
}
|
using System.Runtime.InteropServices;
using FluentAssertions;
using Xunit;
namespace ConcurrencyUtilities.Tests
{
public class PaddedAtomicLongTests
{
private PaddedAtomicLong num = new PaddedAtomicLong();
[Fact]
public void PaddedAtomicLong_ShouldHaveCorrectSize()
{
PaddedAtomicLong.SizeInBytes.Should().Be(Marshal.SizeOf<PaddedAtomicLong>());
}
[Fact]
public void PaddedAtomicLong_DefaultsToZero()
{
this.num.GetValue().Should().Be(0L);
}
[Fact]
public void PaddedAtomicLong_CanBeCreatedWithValue()
{
new PaddedAtomicLong(5L).GetValue().Should().Be(5L);
}
[Fact]
public void PaddedAtomicLong_CanSetAndReadValue()
{
this.num.SetValue(32);
this.num.GetValue().Should().Be(32);
}
[Fact]
public void PaddedAtomicLong_CanGetAndSet()
{
this.num.SetValue(32);
this.num.GetAndSet(64).Should().Be(32);
this.num.GetValue().Should().Be(64);
}
[Fact]
public void PaddedAtomicLong_CanGetAndReset()
{
this.num.SetValue(32);
this.num.GetAndReset().Should().Be(32);
this.num.GetValue().Should().Be(0);
}
[Fact]
public void PaddedAtomicLong_CanBeIncremented()
{
this.num.Increment().Should().Be(1L);
this.num.GetValue().Should().Be(1L);
}
[Fact]
public void PaddedAtomicLong_CanBeIncrementedMultipleTimes()
{
this.num.Increment().Should().Be(1L);
this.num.GetValue().Should().Be(1L);
this.num.Increment().Should().Be(2L);
this.num.GetValue().Should().Be(2L);
this.num.Increment().Should().Be(3L);
this.num.GetValue().Should().Be(3L);
}
[Fact]
public void PaddedAtomicLong_CanBeDecremented()
{
this.num.Decrement().Should().Be(-1L);
this.num.GetValue().Should().Be(-1L);
}
[Fact]
public void PaddedAtomicLong_CanBeDecrementedMultipleTimes()
{
this.num.Decrement().Should().Be(-1L);
this.num.Decrement().Should().Be(-2L);
this.num.Decrement().Should().Be(-3L);
this.num.GetValue().Should().Be(-3L);
}
[Fact]
public void PaddedAtomicLong_CanAddValue()
{
this.num.Add(7L).Should().Be(7L);
this.num.GetValue().Should().Be(7L);
}
[Fact]
public void PaddedAtomicLong_CanBeAssigned()
{
this.num.SetValue(10L);
PaddedAtomicLong y = num;
y.GetValue().Should().Be(10L);
}
[Fact]
public void PaddedAtomicLong_CanGetAndAdd()
{
this.num.SetValue(10L);
this.num.GetAndAdd(5L).Should().Be(10L);
this.num.GetValue().Should().Be(15L);
}
[Fact]
public void PaddedAtomicLong_CanGetAndIncrement()
{
this.num.SetValue(10L);
this.num.GetAndIncrement().Should().Be(10L);
this.num.GetValue().Should().Be(11L);
this.num.GetAndIncrement(5L).Should().Be(11L);
this.num.GetValue().Should().Be(16L);
}
[Fact]
public void PaddedAtomicLong_CanGetAndDecrement()
{
this.num.SetValue(10L);
this.num.GetAndDecrement().Should().Be(10L);
this.num.GetValue().Should().Be(9L);
this.num.GetAndDecrement(5L).Should().Be(9L);
this.num.GetValue().Should().Be(4L);
}
[Fact]
public void PaddedAtomicLong_CanCompareAndSwap()
{
this.num.SetValue(10L);
this.num.CompareAndSwap(5L, 11L).Should().Be(false);
this.num.GetValue().Should().Be(10L);
this.num.CompareAndSwap(10L, 11L).Should().Be(true);
this.num.GetValue().Should().Be(11L);
}
}
}
|
using _4_gRPC;
using Google.Protobuf.WellKnownTypes;
using Grpc.Net.Client;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace _4_Client
{
class Program
{
static async Task Main(string[] args)
{
using var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new Greeter.GreeterClient(channel);
var reply = await client.SayHelloAsync(new HelloRequest() { Name = "Fritz" });
Console.WriteLine($"Greeting: {reply.Message}");
var contact = await client.GetContactByIdAsync(new ContactById { Id = 1 });
Console.WriteLine($"Contact with id 1: {contact.FirstName} {contact.LastName}");
}
}
}
|
using ACMESharp.Protocol.Resources;
namespace ACMESharp.MockServer.Storage
{
public class DbAuthorization
{
public int Id { get; set; }
public int OrderId { get; set; }
public string Url { get; set; }
public Authorization Payload { get; set; }
}
} |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org.
// ****************************************************************
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using NUnit.Core;
using NUnit.Util;
namespace NUnit.UiKit
{
/// <summary>
/// ColorProgressBar provides a custom progress bar with the
/// ability to control the color of the bar and to render itself
/// in either solid or segmented style. The bar can be updated
/// on the fly and has code to avoid repainting the entire bar
/// when that occurs.
/// </summary>
public class ColorProgressBar : System.Windows.Forms.Control
{
#region Instance Variables
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
/// <summary>
/// The current progress value
/// </summary>
private int val = 0;
/// <summary>
/// The minimum value allowed
/// </summary>
private int min = 0;
/// <summary>
/// The maximum value allowed
/// </summary>
private int max = 100;
/// <summary>
/// Amount to advance for each step
/// </summary>
private int step = 1;
/// <summary>
/// Last segment displayed when displaying asynchronously rather
/// than through OnPaint calls.
/// </summary>
private int lastSegmentCount=0;
/// <summary>
/// The brush to use in painting the progress bar
/// </summary>
private Brush foreBrush = null;
/// <summary>
/// The brush to use in painting the background of the bar
/// </summary>
private Brush backBrush = null;
/// <summary>
/// Indicates whether to draw the bar in segments or not
/// </summary>
private bool segmented = false;
#endregion
#region Constructors & Disposer
public ColorProgressBar()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
SetStyle(ControlStyles.ResizeRedraw, true);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
this.ReleaseBrushes();
}
base.Dispose( disposing );
}
#endregion
#region Properties
[Category("Behavior")]
public int Minimum
{
get { return this.min; }
set
{
if (value <= Maximum)
{
if (this.min != value)
{
this.min = value;
this.Invalidate();
}
}
else
{
throw new ArgumentOutOfRangeException("Minimum", value
,"Minimum must be <= Maximum.");
}
}
}
[Category("Behavior")]
public int Maximum
{
get { return this.max; }
set
{
if (value >= Minimum)
{
if (this.max != value)
{
this.max = value;
this.Invalidate();
}
}
else
{
throw new ArgumentOutOfRangeException("Maximum", value
,"Maximum must be >= Minimum.");
}
}
}
[Category("Behavior")]
public int Step
{
get { return this.step; }
set
{
if (value <= Maximum && value >= Minimum)
{
this.step = value;
}
else
{
throw new ArgumentOutOfRangeException("Step", value
,"Must fall between Minimum and Maximum inclusive.");
}
}
}
[Browsable(false)]
private float PercentValue
{
get
{
if (0 != Maximum - Minimum) // NRG 05/28/03: Prevent divide by zero
return((float)this.val / ((float)Maximum - (float)Minimum));
else
return(0);
}
}
[Category("Behavior")]
public int Value
{
get { return this.val; }
set
{
if(value == this.val)
return;
else if(value <= Maximum && value >= Minimum)
{
this.val = value;
this.Invalidate();
}
else
{
throw new ArgumentOutOfRangeException("Value", value
,"Must fall between Minimum and Maximum inclusive.");
}
}
}
[Category("Appearance")]
public bool Segmented
{
get { return segmented; }
set { segmented = value; }
}
#endregion
#region Methods
protected override void OnCreateControl()
{
}
public void PerformStep()
{
int newValue = Value + Step;
if( newValue > Maximum )
newValue = Maximum;
Value = newValue;
}
protected override void OnBackColorChanged(System.EventArgs e)
{
base.OnBackColorChanged(e);
this.Refresh();
}
protected override void OnForeColorChanged(System.EventArgs e)
{
base.OnForeColorChanged(e);
this.Refresh();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
this.lastSegmentCount=0;
this.ReleaseBrushes();
PaintBar(e.Graphics);
ControlPaint.DrawBorder3D(
e.Graphics
,this.ClientRectangle
,Border3DStyle.SunkenOuter);
//e.Graphics.Flush();
}
private void ReleaseBrushes()
{
if(foreBrush != null)
{
foreBrush.Dispose();
backBrush.Dispose();
foreBrush=null;
backBrush=null;
}
}
private void AcquireBrushes()
{
if(foreBrush == null)
{
foreBrush = new SolidBrush(this.ForeColor);
backBrush = new SolidBrush(this.BackColor);
}
}
private void PaintBar(Graphics g)
{
Rectangle theBar = Rectangle.Inflate(ClientRectangle, -2, -2);
int maxRight = theBar.Right-1;
this.AcquireBrushes();
if ( segmented )
{
int segmentWidth = (int)((float)ClientRectangle.Height * 0.66f);
int maxSegmentCount = ( theBar.Width + segmentWidth ) / segmentWidth;
//int maxRight = Bar.Right;
int newSegmentCount = (int)System.Math.Ceiling(PercentValue*maxSegmentCount);
if(newSegmentCount > lastSegmentCount)
{
theBar.X += lastSegmentCount*segmentWidth;
while (lastSegmentCount < newSegmentCount )
{
theBar.Width = System.Math.Min( maxRight - theBar.X, segmentWidth - 2 );
g.FillRectangle( foreBrush, theBar );
theBar.X += segmentWidth;
lastSegmentCount++;
}
}
else if(newSegmentCount < lastSegmentCount)
{
theBar.X += newSegmentCount * segmentWidth;
theBar.Width = maxRight - theBar.X;
g.FillRectangle(backBrush, theBar);
lastSegmentCount = newSegmentCount;
}
}
else
{
//g.FillRectangle( backBrush, theBar );
theBar.Width = theBar.Width * val / max;
g.FillRectangle( foreBrush, theBar );
}
if(Value == Minimum || Value == Maximum)
this.ReleaseBrushes();
}
#endregion
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//
// ProgressBar
//
this.CausesValidation = false;
this.Enabled = false;
this.ForeColor = System.Drawing.SystemColors.Highlight;
this.Name = "ProgressBar";
this.Size = new System.Drawing.Size(432, 24);
}
#endregion
}
public class TestProgressBar : ColorProgressBar, TestObserver
{
private readonly static Color SuccessColor = Color.Lime;
private readonly static Color FailureColor = Color.Red;
private readonly static Color IgnoredColor = Color.Yellow;
public TestProgressBar()
{
Initialize( 100 );
}
private void Initialize( int testCount )
{
Value = 0;
Maximum = testCount;
ForeColor = SuccessColor;
}
private void OnRunStarting( object Sender, TestEventArgs e )
{
Initialize( e.TestCount );
}
private void OnTestLoaded(object sender, TestEventArgs e)
{
Initialize(e.TestCount);
}
private void OnTestReloaded(object sender, TestEventArgs e)
{
if (Services.UserSettings.GetSetting("Options.TestLoader.ClearResultsOnReload", false))
Initialize(e.TestCount);
else
Value = Maximum = e.TestCount;
}
private void OnTestUnloaded(object sender, TestEventArgs e)
{
Initialize( 100 );
}
private void OnTestFinished( object sender, TestEventArgs e )
{
PerformStep();
switch (e.Result.ResultState)
{
case ResultState.NotRunnable:
case ResultState.Failure:
case ResultState.Error:
case ResultState.Cancelled:
ForeColor = FailureColor;
break;
case ResultState.Ignored:
if (ForeColor == SuccessColor)
ForeColor = IgnoredColor;
break;
default:
break;
}
}
private void OnSuiteFinished( object sender, TestEventArgs e )
{
TestResult result = e.Result;
if ( result.FailureSite == FailureSite.TearDown )
switch (result.ResultState)
{
case ResultState.Error:
case ResultState.Failure:
case ResultState.Cancelled:
ForeColor = FailureColor;
break;
}
}
private void OnTestException(object sender, TestEventArgs e)
{
ForeColor = FailureColor;
}
#region TestObserver Members
public void Subscribe(ITestEvents events)
{
events.TestLoaded += new TestEventHandler( OnTestLoaded );
events.TestReloaded += new TestEventHandler(OnTestReloaded);
events.TestUnloaded += new TestEventHandler( OnTestUnloaded );
events.RunStarting += new TestEventHandler( OnRunStarting );
events.TestFinished += new TestEventHandler( OnTestFinished );
events.SuiteFinished += new TestEventHandler( OnSuiteFinished );
events.TestException += new TestEventHandler(OnTestException);
}
#endregion
}
}
|
using System.Collections.Generic;
namespace Uno.UI.TestComparer.Comparer
{
internal class CompareResult
{
public CompareResult(string platform)
=> Platform = platform;
public int TotalTests { get; internal set; }
public int UnchangedTests { get; internal set; }
public List<CompareResultFile> Tests { get;} = new List<CompareResultFile>();
public List<(int index, string path)> Folders { get; } = new List<(int index, string path)>();
public string Platform { get; }
}
}
|
using System.Globalization;
using System.Linq;
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace ServerDevcommands;
public class MouseWheelBinding {
///<summary>Runs any bound commands.</summary>
public static void Execute(float ticks) {
if (ticks == 0f || !Settings.MouseWheelBinding) return;
if (Terminal.m_binds.TryGetValue(KeyCode.None, out var commands)) {
foreach (var command in commands) {
var input = TerminalUtils.Substitute(command, ticks.ToString(CultureInfo.InvariantCulture));
Chat.instance.TryRunCommand(input);
}
}
}
///<summary>Returns whether any commands could run with the current modifier keys.</summary>
public static bool CouldExecute() {
if (!Settings.MouseWheelBinding) return false;
if (Terminal.m_binds.TryGetValue(KeyCode.None, out var commands))
return commands.Any(ModifierKeys.IsValid);
return false;
}
}
[HarmonyPatch(typeof(Player), nameof(Player.UpdatePlacement))]
public class PreventRotation {
static void Prefix(Player __instance, ref int __state) {
__state = __instance.m_placeRotation;
}
static void Postfix(Player __instance, int __state) {
if (MouseWheelBinding.CouldExecute())
__instance.m_placeRotation = __state;
}
}
[HarmonyPatch(typeof(Player), nameof(Player.UpdatePlacementGhost))]
public class PreventGhostRotation {
static void Prefix(Player __instance, ref Quaternion __state) {
if (__instance.m_placementGhost)
__state = __instance.m_placementGhost.transform.rotation;
}
static void Postfix(Player __instance, Quaternion __state) {
if (__instance.m_placementGhost && MouseWheelBinding.CouldExecute())
__instance.m_placementGhost.transform.rotation = __state;
}
}
public class ComfyGizmoPatcher {
public static void DoPatching(Assembly assembly) {
if (assembly == null) return;
ServerDevcommands.Log.LogInfo("\"ComfyGizmo\" detected. Patching \"HandleAxisInput\" for mouse wheel binding.");
Harmony harmony = new("valheim.jerekuusela.server_devcommand.comfygizmo");
var mOriginal = AccessTools.Method(assembly.GetType("Gizmo.ComfyGizmo"), "HandleAxisInput");
var mPrefix = SymbolExtensions.GetMethodInfo(() => Prefix());
harmony.Patch(mOriginal, new(mPrefix));
}
static bool Prefix() => !MouseWheelBinding.CouldExecute();
}
|
//
// System.Runtime.Remoting.Contexts.SynchronizationAttribute.cs
//
// Author:
// Lluis Sanchez Gual (lluis@ximian.com)
//
// (C) Novell, Inc. http://www.ximian.com
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Threading;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Activation;
namespace System.Runtime.Remoting.Contexts
{
[AttributeUsage(AttributeTargets.Class)]
[Serializable]
[System.Runtime.InteropServices.ComVisible (true)]
public class SynchronizationAttribute: ContextAttribute, IContributeClientContextSink, IContributeServerContextSink
{
public const int NOT_SUPPORTED = 1;
public const int SUPPORTED = 2;
public const int REQUIRED = 4;
public const int REQUIRES_NEW = 8;
bool _bReEntrant;
int _flavor;
[NonSerialized]
bool _locked;
[NonSerialized]
int _lockCount;
[NonSerialized]
Mutex _mutex = new Mutex (false);
[NonSerialized]
Thread _ownerThread;
public SynchronizationAttribute ()
: this (REQUIRES_NEW, false)
{
}
public SynchronizationAttribute (bool reEntrant)
: this (REQUIRES_NEW, reEntrant)
{
}
public SynchronizationAttribute (int flag)
: this (flag, false)
{
}
public SynchronizationAttribute (int flag, bool reEntrant)
: base ("Synchronization")
{
if (flag != NOT_SUPPORTED && flag != REQUIRED && flag != REQUIRES_NEW && flag != SUPPORTED)
throw new ArgumentException ("flag");
_bReEntrant = reEntrant;
_flavor = flag;
}
public virtual bool IsReEntrant
{
get { return _bReEntrant; }
}
public virtual bool Locked
{
get
{
return _locked;
}
set
{
if (value)
{
_mutex.WaitOne ();
lock (this)
{
_lockCount++;
if (_lockCount > 1)
ReleaseLock (); // Thread already had the lock
_ownerThread = Thread.CurrentThread;
}
}
else
{
lock (this)
{
while (_lockCount > 0 && _ownerThread == Thread.CurrentThread)
{
_lockCount--;
_mutex.ReleaseMutex ();
_ownerThread = null;
}
}
}
}
}
internal void AcquireLock ()
{
_mutex.WaitOne ();
lock (this)
{
_ownerThread = Thread.CurrentThread;
_lockCount++;
}
}
internal void ReleaseLock ()
{
lock (this)
{
if (_lockCount > 0 && _ownerThread == Thread.CurrentThread) {
_lockCount--;
_mutex.ReleaseMutex ();
_ownerThread = null;
}
}
}
[System.Runtime.InteropServices.ComVisible (true)]
public override void GetPropertiesForNewContext (IConstructionCallMessage ctorMsg)
{
if (_flavor != NOT_SUPPORTED) {
ctorMsg.ContextProperties.Add (this);
}
}
public virtual IMessageSink GetClientContextSink (IMessageSink nextSink)
{
return new SynchronizedClientContextSink (nextSink, this);
}
public virtual IMessageSink GetServerContextSink (IMessageSink nextSink)
{
return new SynchronizedServerContextSink (nextSink, this);
}
[System.Runtime.InteropServices.ComVisible (true)]
public override bool IsContextOK (Context ctx, IConstructionCallMessage msg)
{
SynchronizationAttribute prop = ctx.GetProperty ("Synchronization") as SynchronizationAttribute;
switch (_flavor)
{
case NOT_SUPPORTED: return (prop == null);
case REQUIRED: return (prop != null);
case REQUIRES_NEW: return false;
case SUPPORTED: return true;
}
return false;
}
internal static void ExitContext ()
{
if (Thread.CurrentContext.IsDefaultContext) return;
SynchronizationAttribute prop = Thread.CurrentContext.GetProperty ("Synchronization") as SynchronizationAttribute;
if (prop == null) return;
prop.Locked = false;
}
internal static void EnterContext ()
{
if (Thread.CurrentContext.IsDefaultContext) return;
SynchronizationAttribute prop = Thread.CurrentContext.GetProperty ("Synchronization") as SynchronizationAttribute;
if (prop == null) return;
prop.Locked = true;
}
}
internal class SynchronizedClientContextSink: IMessageSink
{
IMessageSink _next;
SynchronizationAttribute _att;
public SynchronizedClientContextSink (IMessageSink next, SynchronizationAttribute att)
{
_att = att;
_next = next;
}
public IMessageSink NextSink
{
get { return _next; }
}
public IMessageCtrl AsyncProcessMessage (IMessage msg, IMessageSink replySink)
{
if (_att.IsReEntrant)
{
_att.ReleaseLock(); // Unlock when leaving the context
replySink = new SynchronizedContextReplySink (replySink, _att, true);
}
return _next.AsyncProcessMessage (msg, replySink);
}
public IMessage SyncProcessMessage (IMessage msg)
{
if (_att.IsReEntrant)
_att.ReleaseLock (); // Unlock when leaving the context
try
{
return _next.SyncProcessMessage (msg);
}
finally
{
if (_att.IsReEntrant)
_att.AcquireLock ();
}
}
}
internal class SynchronizedServerContextSink: IMessageSink
{
IMessageSink _next;
SynchronizationAttribute _att;
public SynchronizedServerContextSink (IMessageSink next, SynchronizationAttribute att)
{
_att = att;
_next = next;
}
public IMessageSink NextSink
{
get { return _next; }
}
public IMessageCtrl AsyncProcessMessage (IMessage msg, IMessageSink replySink)
{
_att.AcquireLock ();
replySink = new SynchronizedContextReplySink (replySink, _att, false);
return _next.AsyncProcessMessage (msg, replySink);
}
public IMessage SyncProcessMessage (IMessage msg)
{
_att.AcquireLock ();
try
{
return _next.SyncProcessMessage (msg);
}
finally
{
_att.ReleaseLock ();
}
}
}
internal class SynchronizedContextReplySink: IMessageSink
{
IMessageSink _next;
bool _newLock;
SynchronizationAttribute _att;
public SynchronizedContextReplySink (IMessageSink next, SynchronizationAttribute att, bool newLock)
{
_newLock = newLock;
_next = next;
_att = att;
}
public IMessageSink NextSink
{
get { return _next; }
}
public IMessageCtrl AsyncProcessMessage (IMessage msg, IMessageSink replySink)
{
// Never called
throw new NotSupportedException ();
}
public IMessage SyncProcessMessage (IMessage msg)
{
if (_newLock) _att.AcquireLock ();
else _att.ReleaseLock ();
try
{
return _next.SyncProcessMessage (msg);
}
finally
{
if (_newLock)
_att.ReleaseLock ();
}
}
}
}
|
using Microsoft.EntityFrameworkCore;
using Moq;
using SportStore.Data;
using SportStore.Models;
using SportStore.Services;
using SportStore.Services.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace SportStore.Tests.CardServiceTests
{
public class AddItem_Should
{
[Fact]
public async Task Can_Add_New_Lines()
{
var options = new DbContextOptionsBuilder<SportStoreDbContext>()
.UseInMemoryDatabase(databaseName: "Can_Add_New_Lines")
.Options;
Product p1 = new Product { Id = 1, Name = "P1" };
Product p2 = new Product { Id = 2, Name = "P2" };
using (var context = new SportStoreDbContext(options))
{
var service = new CardService(context);
await service.AddItem(p1, 1);
await service.AddItem(p2, 1);
var result = context.CardItems.ToArray();
Assert.Equal(2, result.Length);
Assert.Equal(p1, result[0].Product);
Assert.Equal(p2, result[1].Product);
}
}
[Fact]
public async Task Can_Add_Quantity_For_Existing_Lines()
{
var options = new DbContextOptionsBuilder<SportStoreDbContext>()
.UseInMemoryDatabase(databaseName: "Can_Add_Quantity_For_Existing_Lines")
.Options;
Product p1 = new Product { Id = 1, Name = "P1" };
Product p2 = new Product { Id = 2, Name = "P2" };
using (var context = new SportStoreDbContext(options))
{
var service = new CardService(context);
await service.AddItem(p1, 1);
await service.AddItem(p2, 1);
await service.AddItem(p1, 10);
var result = context.CardItems.ToArray();
Assert.Equal(2, result.Length);
Assert.Equal(11, result[0].Quantity);
Assert.Equal(1, result[1].Quantity);
}
}
}
}
|
using System;
namespace Idfy.IdentificationV2
{
/// <summary>
/// Prefilled input values.
/// </summary>
public class PrefilledInput
{
/// <summary>
/// Prefill the user's national identification number.
/// </summary>
public string Nin { get; set; }
/// <summary>
/// Prefill the user's phone number. Must be prefixed with country code.
/// </summary>
public string PhoneNumber { get; set; }
/// <summary>
/// Prefill the user's date of birth (YYYY-MM-DD).
/// </summary>
public DateTime? DateOfBirth { get; set; }
/// <summary>
/// Prefill the user's username.
/// </summary>
public string Username { get; set; }
}
}
|
using System.Collections.Generic;
namespace AzureTranslator.Models
{
public class TranslationResult
{
public DetectedLanguage? DetectedLanguage { get; set; }
public TextResult? SourceText { get; set; }
public IEnumerable<Translation>? Translations { get; set; }
}
public class DetectedLanguage
{
public string? Language { get; set; }
public float Score { get; set; }
}
public class TextResult
{
public string? Text { get; set; }
public string? Script { get; set; }
}
public class Translation
{
public string? Text { get; set; }
public TextResult? Transliteration { get; set; }
public string? To { get; set; }
public Alignment? Alignment { get; set; }
public SentenceLength? SentLen { get; set; }
}
public class Alignment
{
public string? Proj { get; set; }
}
public class SentenceLength
{
public IEnumerable<int>? SrcSentLen { get; set; }
public IEnumerable<int>? TransSentLen { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace NetLib {
public class PacketBuilder : IDisposable {
private List<byte> _data;
private bool _isDisposed = false;
public PacketBuilder(ushort packetType){
_data = new List<byte>();
Write(packetType);
}
public void Write(byte data) => _data.Add(data);
public void Write(sbyte data) => _data.Add((byte)data);
public void Write(IEnumerable<byte> data) => _data.AddRange(data);
public void Write(short data) => _data.AddRange(BitConverter.GetBytes(data));
public void Write(ushort data) => _data.AddRange(BitConverter.GetBytes(data));
public void Write(int data) => _data.AddRange(BitConverter.GetBytes(data));
public void Write(uint data) => _data.AddRange(BitConverter.GetBytes(data));
public void Write(long data) => _data.AddRange(BitConverter.GetBytes(data));
public void Write(ulong data) => _data.AddRange(BitConverter.GetBytes(data));
public void Write(float data) => _data.AddRange(BitConverter.GetBytes(data));
public void Write(double data) => _data.AddRange(BitConverter.GetBytes(data));
public void Write(string data, Encoding encoding){
byte[] bytes = encoding.GetBytes(data);
_data.AddRange(BitConverter.GetBytes(bytes.Length));
_data.AddRange(bytes);
}
public void Write(string data) => Write(data, Encoding.ASCII);
public void Write(bool data) => _data.AddRange(BitConverter.GetBytes(data));
public byte[] Build(){
byte[] packet = new byte[sizeof(int)+_data.Count];
BitConverter.GetBytes(_data.Count).CopyTo(packet, 0);
_data.CopyTo(packet, sizeof(int));
return packet;
}
/// <summary>
/// Inserts clientIdx infront of the entire packet including the packet body length
/// Used for sending UDP packets from the client to server
/// </summary>
/// <param name="clientIdx"></param>
/// <returns></returns>
public byte[] Build(byte clientIdx){
byte[] packet = new byte[sizeof(byte)+sizeof(int)+_data.Count];
packet[0] = clientIdx;
BitConverter.GetBytes(_data.Count).CopyTo(packet, sizeof(byte));
_data.CopyTo(packet, sizeof(byte)+sizeof(int));
return packet;
}
protected virtual void Dispose(bool disposing){
if(!_isDisposed){
if(disposing)
_data = null;
_isDisposed = true;
}
}
public void Dispose(){
Dispose(true);
GC.SuppressFinalize(this);
}
~PacketBuilder() => Dispose(false);
}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AliyunStorageOptions.cs" company="Hämmer Electronics">
// The project is licensed under the MIT license.
// </copyright>
// <summary>
// The Aliyun storage options class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace NaGet.Aliyun;
/// <summary>
/// The Aliyun storage options class.
/// </summary>
public class AliyunStorageOptions
{
/// <summary>
/// Gets or sets the access key.
/// </summary>
[Required]
public string AccessKey { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the access key secret.
/// </summary>
[Required]
public string AccessKeySecret { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the endpoint.
/// </summary>
[Required]
public string Endpoint { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the bucket.
/// </summary>
[Required]
public string Bucket { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the prefix.
/// </summary>
public string Prefix { get; set; } = string.Empty;
}
|
using System;
using Cats.Errors;
namespace Cats.Infrastructure.Resilience.Failures;
public sealed class UnavailableFailure : IFailure
{
public UnavailableFailure(string method, string type)
{
Method = method ?? throw new ArgumentNullException(nameof(method));
Type = type ?? throw new ArgumentNullException(nameof(type));
}
public string Method { get; }
public string Type { get; }
}
|
using AutoMapper;
using Vidly.Dtos;
using Vidly.Models;
namespace Vidly.App_Start
{
public class MappingProfile : Profile
{
public static void Run()
{
Mapper.Initialize(a => a.AddProfile<MappingProfile>());
}
public MappingProfile()
{
CreateMap<Customer, CustomerDto>().ReverseMap().ForMember(c => c.Id, opt => opt.Ignore());
CreateMap<Movie, MovieDto>().ReverseMap().ForMember(c => c.Id, opt => opt.Ignore());
CreateMap<MembershipType, MembershipTypeDto>().ReverseMap().ForMember(c => c.Id, opt => opt.Ignore());
CreateMap<Genre, GenreDto>().ReverseMap().ForMember(c => c.Id, opt => opt.Ignore());
}
}
} |
using System;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Tumble.Core;
namespace Tumble.Client.Handlers
{
public class ClientRequest : IPipelineHandler
{
public TimeSpan RequestTimeout { get; set; } = new TimeSpan(0, 1, 0);
public async Task InvokeAsync(PipelineContext context, PipelineDelegate next)
{
if (!context.GetFirst(out HttpRequestMessage httpRequestMessage))
throw new PipelineDependencyException<HttpRequestMessage>(this);
HttpClientRequest request = new HttpClientRequest(httpRequestMessage);
CancellationTokenSource cts = new CancellationTokenSource(RequestTimeout);
var cancellationTokens = context.Get<CancellationToken>();
var token = cancellationTokens.Any()
? CancellationTokenSource.CreateLinkedTokenSource(
cancellationTokens.Concat(new[] { cts.Token }).ToArray()
).Token
: cts.Token;
try
{
var result = await request.InvokeAsync(token);
context.Add(result);
await next.Invoke();
}
catch (HttpRequestException ex)
{
throw new PipelineException(this, ex.Message, ex);
}
catch (Exception ex)
{
throw new PipelineException(this, ex.Message, ex);
}
}
}
}
|
@using System.Web.Optimization
@using Fpm.MainUI
@using Fpm.MainUI.Helpers
@model Fpm.ProfileData.Entities.Profile.ContentItem
<link href="@(AppConfig.JsPath)tiny_mce/skins/lightgray/skin.min.css" rel="stylesheet" type="text/css" />
<script src="@(AppConfig.JsPath)tiny_mce/tinymce.min.js" type="text/javascript"></script>
<script src="@(AppConfig.JsPath)tiny_mce/jquery.tinymce.min.js" type="text/javascript"></script>
@Scripts.Render("~/content.js")
@{ Layout = "~/Views/Shared/_LayoutPage.cshtml"; }
@{
ViewBag.Title = "FPM - Create Content";
}
@using (Html.BeginForm("InsertContentItem", "Content", FormMethod.Post, new { id = "SaveNewContent" }))
{
<h2 class="subheading col-md-12">New Content</h2>
@Html.Partial("_ContentErrorMessage")
<div class="delete-indicators">
<label class="content-item-detail-label">Content Key:</label>
@Html.TextBoxFor(model => model.ContentKey, new {@class = "unselected-domain"})
<span class="field-validation-valid" data-valmsg-for="ContentKey" data-valmsg-replace="true"></span>
</div>
@Html.Partial("_ContentDescription")
@Html.Partial("_PlainTextCheckbox")
@Html.Partial("_PlainTextWarning")
@Html.Partial("_ContentTextArea")
@Html.HiddenFor(x => x.Id)
@Html.HiddenFor(x => x.ProfileId)
<div class="row form-group">
<div class="form-control-static col-lg-12">
<input class="btn btn-primary" id="confirm" type="submit" value="Save" />
@Html.Partial("_CancelButton", Model.ProfileId)
</div>
</div>
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace Symbolics
{
public class Subtraction : Operation
{
public Subtraction()
{
Operator = "-";
ParseOrder = ParseOrders.Subtraction;
}
public override double Calculate()
{
return LeftHandSide.Calculate() - RightHandSide.Calculate();
}
public override Expression Parse(string equation)
{
string[] sides = equation.Split(Operator.ToCharArray());
var LeftSide = sides.Reverse().Skip(1).Reverse();
var RightSide = sides.Last();
return new Subtraction
{
LeftHandSide = Expression.Create(String.Join(Operator, LeftSide)),
RightHandSide = Expression.Create(RightSide)
};
}
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
namespace Api.AppStart
{
public static class CorsConfig
{
public static void ConfigureCors(this IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(x => x
//.WithOrigins("http://example.com")
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
}
}
} |
// SPDX-License-Identifier: Apache-2.0
// Licensed to the Ed-Fi Alliance under one or more agreements.
// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
// See the LICENSE and NOTICES files in the project root for more information.
using System;
using System.Linq;
using EdFi.Ods.Api.Common.Models.Resources.BellSchedule.EdFi;
using EdFi.Ods.Api.Common.Models.Resources.StaffEducationOrganizationAssignmentAssociation.EdFi;
using EdFi.Ods.Api.Common.Models.Resources.StudentSchoolAttendanceEvent.EdFi;
using EdFi.Ods.Entities.Common.EdFi;
using EdFi.TestFixture;
using Newtonsoft.Json;
using NUnit.Framework;
using Shouldly;
using Test.Common;
namespace EdFi.Ods.Tests.EdFi.Ods.WebApi.Resources
{
public class ResourceModelReferenceTests
{
public class When_initalizing_a_model_with_an_optional_reference_where_none_of_the_optional_references_properties_are_explicitly_set
: TestFixtureBase
{
// Supplied values
private StaffEducationOrganizationAssignmentAssociation _model;
private IStaffEducationOrganizationAssignmentAssociation _modelInterface;
// Actual values
private string _actualSerializedJson;
// External dependencies
protected override void Arrange()
{
// Set up mocked dependences and supplied values
}
protected override void Act()
{
// Perform the action to be tested
_model = new StaffEducationOrganizationAssignmentAssociation();
// Populate the instance's value, including the shared FK value, but none of the optional reference's values
_modelInterface = _model;
// Set only the required "key" properties on the main model
// This also serves as part of the optional reference, but is "unified" (or shared) from other references.
_modelInterface.StaffUniqueId = "ABC123";
_modelInterface.EducationOrganizationId = 123;
_modelInterface.StaffClassificationDescriptor = "Hello";
_modelInterface.BeginDate = DateTime.Today;
// NOTE: No other properties for the optional reference have been set
_actualSerializedJson = JsonConvert.SerializeObject(_model);
}
[Assert]
public void Should_not_return_default_values_for_nullable_properties_from_optional_reference()
{
// Assert the expected results
_modelInterface.EmploymentHireDate.ShouldBeNull();
_modelInterface.EmploymentEducationOrganizationId.ShouldBeNull();
_modelInterface.EmploymentStatusDescriptor.ShouldBeNull();
}
[Assert]
public void Should_not_include_the_partially_defined_reference_in_JSON_output()
{
_actualSerializedJson.ShouldContain(@"""employmentStaffEducationOrganizationEmploymentAssociationReference"":null");
}
[Assert]
public void Should_not_introduce_a_partially_defined_reference_on_JSON_deserialization()
{
var deserializedModel = DefaultTestJsonSerializer.DeserializeObject<StaffEducationOrganizationAssignmentAssociation>(_actualSerializedJson);
deserializedModel.EmploymentStaffEducationOrganizationEmploymentAssociationReference.ShouldBeNull();
}
}
public class When_setting_and_getting_properties_for_an_optional_reference_on_a_model : TestFixtureBase
{
private StaffEducationOrganizationAssignmentAssociation _model;
private IStaffEducationOrganizationAssignmentAssociation _modelInterface;
[Assert]
public void Should_not_return_values_from_optional_reference_until_all_of_the_references_properties_have_been_set()
{
_model = new StaffEducationOrganizationAssignmentAssociation();
_modelInterface = _model;
// This property is "unified" with other references
_modelInterface.StaffUniqueId = "ABC123";
// Because it's shared by multiple references, this property should return its value
// immediately (it's not **specific** to the optional reference)
_modelInterface.StaffUniqueId.ShouldBe("ABC123");
All_optional_reference_properties_should_still_return_null_values();
// ---------------------------------------------------------
// These properties are specific to the optional reference
// ---------------------------------------------------------
_modelInterface.EmploymentEducationOrganizationId = 123;
All_optional_reference_properties_should_still_return_null_values();
Optional_reference_should_still_be_null();
_modelInterface.EmploymentStatusDescriptor = "XYZ";
All_optional_reference_properties_should_still_return_null_values();
Optional_reference_should_still_be_null();
// After the last property specific to the optional reference is set, they should all return values (reference is complete)
_modelInterface.EmploymentHireDate = DateTime.Today;
All_of_the_optional_reference_properties_should_now_return_values();
Optional_reference_should_NOT_be_null();
}
private void Optional_reference_should_NOT_be_null()
{
_model.EmploymentStaffEducationOrganizationEmploymentAssociationReference.ShouldNotBeNull();
}
private void Optional_reference_should_still_be_null()
{
_model.EmploymentStaffEducationOrganizationEmploymentAssociationReference.ShouldBeNull();
}
private void All_optional_reference_properties_should_still_return_null_values()
{
_modelInterface.EmploymentEducationOrganizationId.ShouldBeNull();
_modelInterface.EmploymentStatusDescriptor.ShouldBeNull();
_modelInterface.EmploymentHireDate.ShouldBeNull();
}
private void All_of_the_optional_reference_properties_should_now_return_values()
{
_modelInterface.EmploymentEducationOrganizationId.ShouldNotBe(null);
_modelInterface.EmploymentStatusDescriptor.ShouldNotBe(null);
_modelInterface.EmploymentHireDate.ShouldNotBe(null);
}
}
[TestFixture]
public class When_setting_and_getting_properties_for_a_required_reference_on_a_model
{
[SetUp]
protected void TestSetup()
{
_model = new StaffEducationOrganizationAssignmentAssociation();
_modelInterface = _model;
}
private StaffEducationOrganizationAssignmentAssociation _model;
private IStaffEducationOrganizationAssignmentAssociation _modelInterface;
[Test]
public void Property_should_be_cleared_by_explicitly_setting_reference_to_null()
{
_modelInterface.StaffUniqueId = "ABC123";
_model.StaffReference = null;
_modelInterface.StaffUniqueId.ShouldBeNull();
}
[Test]
public void Reference_should_be_implicitly_restored_by_setting_the_property_value()
{
_model.StaffReference = null;
_modelInterface.StaffUniqueId = "ABC123";
_model.StaffReference.ShouldNotBeNull();
_modelInterface.StaffUniqueId.ShouldBe("ABC123");
}
[Test]
public void Reference_should_be_null_again_after_property_value_is_returned_to_its_default_value()
{
_modelInterface.StaffUniqueId = "ABC123";
_modelInterface.StaffUniqueId = default(string);
_model.StaffReference.ShouldBeNull();
}
[Test]
public void Reference_should_be_null_before_property_value_is_set()
{
_model.StaffReference.ShouldBeNull();
}
[Test]
public void Reference_should_NOT_be_null_after_property_value_is_set()
{
_modelInterface.StaffUniqueId = "ABC123";
_model.StaffReference.ShouldNotBeNull();
}
}
public class When_deserializing_a_model_with_a_reference_based_on_a_composite_key : TestFixtureBase
{
private StudentSchoolAttendanceEvent _model;
protected override void Act()
{
var json = @"
{
""id"" : ""00000000000000000000000000000000"",
""schoolReference"" : null,
""sessionReference"" : {
""schoolId"" : 123,
""sessionName"" : ""ABC"",
""schoolYear"" : 2013,
""link"" : {
""rel"" : ""Session"",
""href"" : ""/sessions?schoolId=123&schoolYear=2013""
}
},
""studentReference"" : null,
""eventDate"" : ""0001-01-01"",
""attendanceEventCategoryDescriptor"" : null,
""attendanceEventReason"" : null,
""educationalEnvironmentType"" : null,
""_etag"" : null
}
";
_model = DefaultTestJsonSerializer.DeserializeObject<StudentSchoolAttendanceEvent>(json);
}
[Assert]
public void Should_return_a_reference()
{
_model.SessionReference.ShouldNotBeNull();
}
[Assert]
public void Reference_should_return_the_non_default_values()
{
_model.SessionReference.SchoolId.ShouldBe(123);
_model.SessionReference.SessionName.ShouldBe("ABC");
((int) _model.SessionReference.SchoolYear).ShouldBe(2013);
}
}
public class When_deserializing_a_model_with_a_reference_based_on_a_composite_key_with_backReference_presence : TestFixtureBase
{
private BellSchedule _model;
/* C# initializer helper
private BellSchedule _model = new BellSchedule
{
BellScheduleName = "ScheduleName",
BellScheduleMeetingTimes = new[]
{
new BellScheduleMeetingTime
{
ClassPeriodReference = new BellScheduleMeetingTimeToClassPeriodReference
{
ClassPeriodName = "ABC"
},
StartTime = DateTime.Now.TimeOfDay,
EndTime = new TimeSpan(1, 0, 0),
}
},
CalendarDateReference = new CalendarDateReference
{
Date = DateTime.Now,
EducationOrganizationId = 1,
},
SchoolReference = new SchoolReference
{
SchoolId = 10
},
GradeLevelDescriptor = "A",
};
*/
protected override void Act()
{
const string json = @"
{
'calendarDateReference' : {
'Date' : '2000-01-01',
'schoolId' : 1,
},
'schoolReference' : {
'schoolId' : 10
},
'gradeLevelDescriptor' : 'A',
'name' : 'ScheduleName',
'classPeriods' : [
{
'classPeriodReference' : {
'classPeriodName' : 'ABC',
'schoolId' : 10,
}
}
],
}
";
_model = JsonConvert.DeserializeObject<BellSchedule>(json);
}
[Assert]
public void Should_return_a_reference()
{
_model.BellScheduleClassPeriods.First()
.ClassPeriodReference.ShouldNotBeNull();
}
[Assert]
public void Reference_should_return_the_non_default_values()
{
_model.BellScheduleClassPeriods.First()
.ClassPeriodReference.ClassPeriodName.ShouldBe("ABC");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Drawing;
namespace L2Package.DataStructures
{
public class UColor : IXmlSerializable, IUnrealExportable
{
[UEExport]
public byte r { set; get; }
[UEExport]
public byte g { set; get; }
[UEExport]
public byte b { set; get; }
[UEExport]
public byte a { set; get; }
public void Deserialize(System.Xml.Linq.XElement element)
{
if (element.Attribute("class").Value != "Color")
throw new Exception("Wrong class.");
a = Convert.ToByte(Utility.GetElement(element, "a").Value.ToString());
r = Convert.ToByte(Utility.GetElement(element, "r").Value.ToString());
g = Convert.ToByte(Utility.GetElement(element, "g").Value.ToString());
b = Convert.ToByte(Utility.GetElement(element, "b").Value.ToString());
}
public System.Xml.Linq.XElement SerializeXML(string Name)
{
return new XElement(Name,
new XAttribute("class", "Color"),
new XElement("b",b),
new XElement("g",g),
new XElement("r",r),
new XElement("a",a)
);
}
public Color ToColor()
{
return Color.FromArgb(a, r, g, b);
}
public string UnrealString
{
get
{
return Utility.GetExport(this);
}
}
public void ResetTemplate()
{
UColor.Template = null;
}
private static string Template = null;
public string UnrealStringTemplate
{
set
{
Template = value;
Utility.SetTemplate(this.GetType().Name, Template);
}
get
{
if (!string.IsNullOrEmpty(Template)) return Template;
Template = Utility.GetTemplate(this.GetType().Name);
return Template;
}
}
public string[] PropertiesList
{
get
{
return Utility.GetExportProperties(this.GetType());
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using IniParser;
using IniParser.Model;
namespace Kana2Romaji
{
static class Program
{
public static IniData UstData;
private static Dictionary<string,string> RmDictionary = new Dictionary<string, string>();
private static readonly Encoding EncodeJPN = Encoding.GetEncoding("Shift_JIS");
private static readonly string UstHeader = "[#VERSION]\r\n" + "UST Version 1.20\r\n";
static void Main(string[] path)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Parallel.ForEach(Resource.Table.Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries), item =>
{
RmDictionary.Add(item.Split(',')[0], item.Split(',')[1]);
});
if (!string.IsNullOrWhiteSpace(string.Join("", path)))
{
string ustFileStr = File.ReadAllText(string.Join("", path), EncodeJPN)
.Replace(UstHeader, "");
UstData = new FileIniDataParser().Parser.Parse(ustFileStr);
UstData.Sections.RemoveSection("#PREV");
UstData.Sections.RemoveSection("#NEXT");
UstData.Sections.RemoveSection("#SETTING");
//foreach (var itemSection in UstData.Sections)
Parallel.ForEach(UstData.Sections, itemSection =>
{
if (itemSection.Keys["Lyric"] == "R") return;
try
{
if (itemSection.Keys["Lyric"].Contains(" "))
itemSection.Keys["Lyric"] = itemSection.Keys["Lyric"].Trim().Split(' ')[0] + " " +
RmDictionary[
itemSection.Keys["Lyric"].Trim().Split(' ')[1]];
else
itemSection.Keys["Lyric"] = RmDictionary[itemSection.Keys["Lyric"].Trim()];
}
catch (Exception e)
{
Console.WriteLine(e);
}
});
File.WriteAllText(string.Join("", path),
UstHeader + UstData.ToString().Replace(" = ", "=").Replace("\r\n\r\n", "\r\n"), EncodeJPN);
}
else
{
Console.WriteLine(@"未包含应有的参数,请作为UTAU插件使用");
Console.ReadKey();
}
}
}
}
|
using ApprovalCenter.Domain.Core.Commands;
using System;
namespace ApprovalCenter.Domain.Category.Commands
{
public abstract class CategoryCommand : CommandIdentity
{
public string Name { get; protected set; }
public string Description { get; protected set; }
public DateTime DateCreate { get; protected set; }
public DateTime DateEdit { get; protected set; }
}
}
|
using System;
namespace DesignLibrary
{
[AttributeUsage(AttributeTargets.All)]
public sealed class GoodCustomAttribute : Attribute
{
string mandatory;
string optional;
public GoodCustomAttribute(string mandatoryData)
{
mandatory = mandatoryData;
}
public string MandatoryData
{
get { return mandatory; }
}
public string OptionalData
{
get { return optional; }
set { optional = value; }
}
}
}
namespace DesignLibrary
{
public class MyClass
{
string myProperty = "Hello";
string myOtherProperty = "World";
//<Snippet1>
[GoodCustomAttribute("ThisIsSomeMandatoryData", OptionalData = "ThisIsSomeOptionalData")]
public string MyProperty
{
get { return myProperty; }
set { myProperty = value; }
}
[GoodCustomAttribute("ThisIsSomeMoreMandatoryData")]
public string MyOtherProperty
{
get { return myOtherProperty; }
set { myOtherProperty = value; }
}
//</Snippet1>
}
} |
using Newtonsoft.Json;
namespace SalesforceSdk.Models
{
public class CreateJobRequest
{
/// <summary>
/// The column delimiter used for CSV job data.
/// </summary>
/// <remarks>
/// Values include:
/// BACKQUOTE—backquote character(`)
/// CARET—caret character(^)
/// COMMA—comma character(,) which is the default delimiter
/// PIPE—pipe character(|)
/// SEMICOLON—semicolon character(;)
/// TAB—tab character
/// </remarks>
[JsonProperty("columnDelimiter", NullValueHandling = NullValueHandling.Ignore)]
public string ColumnDelimiter { get; set; }
/// <summary>
/// The content type for the job. The only valid value (and the default)
/// is CSV.
/// </summary>
[JsonProperty("contentType", NullValueHandling = NullValueHandling.Ignore)]
public string ContentType { get; set; }
/// <summary>
/// The external ID field in the object being updated. Only needed for
/// upsert operations. Field values must also exist in CSV job data.
/// </summary>
[JsonProperty("externalIdFieldName", NullValueHandling = NullValueHandling.Ignore)]
public string ExternalIdFieldName { get; set; }
/// <summary>
/// The line ending used for CSV job data, marking the end of a data row.
/// The default is LF.
/// </summary>
/// <remarks>
/// Valid values are:
/// LF—linefeed character
/// CRLF—carriage return character followed by a linefeed character
/// </remarks>
[JsonProperty("lineEnding", NullValueHandling = NullValueHandling.Ignore)]
public string LineEnding { get; set; }
/// <summary>
/// The object type for the data being processed. Use only a single object
/// type per job.
/// </summary>
[JsonProperty("object")]
public string Object { get; set; }
/// <summary>
/// The processing operation for the job.
/// </summary>
/// <remarks>
/// The processing operation for the job. Valid values are:
/// insert
/// delete
/// update
/// upsert
/// </remarks>
[JsonProperty("operation")]
public string Operation { get; set; }
}
/// <summary>
///
/// </summary>
/// <remarks>
/// {
/// "id":"...........",
/// "operation":"insert",
/// "object":"Account",
/// "createdById":".............",
/// "createdDate":"2019-08-27T21:28:28.000+0000",
/// "systemModstamp":"2019-08-27T21:28:28.000+0000",
/// "state":"Open",
/// "concurrencyMode":"Parallel",
/// "contentType":"CSV",
/// "apiVersion":46.0,
/// "contentUrl":"services/data/v46.0/jobs/ingest/............/batches",
/// "lineEnding":"CRLF",
/// "columnDelimiter":"COMMA"
/// }
/// </remarks>
public class CreateJobResponse : JobInfo
{
[JsonProperty("externalIdFieldName")]
public string ExternalIdFieldName { get; set; }
}
public static class Objects
{
public static readonly string CONTACT = "Contact";
}
public static class ColumnDelimiters
{
public static readonly string BACKQUOTE = "BACKQUOTE";
public static readonly string CARET = "CARET";
public static readonly string COMMA = "COMMA";
}
public static class ContentTypes
{
public static readonly string CSV = "CSV";
}
public static class LineEndings
{
/// <summary>
/// linefeed character
/// </summary>
public static readonly string LF = "LF";
/// <summary>
/// carriage return character followed by a linefeed character
/// </summary>
public static readonly string CRLF = "CRLF";
}
public static class Operations
{
public static readonly string INSERT = "insert";
public static readonly string DELETE = "delete";
public static readonly string UPDATE = "update";
public static readonly string UPSERT = "upsert";
}
public static class States
{
/// <summary>
/// The job was created and is open for data uploads.
/// </summary>
public static readonly string OPEN = "Open";
/// <summary>
/// All job data has been uploaded and the job is ready to be processed.
/// Salesforce has put the job in the queue.
/// </summary>
public static readonly string UPLOADCOMPLETE = "UploadComplete";
/// <summary>
/// The job is being processed by Salesforce. This includes automatic
/// optimized chunking of job data and processing of job operations.
/// </summary>
public static readonly string INPROGRESS = "InProgress";
/// <summary>
/// The job was processed.
/// </summary>
public static readonly string JOBCOMPLETE = "JobComplete";
/// <summary>
/// The job was canceled by the job creator, or by a user with the
/// “Manage Data Integrations” permission.
/// </summary>
public static readonly string ABORTED = "Aborted";
public static readonly string FAILED = "Failed";
}
}
|
namespace TakTikan.Tailor.Web.DashboardCustomization
{
public class WidgetViewDefinition : ViewDefinition
{
public byte DefaultWidth { get; }
public byte DefaultHeight { get; }
public WidgetViewDefinition(
string id,
string viewFile,
string javascriptFile = null,
string cssFile = null,
byte defaultWidth = 12,
byte defaultHeight = 10) : base(id, viewFile, javascriptFile, cssFile)
{
DefaultWidth = defaultWidth;
DefaultHeight = defaultHeight;
}
}
}
|
using System;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
using LiveSplit.VampireSurvivors.Attributes;
using LiveSplit.VampireSurvivors.Images;
using LiveSplit.VampireSurvivors.Model.SaveData;
using DescriptionAttribute = LiveSplit.VampireSurvivors.Attributes.DescriptionAttribute;
namespace LiveSplit.VampireSurvivors.UI.Controls {
public partial class AchievementControl : UserControl, INotifyPropertyChanged {
private static readonly ImageResource CheckedResource = new ImageResource("checkbox_checked.png");
private static readonly ImageResource UncheckedResource = new ImageResource("checkbox.png");
private readonly ImageResource _resource;
private bool _isAchieved;
public bool IsAchieved {
get => _isAchieved;
set {
_isAchieved = value;
// indicate that the image has changed
OnPropertyChanged(nameof(CheckedImage));
}
}
public Image CheckedImage => IsAchieved ? CheckedResource.Image : UncheckedResource.Image;
public AchievementControl() {
InitializeComponent();
}
public AchievementControl(Achievement ach) : this() {
_resource = ach.GetResource();
if (ach.GetAttribute<DescriptionAttribute>() is DescriptionAttribute attr) {
var tt = new ToolTip();
tt.SetToolTip(imgAchievement, attr.Description);
}
}
private void AchievementControl_Load(object sender, EventArgs e) {
imgCheckbox.DataBindings.Add("Image", this, nameof(CheckedImage));
imgAchievement.Image = _resource?.Image;
Disposed += OnDisposed;
}
private void OnDisposed(object sender, EventArgs e) {
_resource?.Dispose();
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|
using System;
namespace DearInventoryLib.Model.Common
{
public class AttachmentLineModel : DIModel
{
public string ContentType { get; set; }
public bool IsDefault { get; set; }
public string FileName { get; set; }
public string DownloadUrl { get; set; }
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IdentityModel.Tokens;
using System.Security.Claims;
using System.Security.Principal;
using System.Xml;
namespace WcfService
{
internal class AcceptAnyUsernameSecurityTokenHandler : UserNameSecurityTokenHandler
{
public override bool CanValidateToken { get { return true; } }
public override ReadOnlyCollection<ClaimsIdentity> ValidateToken(SecurityToken token)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
UserNameSecurityToken usernameToken = token as UserNameSecurityToken;
if (usernameToken == null)
{
throw new ArgumentException("token", "Not a UserNameSecurityToken");
}
try
{
string userName = usernameToken.UserName;
string password = usernameToken.Password;
var identity = new GenericIdentity(userName);
identity.AddClaim(new Claim(ClaimTypes.AuthenticationInstant, XmlConvert.ToString(DateTime.UtcNow, "yyyy-MM-ddTHH:mm:ss.fffZ"), ClaimValueTypes.DateTime));
identity.AddClaim(new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Password));
if (this.Configuration.SaveBootstrapContext)
{
if (RetainPassword)
{
identity.BootstrapContext = new BootstrapContext(usernameToken, this);
}
else
{
identity.BootstrapContext = new BootstrapContext(new UserNameSecurityToken(usernameToken.UserName, null), this);
}
}
TraceTokenValidationSuccess(token);
List<ClaimsIdentity> identities = new List<ClaimsIdentity>(1);
identities.Add(identity);
return identities.AsReadOnly();
}
catch (Exception e)
{
TraceTokenValidationFailure(token, e.Message);
throw e;
}
}
}
}
|
using System;
using OutlookMatters.Core.Chat;
using OutlookMatters.Core.Mattermost.v4.Interface;
namespace OutlookMatters.Core.Mattermost.v4
{
public class ChatFactory : IChatFactory, IChatChannelFactory, IChatPostFactory
{
public ISession NewInstance(IRestService restService, Uri baseUri, string token, string teamId)
{
return new SessionImpl(restService, baseUri, token, teamId, this, this);
}
public IChatChannel NewInstance(IRestService restService, Uri baseUri, string token, string teamId,
Channel channel)
{
return new ChatChannel(restService, baseUri, token, teamId, channel);
}
public IChatPost NewInstance(IRestService restService, Uri baseUri, string token, string teamId, Post post)
{
return new ChatPost(restService, baseUri, token, teamId, post);
}
}
} |
using System;
using Moq;
using NUnit.Framework;
using SisoDb.Dac;
using SisoDb.DbSchema;
using SisoDb.Structures.Schemas;
using SisoDb.UnitTests.TestFactories;
namespace SisoDb.UnitTests.DbSchema
{
[TestFixture]
public class DbSchemaManagerTests : UnitTestBase
{
private IStructureSchema _structureSchema;
protected override void OnFixtureInitialize()
{
_structureSchema = StructureSchemaTestFactory.Stub<Class_53966417_B25D_49E1_966B_58754110781C>(
indexAccessorsPaths: new[] { "IndexableMember1", "IndexableMember2" });
}
private Mock<IDbClient> CreateDbClientFake()
{
var dbClientFake = new Mock<IDbClient>();
var id = Guid.NewGuid();
dbClientFake.SetupGet(f => f.Id).Returns(id);
return dbClientFake;
}
[Test]
public void UpsertStructureSet_WhenNeverCalled_UpserterIsCalledOnce()
{
var settings = new Mock<IDbSettings>();
settings.SetupGet(f => f.AllowDynamicSchemaCreation).Returns(true);
settings.SetupGet(f => f.AllowDynamicSchemaUpdates).Returns(true);
var dbFake = new Mock<ISisoDatabase>();
dbFake.SetupGet(f => f.Settings).Returns(settings.Object);
var upserterFake = new Mock<IDbSchemaUpserter>();
var dbClientFake = CreateDbClientFake();
var manager = new DbSchemas(dbFake.Object, upserterFake.Object);
manager.Upsert(_structureSchema, dbClientFake.Object);
upserterFake.Verify(f => f.Upsert(_structureSchema, dbClientFake.Object, true, true), Times.Once());
}
[Test]
public void UpsertStructureSet_WhenCalledTwice_UpserterIsCalledOnceNotTwice()
{
var settings = new Mock<IDbSettings>();
settings.SetupGet(f => f.AllowDynamicSchemaCreation).Returns(true);
settings.SetupGet(f => f.AllowDynamicSchemaUpdates).Returns(true);
var dbFake = new Mock<ISisoDatabase>();
dbFake.SetupGet(f => f.Settings).Returns(settings.Object);
var upserterFake = new Mock<IDbSchemaUpserter>();
var dbClientFake = CreateDbClientFake();
var manager = new DbSchemas(dbFake.Object, upserterFake.Object);
manager.Upsert(_structureSchema, dbClientFake.Object);
manager.Upsert(_structureSchema, dbClientFake.Object);
upserterFake.Verify(f => f.Upsert(_structureSchema, dbClientFake.Object, true, true), Times.Once());
}
[Test]
public void UpsertStructureSet_WhenDbSettingsDoesNotAllowAnyChanges_UpserterIsNeverCalled()
{
var settings = new Mock<IDbSettings>();
settings.SetupGet(f => f.AllowDynamicSchemaCreation).Returns(false);
settings.SetupGet(f => f.AllowDynamicSchemaUpdates).Returns(false);
var dbFake = new Mock<ISisoDatabase>();
dbFake.SetupGet(f => f.Settings).Returns(settings.Object);
var upserterFake = new Mock<IDbSchemaUpserter>();
var dbClientFake = CreateDbClientFake();
var manager = new DbSchemas(dbFake.Object, upserterFake.Object);
manager.Upsert(_structureSchema, dbClientFake.Object);
upserterFake.Verify(f => f.Upsert(_structureSchema, dbClientFake.Object, false, false), Times.Never());
}
[Test]
public void UpsertStructureSet_WhenDbSettingsAllowsCreationButNotUpdate_UpserterIsCalledOnce()
{
var settings = new Mock<IDbSettings>();
settings.SetupGet(f => f.AllowDynamicSchemaCreation).Returns(true);
settings.SetupGet(f => f.AllowDynamicSchemaUpdates).Returns(false);
var dbFake = new Mock<ISisoDatabase>();
dbFake.SetupGet(f => f.Settings).Returns(settings.Object);
var upserterFake = new Mock<IDbSchemaUpserter>();
var dbClientFake = CreateDbClientFake();
var manager = new DbSchemas(dbFake.Object, upserterFake.Object);
manager.Upsert(_structureSchema, dbClientFake.Object);
upserterFake.Verify(f => f.Upsert(_structureSchema, dbClientFake.Object, true, false), Times.Once());
}
[Test]
public void UpsertStructureSet_WhenDbSettingsAllowsUpdateButNotCreation_UpserterIsCalledOnce()
{
var settings = new Mock<IDbSettings>();
settings.SetupGet(f => f.AllowDynamicSchemaCreation).Returns(false);
settings.SetupGet(f => f.AllowDynamicSchemaUpdates).Returns(true);
var dbFake = new Mock<ISisoDatabase>();
dbFake.SetupGet(f => f.Settings).Returns(settings.Object);
var upserterFake = new Mock<IDbSchemaUpserter>();
var dbClientFake = CreateDbClientFake();
var manager = new DbSchemas(dbFake.Object, upserterFake.Object);
manager.Upsert(_structureSchema, dbClientFake.Object);
upserterFake.Verify(f => f.Upsert(_structureSchema, dbClientFake.Object, false, true), Times.Once());
}
[Test]
public void DropStructureSet_WhenCalledTwice_DropperIsCalledTwice()
{
var upserterFake = new Mock<IDbSchemaUpserter>();
var dbClientFake = CreateDbClientFake();
var manager = new DbSchemas(Mock.Of<ISisoDatabase>(), upserterFake.Object);
manager.Drop(_structureSchema, dbClientFake.Object);
manager.Drop(_structureSchema, dbClientFake.Object);
dbClientFake.Verify(f => f.Drop(_structureSchema), Times.Exactly(2));
}
private class Class_53966417_B25D_49E1_966B_58754110781C
{
public Guid StructureId { get; set; }
public string IndexableMember1 { get; set; }
public int IndexableMember2 { get; set; }
}
}
} |
using System;
using System.Linq;
using System.Linq.Expressions;
using CrmSystem.Domain;
using CrmSystem.Domain.Models;
using CrmSystem.Domain.Repositories;
using CrmSystem.EntityFramework.Repositories;
namespace CrmSystem.EntityFramework
{
public class UnitOfWork:IUnitOfWork
{
private CrmSystemContext _context;
public UnitOfWork(CrmSystemContext context)
{
_context = context;
Contacts = new ContactRepository(_context);
Employees = new EmployeeRepository(_context);
Products = new Repository<Product>(_context);
ContactTasks = new ContactTaskRepository(_context);
LeadSources = new Repository<LeadSource>(_context);
Contracts = new ContractRepository(_context);
Companies = new Repository<Company>(_context);
RequestedEmployees = new RequestedEmployeeRepository(_context);
ContactNotes = new ContactNoteRepository(_context);
ContractNotes = new ContractNoteRepository(_context);
TaskNotes = new TaskNoteRepository(_context);
Stages = new StageRepository(_context);
}
public void Dispose()
{
_context.Dispose();
}
public IContactRepository Contacts { get; }
public IEmployeeRepository Employees { get; }
public IContractRepository Contracts { get; }
public IRepository<Product> Products { get;}
public IContactTaskRepository ContactTasks { get; }
public IRepository<LeadSource> LeadSources { get; }
public IRepository<Company> Companies { get; }
public IRequestedEmployeeRepository RequestedEmployees { get; }
public IContactNoteRepository ContactNotes { get; }
public IContractNoteRepository ContractNotes { get; }
public ITaskNoteRepository TaskNotes { get; }
public IStageRepository Stages { get; }
//public void ExplicitLoading<TEntity2>(Expression<Func<TEntity2, bool>> predicate) where TEntity2 : class
//{
// _context.Set<TEntity2>().Where(predicate).Load();
//}
public void Save()
{
_context.SaveChanges();
}
}
} |
using Neutronium.BuildingBlocks.Application.ViewModels;
using Neutronium.SPA.ViewModel.Common;
namespace Neutronium.SPA.ViewModel
{
/// <summary>
/// ViewModel for the "about" route
/// </summary>
public class AboutViewModel
{
public ApplicationInformation Information => GlobalApplicationInformation.Information;
public string[] Descriptions { get; } =
{
Resource.About1,
Resource.About2,
Resource.About3
};
}
}
|
using System.Collections.Generic;
using EdFi.Security.DataAccess.Models;
namespace EdFi.Security.DataAccess.Caching
{
public class InstanceSecurityRepositoryCacheObject
{
public Application Application { get; }
public List<Action> Actions { get; }
public List<ClaimSet> ClaimSets { get; }
public List<ResourceClaim> ResourceClaims { get; }
public List<AuthorizationStrategy> AuthorizationStrategies { get; }
public List<ClaimSetResourceClaimAction> ClaimSetResourceClaimActions { get; }
public List<ResourceClaimAction> ResourceClaimActions { get; }
public InstanceSecurityRepositoryCacheObject(
Application application,
List<Action> actions,
List<ClaimSet> claimSets,
List<ResourceClaim> resourceClaims,
List<AuthorizationStrategy> authorizationStrategies,
List<ClaimSetResourceClaimAction> claimSetResourceClaimActions,
List<ResourceClaimAction> resourceClaimActions)
{
Application = application;
Actions = actions;
ClaimSets = claimSets;
ResourceClaims = resourceClaims;
AuthorizationStrategies = authorizationStrategies;
ClaimSetResourceClaimActions = claimSetResourceClaimActions;
ResourceClaimActions = resourceClaimActions;
}
}
} |
using System.Collections.Generic;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using Common.YamlDotNet;
using FluentValidation;
using TrashLib.Config;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
namespace Trash.Config;
public class ConfigurationLoader<T> : IConfigurationLoader<T>
where T : IServiceConfiguration
{
private readonly IConfigurationProvider _configProvider;
private readonly IDeserializer _deserializer;
private readonly IFileSystem _fileSystem;
private readonly IValidator<T> _validator;
public ConfigurationLoader(
IConfigurationProvider configProvider,
IFileSystem fileSystem,
IObjectFactory objectFactory,
IValidator<T> validator)
{
_configProvider = configProvider;
_fileSystem = fileSystem;
_validator = validator;
_deserializer = new DeserializerBuilder()
.IgnoreUnmatchedProperties()
.WithNamingConvention(UnderscoredNamingConvention.Instance)
.WithTypeConverter(new YamlNullableEnumTypeConverter())
.WithObjectFactory(objectFactory)
.Build();
}
public IEnumerable<T> Load(string propertyName, string configSection)
{
using var stream = _fileSystem.File.OpenText(propertyName);
return LoadFromStream(stream, configSection);
}
public IEnumerable<T> LoadFromStream(TextReader stream, string configSection)
{
var parser = new Parser(stream);
parser.Consume<StreamStart>();
parser.Consume<DocumentStart>();
parser.Consume<MappingStart>();
var validConfigs = new List<T>();
while (parser.TryConsume<Scalar>(out var key))
{
if (key.Value != configSection)
{
parser.SkipThisAndNestedEvents();
continue;
}
var configs = _deserializer.Deserialize<List<T>?>(parser);
if (configs == null)
{
parser.SkipThisAndNestedEvents();
continue;
}
ValidateConfigs(configSection, configs, validConfigs);
parser.SkipThisAndNestedEvents();
}
if (validConfigs.Count == 0)
{
throw new ConfigurationException(configSection, typeof(T), "There are no configured instances defined");
}
return validConfigs;
}
private void ValidateConfigs(string configSection, IEnumerable<T> configs, ICollection<T> validConfigs)
{
foreach (var config in configs)
{
var result = _validator.Validate(config);
if (result is {IsValid: false})
{
throw new ConfigurationException(configSection, typeof(T), result.Errors);
}
validConfigs.Add(config);
}
}
public IEnumerable<T> LoadMany(IEnumerable<string> configFiles, string configSection)
{
foreach (var config in configFiles.SelectMany(file => Load(file, configSection)))
{
_configProvider.ActiveConfiguration = config;
yield return config;
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
namespace AzureIoTEdgeModbus.Slave
{
public class WriteOperation : ModbusOperation
{
[JsonProperty(Required = Required.Always)]
public string HwId { get; set; }
[JsonProperty(Required = Required.Always)]
public float Value { get; set; }
[JsonIgnore]
public UInt16 IntValueToWrite { get; set; }
}
}
|
using Android.App;
using Java.Lang;
using Android.OS;
using Android.Content;
namespace AlarmDemo
{
[Activity(Label = "AlarmDemo", MainLauncher = true)]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
ScheduleAlarm(this);
}
public static void ScheduleAlarm(Context context)
{
Intent data = new Intent(context,
Class.FromType(typeof(MyBroadcastReceiver)));
PendingIntent intent = PendingIntent.GetBroadcast(context,
0,
data,
PendingIntentFlags.OneShot);
AlarmManager m = (AlarmManager)context.GetSystemService(Context.AlarmService);
m.Set(AlarmType.ElapsedRealtimeWakeup,
SystemClock.ElapsedRealtime() + 5000, intent);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpBasic.Basic
{
public class DateTimeDemo
{
public static void TestDemo()
{
TimeSpan ts = DateTime.Now - DateTime.Parse("2017/3/24 19:19:00");
DateTime tem = DateTime.Parse("2017-11-01");
string ss = tem.ToString("yyyyMMdd");
DateTime today = DateTime.Today;//当前日期{2016/9/14 0:00:00}
DateTime monthStart = today.AddDays(1 - today.Day); //月初
DateTime monthEnd = today.AddDays(1 - today.Day).AddMonths(1).AddDays(-1);//月末
DateTime preMonthStart = today.AddDays(1 - today.Day).AddMonths(-1);//上月初
DateTime preMonthEnd = today.AddDays(1 - today.Day).AddDays(-1); //上月末
DateTime nextMonthStart = today.AddDays(1 - today.Day).AddMonths(1); //下个月初
DateTime nextMonthEnd = today.AddDays(1 - today.Day).AddMonths(2).AddDays(-1); //下个月末
Console.WriteLine(monthStart.ToString() + "..." + nextMonthStart.ToString() + "..." + monthEnd.ToString());
Console.ReadLine();
}
/// <summary>
/// 取得某月的第一天
/// </summary>
/// <param name="datetime">要取得月份第一天的时间</param>
/// <returns></returns>
public static DateTime FirstDayOfMonth(DateTime datetime)
{
return datetime.AddDays(1 - datetime.Day);
}
/// <summary>
/// 取得某月的最后一天
/// </summary>
/// <param name="datetime">要取得月份最后一天的时间</param>
/// <returns></returns>
public static DateTime LastDayOfMonth(DateTime datetime)
{
return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
}
}
}
|
using System;
using System.Collections.ObjectModel;
using System.Linq;
using DasBlog.Tests.Support.Interfaces;
using Microsoft.Extensions.Logging;
namespace DasBlog.Tests.Support
{
public class BashScriptPlatform : IScriptPlatform
{
private ILogger<BashScriptPlatform> logger;
public BashScriptPlatform(ILogger<BashScriptPlatform> logger)
{
this.logger = logger;
}
/// <inheritdoc cref="IScriptPlatform"/>
public string GetCmdExe(bool suppressLog = false)
{
return "bash";
}
/// <inheritdoc cref="IScriptPlatform"/>
public string GetNameAndScriptSubDirectory(string scriptId)
{
return $"bash/{scriptId}.sh";
}
/// <inheritdoc cref="IScriptPlatform"/>
public string[] GetShellFlags()
{
return new [] {"-c"};
}
/// <inheritdoc cref="IScriptPlatform"/>
public void GatherArgsForPsi(Collection<string> psiArgumentList
, object[] shellFlags, string scriptPathAndName, object[] scriptArgs)
{
foreach (var arg in shellFlags)
{
psiArgumentList.Add((string)arg);
}
var shellArg = string.Join(" ", scriptArgs.Select(a => $"'{a}'"));
psiArgumentList.Add($"'{scriptPathAndName}' {shellArg}");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GenVarStorage : MonoBehaviour
{
// Save these numbers so you can pass them over
public int ChunkGridSize = 0;
public int ChunkSizeX = 0;
public int ChunkSizeZ = 0;
}
|
using DnsClient;
using Masuit.Tools.Config;
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
namespace Masuit.Tools.Core.Validator
{
/// <summary>
/// 邮箱校验
/// </summary>
public class IsEmailAttribute : ValidationAttribute
{
private readonly bool _valid;
/// <summary>
/// 域白名单
/// </summary>
private string WhiteList { get; }
/// <summary>
/// 域黑名单
/// </summary>
private string BlockList { get; }
/// <summary>
/// 可在配置文件AppSetting节中添加EmailDomainWhiteList配置邮箱域名白名单,EmailDomainBlockList配置邮箱域名黑名单,英文分号(;)或感叹号(!)或逗号(,)分隔,每个单独的元素支持正则表达式
/// </summary>
/// <param name="valid">是否检查邮箱的有效性</param>
public IsEmailAttribute(bool valid = true)
{
WhiteList = Regex.Replace(ConfigHelper.GetConfigOrDefault("EmailDomainWhiteList"), @"(\w)\.([a-z]+),?", @"$1\.$2!").Trim('!');
BlockList = Regex.Replace(ConfigHelper.GetConfigOrDefault("EmailDomainBlockList"), @"(\w)\.([a-z]+),?", @"$1\.$2!").Trim('!');
_valid = valid;
}
/// <summary>
/// 邮箱校验
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public override bool IsValid(object value)
{
if (value == null)
{
ErrorMessage = "邮箱不能为空!";
return false;
}
var email = (string)value;
if (email.Length < 7)
{
ErrorMessage = "您输入的邮箱格式不正确!";
return false;
}
if (email.Length > 256)
{
ErrorMessage = "您输入的邮箱无效,请使用真实有效的邮箱地址!";
return false;
}
if (!string.IsNullOrEmpty(BlockList) && BlockList.Split(new[] { '!', ';' }, StringSplitOptions.RemoveEmptyEntries).Any(item => Regex.IsMatch(email, item)))
{
ErrorMessage = "您输入的邮箱无效,请使用真实有效的邮箱地址!";
return false;
}
if (!string.IsNullOrEmpty(WhiteList) && WhiteList.Split('!').Any(item => Regex.IsMatch(email, item)))
{
return true;
}
var isMatch = email.MatchEmail().isMatch;
if (isMatch && _valid)
{
var nslookup = new LookupClient();
var records = nslookup.Query(email.Split('@')[1], QueryType.MX).Answers.MxRecords().ToList();
if (!string.IsNullOrEmpty(BlockList) && records.Any(r => BlockList.Split('!').Any(item => Regex.IsMatch(r.Exchange.Value, item))))
{
ErrorMessage = "您输入的邮箱无效,请使用真实有效的邮箱地址!";
return false;
}
var task = records.SelectAsync(r => Dns.GetHostAddressesAsync(r.Exchange.Value).ContinueWith(t =>
{
if (t.IsCanceled || t.IsFaulted)
{
return new[] { IPAddress.Loopback };
}
return t.Result;
}));
isMatch = task.Result.SelectMany(a => a).Any(ip => !ip.IsPrivateIP());
}
if (isMatch)
{
return true;
}
ErrorMessage = "您输入的邮箱格式不正确!";
return false;
}
}
} |
using clean.architecture.core.Entities;
using clean.architecture.core.SharedKernel;
using System;
using System.Collections.Generic;
using System.Text;
namespace clean.architecture.core.Events
{
public class ToDoItemCompletedEvent : BaseDomainEvent
{
private ToDoItem completedItem;
public ToDoItemCompletedEvent(ToDoItem item)
{
completedItem = item;
}
}
}
|
namespace MicroLite.Tests.Core
{
using System;
using System.Data;
using MicroLite.Core;
using MicroLite.Dialect;
using MicroLite.Driver;
using MicroLite.Listeners;
using MicroLite.Mapping;
using MicroLite.Tests.TestEntities;
using Moq;
using Xunit;
/// <summary>
/// Unit Tests for the <see cref="Session"/> class.
/// </summary>
public class SessionTests : UnitTest
{
[Fact]
public void AdvancedReturnsSameSessionByDifferentInterface()
{
var session = new Session(
ConnectionScope.PerTransaction,
new Mock<ISqlDialect>().Object,
new Mock<IDbDriver>().Object,
new SessionListeners());
var advancedSession = session.Advanced;
Assert.Same(session, advancedSession);
}
[Fact]
public void DeleteInstanceInvokesListeners()
{
var customer = new Customer
{
Id = 187224
};
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildDeleteSqlQuery(It.IsNotNull<IObjectInfo>(), customer.Id)).Returns(new SqlQuery(""));
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(1);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
int counter = 0;
var mockListener1 = new Mock<IDeleteListener>();
mockListener1.Setup(x => x.AfterDelete(customer, 1)).Callback(() => Assert.Equal(4, ++counter));
mockListener1.Setup(x => x.BeforeDelete(customer)).Callback(() => Assert.Equal(1, ++counter));
var mockListener2 = new Mock<IDeleteListener>();
mockListener2.Setup(x => x.AfterDelete(customer, 1)).Callback(() => Assert.Equal(3, ++counter));
mockListener2.Setup(x => x.BeforeDelete(customer)).Callback(() => Assert.Equal(2, ++counter));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners(
new[] { mockListener1.Object, mockListener2.Object },
new IInsertListener[0],
new IUpdateListener[0]));
session.DeleteAsync(customer).Wait();
mockListener1.VerifyAll();
mockListener2.VerifyAll();
}
[Fact]
public void DeleteInstanceReturnsFalseIfNoRecordsDeleted()
{
var customer = new Customer
{
Id = 14556
};
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildDeleteSqlQuery(It.IsNotNull<IObjectInfo>(), customer.Id)).Returns(new SqlQuery(""));
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(0);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
Assert.False(session.DeleteAsync(customer).Result);
mockSqlDialect.VerifyAll();
mockDbDriver.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void DeleteInstanceReturnsTrueIfRecordDeleted()
{
var customer = new Customer
{
Id = 14556
};
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildDeleteSqlQuery(It.IsNotNull<IObjectInfo>(), customer.Id)).Returns(new SqlQuery(""));
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(1);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
Assert.True(session.DeleteAsync(customer).Result);
mockSqlDialect.VerifyAll();
mockDbDriver.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void DeleteInstanceThrowsArgumentNullExceptionForNullInstance()
{
var session = new Session(
ConnectionScope.PerTransaction,
new Mock<ISqlDialect>().Object,
new Mock<IDbDriver>().Object,
new SessionListeners());
var exception = Assert.Throws<ArgumentNullException>(
() => session.DeleteAsync(null).Result);
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void DeleteInstanceThrowsMicroLiteExceptionIfExecuteNonQueryThrowsException()
{
var customer = new Customer
{
Id = 187224
};
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildDeleteSqlQuery(It.IsNotNull<IObjectInfo>(), customer.Id)).Returns(new SqlQuery(""));
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Throws<InvalidOperationException>();
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
var exception = Assert.Throws<AggregateException>(() => session.DeleteAsync(customer).Wait());
Assert.IsType<MicroLiteException>(exception.InnerException);
Assert.IsType<InvalidOperationException>(exception.InnerException.InnerException);
Assert.Equal(exception.InnerException.InnerException.Message, exception.InnerException.Message);
// Command should still be disposed.
mockCommand.VerifyAll();
}
[Fact]
public void DeleteInstanceThrowsMicroLiteExceptionIfIdentifierNotSet()
{
var customer = new Customer
{
Id = 0
};
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(new Mock<IDbCommand>().Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
var session = new Session(
ConnectionScope.PerTransaction,
new Mock<ISqlDialect>().Object,
mockDbDriver.Object,
new SessionListeners());
var exception = Assert.Throws<AggregateException>(
() => session.DeleteAsync(customer).Result);
Assert.IsType<MicroLiteException>(exception.InnerException);
Assert.Equal(ExceptionMessages.Session_IdentifierNotSetForDelete, exception.InnerException.Message);
}
[Fact]
public void DeleteInstanceThrowsObjectDisposedExceptionIfDisposed()
{
var session = new Session(
ConnectionScope.PerTransaction,
new Mock<ISqlDialect>().Object,
new Mock<IDbDriver>().Object,
new SessionListeners());
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.DeleteAsync(new Customer()).Result);
}
[Fact]
public void DeleteTypeByIdentifierReturnsFalseIfNoRecordsDeleted()
{
var type = typeof(Customer);
var identifier = 1234;
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildDeleteSqlQuery(It.IsNotNull<IObjectInfo>(), identifier)).Returns(new SqlQuery(""));
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(0);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
Assert.False(session.DeleteAsync(type, identifier).Result);
mockSqlDialect.VerifyAll();
mockDbDriver.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void DeleteTypeByIdentifierReturnsTrueIfRecordDeleted()
{
var type = typeof(Customer);
var identifier = 1234;
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildDeleteSqlQuery(It.IsNotNull<IObjectInfo>(), identifier)).Returns(new SqlQuery(""));
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(1);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
Assert.True(session.DeleteAsync(type, identifier).Result);
mockSqlDialect.VerifyAll();
mockDbDriver.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void DeleteTypeByIdentifierThrowsArgumentNullExceptionForNullIdentifier()
{
var session = new Session(
ConnectionScope.PerTransaction,
new Mock<ISqlDialect>().Object,
new Mock<IDbDriver>().Object,
new SessionListeners());
var exception = Assert.Throws<ArgumentNullException>(
() => session.DeleteAsync(typeof(Customer), null).Result);
Assert.Equal("identifier", exception.ParamName);
}
[Fact]
public void DeleteTypeByIdentifierThrowsArgumentNullExceptionForNullType()
{
var session = new Session(
ConnectionScope.PerTransaction,
new Mock<ISqlDialect>().Object,
new Mock<IDbDriver>().Object,
new SessionListeners());
var exception = Assert.Throws<ArgumentNullException>(
() => session.DeleteAsync(null, 1234).Result);
Assert.Equal("type", exception.ParamName);
}
[Fact]
public void DeleteTypeByIdentifierThrowsMicroLiteExceptionIfExecuteNonQueryThrowsException()
{
var type = typeof(Customer);
var identifier = 1234;
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildDeleteSqlQuery(It.IsNotNull<IObjectInfo>(), identifier)).Returns(new SqlQuery(""));
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Throws<InvalidOperationException>();
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
var exception = Assert.Throws<AggregateException>(() => session.DeleteAsync(type, identifier).Result);
Assert.IsType<MicroLiteException>(exception.InnerException);
Assert.IsType<InvalidOperationException>(exception.InnerException.InnerException);
Assert.Equal(exception.InnerException.InnerException.Message, exception.InnerException.Message);
// Command should still be disposed.
mockCommand.VerifyAll();
}
[Fact]
public void DeleteTypeByIdentifierThrowsObjectDisposedExceptionIfDisposed()
{
var session = new Session(
ConnectionScope.PerTransaction,
new Mock<ISqlDialect>().Object,
new Mock<IDbDriver>().Object,
new SessionListeners());
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.DeleteAsync(typeof(Customer), 1234).Result);
}
[Fact]
public void ExecuteBuildsAndExecutesCommandNotInTransaction()
{
var result = 1;
var mockSqlDialect = new Mock<ISqlDialect>();
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(result);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
Assert.Equal(result, session.ExecuteAsync(new SqlQuery("")).Result);
mockDbDriver.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void ExecuteScalarBuildsAndExecutesCommand()
{
var result = new object();
var mockSqlDialect = new Mock<ISqlDialect>();
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteScalar()).Returns(result);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
Assert.Equal(result, session.ExecuteScalarAsync<object>(new SqlQuery("")).Result);
mockDbDriver.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void ExecuteScalarThrowsArgumentNullExceptionForNullSqlQuery()
{
var session = new Session(
ConnectionScope.PerTransaction,
new Mock<ISqlDialect>().Object,
new Mock<IDbDriver>().Object,
new SessionListeners());
var exception = Assert.Throws<ArgumentNullException>(
() => session.ExecuteScalarAsync<object>(null).Result);
Assert.Equal("sqlQuery", exception.ParamName);
}
[Fact]
public void ExecuteScalarThrowsObjectDisposedExceptionIfDisposed()
{
var session = new Session(
ConnectionScope.PerTransaction,
new Mock<ISqlDialect>().Object,
new Mock<IDbDriver>().Object,
new SessionListeners());
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.ExecuteScalarAsync<int>(new SqlQuery("SELECT")).Result);
}
[Fact]
public void ExecuteScalarUsesTypeConvertersToResolveResultType()
{
var result = (byte)1;
var mockSqlDialect = new Mock<ISqlDialect>();
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteScalar()).Returns(result);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
Assert.Equal((CustomerStatus)result, session.ExecuteScalarAsync<CustomerStatus>(new SqlQuery("")).Result);
mockDbDriver.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void ExecuteThrowsArgumentNullExceptionForNullSqlQuery()
{
var session = new Session(
ConnectionScope.PerTransaction,
new Mock<ISqlDialect>().Object,
new Mock<IDbDriver>().Object,
new SessionListeners());
var exception = Assert.Throws<ArgumentNullException>(
() => session.ExecuteAsync(null).Result);
Assert.Equal("sqlQuery", exception.ParamName);
}
[Fact]
public void ExecuteThrowsObjectDisposedExceptionIfDisposed()
{
var session = new Session(
ConnectionScope.PerTransaction,
new Mock<ISqlDialect>().Object,
new Mock<IDbDriver>().Object,
new SessionListeners());
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.ExecuteAsync(new SqlQuery("SELECT")).Result);
}
[Fact]
public void InsertBuildsAndExecutesAnInsertCommandOnlyIfIdentifierStrategyAssigned()
{
ObjectInfo.MappingConvention = new ConventionMappingConvention(
UnitTest.GetConventionMappingSettings(IdentifierStrategy.Assigned));
var customer = new Customer
{
Id = 12345
};
var insertSqlQuery = new SqlQuery("INSERT");
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildInsertSqlQuery(It.IsNotNull<IObjectInfo>(), customer)).Returns(insertSqlQuery);
mockSqlDialect.Setup(x => x.SupportsSelectInsertedIdentifier).Returns(false);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(1);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
session.InsertAsync(customer).Wait();
mockSqlDialect.Verify(x => x.BuildInsertSqlQuery(It.IsNotNull<IObjectInfo>(), customer), Times.Once());
mockSqlDialect.Verify(x => x.BuildSelectInsertIdSqlQuery(It.IsAny<IObjectInfo>()), Times.Never());
mockDbDriver.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void InsertBuildsAndExecutesAnInsertCommandOnlyIfIdentifierStrategyNotAssignedAndSqlDialectDoesNotSupportSelectInsertedIdentifier()
{
ObjectInfo.MappingConvention = new ConventionMappingConvention(
UnitTest.GetConventionMappingSettings(IdentifierStrategy.DbGenerated));
var customer = new Customer();
var insertSqlQuery = new SqlQuery("INSERT");
object identifier = 23543;
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildInsertSqlQuery(It.IsNotNull<IObjectInfo>(), customer)).Returns(insertSqlQuery);
mockSqlDialect.Setup(x => x.SupportsSelectInsertedIdentifier).Returns(false);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteScalar()).Returns(identifier);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
session.InsertAsync(customer).Wait();
mockSqlDialect.Verify(x => x.BuildInsertSqlQuery(It.IsNotNull<IObjectInfo>(), customer), Times.Once());
mockSqlDialect.Verify(x => x.BuildSelectInsertIdSqlQuery(It.IsAny<IObjectInfo>()), Times.Never());
mockDbDriver.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void InsertBuildsAndExecutesCombinedCommandIfIdentifierStrategyNotAssignedAndSqlDialectSupportsSelectInsertedIdentifierAndDbDriverSupportsBatchedQueries()
{
ObjectInfo.MappingConvention = new ConventionMappingConvention(
UnitTest.GetConventionMappingSettings(IdentifierStrategy.DbGenerated));
var customer = new Customer();
var insertSqlQuery = new SqlQuery("INSERT");
var selectIdSqlQuery = new SqlQuery("SELECT");
var combinedSqlQuery = new SqlQuery("INSERT;SELECT");
object identifier = 23543;
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildInsertSqlQuery(It.IsNotNull<IObjectInfo>(), customer)).Returns(insertSqlQuery);
mockSqlDialect.Setup(x => x.BuildSelectInsertIdSqlQuery(It.IsNotNull<IObjectInfo>())).Returns(selectIdSqlQuery);
mockSqlDialect.Setup(x => x.SupportsSelectInsertedIdentifier).Returns(true);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteScalar()).Returns(identifier);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
mockDbDriver.Setup(x => x.SupportsBatchedQueries).Returns(true);
mockDbDriver.Setup(x => x.Combine(insertSqlQuery, selectIdSqlQuery)).Returns(combinedSqlQuery);
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
session.InsertAsync(customer).Wait();
mockSqlDialect.VerifyAll();
mockDbDriver.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void InsertBuildsAndExecutesIndividualCommandsIfIdentifierStrategyNotAssignedAndSqlDialectSupportsSelectInsertedIdentifierAndDbDriverDoesNotSupportBatchedQueries()
{
ObjectInfo.MappingConvention = new ConventionMappingConvention(
UnitTest.GetConventionMappingSettings(IdentifierStrategy.DbGenerated));
var customer = new Customer();
var insertSqlQuery = new SqlQuery("INSERT");
var selectIdSqlQuery = new SqlQuery("SELECT");
object identifier = 23543;
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildInsertSqlQuery(It.IsNotNull<IObjectInfo>(), customer)).Returns(insertSqlQuery);
mockSqlDialect.Setup(x => x.BuildSelectInsertIdSqlQuery(It.IsNotNull<IObjectInfo>())).Returns(selectIdSqlQuery);
mockSqlDialect.Setup(x => x.SupportsSelectInsertedIdentifier).Returns(true);
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery());
mockCommand.Setup(x => x.ExecuteScalar()).Returns(identifier);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
mockDbDriver.Setup(x => x.SupportsBatchedQueries).Returns(false);
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
session.InsertAsync(customer).Wait();
mockSqlDialect.VerifyAll();
mockDbDriver.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void InsertInvokesListeners()
{
var customer = new Customer();
object identifier = 23543;
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildInsertSqlQuery(It.IsNotNull<IObjectInfo>(), customer)).Returns(new SqlQuery(""));
mockSqlDialect.Setup(x => x.BuildSelectInsertIdSqlQuery(It.IsNotNull<IObjectInfo>())).Returns(new SqlQuery(""));
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteScalar()).Returns(identifier);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
int counter = 0;
var mockListener1 = new Mock<IInsertListener>();
mockListener1.Setup(x => x.AfterInsert(customer, identifier)).Callback(() => Assert.Equal(4, ++counter));
mockListener1.Setup(x => x.BeforeInsert(customer)).Callback(() => Assert.Equal(1, ++counter));
var mockListener2 = new Mock<IInsertListener>();
mockListener2.Setup(x => x.AfterInsert(customer, identifier)).Callback(() => Assert.Equal(3, ++counter));
mockListener2.Setup(x => x.BeforeInsert(customer)).Callback(() => Assert.Equal(2, ++counter));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners(
new IDeleteListener[0],
new[] { mockListener1.Object, mockListener2.Object },
new IUpdateListener[0]));
session.InsertAsync(customer).Wait();
mockListener1.VerifyAll();
mockListener2.VerifyAll();
}
[Fact]
public void InsertThrowsArgumentNullExceptionForNullInstance()
{
var session = new Session(
ConnectionScope.PerTransaction,
new Mock<ISqlDialect>().Object,
new Mock<IDbDriver>().Object,
new SessionListeners());
var exception = Assert.Throws<ArgumentNullException>(
() => session.InsertAsync(null).Wait());
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void InsertThrowsMicroLiteExceptionIfExecuteScalarThrowsException()
{
var customer = new Customer();
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildInsertSqlQuery(It.IsNotNull<IObjectInfo>(), customer)).Returns(new SqlQuery(""));
mockSqlDialect.Setup(x => x.BuildSelectInsertIdSqlQuery(It.IsNotNull<IObjectInfo>())).Returns(new SqlQuery(""));
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteScalar()).Throws<InvalidOperationException>();
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
var exception = Assert.Throws<AggregateException>(() => session.InsertAsync(customer).Wait());
Assert.IsType<MicroLiteException>(exception.InnerException);
Assert.IsType<InvalidOperationException>(exception.InnerException.InnerException);
Assert.Equal(exception.InnerException.InnerException.Message, exception.InnerException.Message);
// Command should still be disposed.
mockCommand.VerifyAll();
}
[Fact]
public void InsertThrowsObjectDisposedExceptionIfDisposed()
{
var session = new Session(
ConnectionScope.PerTransaction,
new Mock<ISqlDialect>().Object,
new Mock<IDbDriver>().Object,
new SessionListeners());
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.InsertAsync(new Customer()).Wait());
}
[Fact]
public void UpdateInstanceBuildsAndExecutesQuery()
{
var customer = new Customer
{
Id = 187224
};
var rowsAffected = 1;
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildUpdateSqlQuery(It.IsNotNull<IObjectInfo>(), customer)).Returns(new SqlQuery(""));
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(rowsAffected);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
session.UpdateAsync(customer).Wait();
mockSqlDialect.VerifyAll();
mockDbDriver.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void UpdateInstanceInvokesListeners()
{
var customer = new Customer
{
Id = 187224
};
var rowsAffected = 1;
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildUpdateSqlQuery(It.IsNotNull<IObjectInfo>(), customer)).Returns(new SqlQuery(""));
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(rowsAffected);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
int counter = 0;
var mockListener1 = new Mock<IUpdateListener>();
mockListener1.Setup(x => x.AfterUpdate(customer, 1)).Callback(() => Assert.Equal(4, ++counter));
mockListener1.Setup(x => x.BeforeUpdate(customer)).Callback(() => Assert.Equal(1, ++counter));
var mockListener2 = new Mock<IUpdateListener>();
mockListener2.Setup(x => x.AfterUpdate(customer, 1)).Callback(() => Assert.Equal(3, ++counter));
mockListener2.Setup(x => x.BeforeUpdate(customer)).Callback(() => Assert.Equal(2, ++counter));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners(
new IDeleteListener[0],
new IInsertListener[0],
new[] { mockListener1.Object, mockListener2.Object }));
session.UpdateAsync(customer).Wait();
mockListener1.VerifyAll();
mockListener2.VerifyAll();
}
[Fact]
public void UpdateInstanceReturnsFalseIfNoRecordsUpdated()
{
var customer = new Customer
{
Id = 187224
};
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildUpdateSqlQuery(It.IsNotNull<IObjectInfo>(), customer)).Returns(new SqlQuery(""));
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(0);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
Assert.False(session.UpdateAsync(customer).Result);
mockSqlDialect.VerifyAll();
mockDbDriver.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void UpdateInstanceReturnsTrueIfRecordUpdated()
{
var customer = new Customer
{
Id = 187224
};
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildUpdateSqlQuery(It.IsNotNull<IObjectInfo>(), customer)).Returns(new SqlQuery(""));
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(1);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
Assert.True(session.UpdateAsync(customer).Result);
mockSqlDialect.VerifyAll();
mockDbDriver.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void UpdateInstanceThrowsArgumentNullExceptionForNullInstance()
{
var session = new Session(
ConnectionScope.PerTransaction,
new Mock<ISqlDialect>().Object,
new Mock<IDbDriver>().Object,
new SessionListeners());
var exception = Assert.Throws<ArgumentNullException>(
() => session.UpdateAsync((Customer)null).Result);
Assert.Equal("instance", exception.ParamName);
}
[Fact]
public void UpdateInstanceThrowsMicroLiteExceptionIfExecuteNonQueryThrowsException()
{
var customer = new Customer
{
Id = 187224
};
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildUpdateSqlQuery(It.IsNotNull<IObjectInfo>(), customer)).Returns(new SqlQuery(""));
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Throws<InvalidOperationException>();
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
var exception = Assert.Throws<AggregateException>(() => session.UpdateAsync(customer).Wait());
Assert.IsType<MicroLiteException>(exception.InnerException);
Assert.IsType<InvalidOperationException>(exception.InnerException.InnerException);
Assert.Equal(exception.InnerException.InnerException.Message, exception.InnerException.Message);
// Command should still be disposed.
mockCommand.VerifyAll();
}
[Fact]
public void UpdateInstanceThrowsMicroLiteExceptionIfIdentifierNotSet()
{
var customer = new Customer
{
Id = 0
};
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(new Mock<IDbConnection>().Object));
var session = new Session(
ConnectionScope.PerTransaction,
new Mock<ISqlDialect>().Object,
mockDbDriver.Object,
new SessionListeners());
var exception = Assert.Throws<AggregateException>(() => session.UpdateAsync(customer).Wait());
Assert.IsType<MicroLiteException>(exception.InnerException);
Assert.Equal(ExceptionMessages.Session_IdentifierNotSetForUpdate, exception.InnerException.Message);
}
[Fact]
public void UpdateInstanceThrowsObjectDisposedExceptionIfDisposed()
{
var session = new Session(
ConnectionScope.PerTransaction,
new Mock<ISqlDialect>().Object,
new Mock<IDbDriver>().Object,
new SessionListeners());
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.UpdateAsync(new Customer()).Result);
}
[Fact]
public void UpdateObjectDeltaReturnsFalseIfNoRecordUpdated()
{
var objectDelta = new ObjectDelta(typeof(Customer), 1234);
objectDelta.AddChange("Name", "Fred Flintstone");
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildUpdateSqlQuery(objectDelta)).Returns(new SqlQuery(""));
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(0);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
Assert.False(session.UpdateAsync(objectDelta).Result);
mockDbDriver.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void UpdateObjectDeltaReturnsTrueIfRecordUpdated()
{
var objectDelta = new ObjectDelta(typeof(Customer), 1234);
objectDelta.AddChange("Name", "Fred Flintstone");
var mockSqlDialect = new Mock<ISqlDialect>();
mockSqlDialect.Setup(x => x.BuildUpdateSqlQuery(objectDelta)).Returns(new SqlQuery(""));
var mockCommand = new Mock<IDbCommand>();
mockCommand.Setup(x => x.ExecuteNonQuery()).Returns(1);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var mockDbDriver = new Mock<IDbDriver>();
mockDbDriver.Setup(x => x.CreateConnection()).Returns(new MockDbConnectionWrapper(mockConnection.Object));
var session = new Session(
ConnectionScope.PerTransaction,
mockSqlDialect.Object,
mockDbDriver.Object,
new SessionListeners());
Assert.True(session.UpdateAsync(objectDelta).Result);
mockDbDriver.VerifyAll();
mockCommand.VerifyAll();
}
[Fact]
public void UpdateObjectDeltaThrowsArgumentNullExceptionForNullObjectDelta()
{
var session = new Session(
ConnectionScope.PerTransaction,
new Mock<ISqlDialect>().Object,
new Mock<IDbDriver>().Object,
new SessionListeners());
var exception = Assert.Throws<ArgumentNullException>(
() => session.UpdateAsync(default(ObjectDelta)).Result);
Assert.Equal("objectDelta", exception.ParamName);
}
[Fact]
public void UpdateObjectDeltaThrowsMicroLiteExceptionIfItContainsNoChanges()
{
var objectDelta = new ObjectDelta(typeof(Customer), 1234);
var session = new Session(
ConnectionScope.PerTransaction,
new Mock<ISqlDialect>().Object,
new Mock<IDbDriver>().Object,
new SessionListeners());
var exception = Assert.Throws<MicroLiteException>(() => session.UpdateAsync(objectDelta).Result);
Assert.Equal(ExceptionMessages.ObjectDelta_MustContainAtLeastOneChange, exception.Message);
}
[Fact]
public void UpdateObjectDeltaThrowsObjectDisposedExceptionIfDisposed()
{
var session = new Session(
ConnectionScope.PerTransaction,
new Mock<ISqlDialect>().Object,
new Mock<IDbDriver>().Object,
new SessionListeners());
using (session)
{
}
Assert.Throws<ObjectDisposedException>(() => session.UpdateAsync(new ObjectDelta(typeof(Customer), 1234)).Result);
}
}
}
|
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ICSharpCode.SharpZipLib.Zip.Compression;
using Wabbajack.Common;
using Wabbajack.DTOs.BSA.FileStates;
using Wabbajack.DTOs.Streams;
using Wabbajack.Paths;
namespace Wabbajack.Compression.BSA.FO4Archive;
public class FileEntry : IBA2FileEntry
{
internal uint _align;
internal Reader _bsa;
internal uint _dirHash;
internal string _extension;
internal uint _flags;
internal int _index;
internal uint _nameHash;
internal ulong _offset;
internal uint _realSize;
internal uint _size;
public FileEntry(Reader ba2Reader, int index)
{
_index = index;
_bsa = ba2Reader;
var _rdr = ba2Reader._rdr;
_nameHash = _rdr.ReadUInt32();
FullPath = _nameHash.ToString("X");
_extension = Encoding.UTF8.GetString(_rdr.ReadBytes(4));
_dirHash = _rdr.ReadUInt32();
_flags = _rdr.ReadUInt32();
_offset = _rdr.ReadUInt64();
_size = _rdr.ReadUInt32();
_realSize = _rdr.ReadUInt32();
_align = _rdr.ReadUInt32();
}
public bool Compressed => _size != 0;
public string FullPath { get; set; }
public RelativePath Path => FullPath.ToRelativePath();
public uint Size => _realSize;
public AFile State => new BA2File
{
NameHash = _nameHash,
DirHash = _dirHash,
Flags = _flags,
Align = _align,
Compressed = Compressed,
Path = Path,
Extension = _extension,
Index = _index
};
public async ValueTask CopyDataTo(Stream output, CancellationToken token)
{
await using var fs = await _bsa._streamFactory.GetStream();
fs.Seek((long) _offset, SeekOrigin.Begin);
var len = Compressed ? _size : _realSize;
var bytes = new byte[len];
await fs.ReadAsync(bytes.AsMemory(0, (int) len), token);
if (!Compressed)
{
await output.WriteAsync(bytes, token);
}
else
{
var uncompressed = new byte[_realSize];
var inflater = new Inflater();
inflater.SetInput(bytes);
inflater.Inflate(uncompressed);
await output.WriteAsync(uncompressed, token);
}
await output.FlushAsync(token);
}
public async ValueTask<IStreamFactory> GetStreamFactory(CancellationToken token)
{
var ms = new MemoryStream();
await CopyDataTo(ms, token);
ms.Position = 0;
return new MemoryStreamFactory(ms, Path, _bsa._streamFactory.LastModifiedUtc);
}
} |
namespace LostTech.IO.Links {
using System.Runtime.InteropServices;
public static class Symlink {
static readonly IFileSystemLinks Impl =
RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? (IFileSystemLinks)new WindowsLinks()
: new UnixLinks();
/// <summary>
/// Create a symbolic link, pointing to the specified directory
/// </summary>
/// <param name="directoryPath">Which directory the symlink will point to</param>
/// <param name="symlink">Where the symlink will be created</param>
public static void CreateForDirectory(string directoryPath, string symlink)
=> Impl.CreateDirectorySymlink(symlink: symlink, pointingTo: directoryPath);
/// <summary>
/// Create a symbolic link, pointing to the specified file
/// </summary>
/// <param name="filePath">Which file the symlink will point to</param>
/// <param name="symlink">Where the symlink will be created</param>
public static void CreateForFile(string filePath, string symlink)
=> Impl.CreateFileSymlink(symlink: symlink, pointingTo: filePath);
}
}
|
namespace BoatRacingSimulator.Controllers
{
using System;
using System.Collections.Generic;
using Contracts;
using Enumerations;
using Utility;
public class CommandHandler : ICommandHandler
{
public CommandHandler()
: this(new BoatSimulatorController())
{
}
public CommandHandler(IBoatSimulatorController controller)
{
this.Controller = controller;
}
public IBoatSimulatorController Controller { get; private set; }
public string ExecuteCommand(string name, string[] parameters)
{
switch (name)
{
case "CreateBoatEngine":
return this.CreateBoatEngine(parameters);
case "CreateSailBoat":
return this.CreateSailBoat(parameters);
case "CreatePowerBoat":
return this.CreatePowerBoat(parameters);
case "CreateRowBoat":
return this.CreateRowBoat(parameters);
case "CreateYacht":
return this.CreateYaht(parameters);
case "OpenRace":
return this.OpenRace(parameters);
case "SignUpBoat":
return this.Controller.SignUpBoat(parameters[0]);
case "StartRace":
return this.Controller.StartRace();
case "GetStatistic":
return this.Controller.GetStatistic();
default:
throw new InvalidOperationException();
}
}
private string CreateBoatEngine(IReadOnlyList<string> parameters)
{
if (Enum.TryParse(parameters[3], out EngineType engineType))
{
return this.Controller.CreateBoatEngine(
parameters[0],
int.Parse(parameters[1]),
int.Parse(parameters[2]),
engineType);
}
throw new ArgumentException(Constants.IncorrectEngineTypeMessage);
}
private string CreateSailBoat(IReadOnlyList<string> parameters)
{
return this.Controller.CreateSailBoat(
parameters[0],
int.Parse(parameters[1]),
int.Parse(parameters[2]));
}
private string CreatePowerBoat(IReadOnlyList<string> parameters)
{
return this.Controller.CreatePowerBoat(
parameters[0],
int.Parse(parameters[1]),
parameters[2],
parameters[3]);
}
private string CreateRowBoat(IReadOnlyList<string> parameters)
{
return this.Controller.CreateRowBoat(
parameters[0],
int.Parse(parameters[1]),
int.Parse(parameters[2]));
}
private string CreateYaht(IReadOnlyList<string> parameters)
{
return this.Controller.CreateYacht(
parameters[0],
int.Parse(parameters[1]),
parameters[2],
int.Parse(parameters[3]));
}
private string OpenRace(IReadOnlyList<string> parameters)
{
return this.Controller.OpenRace(
int.Parse(parameters[0]),
int.Parse(parameters[1]),
int.Parse(parameters[2]),
bool.Parse(parameters[3]));
}
}
} |
using System.Collections.Generic;
using System.Reflection;
namespace Spencer.NET
{
public interface IConstructorInvoker
{
object InvokeConstructor(ConstructorInfo constructor, IEnumerable<object> parameters);
object InvokeConstructor(IConstructor constructor, IEnumerable<object> parameters);
}
} |
using System.Runtime.InteropServices;
namespace WebView2WrapperWpfTest
{
[ComVisible(true)]
public class TestObject
{
public string Name { get; set; }
public int GetStringLen()
{
return this.Name.Length;
}
public string GetValue(string input)
{
this.Name += input;
return this.Name;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using d60.Cirqus.Aggregates;
using d60.Cirqus.Config;
using d60.Cirqus.Events;
using d60.Cirqus.Serialization;
using d60.Cirqus.Testing.Internals;
using d60.Cirqus.Views;
using d60.Cirqus.Views.ViewManagers;
using Moq;
using NUnit.Framework;
namespace d60.Cirqus.Tests.Bugs
{
[TestFixture]
public class VerifyThatMaxDomainEventsPrBatchHasAValidValue : FixtureBase
{
[Test]
public void WhenCreatingADependantViewDispatcherThenMaxValueIsNotZeroOrLess()
{
//arrange
var viewManager1 = new Mock<IViewManager>().Object;
var viewManager2 = new Mock<IViewManager>().Object;
var domainSerializer = new Mock<IDomainEventSerializer>().Object;
var eventStore = new InMemoryEventStore();
var aggregateRootRepo = new Mock<IAggregateRootRepository>().Object;
var domainTypemapper = new Mock<IDomainTypeNameMapper>().Object;
//act
var sut = new DependentViewManagerEventDispatcher(new[] { viewManager1 }, new[] { viewManager2 }, eventStore,
domainSerializer, aggregateRootRepo, domainTypemapper, null);
//assert
Assert.IsTrue(sut.MaxDomainEventsPerBatch >= 1);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using System.Xml;
using DigitalPlatform;
using DigitalPlatform.CirculationClient;
using DigitalPlatform.CommonControl;
using DigitalPlatform.LibraryClient;
using DigitalPlatform.LibraryClient.localhost;
using DigitalPlatform.LibraryServer;
using DigitalPlatform.RFID;
using DigitalPlatform.Text;
using DigitalPlatform.Xml;
namespace dp2Circulation
{
/// <summary>
/// MainForm 有关 RFID 的功能
/// </summary>
public partial class MainForm
{
public static bool GetOwnerInstitution(
XmlDocument cfg_dom,
string strLocation,
out string isil,
out string alternative)
{
isil = "";
alternative = "";
if (cfg_dom == null)
return false;
return LibraryServerUtil.GetOwnerInstitution(
cfg_dom.DocumentElement,
strLocation,
out isil,
out alternative);
}
#if REMOVED
/*
<rfid>
<ownerInstitution>
<item map="海淀分馆/" isil="test" />
<item map="西城/" alternative="xc" />
</ownerInstitution>
</rfid>
map 为 "/" 或者 "/阅览室" 可以匹配 "图书总库" "阅览室" 这样的 strLocation
map 为 "海淀分馆/" 可以匹配 "海淀分馆/" "海淀分馆/阅览室" 这样的 strLocation
最好单元测试一下这个函数
* */
// parameters:
// cfg_dom 根元素是 rfid
// strLocation 纯净的 location 元素内容。
// isil [out] 返回 ISIL 形态的代码
// alternative [out] 返回其他形态的代码
// return:
// true 找到。信息在 isil 和 alternative 参数里面返回
// false 没有找到
public static bool GetOwnerInstitution(
XmlDocument cfg_dom,
string strLocation,
out string isil,
out string alternative)
{
isil = "";
alternative = "";
if (cfg_dom == null)
return false;
if (strLocation != null
&& strLocation.IndexOfAny(new char[] { '*', '?' }) != -1)
throw new ArgumentException($"参数 {nameof(strLocation)} 值({strLocation})中不应包含字符 '*' '?'", nameof(strLocation));
// 分析 strLocation 是否属于总馆形态,比如“阅览室”
// 如果是总馆形态,则要在前部增加一个 / 字符,以保证可以正确匹配 map 值
// ‘/’字符可以理解为在馆代码和阅览室名字之间插入的一个必要的符号。这是为了弥补早期做法的兼容性问题
Global.ParseCalendarName(strLocation,
out string strLibraryCode,
out string strRoom);
if (string.IsNullOrEmpty(strLibraryCode))
strLocation = "/" + strRoom;
XmlNodeList items = cfg_dom.DocumentElement.SelectNodes(
"ownerInstitution/item");
List<HitItem> results = new List<HitItem>();
foreach (XmlElement item in items)
{
string map = item.GetAttribute("map");
if (StringUtil.RegexCompare(GetRegex(map), strLocation))
// if (strLocation.StartsWith(map))
{
HitItem hit = new HitItem { Map = map, Element = item };
results.Add(hit);
}
}
if (results.Count == 0)
return false;
// 如果命中多个,要选出 map 最长的那一个返回
// 排序,大在前
if (results.Count > 0)
results.Sort((a, b) => { return b.Map.Length - a.Map.Length; });
var element = results[0].Element;
isil = element.GetAttribute("isil");
alternative = element.GetAttribute("alternative");
// 2021/2/1
if (string.IsNullOrEmpty(isil) && string.IsNullOrEmpty(alternative))
{
throw new Exception($"map 元素不合法,isil 和 alternative 属性均为空");
}
return true;
#if NO
foreach (XmlElement item in items)
{
string map = item.GetAttribute("map");
if (strLocation.StartsWith(map))
{
isil = item.GetAttribute("isil");
alternative = item.GetAttribute("alternative");
return true;
}
}
#endif
return false;
}
class HitItem
{
public XmlElement Element { get; set; }
public string Map { get; set; }
}
static string GetRegex(string pattern)
{
if (pattern == null)
pattern = "";
if (pattern.Length > 0 && pattern[pattern.Length - 1] != '*')
pattern += "*";
return "^" + Regex.Escape(pattern)
.Replace(@"\*", ".*")
.Replace(@"\?", ".")
+ "$";
}
#endif
// 从册记录的卷册信息字符串中,获得符合 RFID 标准的 SetInformation 信息
public static string GetSetInformation(string strVolume)
{
if (strVolume.IndexOf("(") == -1)
return null;
int offs = strVolume.IndexOf("(");
if (offs == -1)
return null;
strVolume = strVolume.Substring(offs + 1).Trim();
offs = strVolume.IndexOf(")");
if (offs != -1)
strVolume = strVolume.Substring(0, offs).Trim();
strVolume = StringUtil.Unquote(strVolume, "()");
offs = strVolume.IndexOf(",");
if (offs == -1)
return null;
List<string> parts = StringUtil.ParseTwoPart(strVolume, ",");
// 2 4 6 字符
string left = parts[0].Trim(' ').TrimStart('0');
string right = parts[1].Trim(' ').TrimStart('0');
if (StringUtil.IsNumber(left) == false
|| StringUtil.IsNumber(right) == false)
return null;
// 看值是否超过 0-255
if (int.TryParse(left, out int v) == false)
return null;
if (v < 0 || v > 255)
return null;
if (int.TryParse(right, out v) == false)
return null;
if (v < 0 || v > 255)
return null;
int max_length = Math.Max(left.Length, right.Length);
if (max_length == 0 || max_length > 3)
return null;
return left.PadLeft(max_length, '0') + right.PadLeft(max_length, '0');
}
#region 独立线程写入统计日志
public class StatisLog
{
public BookItem BookItem { get; set; }
public string ReaderName { get; set; }
public TagInfo NewTagInfo { get; set; }
public string Xml { get; set; }
// 写入出错次数
public int ErrorCount { get; set; }
}
static object _lockStatis = new object();
static List<StatisLog> _statisLogs = new List<StatisLog>();
void StartStatisLogWorker(CancellationToken token)
{
bool _hide_dialog = false;
int _hide_dialog_count = 0;
_ = Task.Factory.StartNew(async () =>
{
await WriteStatisLogsAsync(token,
(c, m, buttons, sec) =>
{
DialogResult result = DialogResult.Yes;
if (_hide_dialog == false)
{
this.Invoke((Action)(() =>
{
result = MessageDialog.Show(this,
m,
MessageBoxButtons.YesNoCancel,
MessageBoxDefaultButton.Button1,
"此后不再出现本对话框",
ref _hide_dialog,
buttons,
sec);
}));
_hide_dialog_count = 0;
}
else
{
_hide_dialog_count++;
if (_hide_dialog_count > 10)
_hide_dialog = false;
}
if (result == DialogResult.Yes)
return buttons[0];
else if (result == DialogResult.No)
return buttons[1];
return buttons[2];
}
);
},
token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
}
// TODO: 退出 MainForm 的时候,如果发现有没有来得及写入的事项,要写入临时文件,等下载启动时候重新装入队列
// 循环写入统计日志的过程
async Task WriteStatisLogsAsync(CancellationToken token,
LibraryChannelExtension.delegate_prompt prompt)
{
// TODO: 需要捕获异常,写入错误日志
try
{
while (token.IsCancellationRequested == false)
{
List<StatisLog> error_items = new List<StatisLog>();
// 循环过程不怕 _statisLogs 数组后面被追加新内容
int count = _statisLogs.Count;
for (int i = 0; i < count; i++)
{
var log = _statisLogs[i];
Program.MainForm.OperHistory.AppendHtml($"<div class='debug recpath'>写册 '{HttpUtility.HtmlEncode(log.BookItem.Barcode)}' 的 RFID 标签,记入统计日志</div>");
// parameters:
// prompt_action [out] 重试/中断
// return:
// -2 UID 已经存在
// -1 出错。注意 prompt_action 中有返回值,表明已经提示和得到了用户反馈
// 其他 成功
int nRet = WriteStatisLog("sender",
"subject",
log.Xml,
prompt,
out string prompt_action,
out string strError);
if (nRet == -2)
{
// 如果 UID 重复了,跳过这一条
_statisLogs.RemoveAt(i);
i--;
Program.MainForm.OperHistory.AppendHtml($"<div class='debug error'>{HttpUtility.HtmlEncode(strError)}</div>");
continue;
}
else if (nRet == -1)
{
if (prompt_action == "skip" || prompt_action == "取消")
{
// 跳过这一条
_statisLogs.RemoveAt(i);
i--;
Program.MainForm.OperHistory.AppendHtml($"<div class='debug error'>遇到错误 {HttpUtility.HtmlEncode(strError)} 后用户选择跳过</div>");
continue;
}
log.ErrorCount++;
error_items.Add(log);
// this.ShowMessage(strError, "red", true);
// TODO: 输出到操作历史
Program.MainForm.OperHistory.AppendHtml($"<div class='debug error'>{HttpUtility.HtmlEncode(strError)}</div>");
}
else
Program.MainForm.OperHistory.AppendHtml($"<div class='debug green'>写入成功</div>");
}
lock (_lockStatis)
{
_statisLogs.RemoveRange(0, count);
_statisLogs.AddRange(error_items); // 准备重做
}
if (error_items.Count > 0)
await Task.Delay(TimeSpan.FromMinutes(1), token);
else
await Task.Delay(500, token);
}
}
catch(TaskCanceledException)
{
}
catch (Exception ex)
{
// this.ShowMessage($"后台线程出现异常: {ex.Message}", "red", true);
Program.MainForm.OperHistory.AppendHtml($"<div class='debug error'>{HttpUtility.HtmlEncode($"RFID 统计日志后台线程出现异常: {ex.Message}")}</div>");
WriteErrorLog($"RFID 统计日志后台线程出现异常: {ExceptionUtil.GetDebugText(ex)}");
/*
this.Invoke((Action)(() =>
{
this.Enabled = false; // 禁用界面,迫使操作者关闭窗口重新打开
}));
*/
}
}
public static void AddWritingLog(StatisLog log)
{
XmlDocument dom = new XmlDocument();
dom.LoadXml("<root />");
DomUtil.SetElementText(dom.DocumentElement,
"action", "writeRfidTag");
DomUtil.SetElementText(dom.DocumentElement,
"uid", Guid.NewGuid().ToString());
DomUtil.SetElementText(dom.DocumentElement,
"type", "item");
DomUtil.SetElementText(dom.DocumentElement,
"itemBarcode", log.BookItem.Barcode);
DomUtil.SetElementText(dom.DocumentElement,
"itemLocation", log.BookItem.Location);
// 2019/6/28
DomUtil.SetElementText(dom.DocumentElement,
"itemRefID", log.BookItem.RefID);
DomUtil.SetElementText(dom.DocumentElement,
"tagProtocol", "ISO15693");
DomUtil.SetElementText(dom.DocumentElement,
"tagReaderName", log.ReaderName);
DomUtil.SetElementText(dom.DocumentElement,
"tagAFI", Element.GetHexString(log.NewTagInfo.AFI));
DomUtil.SetElementText(dom.DocumentElement,
"tagBlockSize", log.NewTagInfo.BlockSize.ToString());
DomUtil.SetElementText(dom.DocumentElement,
"tagMaxBlockCount", log.NewTagInfo.MaxBlockCount.ToString());
DomUtil.SetElementText(dom.DocumentElement,
"tagDSFID", Element.GetHexString(log.NewTagInfo.DSFID));
DomUtil.SetElementText(dom.DocumentElement,
"tagUID", log.NewTagInfo.UID);
DomUtil.SetElementText(dom.DocumentElement,
"tagBytes", Convert.ToBase64String(log.NewTagInfo.Bytes));
log.Xml = dom.OuterXml;
lock (_lockStatis)
{
_statisLogs.Add(log);
}
}
// 写入统计日志
// parameters:
// prompt_action [out] 重试/取消
// return:
// -2 UID 已经存在
// -1 出错。注意 prompt_action 中有返回值,表明已经提示和得到了用户反馈
// 其他 成功
public int WriteStatisLog(
string strSender,
string strSubject,
string strXml,
LibraryChannelExtension.delegate_prompt prompt,
out string prompt_action,
out string strError)
{
prompt_action = "";
strError = "";
LibraryChannel channel = this.GetChannel();
try
{
var message = new MessageData
{
strRecipient = "!statis",
strSender = strSender,
strSubject = strSubject,
strMime = "text/xml",
strBody = strXml
};
MessageData[] messages = new MessageData[]
{
message
};
REDO:
long lRet = channel.SetMessage(
"send",
"",
messages,
out MessageData[] output_messages,
out strError);
if (lRet == -1)
{
// 不使用 prompt
if (channel.ErrorCode == ErrorCode.AlreadyExist)
return -2;
if (prompt == null)
return -1;
// TODO: 遇到出错,提示人工介入处理
if (prompt != null)
{
var result = prompt(channel,
strError + "\r\n\r\n(重试) 重试写入; (取消) 取消写入",
new string[] { "重试", "取消" },
10);
if (result == "重试")
goto REDO;
prompt_action = result;
return -1;
}
}
return (int)lRet;
}
finally
{
this.ReturnChannel(channel);
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace MDBX
{
using Interop;
[Flags]
public enum CursorDelOption : int
{
Unspecific = 0,
/// <summary>
/// Enter the new key/data pair only if it does not already appear in the
/// database. This flag may only be specified if the database was opened
/// with MDBX_DUPSORT. The function will return MDBX_KEYEXIST if the
/// key/data pair already appears in the database.
/// </summary>
NoDupData = Constant.MDBX_NODUPDATA,
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using Azure.Storage.Blobs;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using NUnit.Framework;
namespace Azure.AspNetCore.DataProtection.Blobs.Tests
{
public class AzureDataProtectionBuilderExtensionsTest
{
[Test]
public void PersistKeysToAzureBlobStorage_UsesAzureBlobXmlRepository()
{
// Arrange
var client = new BlobClient(new Uri("http://www.example.com"));
var serviceCollection = new ServiceCollection();
var builder = serviceCollection.AddDataProtection();
// Act
builder.PersistKeysToAzureBlobStorage(client);
var services = serviceCollection.BuildServiceProvider();
// Assert
var options = services.GetRequiredService<IOptions<KeyManagementOptions>>();
Assert.IsInstanceOf<AzureBlobXmlRepository>(options.Value.XmlRepository);
}
}
}
|
using Salix.Extensions;
namespace Demo;
public class InputDemo : IConsoleOperation
{
public string OperationName => "input";
public string HelpText =>
"Command to show possibilities of input extensions.";
public Task<int> DoWork()
{
var items = new HashSet<string>
{
"Enter password",
"Wait for Enter",
"Wait for Escape",
"Wait for y/n",
"Wait for specific keys",
"Wait for special keys",
"Exit output demo"
};
bool shouldExit = false;
while (!shouldExit)
{
int selectedItem = Consolix.MenuSelectSingle(items);
Consolix.WriteLine("Selected item index: {0}", selectedItem, ConsoleColor.DarkCyan, ConsoleColor.Cyan);
switch (selectedItem)
{
case 0:
Consolix.WriteLine();
Consolix.Write("Enter password: ");
var psw = Consolix.ReadLineSecret();
Consolix.WriteLine($"Password: {psw}");
Consolix.WriteLine();
break;
case 1:
Consolix.WriteLine();
Consolix.WriteLine("Press Enter (all other keys should not respond): ");
Consolix.ReadEnter();
Consolix.WriteLine();
break;
case 2:
Consolix.WriteLine();
Consolix.WriteLine("Press Escape (all other keys should not respond): ");
Consolix.ReadEscape();
Consolix.WriteLine();
break;
case 3:
Consolix.WriteLine();
Consolix.WriteLine("Press 'y' or 'n' (all other keys should not respond): ");
var yn = Consolix.ReadYesNo();
Consolix.WriteLine($"Pressed {(yn ? "Yes" : "No")}");
Consolix.WriteLine();
break;
case 4:
Consolix.WriteLine();
Consolix.WriteLine("Press 'f' or 'j' (all other keys should not respond): ");
var fj = Consolix.ReadKeys(true, 'f', 'j');
Consolix.WriteLine($"Pressed '{fj}'");
Consolix.WriteLine();
break;
case 5:
Consolix.WriteLine();
Consolix.WriteLine("Press 'Backspace' or 'Delete' (all other keys should not respond): ");
var ctrl = Consolix.ReadKeys(ConsoleKey.Backspace, ConsoleKey.Delete);
Consolix.WriteLine($"Pressed '{ctrl}'");
Consolix.WriteLine();
break;
default:
shouldExit = true;
break;
}
}
return Task.FromResult(0);
}
public bool IsReady => true;
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace ApiPager.Core.Models
{
/// <summary>
/// Summary details for a user
/// </summary>
public class PagedResults<T> : IPagedResults
{
#region private fields
private FilterPageAndSortInfo filterPageAndSortInfo;
#endregion
#region public properties
/// <summary>
/// The number of items that were skipped over from the (potentially filtered) result set
/// </summary>
[Required]
public int? Offset
{
get { return filterPageAndSortInfo?.Offset; }
set
{
if (value == null)
return;
if (filterPageAndSortInfo == null)
filterPageAndSortInfo = new FilterPageAndSortInfo();
filterPageAndSortInfo.Offset = value.Value;
}
}
/// <summary>
/// The number of items returned in this page of the result set
/// </summary>
[Required]
public int? Count
{
get { return ApiPagerUtilities.Min(filterPageAndSortInfo?.Count, filterPageAndSortInfo?.TotalCount); }
set
{
if (value == null)
return;
if (filterPageAndSortInfo == null)
filterPageAndSortInfo = new FilterPageAndSortInfo();
filterPageAndSortInfo.Count = value.Value;
}
}
/// <summary>
/// The total number of items available in the (potentially filtered) result set
/// </summary>
[Required]
public int? TotalCount
{
get { return filterPageAndSortInfo?.TotalCount; }
set
{
if (value == null)
return;
if (filterPageAndSortInfo == null)
filterPageAndSortInfo = new FilterPageAndSortInfo();
filterPageAndSortInfo.TotalCount = value.Value;
}
}
/// <summary>
/// The list of results
/// </summary>
[Required]
public List<T> List { get; set; }
#endregion
#region public methods
public void SetFilterPageAndSortInfo(FilterPageAndSortInfo filterPageAndSortInfo)
{
this.filterPageAndSortInfo = filterPageAndSortInfo;
}
public FilterPageAndSortInfo GetFilterPageAndSortInfo()
{
return filterPageAndSortInfo;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace JOD.Writer.Models.com
{
public class TableTableCell : TableCellBase
{
[XmlAttribute(WriterKeyword.table_style_name)]
public string table_style_name { get; set; }
[XmlAttribute(WriterKeyword.table_number_columns_spanned)]
public string table_number_columns_spanned { get; set; }
[XmlAttribute(WriterKeyword.table_number_rows_spanned)]
public string table_number_rows_spanned { get; set; }
[XmlAttribute(WriterKeyword.office_value_type)]
public string office_value_type { get; set; }
[XmlElement(WriterKeyword.text_p)]
public TextP text_p { get; set; }
}
}
|
using System;
using System.IO;
using System.Threading.Tasks;
using SampleApp.Domain;
using UnityEngine;
namespace SampleApp.Infrastructure
{
public class JsonSaveDataRepsitory : ISaveDataRepository
{
private readonly string _dataPath;
public JsonSaveDataRepsitory()
{
_dataPath = Path.Combine(Application.dataPath, "..", "Saves");
if (!Directory.Exists(_dataPath))
{
Directory.CreateDirectory(_dataPath);
}
}
public async Task<SaveData> FindAsync(string key)
{
var path = $"{_dataPath}/{key}.json";
if (!File.Exists(path)) return null;
var json = await Task.Run(() => File.ReadAllText(path));
var dto = JsonUtility.FromJson<SaveDataDto>(json); // Fix error handling
return new SaveData(dto.name, dto.power, dto.speed, dto.health);
}
public async Task StoreAsync(string key, SaveData saveData)
{
var dto = new SaveDataDto
{
name = saveData.Name,
power = saveData.Power,
speed = saveData.Speed,
health = saveData.Health
};
var json = JsonUtility.ToJson(dto);
await Task.Run(() => File.WriteAllText($"{_dataPath}/{key}.json", json));
}
[Serializable]
private struct SaveDataDto
{
public string name;
public int power;
public int speed;
public int health;
}
}
} |
// <copyright file="RecipeToml.cs" company="Soup">
// Copyright (c) Soup. All rights reserved.
// </copyright>
using Opal;
using Soup.Build.Runtime;
using System;
using System.Threading.Tasks;
using Tomlyn;
using Tomlyn.Syntax;
namespace Soup.Build.Utilities
{
/// <summary>
/// The recipe Toml serialize manager
/// </summary>
internal static class ValueTableTomlUtilities
{
/// <summary>
/// Load from stream
/// </summary>
public static (ValueTable Table, DocumentSyntax Root) Deserialize(
Path tomlFile,
string content)
{
// Read the contents of the recipe file
var documentSyntax = Toml.Parse(content, tomlFile.ToString());
// Load the entire root table
var valueTable = new ValueTable()
{
MirrorSyntax = documentSyntax,
};
var visitor = new ValueTableTomlVisitor(valueTable);
documentSyntax.Accept(visitor);
return (valueTable, documentSyntax);
}
/// <summary>
/// Save the document syntax to the root file
/// </summary>
public static async Task SerializeAsync(DocumentSyntax documentSyntax, System.IO.Stream stream)
{
// Write out the entire root table
var content = documentSyntax.ToString();
using (var writer = new System.IO.StreamWriter(stream))
{
await writer.WriteAsync(content);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenCV.Net;
using System.Runtime.InteropServices;
using System.Reactive.Linq;
using System.ComponentModel;
namespace Bonsai.Vision
{
[Description("Undistorts the observed point coordinates using the specified intrinsic camera matrix.")]
public class UndistortPoints : IntrinsicsTransform
{
public IObservable<Point2f> Process(IObservable<Point2f> source)
{
return Process(source.Select(x => new[] { x })).Select(xs => xs[0]);
}
public IObservable<Point2f[]> Process(IObservable<Point2f[]> source)
{
return Observable.Defer(() =>
{
Mat cameraMatrix = null;
Mat distortionCoefficients = null;
return source.Select(input =>
{
if (cameraMatrix != Intrinsics || distortionCoefficients != Distortion)
{
cameraMatrix = Intrinsics;
distortionCoefficients = Distortion;
}
var output = new Point2f[input.Length];
using (var inputHeader = Mat.CreateMatHeader(input, input.Length, 1, Depth.F32, 2))
using (var outputHeader = Mat.CreateMatHeader(output, output.Length, 1, Depth.F32, 2))
{
CV.UndistortPoints(inputHeader, outputHeader, cameraMatrix, distortionCoefficients);
}
return output;
});
});
}
public IObservable<Mat> Process(IObservable<Mat> source)
{
return Observable.Defer(() =>
{
Mat cameraMatrix = null;
Mat distortionCoefficients = null;
return source.Select(input =>
{
if (cameraMatrix != Intrinsics || distortionCoefficients != Distortion)
{
cameraMatrix = Intrinsics;
distortionCoefficients = Distortion;
}
var output = new Mat(input.Size, input.Depth, input.Channels);
CV.UndistortPoints(input, output, cameraMatrix, distortionCoefficients);
return output;
});
});
}
}
}
|
using System;
namespace LeanCloud.Realtime.CLI.Services
{
public class AppService
{
public AppService()
{
}
}
}
|
using MovieManager.Core.Contracts;
using MovieManager.Core.Entities;
using System.Collections.Generic;
using System.Linq;
namespace MovieManager.Persistence
{
internal class CategoryRepository : ICategoryRepository
{
private readonly ApplicationDbContext _dbContext;
public CategoryRepository(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public (Category, int) GetCategorieWithMostTitles() => _dbContext.Categories
.Select(c => new
{
Category = c,
Count = c.Movies.Count()
})
.OrderByDescending(c => c.Count)
.AsEnumerable()
.Select(t => (t.Category, t.Count))
.First();
public List<(string, int, int)> GetCategoryStatistics1() => _dbContext.Categories
.Select(c => new
{
CategoryName = c.CategoryName,
MovieCount = c.Movies.Count(),
DurationSum = c.Movies
.Select(m => m.Duration)
.Sum()
})
.AsEnumerable()
.Select(t => (t.CategoryName, t.MovieCount, t.DurationSum))
.OrderByDescending(t => t.CategoryName)
.ToList();
public List<(string, double)> GetCategoryStatistics2() => _dbContext.Categories
.Select(c => new
{
CategoryName = c.CategoryName,
DurationAvg = c.Movies
.Select(m => m.Duration)
.Average()
})
.AsEnumerable()
.Select(t => (t.CategoryName, t.DurationAvg))
.OrderByDescending(t => t.DurationAvg)
.ToList();
}
} |
using SysCommand.ConsoleApp;
using SysCommand.Mapping;
namespace SysCommand.Tests.UnitTests.Common.Commands.T37
{
public class Command1 : Command
{
[Argument(ShortName = 'a', LongName = "a1")]
public string A1 { get; set; }
public Command1()
{
EnablePositionalArgs = true;
}
}
}
|
/***********************************************************************************************\
* (C) KAL ATM Software GmbH, 2021
* KAL ATM Software GmbH licenses this file to you under the MIT license.
* See the LICENSE file in the project root for more information.
\***********************************************************************************************/
using XFS4IoTFramework.Common;
namespace CardReader
{
public interface ICardReaderConnection : ICommonConnection
{
void InsertCardEvent();
void MediaInsertedEvent();
void MediaRemovedEvent();
void InvalidTrackDataEvent(XFS4IoT.CardReader.Events.InvalidTrackDataEvent.PayloadData Payload);
void InvalidMediaEvent();
void TrackDetectedEvent(XFS4IoT.CardReader.Events.TrackDetectedEvent.PayloadData Payload);
void RetainBinThresholdEvent(XFS4IoT.CardReader.Events.RetainBinThresholdEvent.PayloadData Payload);
void MediaRetainedEvent();
void MediaDetectedEvent(XFS4IoT.CardReader.Events.MediaDetectedEvent.PayloadData Payload);
void EMVClessReadStatusEvent(XFS4IoT.CardReader.Events.EMVClessReadStatusEvent.PayloadData Payload);
void CardActionEvent(XFS4IoT.CardReader.Events.CardActionEvent.PayloadData Payload);
void PowerSaveChangeEvent(XFS4IoT.Common.Events.PowerSaveChangeEvent.PayloadData Payload);
void DevicePositionEvent(XFS4IoT.Common.Events.DevicePositionEvent.PayloadData Payload);
}
}
|
using Knyaz.Optimus.ScriptExecuting;
namespace Knyaz.Optimus.Dom.Elements
{
/// <summary>
/// Represents <optgroup> html element.
/// </summary>
[JsName("HTMLOptGroupElement")]
public class HtmlOptGroupElement : HtmlElement
{
internal HtmlOptGroupElement(Document ownerDocument) : base(ownerDocument, TagsNames.OptGroup){}
}
} |
namespace DaJet.Export
{
public sealed class BatchInfo
{
public int RowNumber1 { get; set; }
public int RowNumber2 { get; set; }
public bool IsNacked { get; set; }
public int MessagesSent { get; set; }
}
} |
using System.Dynamic;
namespace applicationApi.Models
{
public class SensorsDatabaseSettings : ISensorsDatabaseSettings
{
public string WindSensorsCollectionName { get; set; }
public string PressureSensorsCollectionName { get; set; }
public string TemperatureSensorsCollectionName { get; set; }
public string HumiditySensorsCollectionName { get; set; }
public string ConnectionString { get; set; }
public string DatabaseName { get; set; }
}
public interface ISensorsDatabaseSettings
{
string WindSensorsCollectionName { get; set; }
string PressureSensorsCollectionName { get; set; }
string TemperatureSensorsCollectionName { get; set; }
string HumiditySensorsCollectionName { get; set; }
string ConnectionString { get; set; }
string DatabaseName { get; set; }
}
} |
namespace ToyBoxHHH
{
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Useful script to toggle children using gameObject.SetActive()
///
/// made by @horatiu665
/// </summary>
public class ToggleChildren : MonoBehaviour
{
private List<Transform> childrenCache = new List<Transform>();
[SerializeField]
private Transform whichOne;
[DebugButton]
public void ToggleThisOne(Transform whichOne)
{
transform.GetChildrenNonAlloc(childrenCache);
var indexOfActive = childrenCache.IndexOf(whichOne);
childrenCache.ForEach(t => t.gameObject.SetActive(false));
if (indexOfActive >= 0 && indexOfActive < transform.childCount)
transform.GetChild(indexOfActive).gameObject.SetActive(true);
}
[DebugButton]
public void ToggleNext()
{
transform.GetChildrenNonAlloc(childrenCache);
var indexOfActive = childrenCache.FindIndex(t => t.gameObject.activeInHierarchy);
indexOfActive++;
if (indexOfActive == transform.childCount) indexOfActive = 0;
childrenCache.ForEach(t => t.gameObject.SetActive(false));
transform.GetChild(indexOfActive).gameObject.SetActive(true);
whichOne = transform.GetChild(indexOfActive);
}
[DebugButton]
public void ToggleRandom()
{
transform.GetChildrenNonAlloc(childrenCache);
childrenCache.ForEach(t => t.gameObject.SetActive(false));
var indexOfActive = Random.Range(0, transform.childCount);
transform.GetChild(indexOfActive).gameObject.SetActive(true);
whichOne = transform.GetChild(indexOfActive);
}
}
} |
public class Private : Soldier, IPrivate
{
private double salary;
public Private(int id, string firstName, string lastName, double salary)
: base(id, firstName, lastName)
{
Salary = salary;
}
public double Salary
{
get => salary;
private set => salary = value;
}
public override string ToString()
{
return $"Name: {FirstName} {LastName} Id: {Id} Salary: {Salary:f2}";
}
} |
using System;
using System.Net;
using SocketFlow;
using SocketFlow.Client;
namespace Examples
{
public class ClientExample
{
private static FlowClient client;
private static readonly FlowOptions options = new FlowOptions()
{
DefaultNonPrimitivesObjectUsingAsJson = true
};
public static void Start(int port)
{
Console.WriteLine("Press any key to connect");
Console.ReadKey();
client = new FlowClient(IPAddress.Parse("127.0.0.1"), port, options);
client.Bind<UserMessage>((int)ScEventId.SendUserMessage, ReceiveMessage);
client.Connect();
SendMyName();
ReadAndSend();
}
private static void SendMyName()
{
var name = Console.ReadLine();
client.Send((int)CsEventId.SendName, new UserInput(name));
}
private static void ReceiveMessage(UserMessage value)
{
var t = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write($"{value.UserName}");
Console.ForegroundColor = t;
Console.WriteLine($": {value.Message}");
}
private static void ReadAndSend()
{
while (true)
{
var message = Console.ReadLine();
client.Send((int)CsEventId.SendMessage, new UserInput(message));
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Anno.Domain.Member;
using Anno.Common;
using Anno.Domain.Repository;
namespace Anno.Domain.Service
{
public class MemberService : IMemberService
{
//private readonly SqlSugar.SqlSugarClient _db;
private readonly IBaseRepository _baseRepository;
public MemberService(IBaseRepository baseRepository)
{
//_db = baseRepository.Context;
_baseRepository = baseRepository;
}
public bool ChangePwd(Dto.ChangePwdInputDto args)
{
//Sys_member sysMember = new Sys_member(args.ID);
//sysMember.ChangePwd(args.pwd);
//int x = _db.Updateable(sysMember).UpdateColumns(t => new { t.pwd }).Where(t=>t.pwd==args.oldPwd).ExecuteCommand();
//if (x <= 0)
//{
// throw new ArgumentException("要修改的用户不存在!请重新赋值 Dto.ChangePwdInputDto.ID ");
//}
return true;
}
/// <summary>
/// 添加用户
/// </summary>
/// <param name="m">用户基本信息</param>
/// <param name="lr">用户角色</param>
/// <returns></returns>
//public bool AddUser(Model.sys_member m, List<Model.sys_roles> lr)
//{
// if (string.IsNullOrWhiteSpace(m.name))
// {
// throw new ArgumentException("用户名不能为空");
// }
// if (_db.Queryable<Model.sys_member>().Where(_m => _m.account == m.account).Any())
// {
// throw new ArgumentException("用户已存在");
// }
// if (string.IsNullOrWhiteSpace(m.account))
// {
// throw new ArgumentException("登录名不能为空");
// }
// if (string.IsNullOrWhiteSpace(m.pwd))
// {
// throw new ArgumentException("密码不能为空");
// }
// m.pwd = CryptoHelper.TripleDesEncrypting(m.pwd);
// m.ID = _db.Insertable(m).ExecuteReturnBigIdentity();
// List<Model.sys_member_roles_link> lmr = new List<Model.sys_member_roles_link>();
// foreach (Model.sys_roles r in lr)
// {
// Model.sys_member_roles_link l = new Model.sys_member_roles_link
// {
// mid = m.ID,
// rid = r.ID
// };
// lmr.Add(l);
// }
// _db.Insertable(lmr).ExecuteCommand();
// return true;
//}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Shawn.Utils;
namespace Demo
{
public class MatchProviderInfo : NotifyPropertyChangedBase
{
private string _name;
public string Name
{
get => _name;
set => SetAndNotifyIfChanged(nameof(Name), ref _name, value);
}
private string _title1 = "";
public string Title1
{
get => _title1;
set => SetAndNotifyIfChanged(nameof(Title1), ref _title1, value);
}
private string _title2 = "";
public string Title2
{
get => _title2;
set => SetAndNotifyIfChanged(nameof(Title2), ref _title2, value);
}
private bool _enabled = true;
public bool Enabled
{
get => _enabled;
set => SetAndNotifyIfChanged(nameof(Enabled), ref _enabled, value);
}
}
}
|
using System;
using System.Collections.Generic;
using GSoft.Dynamite.Taxonomy;
using Microsoft.Office.Server.UserProfiles;
namespace GSoft.Dynamite.UserProfile
{
/// <summary>
/// User profile property information.
/// </summary>
public class UserProfilePropertyInfo
{
private readonly IDictionary<int, string> displayNameLocalized = new Dictionary<int, string>();
private readonly IDictionary<int, string> descriptionsLocalized = new Dictionary<int, string>();
/// <summary>
/// Initializes a new instance of the <see cref="UserProfilePropertyInfo"/> class.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="displayName">The display name.</param>
/// <param name="type">The type (PropertyDataType).</param>
public UserProfilePropertyInfo(string name, string displayName, string type) :
this(name, displayName, type, 25, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="UserProfilePropertyInfo"/> class.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="displayName">The display name.</param>
/// <param name="type">The type (PropertyDataType).</param>
/// <param name="length">The length.</param>
public UserProfilePropertyInfo(string name, string displayName, string type, int length) :
this(name, displayName, type, length, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="UserProfilePropertyInfo"/> class.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="displayName">The display name.</param>
/// <param name="type">The type (PropertyDataType).</param>
/// <param name="length">The length.</param>
/// <param name="isMultivalued">if set to <c>true</c> [is multivalued].</param>
public UserProfilePropertyInfo(string name, string displayName, string type, int length, bool isMultivalued)
{
// Validate parameters
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException("name");
}
if (string.IsNullOrEmpty(displayName))
{
throw new ArgumentNullException("displayName");
}
if (length <= 0)
{
throw new ArgumentOutOfRangeException("length");
}
if (string.IsNullOrEmpty(type))
{
throw new ArgumentNullException("type");
}
this.Name = name;
this.DisplayName = displayName;
this.Length = length;
this.PropertyDataType = type;
this.IsMultivalued = isMultivalued;
}
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>
/// The name.
/// </value>
public string Name { get; private set; }
/// <summary>
/// Gets or sets the length.
/// </summary>
/// <value>
/// The length.
/// </value>
public int Length { get; private set; }
/// <summary>
/// Gets or sets the property data type (use PropertyDataType class).
/// </summary>
/// <value>
/// The property data type.
/// </value>
public string PropertyDataType { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether [is multivalued].
/// </summary>
/// <value>
/// <c>true</c> if [is multivalued]; otherwise, <c>false</c>.
/// </value>
public bool IsMultivalued { get; private set; }
/// <summary>
/// Gets or sets the display name.
/// </summary>
/// <value>
/// The display name.
/// </value>
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets the localized display names (LCID and name key/value pairs).
/// </summary>
/// <value>
/// The localized display names.
/// </value>
public IDictionary<int, string> DisplayNameLocalized
{
get
{
return this.displayNameLocalized;
}
}
/// <summary>
/// Gets or sets the description.
/// </summary>
/// <value>
/// The description.
/// </value>
public string Description { get; set; }
/// <summary>
/// Gets or sets the localized descriptions (LCID and name key/value pairs).
/// </summary>
/// <value>
/// The localized descriptions.
/// </value>
public IDictionary<int, string> DescriptionLocalized
{
get
{
return this.descriptionsLocalized;
}
}
/// <summary>
/// Gets or sets a value indicating whether [is alias].
/// </summary>
/// <value>
/// <c>true</c> if [is alias]; otherwise, <c>false</c>.
/// </value>
public bool IsAlias { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [is searchable].
/// </summary>
/// <value>
/// <c>true</c> if [is searchable]; otherwise, <c>false</c>.
/// </value>
public bool IsSearchable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [is visible on viewer].
/// </summary>
/// <value>
/// <c>true</c> if [is visible on viewer]; otherwise, <c>false</c>.
/// </value>
public bool IsVisibleOnViewer { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [is visible on editor].
/// </summary>
/// <value>
/// <c>true</c> if [is visible on editor]; otherwise, <c>false</c>.
/// </value>
public bool IsVisibleOnEditor { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [is user editable].
/// </summary>
/// <value>
/// <c>true</c> if [is user editable]; otherwise, <c>false</c>.
/// </value>
public bool IsUserEditable { get; set; }
/// <summary>
/// Gets or sets the default privacy. In other words, who can see the information. For a user profile
/// property to be crawled, the privacy needs to be set to public.
/// </summary>
/// <value>
/// The default privacy.
/// </value>
public Privacy? DefaultPrivacy { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [is replicable].
/// </summary>
/// <value>
/// <c>true</c> if [is replicable]; otherwise, <c>false</c>.
/// </value>
public bool IsReplicable { get; set; }
/// <summary>
/// Gets or sets the separator.
/// </summary>
/// <value>
/// The separator.
/// </value>
public MultiValueSeparator Separator { get; set; }
/// <summary>
/// Gets or sets the term set.
/// </summary>
/// <value>
/// The term set.
/// </value>
public TermSetInfo TermSetInfo { get; set; }
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace LightBDD.Framework.Reporting.Formatters.Html
{
internal class TagBuilder : IHtmlNode
{
private readonly List<KeyValuePair<string, string>> _attributes = new List<KeyValuePair<string, string>>();
private bool _skipEmpty;
private IHtmlNode[] _nodes = new IHtmlNode[0];
private bool _spaceBefore;
private bool _spaceAfter;
private readonly string _tag;
public TagBuilder(Html5Tag tag)
{
_tag = tag.ToString().ToLowerInvariant();
}
public TagBuilder Attribute(Html5Attribute attribute, string value)
{
return Attribute(attribute.ToString().ToLowerInvariant(), value);
}
public TagBuilder Attribute(string attribute, string value)
{
_attributes.Add(new KeyValuePair<string, string>(attribute, value));
return this;
}
public TagBuilder Content(params IHtmlNode[] nodes)
{
_nodes = nodes;
return this;
}
public TagBuilder Content(IEnumerable<IHtmlNode> nodes)
{
_nodes = nodes.ToArray();
return this;
}
public TagBuilder Content(string content, bool trimContent = true, bool escapeContent = true)
{
content ??= string.Empty;
if (trimContent)
content = content.Trim();
if (content == string.Empty)
return Content();
return Content(Html.Text(content).Escape(escapeContent));
}
public TagBuilder SkipEmpty()
{
_skipEmpty = true;
return this;
}
public TagBuilder Class(string className)
{
return Attribute(Html5Attribute.Class, className);
}
public TagBuilder Href(string href)
{
return Attribute(Html5Attribute.Href, href);
}
public TagBuilder Id(string id)
{
return Attribute(Html5Attribute.Id, id);
}
public TagBuilder For(string forTag)
{
return Attribute(Html5Attribute.For, forTag);
}
public TagBuilder Checked(bool isChecked = true)
{
if (!isChecked)
return this;
return Attribute(Html5Attribute.Checked, null);
}
public TagBuilder OnClick(string jsCode)
{
return Attribute(Html5Attribute.Onclick, jsCode);
}
public TagBuilder Name(string name)
{
return Attribute(Html5Attribute.Name, name);
}
public TagBuilder SpaceBefore()
{
_spaceBefore = true;
return this;
}
public TagBuilder SpaceAfter()
{
_spaceAfter = true;
return this;
}
public HtmlTextWriter Write(HtmlTextWriter writer)
{
if (_skipEmpty && _nodes.Length == 0)
return writer;
if (_spaceBefore)
writer.Write(" ");
if (_nodes.Any())
{
writer.OpenTag(_tag, _attributes);
foreach (var node in _nodes)
node.Write(writer);
writer.CloseTag(_tag);
}
else
writer.WriteTag(_tag, _attributes);
if (_spaceAfter)
writer.Write(" ");
return writer;
}
}
} |
/**
* 缓冲区
**/
using System;
using System.Text;
namespace cocosocket4unity
{
public class ByteBuf
{
private byte[] data;
private int readerIndex;
private int writerIndex;
private int markReader;
private int markWriter;
/**
* 初始化
**/
public ByteBuf (int capacity)
{
this.data = new byte[capacity];
readerIndex = 0;
writerIndex = 0;
markReader = 0;
markWriter = 0;
}
public ByteBuf(byte[] content)
{
this.data = content;
readerIndex = 0;
writerIndex = content.Length;
markReader = 0;
markWriter = 0;
}
private ByteBuf()
{
}
/**
* 容量
**/
public int Capacity ()
{
return data.Length;
}
/**
* 扩容
*/
public ByteBuf Capacity (int nc)
{
if (nc > data.Length)
{
byte[] old = data;
data = new byte[nc];
Array.Copy (old, data, old.Length);
}
return this;
}
/**
* 清除掉所有标记
* @return
**/
public ByteBuf Clear ()
{
readerIndex = 0;
writerIndex = 0;
markReader = 0;
markWriter = 0;
return this;
}
/**
* 拷贝
**/
public ByteBuf Copy()
{
ByteBuf item = new ByteBuf(data.Length);
Array.Copy (this.data, item.data, data.Length);
item.readerIndex = readerIndex;
item.writerIndex = writerIndex;
item.markReader = markReader;
item.markWriter = markWriter;
return item;
}
/// <summary>
/// 浅拷贝
/// </summary>
/// <returns></returns>
public ByteBuf Duplicate()
{
ByteBuf item = new ByteBuf();
item.readerIndex = readerIndex;
item.writerIndex = writerIndex;
item.markReader = markReader;
item.markWriter = markWriter;
item.data = data;
return item;
}
/**
* 获取一个字节
**/
public byte GetByte(int index)
{
if (index < data.Length)
{
return data[index];
}
return (byte)0;
}
/// <summary>
/// 读取四字节整形
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public int GetInt(int index)
{
if (index + 3 < data.Length)
{
int ret = ((int) data[index]) << 24;
ret |= ((int) data[index + 1]) << 16;
ret |= ((int) data[index + 2]) << 8;
ret |= ((int) data[index + 3]);
return ret;
}
return 0;
}
/// <summary>
/// 小头的读取
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public int GetIntLE(int index)
{
if (index + 3 < data.Length)
{
int ret = ((int)data[index]);
ret |= ((int)data[index + 1]) << 8;
ret |= ((int)data[index + 2]) << 16;
ret |= ((int)data[index + 3])<<24;
return ret;
}
return 0;
}
/**
* 读取两字节整形
**/
public short GetShort(int index)
{
if (index + 1 < data.Length)
{
short r1 = (short)(data[index] << 8);
short r2 = (short)(data[index + 1]);
short ret = (short)(r1 | r2);
return ret;
}
return 0;
}
/// <summary>
/// 读取两字节整形
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public short GetShortLE(int index)
{
if (index + 1 < data.Length)
{
short r1 = (short)(data[index]);
short r2 = (short)(data[index + 1]<<8);
short ret = (short)(r1 | r2);
return ret;
}
return 0;
}
/**
* 标记读
**/
public ByteBuf MarkReaderIndex()
{
markReader = readerIndex;
return this;
}
/**
* 标记写
**/
public ByteBuf MarkWriterIndex()
{
markWriter = writerIndex;
return this;
}
/**
* 可写长度
**/
public int MaxWritableBytes()
{
return data.Length - writerIndex;
}
/**
* 读取一个字节
**/
public byte ReadByte()
{
if (readerIndex < writerIndex)
{
byte ret = data[readerIndex++];
return ret;
}
return (byte)0;
}
/**
* 读取四字节整形
**/
public int ReadInt()
{
if (readerIndex + 3 < writerIndex)
{
int ret = (int)(((data [readerIndex++]) << 24) & 0xff000000);
ret |= (((data [readerIndex++]) << 16) & 0x00ff0000);
ret |= (((data [readerIndex++]) << 8) & 0x0000ff00);
ret |= (((data [readerIndex++])) & 0x000000ff);
return ret;
}
return 0;
}
/// <summary>
/// 小头读取
/// </summary>
/// <returns></returns>
public int ReadIntLE()
{
if (readerIndex + 3 < writerIndex)
{
int ret = (((data[readerIndex++])) & 0x000000ff);
ret |= (((data[readerIndex++]) << 8) & 0x0000ff00);
ret |= (((data[readerIndex++]) << 16) & 0x00ff0000);
ret |= (int)(((data[readerIndex++]) <<24) & 0xff000000);
return ret;
}
return 0;
}
/// <summary>
/// 读取两个字节的整形
/// </summary>
/// <returns></returns>
public short ReadShort()
{
if (readerIndex + 1 < writerIndex)
{
int h = data[readerIndex++];
int l = data[readerIndex++]&0x000000ff;
int len = ((h << 8)&0x0000ff00) | (l);
return (short)len;
}
return 0;
}
/// <summary>
/// 小头读取
/// </summary>
/// <returns></returns>
public short ReadShortLE()
{
if (readerIndex + 1 < writerIndex)
{
int l = data[readerIndex++];
int h = data[readerIndex++] & 0x000000ff;
int len = ((h << 8) & 0x0000ff00) | (l);
return (short)len;
}
return 0;
}
/// <summary>
/// 可读字节数
/// </summary>
/// <returns></returns>
public int ReadableBytes()
{
return writerIndex - readerIndex;
}
/**
* 读指针
**/
public int ReaderIndex()
{
return readerIndex;
}
/**
* 移动读指针
**/
public ByteBuf ReaderIndex(int readerIndex)
{
if (readerIndex <= writerIndex)
{
this.readerIndex = readerIndex;
}
return this;
}
/**
* 重置读指针
**/
public ByteBuf ResetReaderIndex()
{
if (markReader <= writerIndex)
{
this.readerIndex = markReader;
}
return this;
}
/**
* 重置写指针
**/
public ByteBuf ResetWriterIndex()
{
if (markWriter >= readerIndex)
{
writerIndex = markWriter;
}
return this;
}
/**
* 设置字节
**/
public ByteBuf SetByte(int index, byte value)
{
if (index < data.Length)
{
data[index] = value;
}
return this;
}
/**
* 设置字节
**/
public ByteBuf SetBytes(int index, byte[] src, int from, int len)
{
if (index + len <= len)
{
Array.Copy (src, from, data, index, len);
}
return this;
}
/**
* 设置读写指针
**/
public ByteBuf SetIndex(int readerIndex, int writerIndex)
{
if (readerIndex >= 0 && readerIndex <= writerIndex && writerIndex <= data.Length)
{
this.readerIndex = readerIndex;
this.writerIndex = writerIndex;
}
return this;
}
/**
* 设置四字节整形
**/
public ByteBuf SetInt(int index, int value)
{
if (index + 4 <= data.Length)
{
data[index++] = (byte)((value >> 24) & 0xff);
data[index++] = (byte)((value >> 16) & 0xff);
data[index++] = (byte)((value >> 8) & 0xff);
data[index++] = (byte)(value & 0xff);
}
return this;
}
/// <summary>
/// 设置小头整形
/// </summary>
/// <param name="index"></param>
/// <param name="value"></param>
/// <returns></returns>
public ByteBuf SetIntLE(int index, int value)
{
if (index + 4 <= data.Length)
{
data[index++] = (byte)(value & 0xff);
data[index++] = (byte)((value >> 8) & 0xff);
data[index++] = (byte)((value >> 16) & 0xff);
data[index++] = (byte)((value >> 24) & 0xff);
}
return this;
}
/**
* 设置两字节整形
**/
public ByteBuf SetShort(int index, short value)
{
if (index + 2 <= data.Length)
{
data[index++] = (byte)((value >> 8) & 0xff);
data[index++] = (byte)(value & 0xff);
}
return this;
}
/// <summary>
/// 小头整形
/// </summary>
/// <param name="index"></param>
/// <param name="value"></param>
/// <returns></returns>
public ByteBuf SetShortLE(int index, short value)
{
if (index + 2 <= data.Length)
{
data[index++] = (byte)(value & 0xff);
data[index++] = (byte)((value >> 8) & 0xff);
}
return this;
}
/**
* 略过一些字节
**/
public ByteBuf SkipBytes(int length)
{
if (readerIndex + length <= writerIndex)
{
readerIndex += length;
}
return this;
}
/**
* 剩余的可写字节数
**/
public int WritableBytes()
{
return data.Length - writerIndex;
}
/**
* 写入一个字节
*
**/
public ByteBuf WriteByte(byte value)
{
this.Capacity(writerIndex + 1);
this.data[writerIndex++] = value;
return this;
}
/**
* 写入四字节整形
**/
public ByteBuf WriteInt(int value)
{
Capacity(writerIndex + 4);
data[writerIndex++] = (byte)((value >> 24) & 0xff);
data[writerIndex++] = (byte)((value >> 16) & 0xff);
data[writerIndex++] = (byte)((value >> 8) & 0xff);
data[writerIndex++] = (byte)(value & 0xff);
return this;
}
/// <summary>
/// 写入四字节小头
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public ByteBuf WriteIntLE(int value)
{
Capacity(writerIndex + 4);
data[writerIndex++] = (byte)(value & 0xff);
data[writerIndex++] = (byte)((value >> 8) & 0xff);
data[writerIndex++] = (byte)((value >> 16) & 0xff);
data[writerIndex++] = (byte)((value >> 24) & 0xff);
return this;
}
/**
* 写入两字节整形
**/
public ByteBuf WriteShort(short value)
{
Capacity(writerIndex + 2);
data[writerIndex++] = (byte)((value >> 8) & 0xff);
data[writerIndex++] = (byte)(value & 0xff);
return this;
}
/// <summary>
/// 两字节小头
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public ByteBuf WriteShortLE(short value)
{
Capacity(writerIndex + 2);
data[writerIndex++] = (byte)(value & 0xff);
data[writerIndex++] = (byte)((value >> 8) & 0xff);
return this;
}
/**
* 写入一部分字节
**/
public ByteBuf WriteBytes(ByteBuf src)
{
int sum = src.writerIndex - src.readerIndex;
Capacity(writerIndex + sum);
if (sum > 0)
{
Array.Copy (src.data, src.readerIndex, data, writerIndex, sum);
writerIndex += sum;
src.readerIndex += sum;
}
return this;
}
/**
* 写入一部分字节
**/
public ByteBuf WriteBytes(ByteBuf src ,int len)
{
if (len > 0)
{
Capacity(writerIndex + len);
Array.Copy (src.data, src.readerIndex, data, writerIndex, len);
writerIndex += len;
src.readerIndex += len;
}
return this;
}
/**
* 写入一部分字节
**/
public ByteBuf WriteBytes(byte[] src)
{
int sum = src.Length;
Capacity(writerIndex + sum);
if (sum > 0)
{
Array.Copy (src, 0, data, writerIndex, sum);
writerIndex += sum;
}
return this;
}
/**
* 写入一部分字节
**/
public ByteBuf WriteBytes(byte[] src,int off,int len)
{
int sum = len;
if (sum > 0)
{
Capacity(writerIndex + sum);
Array.Copy (src,off, data, writerIndex, sum);
writerIndex += sum;
}
return this;
}
/**
* 读取utf字符串(大头)
**/
public string ReadUTF8()
{
short len = ReadShort(); // 字节数
byte[] charBuff = new byte[len]; //
Array.Copy (data, readerIndex, charBuff, 0, len);
readerIndex += len;
return Encoding.UTF8.GetString (charBuff);
}
/// <summary>
/// 读取utf8(小头)
/// </summary>
/// <returns></returns>
public string ReadUTF8LE()
{
short len = ReadShortLE(); // 字节数
byte[] charBuff = new byte[len]; //
Array.Copy(data, readerIndex, charBuff, 0, len);
readerIndex += len;
return Encoding.UTF8.GetString(charBuff);
}
/**
* 写入utf字符串
*
**/
public ByteBuf WriteUTF8(string value)
{
byte[] content = Encoding.UTF8.GetBytes (value.ToCharArray());
int len = content.Length;
Capacity(writerIndex + len + 2);
WriteShort((short) len);
Array.Copy (content, 0, data, writerIndex, len);
writerIndex += len;
return this;
}
/// <summary>
/// 写入utf8(小头)
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public ByteBuf WriteUTF8LE(string value)
{
byte[] content = Encoding.UTF8.GetBytes(value.ToCharArray());
int len = content.Length;
Capacity(writerIndex + len + 2);
WriteShortLE((short)len);
Array.Copy(content, 0, data, writerIndex, len);
writerIndex += len;
return this;
}
/**
* 写指针
**/
public int WriterIndex()
{
return writerIndex;
}
/**
* 移动写指针
**/
public ByteBuf WriterIndex(int writerIndex)
{
if (writerIndex >= readerIndex && writerIndex <= data.Length)
{
this.writerIndex = writerIndex;
}
return this;
}
/**
* 原始字节数组
**/
public byte[] GetRaw()
{
return data;
}
}
}
|
/*
* Copyright (c) 2014-2015 Håkan Edling
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
* http://github.com/piranhacms/piranha.vnext
*
*/
using AutoMapper;
using System;
using System.Collections.Generic;
using System.IO;
using Piranha.Extend;
namespace Piranha.Manager
{
/// <summary>
/// The main entry point for the manager module.
/// </summary>
public class ManagerModule : IModule
{
#region Inner classes
/// <summary>
/// Class representing an embedded resource.
/// </summary>
internal class Resource
{
/// <summary>
/// Gets/sets the resource name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the content type.
/// </summary>
public string ContentType { get; set; }
}
#endregion
#region Members
/// <summary>
/// Gets the internal collection of embedded resources.
/// </summary>
internal static IDictionary<string, Resource> Resources { get; private set; }
/// <summary>
/// Gets the last modification date of the manager module.
/// </summary>
internal static DateTime LastModified { get; private set; }
#endregion
/// <summary>
/// Default constructor.
/// </summary>
public ManagerModule() {
Resources = new Dictionary<string, Resource>();
LastModified = new FileInfo(typeof(ManagerModule).Assembly.Location).LastWriteTime;
}
/// <summary>
/// Initializes the module. This method should be used for
/// ensuring runtime resources and registering hooks.
/// </summary>
public void Init() {
// Alias
Mapper.CreateMap<Piranha.Models.Alias, Models.Alias.ListItem>()
.ForMember(a => a.Saved, o => o.Ignore())
.ForMember(a => a.Created, o => o.MapFrom(m => m.Created.ToString("yyyy-MM-dd")))
.ForMember(a => a.Updated, o => o.MapFrom(m => m.Updated.ToString("yyyy-MM-dd")));
Mapper.CreateMap<Piranha.Models.Alias, Models.Alias.EditModel>();
Mapper.CreateMap<Models.Alias.EditModel, Piranha.Models.Alias>()
.ForMember(a => a.Id, o => o.Ignore())
.ForMember(a => a.Created, o => o.Ignore())
.ForMember(a => a.Updated, o => o.Ignore());
// Author
Mapper.CreateMap<Piranha.Models.Author, Models.Author.ListItem>()
.ForMember(a => a.Saved, o => o.Ignore())
.ForMember(a => a.GravatarUrl, o => o.Ignore())
.ForMember(a => a.Created, o => o.MapFrom(m => m.Created.ToString("yyyy-MM-dd")))
.ForMember(a => a.Updated, o => o.MapFrom(m => m.Updated.ToString("yyyy-MM-dd")));
Mapper.CreateMap<Piranha.Models.Author, Models.Author.EditModel>()
.ForMember(a => a.GravatarUrl, o => o.Ignore());
Mapper.CreateMap<Models.Author.EditModel, Piranha.Models.Author>()
.ForMember(a => a.Id, o => o.Ignore())
.ForMember(a => a.Created, o => o.Ignore())
.ForMember(a => a.Updated, o => o.Ignore());
// Block
Mapper.CreateMap<Piranha.Models.Block, Models.Block.ListItem>()
.ForMember(b => b.Saved, o => o.Ignore())
.ForMember(b => b.Created, o => o.MapFrom(m => m.Created.ToString("yyyy-MM-dd")))
.ForMember(b => b.Updated, o => o.MapFrom(m => m.Updated.ToString("yyyy-MM-dd")));
Mapper.CreateMap<Piranha.Models.Block, Models.Block.EditModel>();
Mapper.CreateMap<Models.Block.EditModel, Piranha.Models.Block>()
.ForMember(b => b.Id, o => o.Ignore())
.ForMember(b => b.Created, o => o.Ignore())
.ForMember(b => b.Updated, o => o.Ignore());
// Category
Mapper.CreateMap<Piranha.Models.Category, Models.Category.ListItem>()
.ForMember(c => c.Saved, o => o.Ignore())
.ForMember(c => c.Created, o => o.MapFrom(m => m.Created.ToString("yyyy-MM-dd")))
.ForMember(c => c.Updated, o => o.MapFrom(m => m.Updated.ToString("yyyy-MM-dd")));
Mapper.CreateMap<Piranha.Models.Category, Models.Category.EditModel>();
Mapper.CreateMap<Models.Category.EditModel, Piranha.Models.Category>()
.ForMember(b => b.Id, o => o.Ignore())
.ForMember(b => b.Created, o => o.Ignore())
.ForMember(b => b.Updated, o => o.Ignore());
// Page type
Mapper.CreateMap<Piranha.Models.PageType, Models.PageType.EditModel>()
.ForMember(t => t.PropertyTypes, o => o.Ignore())
.ForMember(t => t.RegionTypes, o => o.Ignore());
Mapper.CreateMap<Models.PageType.EditModel, Piranha.Models.PageType>()
.ForMember(t => t.Id, o => o.Ignore())
.ForMember(t => t.Properties, o => o.Ignore())
.ForMember(t => t.Regions, o => o.Ignore())
.ForMember(t => t.Created, o => o.Ignore())
.ForMember(t => t.Updated, o => o.Ignore());
Mapper.CreateMap<Piranha.Models.PageTypeProperty, Models.PageType.EditModel.PagePart>();
Mapper.CreateMap<Piranha.Models.PageTypeRegion, Models.PageType.EditModel.PagePart>();
// Post
Mapper.CreateMap<Piranha.Models.Post, Models.Post.EditModel>()
.ForMember(p => p.Authors, o => o.Ignore())
.ForMember(p => p.Categories, o => o.Ignore())
.ForMember(p => p.Comments, o => o.Ignore())
.ForMember(p => p.SelectedCategories, o => o.Ignore())
.ForMember(p => p.Action, o => o.Ignore());
Mapper.CreateMap<Models.Post.EditModel, Piranha.Models.Post>()
.ForMember(p => p.Id, o => o.Ignore())
.ForMember(p => p.Type, o => o.Ignore())
.ForMember(p => p.Author, o => o.Ignore())
.ForMember(p => p.Attachments, o => o.Ignore())
.ForMember(p => p.Comments, o => o.Ignore())
.ForMember(p => p.CommentCount, o => o.Ignore())
.ForMember(p => p.Categories, o => o.Ignore())
.ForMember(p => p.Created, o => o.Ignore())
.ForMember(p => p.Updated, o => o.Ignore())
.ForMember(p => p.Published, o => o.Ignore());
// Post type
Mapper.CreateMap<Piranha.Models.PostType, Models.PostType.EditModel>();
Mapper.CreateMap<Models.PostType.EditModel, Piranha.Models.PostType>()
.ForMember(t => t.Id, o => o.Ignore())
.ForMember(t => t.IncludeInRss, o => o.Ignore())
.ForMember(t => t.Created, o => o.Ignore())
.ForMember(t => t.Updated, o => o.Ignore());
Mapper.AssertConfigurationIsValid();
// Register pre-compiled views
AspNet.Hooks.RegisterPrecompiledViews += assemblies => {
assemblies.Add(typeof(ManagerModule).Assembly);
};
// Scan precompiled resources
foreach (var name in typeof(ManagerModule).Assembly.GetManifestResourceNames()) {
Resources.Add(name.Replace("Piranha.Areas.Manager.Assets.", "").ToLower(), new Resource() {
Name = name, ContentType = GetContentType(name)
}) ;
}
}
#region Private methods
/// <summary>
/// Gets the content type from the resource name.
/// </summary>
/// <param name="name">The resource name</param>
/// <returns>The content type</returns>
private string GetContentType(string name) {
if (name.EndsWith(".js")) {
return "text/javascript" ;
} else if (name.EndsWith(".css")) {
return "text/css" ;
} else if (name.EndsWith(".png")) {
return "image/png" ;
} else if (name.EndsWith(".jpg")) {
return "image/jpg" ;
} else if (name.EndsWith(".gif")) {
return "image/gif" ;
} else if (name.EndsWith(".ico")) {
return "image/ico" ;
} else if (name.EndsWith(".eot")) {
return "application/vnd.ms-fontobject" ;
} else if (name.EndsWith(".ttf")) {
return "application/octet-stream" ;
} else if (name.EndsWith(".svg")) {
return "image/svg+xml" ;
} else if (name.EndsWith(".woff")) {
return "application/x-woff" ;
}
return "application/unknown" ;
}
#endregion
}
} |
namespace Microsoft.Web.Mvc
{
public enum SerializationMode
{
Signed = 0,
EncryptedAndSigned = 1
}
}
|
using System;
using System.Windows.Forms;
namespace Sdl.SDK.LanguagePlatform.Samples.TmLookup
{
public partial class frmSettings : Form
{
public frmSettings()
{
InitializeComponent();
}
#region "PropFuzzy"
// Property for setting the minimum fuzzy match value
// that should be used during the search.
public static int MinFuzzy
{
get;
set;
}
#endregion
#region "PropMaxHits"
// Property for setting the maximum amount of hits to return
// from the TM.
public static int MaxHits
{
get;
set;
}
#endregion
#region "fuzziness"
private void trackFuzzy_Scroll(object sender, EventArgs e)
{
this.lblFuzzyValue.Text = this.trackFuzzy.Value.ToString();
}
#endregion
#region "cancel"
private void btnCancel_Click(object sender, EventArgs e)
{
this.Hide();
}
#endregion
#region "ok"
// Apply the setting values from the form.
private void btnOK_Click(object sender, EventArgs e)
{
MaxHits = Convert.ToInt32(this.txtMaxHits.Text.ToString());
MinFuzzy = this.trackFuzzy.Value;
this.Hide();
}
#endregion
#region "default"
// Reset the control elements to the corresponding default values.
private void btnDefaults_Click(object sender, EventArgs e)
{
this.trackFuzzy.Value = 70;
this.lblFuzzyValue.Text = "70";
this.txtMaxHits.Text = "30";
}
#endregion
private void frmSettings_Load(object sender, EventArgs e)
{
}
}
}
|
using DarkMatterWasm.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DarkMatterWasm.Shared.Models;
using DarkMatterWeb.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace DarkMatterWasm.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class CrewController : ControllerBase
{
private readonly ILogger<ContactController> logger;
private readonly AirTableService airtableService;
public CrewController(ILogger<ContactController> logger, AirTableService airtableService)
{
this.logger = logger;
this.airtableService = airtableService;
}
[HttpGet]
public async Task<IEnumerable<CrewMember>> Get()
{
return await airtableService.GetCrewMembersAsync();
}
}
}
|
using System;
using IniParser.Model;
using NUnit.Framework;
namespace IniFileParser.Tests.Unit.Model
{
[TestFixture, Category("Test of data structures used to hold information retrieved for an INI file")]
public class SectionDataTests
{
[Test]
public void check_default_values()
{
var sd = new SectionData("section_test");
Assert.That(sd, Is.Not.Null);
Assert.That(sd.SectionName, Is.EqualTo("section_test"));
Assert.That(sd.LeadingComments, Is.Empty);
Assert.That(sd.Keys, Is.Empty);
}
[Test, ExpectedException(typeof(ArgumentException))]
public void create_section_with_invalid_name()
{
new SectionData("");
Assert.Fail("I shouldn't be able to create a section with an empty section name");
}
[Test]
public void change_section_name_with_invalid_name()
{
var sd = new SectionData("section_test");
sd.SectionName = "";
Assert.That(sd.SectionName, Is.EqualTo("section_test"));
}
[Test]
public void change_section_name()
{
var sd = new SectionData("section_test");
sd.SectionName = "section_test_2";
Assert.That(sd, Is.Not.Null);
Assert.That(sd.SectionName, Is.EqualTo("section_test_2"));
Assert.That(sd.LeadingComments, Is.Empty);
Assert.That(sd.Keys, Is.Empty);
}
[Test]
public void add_keys_to_section()
{
string strKeyTest = "Mykey";
string strValueTest = "My value";
var sd = new SectionData("section_test");
//Add key
sd.Keys.AddKey(strKeyTest);
Assert.That(sd.Keys.Count, Is.EqualTo(1));
Assert.That(sd.Keys.ContainsKey(strKeyTest), Is.True);
//Assign value
sd.Keys.GetKeyData(strKeyTest).Value = strValueTest;
Assert.That(sd.Keys.GetKeyData(strKeyTest).Value, Is.EqualTo(strValueTest));
}
[Test]
public void try_adding_duplicated_keys_to_section()
{
string strKeyTest = "Mykey";
var sd = new SectionData("section_test");
//Add key
sd.Keys.AddKey(strKeyTest);
Assert.That(sd.Keys.Count, Is.EqualTo(1));
Assert.That(sd.Keys.ContainsKey(strKeyTest), Is.True);
sd.Keys.AddKey(strKeyTest);
Assert.That(sd.Keys.Count, Is.EqualTo(1));
}
[Test]
public void remove_key_from_section()
{
string strKeyTest = "Mykey";
var sd = new SectionData("section_test");
//Add key
sd.Keys.AddKey(strKeyTest);
Assert.That(sd.Keys.Count, Is.EqualTo(1));
Assert.That(sd.Keys.ContainsKey(strKeyTest), Is.True);
sd.Keys.RemoveKey(strKeyTest);
Assert.That(sd.Keys.Count, Is.EqualTo(0));
Assert.That(sd.Keys.ContainsKey(strKeyTest), Is.False);
}
[Test]
public void try_removing_non_existing_key_from_section()
{
string strKeyTest = "Mykey";
var sd = new SectionData("section_test");
//Add key
sd.Keys.AddKey(strKeyTest);
sd.Keys.RemoveKey("asdf");
Assert.That(sd.Keys.Count, Is.EqualTo(1));
Assert.That(sd.Keys.ContainsKey(strKeyTest), Is.True);
Assert.That(sd.Keys.ContainsKey("asdf"), Is.False);
}
[Test]
public void try_accessing_non_existing_key()
{
var sd = new SectionData("section_test");
//Access invalid keydata
Assert.That(sd.Keys["asdf"], Is.Null);
}
[Test]
public void check_you_can_merge_sections()
{
var destinySection = new SectionData("destiny_section");
var newSection= new SectionData("new_section");
//Add key
destinySection.Keys.AddKey("key1","value1");
destinySection.Keys.AddKey("key2","value2");
newSection.Keys.AddKey("key2","newvalue2");
newSection.Keys.AddKey("key3","value3");
destinySection.Merge(newSection);
Assert.That(destinySection.Keys["key1"], Is.EqualTo("value1"));
Assert.That(destinySection.Keys["key2"], Is.EqualTo("newvalue2"));
Assert.That(destinySection.Keys.ContainsKey("key3"));
Assert.That(destinySection.Keys["key3"], Is.EqualTo("value3"));
}
[Test]
public void check_deep_clone()
{
var section = new SectionData("ori_section");
section.Keys.AddKey("key1", "value1");
section.Keys.AddKey("key2", "value2");
var copy = (SectionData)section.Clone();
copy.Keys["key1"] = "value3";
copy.Keys["key2"] = "value4";
Assert.That(section.Keys["key1"], Is.EqualTo("value1"));
Assert.That(section.Keys["key2"], Is.EqualTo("value2"));
}
}
}
|
@model Test.Models.NewsViewModel
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Sport</h1>
<h2>@Model.Title</h2>
<p>@Model.Content</p> |
namespace Windows.Foundation
{
public enum AsyncStatus
{
Canceled = 2,
/// <summary>The operation has completed.</summary>
Completed = 1,
Error = 3,
/// <summary>The operation has started.</summary>
Started = 0
}
} |
using System;
namespace Initio_4tronix.CarController
{
public class Motor
{
public MotorController MotorController { get; set; }
public int MotorNumber { get; set; }
public int MotorPwmPin { get; set; }
public int MotorIn1Pin { get; set; }
public int MotorIn2Pin { get; set; }
public Motor(MotorController motorController, int motorNumber)
{
MotorController = motorController;
MotorNumber = motorNumber;
int motorPwmPin = 0, motorIn2Pin = 0, motorIn1Pin = 0;
if (motorNumber == 0)
{
motorPwmPin = 8;
motorIn1Pin = 9;
motorIn2Pin = 10;
}
else if (motorNumber == 1)
{
motorPwmPin = 13;
motorIn1Pin = 12;
motorIn2Pin = 11;
}
else if (motorNumber == 2)
{
motorPwmPin = 2;
motorIn1Pin = 3;
motorIn2Pin = 4;
}
else if (motorNumber == 3)
{
motorPwmPin = 7;
motorIn1Pin = 6;
motorIn2Pin = 5;
}
else
{
throw new Exception("Motor must be between 1 and 4 inclusive");
}
MotorPwmPin = motorPwmPin;
MotorIn1Pin = motorIn2Pin;
MotorIn2Pin = motorIn1Pin;
}
public void Run(MotorAction command)
{
if (MotorController == null)
{
return;
}
if (command == MotorAction.FORWARD)
{
MotorController.SetPin(MotorIn2Pin, 0);
MotorController.SetPin(MotorIn1Pin, 1);
}
else if (command == MotorAction.BACKWARD)
{
MotorController.SetPin(MotorIn1Pin, 0);
MotorController.SetPin(MotorIn2Pin, 1);
}
else if (command == MotorAction.RELEASE)
{
MotorController.SetPin(MotorIn1Pin, 0);
MotorController.SetPin(MotorIn2Pin, 0);
}
}
public void SetSpeed(int speed)
{
if (speed < 0)
{
speed = 0;
}
else if (speed > 255)
{
speed = 255;
}
MotorController.PwmController.SetPwm((byte)MotorPwmPin, 0, (ushort)(speed * 16));
}
}
public enum MotorAction
{
FORWARD = 1,
BACKWARD = 2,
BRAKE = 3,
RELEASE = 4,
SINGLE = 1,
DOUBLE = 2,
INTERLEAVE = 3,
MICROSTEP = 4
}
}
|
using System.ComponentModel;
namespace Grasews.Domain.Enums
{
public enum ResetPasswordStatusEnum
{
[Description("The password reset has been requested")]
Requested = 0,
[Description("The password reset has been processed")]
Processed = 1,
}
} |
namespace BinaryDataSerialization.Test.Issues.Issue90
{
public abstract class TxpFile
{
[FieldOrder(0)] public char[] Magic = { 'T', 'X', 'P' };
[FieldOrder(1)]
[Subtype("Magic", "TXP", typeof(TxpTexture))]
[Subtype("Magic", "TXP", typeof(TxpTextureAtlas))]
public TxpBase txp;
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.IO;
using System.IO.Compression;
using System.Threading;
using OpenTK;
using Util;
namespace Terrain
{
public class ChunkCache
{
public Int32 byteCount { get; set; } //a 0 offset means it's just air
public byte[] compresedData { get; set; }
public ChunkCache()
{
}
}
public class TerrainCache
{
String myFilename;
ConcurrentDictionary<UInt64, ChunkCache> myCacheDb = new ConcurrentDictionary<UInt64, ChunkCache>();
public int sizeInBytes { get; set; }
public int chunkCount { get; set; }
public TerrainCache(String path)
{
myFilename = path;
if (loadDatabase() == false)
{
throw new Exception("Failed to initialize game world data");
}
}
public void reset()
{
//delete the database on disk
File.Delete(myFilename);
myCacheDb.Clear();
chunkCount = 0;
if (loadDatabase() == false)
{
throw new Exception("Failed to initialize game world data");
}
}
public void reload()
{
if (loadDatabase() == false)
{
throw new Exception("Failed to initialize game world data");
}
}
public void shutdown()
{
saveDatabase();
}
public bool containsChunk(UInt64 id)
{
return myCacheDb.ContainsKey(id);
}
public Chunk findChunk(UInt64 id)
{
Chunk chunk = null;
ChunkCache ti=null;
if (myCacheDb.TryGetValue(id, out ti) == false) // is it loaded, but compressed?
{
return null; //this means that the generator needs to create it
}
else //decompress it
{
chunk = new Chunk(Vector3.Zero);
chunk.chunkKey = new ChunkKey(id);
if (ti.byteCount != 0)
{
byte[] data = decompressChunk(ti.compresedData);
chunk.deserialize(data);
}
}
return chunk;
}
public byte[] compressedChunk(UInt64 id)
{
ChunkCache ti = null;
if (myCacheDb.TryGetValue(id, out ti) == false) // is it loaded, but compressed?
{
return null;
}
return ti.compresedData;
}
public void updateChunk(Chunk chunk)
{
UInt64 key = chunk.key;
if (myCacheDb.ContainsKey(key) == true)
{
//update metric
sizeInBytes -= myCacheDb[key].byteCount;
}
else
{
chunkCount++;
}
ChunkCache ti = new ChunkCache();
//save a little space on empty chunks
//TODO: revisit this in case of dynamic chunks or variable size chunks
if (chunk.isAir() == true)
{
ti.byteCount = 0;
ti.compresedData = new byte[0];
}
else
{
byte[] data = chunk.serialize();
data = compressChunk(data);
ti.byteCount = data.Length;
ti.compresedData = data;
//update metric
sizeInBytes += ti.byteCount;
}
myCacheDb[key] = ti;
}
public Chunk handleResponse(TerrainResponseEvent tcr)
{
Chunk chunk = new Chunk(Vector3.Zero);
chunk.chunkKey = new ChunkKey(tcr.chunkId);
byte[] data = decompressChunk(tcr.data.ToArray());
chunk.deserialize(data);
updateChunk(chunk);
return chunk;
}
#region file handling
bool loadDatabase()
{
Info.print("Loading game world: {0}", myFilename);
if (File.Exists(myFilename) == false)
{
Error.print("Unable to find game world {0}", myFilename);
return true;
}
using (BinaryReader reader = new BinaryReader(File.Open(myFilename, FileMode.Open)))
{
//read the header
Char[] fileType = reader.ReadChars(4);
if (fileType[0] != 'O' ||
fileType[1] != 'C' ||
fileType[2] != 'T' ||
fileType[3] != 'A')
{
return false;
}
int version = reader.ReadInt32();
if (version != 1)
return false;
int indexCount = reader.ReadInt32();
Info.print("Reading {0} chunk records", indexCount);
for (int i = 0; i < indexCount; i++)
{
ChunkCache ti= new ChunkCache();
UInt64 id = reader.ReadUInt64();
ti.byteCount = reader.ReadInt32();
ti.compresedData = reader.ReadBytes(ti.byteCount);
myCacheDb[id] = ti;
//update metric
sizeInBytes += ti.byteCount;
chunkCount++;
}
Info.print("Done");
}
return true;
}
bool saveDatabase()
{
using (BinaryWriter writer = new BinaryWriter(File.Open(myFilename, FileMode.Create)))
{
//gather some info
Char[] octa = new Char[4] { 'O', 'C', 'T', 'A' };
int recordCount=myCacheDb.Count;
//Write the header
writer.Write(octa); //4 letter identifier
writer.Write(1); //version number
writer.Write(recordCount); //size of the chunk
foreach (KeyValuePair<UInt64, ChunkCache> ti in myCacheDb)
{
writer.Write(ti.Key); //UInt64 chunk key
writer.Write(ti.Value.compresedData.Length); //size in bytes of the compressed chunk
writer.Write(ti.Value.compresedData); //compressed chunk data
}
}
return true;
}
#endregion
#region compression
byte[] compressChunk(byte[] data)
{
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gzs = new GZipStream(ms, CompressionMode.Compress))
{
// Write the data to the stream to compress it
gzs.Write(BitConverter.GetBytes(data.Length), 0, sizeof(int));
gzs.Write(data, 0, data.Length);
gzs.Close();
}
// Get the compressed byte array back
return ms.ToArray();
}
}
byte[] decompressChunk(byte[] data)
{
using (MemoryStream ms = new MemoryStream(data))
{
using (GZipStream gzs = new GZipStream(ms, CompressionMode.Decompress))
{
byte[] dataSizeArray = new byte[sizeof(int)];
gzs.Read(dataSizeArray, 0, dataSizeArray.Length);
int dataSize = BitConverter.ToInt32(dataSizeArray, 0);
byte[] ret = new byte[dataSize];
gzs.Read(ret, 0, ret.Length);
return ret;
}
}
}
#endregion
}
} |
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// ZhimaCustomerBehaviorSyncModel Data Structure.
/// </summary>
public class ZhimaCustomerBehaviorSyncModel : AlipayObject
{
/// <summary>
/// 反馈行为
/// </summary>
[JsonPropertyName("behavior")]
public List<string> Behavior { get; set; }
/// <summary>
/// 行为所携带的内容,fulfillment:{"subjectDeltaNum":"1","subjectType":"subject"}
/// </summary>
[JsonPropertyName("behavior_content")]
public string BehaviorContent { get; set; }
/// <summary>
/// 约定编号
/// </summary>
[JsonPropertyName("contract_no")]
public string ContractNo { get; set; }
/// <summary>
/// 业务发生时间
/// </summary>
[JsonPropertyName("gmt_service")]
public string GmtService { get; set; }
/// <summary>
/// 主体类型B或者C
/// </summary>
[JsonPropertyName("principal_type")]
public string PrincipalType { get; set; }
/// <summary>
/// 芝麻信用service_id,由芝麻信用提供
/// </summary>
[JsonPropertyName("service_id")]
public string ServiceId { get; set; }
/// <summary>
/// 芝麻信用service_id,由芝麻信用提供
/// </summary>
[JsonPropertyName("subject_id")]
public string SubjectId { get; set; }
/// <summary>
/// 外部订单号,商户请求的唯一标志,64位长度的字母数字下划线组合。该标识作为对账的关键信息,商户要保证其唯一性
/// </summary>
[JsonPropertyName("transaction_id")]
public string TransactionId { get; set; }
/// <summary>
/// 蚂蚁统一会员ID
/// </summary>
[JsonPropertyName("user_id")]
public string UserId { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Goodreads8.ViewModel.Model
{
class Topic
{
public int Id { get; set; }
public String Title { get; set; }
public DateTime LastCommentAt { get; set; }
public int CommentCount { get; set; }
public List<Comment> Comments { get; set; }
public String Author { get; set; }
public class Comment
{
public int Id { get; set; }
public String Body { get; set; }
public Profile User { get; set; }
public DateTime UpdatedAt { get; set; }
public String ListViewText
{
get
{
if (User == null || string.IsNullOrEmpty(User.Name))
return "Unknown";
if (UpdatedAt == null)
return User.Name;
return User.Name + ", " + UpdatedAt.ToString("MMMM dd, h:mm tt");
}
}
}
public String ListViewText
{
get
{
String user = Author;
if (String.IsNullOrEmpty(user))
user = "Unknown";
if (LastCommentAt == null || LastCommentAt == DateTime.MinValue)
return user;
return user + ", " + LastCommentAt.ToString("MMMM dd, h:mm tt");
}
}
public String CommentCountText
{
get
{
return CommentCount.ToString() + " post(s)";
}
}
}
}
|
using System.Collections.Generic;
using NUnit.Framework;
using Nvelope.Data;
namespace Nvelope.Tests.Data
{
[TestFixture]
public class DataProxyTests
{
[Test]
public void NoOverrides()
{
var data = new
{
Name = "Brian",
Id = 168337
};
DataProxy d = new DataProxy(new Dictionary<string, string>(), data);
Assert.AreEqual("Brian", d["Name"]);
Assert.AreEqual("168337", d["Id"]);
}
[Test]
public void OnlyOverrides()
{
var overrides = new Dictionary<string, string>();
overrides.Add("Name", "Brian");
overrides.Add("Id", "168337");
DataProxy d = new DataProxy(overrides);
Assert.AreEqual("Brian", d["Name"]);
Assert.AreEqual("168337", d["Id"]);
}
[Test]
public void Mixed()
{
var data = new
{
Name = "Brian",
Id = 168337
};
var overrides = new Dictionary<string, string>();
overrides.Add("Color", "Red");
DataProxy d = new DataProxy(overrides, data);
Assert.AreEqual("Brian", d["Name"]);
Assert.AreEqual("168337", d["Id"]);
Assert.AreEqual("Red", d["Color"]);
// Now, name should be returned as Bjorn, even though the underlying
// object still says Brian
overrides.Add("Name", "Bjorn");
d = new DataProxy(overrides, data);
Assert.AreEqual("Bjorn", d["Name"]);
Assert.AreEqual("168337", d["Id"]);
Assert.AreEqual("Red", d["Color"]);
}
[Test]
public void KeyNotFound()
{
var data = new
{
Name = "Brian",
Id = 168337
};
var overrides = new Dictionary<string, string>();
overrides.Add("Color", "Red");
DataProxy d = new DataProxy(overrides, data);
string res = "";
Assert.Throws(typeof(KeyNotFoundException),() => res = d["Foobar"]);
}
[Test (Description="Verifies that the DataProxy class can correctly handle a Dictionary")]
public void Dictionary()
{
var data = new Dictionary<string, object>(){
{ "FirstName", "Bruce" },
{ "LastName", "Wayne" },
{ "Age", 42 }
};
var overrides = new Dictionary<string, string>();
overrides.Add("FirstName", "Batman");
var d = new DataProxy(overrides, data);
Assert.AreEqual("Batman", d["FirstName"]);
Assert.AreEqual("Wayne", d["LastName"]);
Assert.AreEqual("42", d["Age"]);
}
}
}
|
using Example.Core.ExternalApi.ExampleAuthApi.Dto.Data;
using Example.Core.ExternalApi.ExampleAuthApi.Dto.Login;
using Example.Domain.Model.Integration;
using System.Collections.Generic;
namespace Example.Core.ExternalApi.ExtenalApiExample
{
internal class ExampleAuthApi : BaseExternalApi
{
public ExampleAuthApi(IntegrationModel model) : base(model.BaseUrl, model.Token)
{
}
public LoginResponseDto Login(LoginRequestDto request)
{
return HttpPost<LoginResponseDto>("login", request);
}
public List<OrderDto> GetOrderList(DataRequestDto request)
{
return HttpGet<List<OrderDto>>("example/external_order_system/order", request);
}
public OrderDto GetOrderById(long dataId)
{
return HttpGet<OrderDto>($"example/external_order_system/order/{dataId}");
}
public OrderDto CreateOrder(OrderDto dto)
{
return HttpPost<OrderDto>($"example/external_order_system/order", dto);
}
internal void DeleteOrder(string externalOrderId)
{
HttpDelete($"example/external_order_system/order/{externalOrderId}");
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.