content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using UnityEditor;
using UnityEngine;
using WeaverCore.Attributes;
using WeaverCore.Editor.Settings;
using WeaverCore.Editor.Utilities;
using WeaverCore.Utilities;
using UnityEditor.PackageManager;
using UnityEditor.PackageManager.Requests;
using PackageClient = UnityEditor.PackageManager.Client;
namespace WeaverCore.Editor.Compilation
{
/// <summary>
/// Contains the tools needed for building mod assemblies
/// </summary>
public static class BuildTools
{
static DirectoryInfo weaverCoreFolder;
/// <summary>
/// The folder that contains all of WeaverCore's assets
/// </summary>
public static DirectoryInfo WeaverCoreFolder
{
get
{
if (weaverCoreFolder == null)
{
var asmDef = PathUtilities.ProjectFolder.GetFiles("WeaverCore.asmdef", SearchOption.AllDirectories);
if (asmDef.Length > 0)
{
weaverCoreFolder = asmDef[0].Directory;
}
}
return weaverCoreFolder;
}
}
/// <summary>
/// The default build location for WeaverCore
/// </summary>
public static FileInfo WeaverCoreBuildLocation = new FileInfo(WeaverCoreFolder.AddSlash() + $"Other Projects~{Path.DirectorySeparatorChar}WeaverCore.Game{Path.DirectorySeparatorChar}WeaverCore Build{Path.DirectorySeparatorChar}WeaverCore.dll");
/// <summary>
/// Used to represent an asynchronous assembly build task
/// </summary>
class BuildTask<T> : IAsyncBuildTask<T>
{
/// <inheritdoc/>
public T Result { get; set; }
/// <inheritdoc/>
public bool Completed { get; set; }
/// <inheritdoc/>
object IAsyncBuildTask.Result { get { return Result; } set { Result = (T)value; } }
}
/// <summary>
/// Contains all the parameters needed to build a mod assembly
/// </summary>
class BuildParameters
{
/// <summary>
/// The directory the mod is being placed in when built
/// </summary>
public DirectoryInfo BuildDirectory;
/// <summary>
/// The file name of the built assembly
/// </summary>
public string FileName;
/// <summary>
/// The full path of where the assembly is going to be located when built
/// </summary>
public FileInfo BuildPath
{
get
{
return new FileInfo(PathUtilities.AddSlash(BuildDirectory.FullName) + FileName);
}
set
{
BuildDirectory = value.Directory;
FileName = value.Name;
}
}
/// <summary>
/// A list of script paths that are included in the build
/// </summary>
public List<string> Scripts = new List<string>();
/// <summary>
/// A list of assembly reference paths that are to be included in the build process
/// </summary>
public List<string> AssemblyReferences = new List<string>();
/// <summary>
/// A list of assembly reference paths to be excluded from the build process
/// </summary>
public List<string> ExcludedReferences = new List<string>();
/// <summary>
/// A list of #defines to include in the build process
/// </summary>
public List<string> Defines = new List<string>();
/// <summary>
/// The target platform the mod is being built against
/// </summary>
public BuildTarget Target = BuildTarget.StandaloneWindows;
/// <summary>
/// The target group the mod is being built against
/// </summary>
public BuildTargetGroup Group = BuildTargetGroup.Standalone;
}
/// <summary>
/// Contains the output information of a assembly build process
/// </summary>
public class BuildOutput
{
public bool Success;
public List<FileInfo> OutputFiles = new List<FileInfo>();
}
/// <summary>
/// Builds a WeaverCore DLL without any resources embedded into it. This also runs <see cref="BuildHollowKnightAsm(FileInfo)"/> and puts it into the same output directory, since WeaverCore depends on it
/// </summary>
/// <returns>The output file</returns>
public static IAsyncBuildTask<BuildOutput> BuildPartialWeaverCore(FileInfo outputPath)
{
var task = new BuildTask<BuildOutput>();
UnboundCoroutine.Start(BuildPartialWeaverCoreRoutine(outputPath,task));
return task;
}
static IEnumerator BuildPartialWeaverCoreRoutine(FileInfo outputPath, BuildTask<BuildOutput> task)
{
if (task == null)
{
task = new BuildTask<BuildOutput>();
}
task.Result = new BuildOutput();
var buildDirectory = outputPath.Directory;
var hkFile = new FileInfo(PathUtilities.AddSlash(buildDirectory.FullName) + "Assembly-CSharp.dll");
var hkBuildTask = BuildHollowKnightAsm(hkFile);
yield return new WaitUntil(() => hkBuildTask.Completed);
task.Result.Success = hkBuildTask.Result.Success;
task.Result.OutputFiles = hkBuildTask.Result.OutputFiles;
if (!hkBuildTask.Result.Success)
{
task.Completed = true;
yield break;
}
yield return BuildAssembly(new BuildParameters
{
BuildPath = outputPath,
AssemblyReferences = hkBuildTask.Result.OutputFiles.Select(f => f.FullName).ToList(),
Defines = new List<string>
{
"GAME_BUILD"
},
ExcludedReferences = new List<string>
{
"Library/ScriptAssemblies/WeaverCore.dll",
"Library/ScriptAssemblies/HollowKnight.dll",
"Library/ScriptAssemblies/HollowKnight.FirstPass.dll",
"Library/ScriptAssemblies/WeaverCore.Editor.dll",
"Library/ScriptAssemblies/WeaverBuildTools.dll",
"Library/ScriptAssemblies/TMPro.Editor.dll",
"Library/ScriptAssemblies/0Harmony.dll",
"Library/ScriptAssemblies/Mono.Cecil.dll",
"Library/ScriptAssemblies/JUNK.dll"
},
Scripts = ScriptFinder.FindAssemblyScripts("WeaverCore")
}, BuildPresetType.Game,task);
}
/// <summary>
/// Builds a DLL using the scripts from WeaverCore/Hollow Knight
/// </summary>
/// <param name="outputPath">The path the file will be placed</param>
/// <returns></returns>
public static IAsyncBuildTask<BuildOutput> BuildHollowKnightAsm(FileInfo outputPath)
{
var task = new BuildTask<BuildOutput>();
UnboundCoroutine.Start(BuildHollowKnightAsmRoutine(outputPath, task));
return task;
}
static IEnumerator BuildHollowKnightAsmRoutine(FileInfo outputPath, BuildTask<BuildOutput> task)
{
if (task == null)
{
task = new BuildTask<BuildOutput>();
}
BuildTask<BuildOutput> firstPassTask = new BuildTask<BuildOutput>();
var firstPassLocation = new FileInfo(outputPath.Directory.AddSlash() + "Assembly-CSharp-firstpass.dll");
yield return BuildAssembly(new BuildParameters
{
BuildPath = firstPassLocation,
Scripts = ScriptFinder.FindAssemblyScripts("HollowKnight.FirstPass"),
Defines = new List<string>
{
"GAME_BUILD"
},
ExcludedReferences = new List<string>
{
"Library/ScriptAssemblies/HollowKnight.dll",
"Library/ScriptAssemblies/HollowKnight.FirstPass.dll",
"Library/ScriptAssemblies/JUNK.dll"
},
}, BuildPresetType.Game, firstPassTask);
if (!firstPassTask.Result.Success)
{
task.Completed = true;
task.Result = firstPassTask.Result;
yield break;
}
yield return BuildAssembly(new BuildParameters
{
BuildPath = outputPath,
Scripts = ScriptFinder.FindAssemblyScripts("HollowKnight"),
Defines = new List<string>
{
"GAME_BUILD"
},
ExcludedReferences = new List<string>
{
"Library/ScriptAssemblies/HollowKnight.dll",
"Library/ScriptAssemblies/HollowKnight.FirstPass.dll",
"Library/ScriptAssemblies/JUNK.dll"
},
AssemblyReferences = new List<string>
{
firstPassLocation.FullName
}
}, BuildPresetType.Game, task);
if (!task.Result.Success)
{
yield break;
}
}
static IEnumerator BuildAssembly(BuildParameters parameters, BuildPresetType presetType, BuildTask<BuildOutput> task)
{
task.Completed = false;
if (task.Result == null)
{
task.Result = new BuildOutput();
}
else
{
task.Result.Success = false;
}
var builder = new AssemblyCompiler();
builder.BuildDirectory = parameters.BuildDirectory;
builder.FileName = parameters.FileName;
builder.Scripts = parameters.Scripts;
builder.Target = parameters.Target;
builder.TargetGroup = parameters.Group;
builder.References = parameters.AssemblyReferences;
builder.ExcludedReferences = parameters.ExcludedReferences;
builder.Defines = parameters.Defines;
if (builder.Scripts == null || builder.Scripts.Count == 0)
{
Debug.LogError("There are no scripts to build");
task.Result.Success = false;
task.Completed = true;
yield break;
}
if (presetType == BuildPresetType.Game || presetType == BuildPresetType.Editor)
{
builder.AddUnityReferences();
}
if (presetType == BuildPresetType.Game)
{
builder.RemoveEditorReferences();
}
if (!parameters.BuildPath.Directory.Exists)
{
parameters.BuildPath.Directory.Create();
}
if (parameters.BuildPath.Exists)
{
parameters.BuildPath.Delete();
}
AssemblyCompiler.OutputDetails output = new AssemblyCompiler.OutputDetails();
yield return builder.Build(output);
if (output.Success)
{
task.Result.OutputFiles.Add(parameters.BuildPath);
}
task.Result.Success = output.Success;
task.Completed = true;
}
static IEnumerator BuildPartialModAsmRoutine(FileInfo outputPath, BuildTask<BuildOutput> task)
{
if (task == null)
{
task = new BuildTask<BuildOutput>();
}
var weaverCoreTask = BuildPartialWeaverCore(WeaverCoreBuildLocation);
yield return new WaitUntil(() => weaverCoreTask.Completed);
if (!weaverCoreTask.Result.Success)
{
task.Completed = true;
task.Result = new BuildOutput
{
Success = false
};
Debug.Log("Failed to build WeaverCore");
yield break;
}
var parameters = new BuildParameters
{
BuildPath = outputPath,
Scripts = ScriptFinder.FindAssemblyScripts("Assembly-CSharp"),
Defines = new List<string>
{
"GAME_BUILD"
},
ExcludedReferences = new List<string>
{
"Library/ScriptAssemblies/HollowKnight.dll",
"Library/ScriptAssemblies/HollowKnight.FirstPass.dll",
"Library/ScriptAssemblies/JUNK.dll",
"Library/ScriptAssemblies/WeaverCore.dll",
"Library/ScriptAssemblies/Assembly-CSharp.dll"
}
};
foreach (var outputFile in weaverCoreTask.Result.OutputFiles)
{
parameters.AssemblyReferences.Add(outputFile.FullName);
}
yield return BuildAssembly(parameters, BuildPresetType.Game, task);
}
/// <summary>
/// Starts the mod assembly build process
/// </summary>
public static void BuildMod()
{
BuildMod(new FileInfo(GetModBuildFileLocation()));
}
/// <summary>
/// Stars the mod assembly build process
/// </summary>
/// <param name="outputPath">The output location of the mod assembly</param>
public static void BuildMod(FileInfo outputPath)
{
UnboundCoroutine.Start(BuildModRoutine(outputPath, null));
}
/// <summary>
/// Builds the "WeaverCore.dll" assembly
/// </summary>
public static void BuildWeaverCore()
{
BuildWeaverCore(new FileInfo(GetModBuildFolder() + "WeaverCore.dll"));
}
/// <summary>
/// Builds the "WeaverCore.dll" assembly
/// </summary>
/// <param name="outputPath">The output location of the "WeaverCore.dll" assembly</param>
public static void BuildWeaverCore(FileInfo outputPath)
{
UnboundCoroutine.Start(BuildWeaverCoreRoutine(outputPath, null));
}
static IEnumerator BuildWeaverCoreRoutine(FileInfo outputPath, BuildTask<BuildOutput> task)
{
if (task == null)
{
task = new BuildTask<BuildOutput>();
}
yield return BuildPartialWeaverCoreRoutine(outputPath, task);
if (!task.Result.Success)
{
yield break;
}
task.Result.Success = false;
yield return BuildWeaverCoreGameRoutine(null, task);
if (!task.Result.Success)
{
yield break;
}
BundleTools.BuildAndEmbedAssetBundles(null, outputPath, typeof(BuildTools).GetMethod(nameof(OnBuildFinish)));
}
static IEnumerator BuildModRoutine(FileInfo outputPath, BuildTask<BuildOutput> task)
{
if (task == null)
{
task = new BuildTask<BuildOutput>();
}
var modBuildLocation = new FileInfo(outputPath.Directory.CreateSubdirectory(BuildScreen.BuildSettings.ModName).AddSlash() + BuildScreen.BuildSettings.ModName + ".dll");
yield return BuildPartialModAsmRoutine(modBuildLocation, task);
if (!task.Result.Success)
{
yield break;
}
task.Result.Success = false;
yield return BuildWeaverCoreGameRoutine(null, task);
if (!task.Result.Success)
{
yield break;
}
var weaverCoreOutputLocation = outputPath.Directory.CreateSubdirectory("WeaverCore").AddSlash() + "WeaverCore.dll";
File.Copy(WeaverCoreBuildLocation.FullName, weaverCoreOutputLocation, true);
BundleTools.BuildAndEmbedAssetBundles(modBuildLocation, new FileInfo(weaverCoreOutputLocation),typeof(BuildTools).GetMethod(nameof(OnBuildFinish)));
}
[OnInit]
static void Init()
{
bool ranMethod = false;
//Check if a build function is scheduled to run, and run it if there is one
if (PersistentData.ContainsData<BundleTools.BundleBuildData>())
{
var bundleData = BundleTools.Data;
if (bundleData?.NextMethod.Method != null)
{
ranMethod = true;
var method = bundleData.NextMethod.Method;
UnboundCoroutine.Start(Delay());
IEnumerator Delay()
{
yield return new WaitForSeconds(0.5f);
if (EditorApplication.isCompiling)
{
yield return new WaitUntil(() => !EditorApplication.isCompiling);
}
yield return new WaitForSeconds(0.5f);
bundleData.NextMethod = default;
PersistentData.StoreData(bundleData);
PersistentData.SaveData();
method.Invoke(null, null);
}
}
}
//Check dependencies if a build function is not scheduled to be run
if (!ranMethod)
{
DependencyChecker.CheckDependencies();
}
}
/// <summary>
/// Builds the WeaverCore.Game Assembly
/// </summary>
public static void BuildWeaverCoreGameAsm()
{
BuildWeaverCoreGameAsm(null);
}
/// <summary>
/// Builds the WeaverCore.Game Assembly
/// </summary>
/// <param name="outputPath">The output path of the build. If set to null, it will be placed in the default build location</param>
public static void BuildWeaverCoreGameAsm(FileInfo outputPath)
{
UnboundCoroutine.Start(BuildWeaverCoreGameRoutine(outputPath,null));
}
static IEnumerator BuildWeaverCoreGameRoutine(FileInfo outputPath, BuildTask<BuildOutput> task)
{
return BuildXmlProjectRoutine(new FileInfo(WeaverCoreFolder.AddSlash() + $"Other Projects~{Path.DirectorySeparatorChar}WeaverCore.Game{Path.DirectorySeparatorChar}WeaverCore.Game{Path.DirectorySeparatorChar}WeaverCore.Game.csproj"), outputPath, task);
}
class XmlReference
{
public string AssemblyName;
public FileInfo HintPath;
}
static IEnumerator BuildXmlProjectRoutine(FileInfo xmlProjectFile, FileInfo outputPath, BuildTask<BuildOutput> task)
{
if (task == null)
{
task = new BuildTask<BuildOutput>();
}
using (var stream = File.OpenRead(xmlProjectFile.FullName))
{
using (var reader = XmlReader.Create(stream, new XmlReaderSettings { IgnoreComments = true }))
{
reader.ReadToFollowing("Project");
reader.ReadToDescendant("PropertyGroup");
reader.ReadToFollowing("PropertyGroup");
reader.ReadToDescendant("OutputPath");
if (outputPath == null)
{
var foundOutputPath = reader.ReadElementContentAsString();
if (Path.IsPathRooted(foundOutputPath))
{
outputPath = new FileInfo(PathUtilities.AddSlash(foundOutputPath) + "WeaverCore.Game.dll");
}
else
{
outputPath = new FileInfo(PathUtilities.AddSlash(xmlProjectFile.Directory.FullName) + PathUtilities.AddSlash(foundOutputPath) + "WeaverCore.Game.dll");
}
}
reader.ReadToFollowing("ItemGroup");
List<XmlReference> References = new List<XmlReference>();
List<string> Scripts = new List<string>();
while (reader.Read())
{
if (reader.Name == "Reference")
{
var referenceName = reader.GetAttribute("Include");
FileInfo hintPath = null;
while (reader.Read() && reader.Name != "Reference")
{
if (reader.Name == "HintPath")
{
var contents = reader.ReadElementContentAsString();
if (Path.IsPathRooted(contents))
{
hintPath = new FileInfo(contents);
}
else
{
hintPath = new FileInfo(PathUtilities.AddSlash(xmlProjectFile.Directory.FullName) + contents);
}
}
}
if (referenceName.Contains("Version=") || referenceName.Contains("Culture=") || referenceName.Contains("PublicKeyToken=") || referenceName.Contains("processorArchitecture="))
{
referenceName = new AssemblyName(referenceName).Name;
}
References.Add(new XmlReference
{
AssemblyName = referenceName,
HintPath = hintPath
});
}
else if (reader.Name == "ItemGroup")
{
break;
}
}
foreach (var scriptFile in xmlProjectFile.Directory.GetFiles("*.cs",SearchOption.AllDirectories))
{
Scripts.Add(scriptFile.FullName);
}
List<DirectoryInfo> AssemblySearchDirectories = new List<DirectoryInfo>
{
new DirectoryInfo(PathUtilities.AddSlash(GameBuildSettings.Settings.HollowKnightLocation) + $"hollow_knight_Data{Path.DirectorySeparatorChar}Managed"),
new FileInfo(typeof(UnityEditor.EditorWindow).Assembly.Location).Directory
};
List<string> AssemblyReferences = new List<string>();
foreach (var xmlRef in References)
{
if (xmlRef.AssemblyName == "System")
{
continue;
}
if (xmlRef.HintPath != null && xmlRef.HintPath.Exists)
{
AssemblyReferences.Add(xmlRef.HintPath.FullName);
}
else
{
bool found = false;
foreach (var searchDir in AssemblySearchDirectories)
{
var filePath = PathUtilities.AddSlash(searchDir.FullName) + xmlRef.AssemblyName + ".dll";
if (File.Exists(filePath))
{
found = true;
AssemblyReferences.Add(filePath);
break;
}
}
if (!found)
{
Debug.LogError("Unable to find WeaverCore.Game Reference -> " + xmlRef.AssemblyName);
}
}
}
var scriptAssemblies = new DirectoryInfo($"Library{Path.DirectorySeparatorChar}ScriptAssemblies").GetFiles("*.dll");
List<string> exclusions = new List<string>();
foreach (var sa in scriptAssemblies)
{
exclusions.Add(PathUtilities.ConvertToProjectPath(sa.FullName));
}
var weaverCoreLibraries = new DirectoryInfo(WeaverCoreFolder.AddSlash() + "Libraries").GetFiles("*.dll");
foreach (var wl in weaverCoreLibraries)
{
exclusions.Add(PathUtilities.ConvertToProjectPath(wl.FullName));
}
var editorDir = new FileInfo(typeof(UnityEditor.EditorWindow).Assembly.Location).Directory;
foreach (var ueFile in editorDir.Parent.GetFiles("UnityEngine.dll", SearchOption.AllDirectories))
{
exclusions.Add(ueFile.FullName);
}
yield return BuildAssembly(new BuildParameters
{
BuildPath = outputPath,
Scripts = Scripts,
Defines = new List<string>
{
"GAME_BUILD"
},
ExcludedReferences = exclusions,
AssemblyReferences = AssemblyReferences,
}, BuildPresetType.None, task);
}
}
yield break;
}
/// <summary>
/// Gets the location of where the mod assembly is going to be placed in
/// </summary>
public static string GetModBuildFolder()
{
string compileLocation = null;
if (compileLocation == null)
{
if (!string.IsNullOrEmpty(BuildScreen.BuildSettings?.BuildLocation))
{
compileLocation = BuildScreen.BuildSettings.BuildLocation;
}
else
{
compileLocation = SelectionUtilities.SelectFolder("Select where you want to place the finished mod", "");
if (compileLocation == null)
{
throw new Exception("An invalid path specified for building the mod");
}
}
}
return PathUtilities.AddSlash(compileLocation);
}
/// <summary>
/// Gets the full path of where the mod assembly is going to be placed in
/// </summary>
/// <returns></returns>
public static string GetModBuildFileLocation()
{
return GetModBuildFolder() + BuildScreen.BuildSettings.ModName + ".dll";
}
/// <summary>
/// Called when a mod assembly build is completed
/// </summary>
public static void OnBuildFinish()
{
if (BuildScreen.BuildSettings.StartGame)
{
Debug.Log("<b>Starting Game</b>");
var hkEXE = new FileInfo(GameBuildSettings.Settings.HollowKnightLocation + "\\hollow_knight.exe");
if (hkEXE.FullName.Contains("steamapps"))
{
var steamDirectory = hkEXE.Directory;
while (steamDirectory.Name != "Steam")
{
steamDirectory = steamDirectory.Parent;
if (steamDirectory == null)
{
break;
}
}
if (steamDirectory != null)
{
System.Diagnostics.Process.Start(steamDirectory.FullName + "\\steam.exe", "steam://rungameid/367520");
return;
}
}
System.Diagnostics.Process.Start(hkEXE.FullName);
}
DependencyChecker.CheckDependencies();
}
}
}
| 29.25 | 254 | 0.684597 | [
"MIT"
] | nickc01/CrystalCore | WeaverCore.Editor/Compilation/BuildTools.cs | 21,530 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml;
using NSoupSpider;
using NSoup.Nodes;
using NSoup;
namespace NSoupSpiderTester
{
[TestClass]
public class ExtractTaskDocumentTester
{
//string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string baseDir = @"E:\Dev\proj\EnterpriseCommon\NSoupSpider\NSoupSpiderTester\bin\Debug";
[TestMethod]
public void DocReaderSellerNameTest()
{
TestDocumentWithRules(Path.Combine(baseDir, @"testDocs\olp_merch_rating_3.htm"), Path.Combine(baseDir, @"rules\sellerName-uk.xml"));
}
void TestDocumentWithRules(string docPath, string rulePath)
{
ExtractTaskDocument taskDoc = new ExtractTaskDocument(rulePath).BindRules();
taskDoc.ExtractArguments.Add("SiteUrl", "https://www.amazon.co.uk");
taskDoc.ExtractArguments.Add("Asin", "B009A4A8ZO");
taskDoc.ExtractArguments.Add("SellerId", "APZXIW0LSZ4VN");
//Document rootDoc = extraTask.GetStartupDocument();
string html = File.ReadAllText(docPath);
Document rootDoc = NSoupClient.Parse(html);
fetchPageData:
using (ExecutionContextScope scope = new ExecutionContextScope())
{
ExtractDocumentReport report = taskDoc.ExtractWith(rootDoc);
if (!report.IsSuccess())
{
throw report.ExtractExcetpion;
}
else
{
ExtractPagerNode node = taskDoc.GetPagerNode();
if (node != null)
{
List<string> nextUrls = node.GetPageUrlList();
if (node.PageListType == PagerType.ByNext)
{
if (nextUrls.Any())
{
taskDoc.DocumentUrl = nextUrls[0];
rootDoc = taskDoc.GetDocumentByUrl(taskDoc.DocumentUrl);
goto fetchPageData;
}
}
else
{
string currentDocUrl = taskDoc.EntryUrl.GetUrl();
}
}
}
}
}
[TestMethod]
public void DocReaderGrabBuyboxWinnerTest()
{
TestDocumentWithRules(Path.Combine(baseDir, @"testDocs\GrabBuyboxWinner.htm"), Path.Combine(baseDir, @"rules\GrabBuyboxWinnerHandler-uk.xml"));
}
[TestMethod]
public void DocReaderAsinImageTest()
{
TestDocumentWithRules(Path.Combine(baseDir, @"testDocs\GrabBuyboxWinner.htm"), Path.Combine(baseDir, @"rules\asinImage-uk.xml"));
}
[TestMethod]
public void GrabOfferListingsHandlerTest()
{
TestDocumentWithRules(Path.Combine(baseDir, @"testDocs\offer-listing-B009A4A8ZO.htm"), Path.Combine(baseDir, @"rules\GrabOfferListingsHandler-uk.xml"));
}
}
}
| 35.193548 | 164 | 0.559731 | [
"MIT"
] | ridgew/NSoupSpider | NSoupSpiderTester/ExtractTaskDocumentTester.cs | 3,275 | C# |
using System;
using BuildingBlocks.CQRS.QueryHandling;
using EcommerceDDD.Application.EventSourcing.StoredEventsData;
using FluentValidation;
using FluentValidation.Results;
using System.Collections.Generic;
namespace EcommerceDDD.Application.Orders.ListOrderStoredEvents
{
public class ListOrderStoredEventsQuery : Query<IList<StoredEventData>>
{
public Guid OrderId { get; }
public ListOrderStoredEventsQuery(Guid orderId)
{
OrderId = orderId;
}
public override ValidationResult Validate()
{
return new ListOrderStoredEventsQueryValidator().Validate(this);
}
}
public class ListOrderStoredEventsQueryValidator : AbstractValidator<ListOrderStoredEventsQuery>
{
public ListOrderStoredEventsQueryValidator()
{
RuleFor(x => x.OrderId).NotEqual(Guid.Empty).WithMessage("OrderId is empty.");
}
}
}
| 28.454545 | 100 | 0.705005 | [
"MIT"
] | AELMOUMNI/EcommerceDDD | src/EcommerceDDD.Application/Orders/ListOrderStoredEvents/ListOrderStoredEventsQuery.cs | 941 | C# |
using UnityEngine;
public class ScoreKeeper : MonoBehaviour
{
int correctAnswers = 0;
int questionsSeen = 0;
public int GetCorrecAnswers()
{
return correctAnswers;
}
public void IncrementCorrectAnswers()
{
correctAnswers++;
}
public int GetQuestionsSeen()
{
return questionsSeen;
}
public void IncrementQuestionsSeen()
{
questionsSeen++;
}
public int CalculateScore()
{
return Mathf.RoundToInt(correctAnswers / (float)questionsSeen * 100);
}
}
| 16.909091 | 77 | 0.620072 | [
"MIT"
] | Miillky/unity-developer-2D | Quiz Master/Assets/Scripts/ScoreKeeper.cs | 558 | C# |
using System.IO;
namespace DogOS.Utils.FileTypes
{
public static class Ini
{
// From: https://stackoverflow.com/a/55752753/13617487
public static string ReadFile(string SECTION, string KEY, string PATH, string DEFAULT_VALUE = "")
{
// read all lines from the file
string[] READER_LINES = File.ReadAllLines(PATH);
// we are going to capture the value of a "section" line here, so we can
// test to see if subsequent lines belong to the section we are
// looking for
string CURRENT_SECTION = "";
// itterate all the lines until we find the section and key we want
foreach (string READER_LINE in READER_LINES)
{
// detect if the line is a [SECTION_NAME] and capture it as the current section
if (READER_LINE.StartsWith("[") && READER_LINE.EndsWith("]"))
{
CURRENT_SECTION = READER_LINE;
}
else if (CURRENT_SECTION.Equals($"[{SECTION}]"))
{
// The current line is not a section header
// The current section is the section we are looking for, so lets process
// the lines within it
// now lets split the current line into a key/value pair using = as the delimitor
string[] lineParts = READER_LINE.Split(new[] { '=' }, 2);
// test if part 1 of the line matches the KEY we are looking for
if (lineParts.Length >= 1 && lineParts[0] == KEY)
{
// we have found the key.
// now return part 2 of the line as the value, or DEFAULT_VALUE if the split
// operation above could not find a part 2 to add to the list
return lineParts.Length >= 2
? lineParts[1]
: DEFAULT_VALUE;
}
}
}
// we have not found a match, so return the default value instead
return DEFAULT_VALUE;
}
}
} | 41.867925 | 105 | 0.515097 | [
"BSD-3-Clause"
] | DogOSdev/DogOS | DogOS/Utils/FileTypes/Ini.cs | 2,219 | C# |
//------------------------------------------------------------------------------
// <自动生成>
// 此代码由工具生成。
//
// 对此文件的更改可能导致不正确的行为,如果
// 重新生成代码,则所做更改将丢失。
// </自动生成>
//------------------------------------------------------------------------------
namespace Wedonek.Web.RpcMer
{
public partial class RpcMerInfo
{
}
}
| 19.555556 | 81 | 0.289773 | [
"Apache-2.0"
] | tc303730352/WedonekRpcFrame | Source/Wedonek.Web/RpcMer/RpcMerInfo.aspx.designer.cs | 460 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("5.ClosestTwoPoints")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("5.ClosestTwoPoints")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ae37dee4-6b00-40ac-bf85-f6c6ab2df168")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.945946 | 84 | 0.748575 | [
"MIT"
] | TsvetanNikolov123/CSharp---Programming-Fundamentals-Extended | 27 Objects and Simple Classes/5.ClosestTwoPoints/Properties/AssemblyInfo.cs | 1,407 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the codecommit-2015-04-13.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.CodeCommit.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.CodeCommit.Model.Internal.MarshallTransformations
{
/// <summary>
/// ListBranches Request Marshaller
/// </summary>
public class ListBranchesRequestMarshaller : IMarshaller<IRequest, ListBranchesRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((ListBranchesRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(ListBranchesRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.CodeCommit");
string target = "CodeCommit_20150413.ListBranches";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-04-13";
request.HttpMethod = "POST";
request.ResourcePath = "/";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetNextToken())
{
context.Writer.WritePropertyName("nextToken");
context.Writer.Write(publicRequest.NextToken);
}
if(publicRequest.IsSetRepositoryName())
{
context.Writer.WritePropertyName("repositoryName");
context.Writer.Write(publicRequest.RepositoryName);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static ListBranchesRequestMarshaller _instance = new ListBranchesRequestMarshaller();
internal static ListBranchesRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListBranchesRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.225225 | 139 | 0.621228 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/CodeCommit/Generated/Model/Internal/MarshallTransformations/ListBranchesRequestMarshaller.cs | 3,910 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the securityhub-2018-10-26.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.SecurityHub.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SecurityHub.Model.Internal.MarshallTransformations
{
/// <summary>
/// ListEnabledProductsForImport Request Marshaller
/// </summary>
public class ListEnabledProductsForImportRequestMarshaller : IMarshaller<IRequest, ListEnabledProductsForImportRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((ListEnabledProductsForImportRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(ListEnabledProductsForImportRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.SecurityHub");
request.HttpMethod = "GET";
string uriResourcePath = "/productSubscriptions";
if (publicRequest.IsSetMaxResults())
request.Parameters.Add("MaxResults", StringUtils.FromInt(publicRequest.MaxResults));
if (publicRequest.IsSetNextToken())
request.Parameters.Add("NextToken", StringUtils.FromString(publicRequest.NextToken));
request.ResourcePath = uriResourcePath;
request.UseQueryString = true;
return request;
}
private static ListEnabledProductsForImportRequestMarshaller _instance = new ListEnabledProductsForImportRequestMarshaller();
internal static ListEnabledProductsForImportRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListEnabledProductsForImportRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.32967 | 171 | 0.666563 | [
"Apache-2.0"
] | DalavanCloud/aws-sdk-net | sdk/src/Services/SecurityHub/Generated/Model/Internal/MarshallTransformations/ListEnabledProductsForImportRequestMarshaller.cs | 3,215 | C# |
//-----------------------------------------------------------------------
// <copyright file="RemoteWatcher.cs" company="Akka.NET Project">
// Copyright (C) 2009-2019 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2019 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Akka.Actor;
using Akka.Configuration;
using Akka.Dispatch;
using Akka.Dispatch.SysMsg;
using Akka.Event;
using Akka.Util.Internal;
namespace Akka.Remote
{
/// <summary>
/// INTERNAL API
///
/// Remote nodes with actors that are watched are monitored by this actor to be able
/// to detect network failures and process crashes. <see cref="RemoteActorRefProvider"/>
/// intercepts Watch and Unwatch system messages and sends corresponding
/// <see cref="RemoteWatcher.WatchRemote"/> and <see cref="RemoteWatcher.UnwatchRemote"/> to this actor.
///
/// For a new node to be watched this actor periodically sends <see cref="RemoteWatcher.Heartbeat"/>
/// to the peer actor on the other node, which replies with <see cref="RemoteWatcher.HeartbeatRsp"/>
/// message back. The failure detector on the watching side monitors these heartbeat messages.
/// If arrival of heartbeat messages stops it will be detected and this actor will publish
/// <see cref="AddressTerminated"/> to the <see cref="AddressTerminatedTopic"/>.
///
/// When all actors on a node have been unwatched it will stop sending heartbeat messages.
///
/// For bi-directional watch between two nodes the same thing will be established in
/// both directions, but independent of each other.
/// </summary>
public class RemoteWatcher : UntypedActor, IRequiresMessageQueue<IUnboundedMessageQueueSemantics>
{
/// <summary>
/// TBD
/// </summary>
/// <param name="failureDetector">TBD</param>
/// <param name="heartbeatInterval">TBD</param>
/// <param name="unreachableReaperInterval">TBD</param>
/// <param name="heartbeatExpectedResponseAfter">TBD</param>
/// <returns>TBD</returns>
public static Props Props(
IFailureDetectorRegistry<Address> failureDetector,
TimeSpan heartbeatInterval,
TimeSpan unreachableReaperInterval,
TimeSpan heartbeatExpectedResponseAfter)
{
return Actor.Props.Create(() => new RemoteWatcher(failureDetector, heartbeatInterval, unreachableReaperInterval, heartbeatExpectedResponseAfter))
.WithDeploy(Deploy.Local);
}
/// <summary>
/// TBD
/// </summary>
public abstract class WatchCommand
{
readonly IInternalActorRef _watchee;
readonly IInternalActorRef _watcher;
/// <summary>
/// TBD
/// </summary>
/// <param name="watchee">TBD</param>
/// <param name="watcher">TBD</param>
protected WatchCommand(IInternalActorRef watchee, IInternalActorRef watcher)
{
_watchee = watchee;
_watcher = watcher;
}
/// <summary>
/// TBD
/// </summary>
public IInternalActorRef Watchee => _watchee;
/// <summary>
/// TBD
/// </summary>
public IInternalActorRef Watcher => _watcher;
}
/// <summary>
/// TBD
/// </summary>
public sealed class WatchRemote : WatchCommand
{
/// <summary>
/// TBD
/// </summary>
/// <param name="watchee">TBD</param>
/// <param name="watcher">TBD</param>
public WatchRemote(IInternalActorRef watchee, IInternalActorRef watcher)
: base(watchee, watcher)
{
}
}
/// <summary>
/// TBD
/// </summary>
public sealed class UnwatchRemote : WatchCommand
{
/// <summary>
/// TBD
/// </summary>
/// <param name="watchee">TBD</param>
/// <param name="watcher">TBD</param>
public UnwatchRemote(IInternalActorRef watchee, IInternalActorRef watcher)
: base(watchee, watcher)
{
}
}
/// <summary>
/// TBD
/// </summary>
public sealed class Heartbeat : IPriorityMessage
{
private Heartbeat()
{
}
private static readonly Heartbeat _instance = new Heartbeat();
/// <summary>
/// TBD
/// </summary>
public static Heartbeat Instance
{
get
{
return _instance;
}
}
}
/// <summary>
/// TBD
/// </summary>
public class HeartbeatRsp : IPriorityMessage
{
readonly int _addressUid;
/// <summary>
/// TBD
/// </summary>
/// <param name="addressUid">TBD</param>
public HeartbeatRsp(int addressUid)
{
_addressUid = addressUid;
}
/// <summary>
/// TBD
/// </summary>
public int AddressUid
{
get { return _addressUid; }
}
}
// sent to self only
/// <summary>
/// TBD
/// </summary>
public class HeartbeatTick
{
private HeartbeatTick() { }
private static readonly HeartbeatTick _instance = new HeartbeatTick();
/// <summary>
/// TBD
/// </summary>
public static HeartbeatTick Instance
{
get
{
return _instance;
}
}
}
/// <summary>
/// TBD
/// </summary>
public class ReapUnreachableTick
{
private ReapUnreachableTick() { }
private static readonly ReapUnreachableTick _instance = new ReapUnreachableTick();
/// <summary>
/// TBD
/// </summary>
public static ReapUnreachableTick Instance
{
get
{
return _instance;
}
}
}
/// <summary>
/// TBD
/// </summary>
public sealed class ExpectedFirstHeartbeat
{
readonly Address _from;
/// <summary>
/// TBD
/// </summary>
/// <param name="from">TBD</param>
public ExpectedFirstHeartbeat(Address @from)
{
_from = @from;
}
/// <summary>
/// TBD
/// </summary>
public Address From
{
get { return _from; }
}
}
// test purpose
/// <summary>
/// TBD
/// </summary>
public sealed class Stats
{
/// <inheritdoc/>
public override bool Equals(object obj)
{
var other = obj as Stats;
if (other == null) return false;
return _watching == other._watching && _watchingNodes == other._watchingNodes;
}
/// <inheritdoc/>
public override int GetHashCode()
{
unchecked
{
var hash = 17;
hash = hash * 23 + _watching.GetHashCode();
hash = hash * 23 + _watchingNodes.GetHashCode();
return hash;
}
}
/// <summary>
/// TBD
/// </summary>
public static Stats Empty = Counts(0, 0);
/// <summary>
/// TBD
/// </summary>
/// <param name="watching">TBD</param>
/// <param name="watchingNodes">TBD</param>
/// <returns>TBD</returns>
public static Stats Counts(int watching, int watchingNodes)
{
return new Stats(watching, watchingNodes);
}
readonly int _watching;
readonly int _watchingNodes;
readonly ImmutableHashSet<Tuple<IActorRef, IActorRef>> _watchingRefs;
readonly ImmutableHashSet<Address> _watchingAddresses;
/// <summary>
/// TBD
/// </summary>
/// <param name="watching">TBD</param>
/// <param name="watchingNodes">TBD</param>
public Stats(int watching, int watchingNodes) : this(watching, watchingNodes,
ImmutableHashSet<Tuple<IActorRef, IActorRef>>.Empty, ImmutableHashSet<Address>.Empty) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="watching">TBD</param>
/// <param name="watchingNodes">TBD</param>
/// <param name="watchingRefs">TBD</param>
/// <param name="watchingAddresses">TBD</param>
public Stats(int watching, int watchingNodes, ImmutableHashSet<Tuple<IActorRef, IActorRef>> watchingRefs, ImmutableHashSet<Address> watchingAddresses)
{
_watching = watching;
_watchingNodes = watchingNodes;
_watchingRefs = watchingRefs;
_watchingAddresses = watchingAddresses;
}
/// <summary>
/// TBD
/// </summary>
public int Watching => _watching;
/// <summary>
/// TBD
/// </summary>
public int WatchingNodes => _watchingNodes;
/// <summary>
/// TBD
/// </summary>
public ImmutableHashSet<Tuple<IActorRef, IActorRef>> WatchingRefs => _watchingRefs;
/// <summary>
/// TBD
/// </summary>
public ImmutableHashSet<Address> WatchingAddresses => _watchingAddresses;
/// <inheritdoc/>
public override string ToString()
{
string FormatWatchingRefs()
{
if (!_watchingRefs.Any()) return "";
return $"{string.Join(", ", _watchingRefs.Select(r => r.Item2.Path.Name + "-> " + r.Item1.Path.Name))}";
}
string FormatWatchingAddresses()
{
if (!_watchingAddresses.Any()) return "";
return string.Join(",", WatchingAddresses);
}
return $"Stats(watching={_watching}, watchingNodes={_watchingNodes}, watchingRefs=[{FormatWatchingRefs()}], watchingAddresses=[{FormatWatchingAddresses()}])";
}
/// <summary>
/// TBD
/// </summary>
/// <param name="watching">TBD</param>
/// <param name="watchingNodes">TBD</param>
/// <param name="watchingRefs">TBD</param>
/// <param name="watchingAddresses">TBD</param>
/// <returns>TBD</returns>
public Stats Copy(int watching, int watchingNodes, ImmutableHashSet<Tuple<IActorRef, IActorRef>> watchingRefs = null, ImmutableHashSet<Address> watchingAddresses = null)
{
return new Stats(watching, watchingNodes, watchingRefs ?? WatchingRefs, watchingAddresses ?? WatchingAddresses);
}
}
/// <summary>
/// TBD
/// </summary>
/// <param name="failureDetector">TBD</param>
/// <param name="heartbeatInterval">TBD</param>
/// <param name="unreachableReaperInterval">TBD</param>
/// <param name="heartbeatExpectedResponseAfter">TBD</param>
/// <exception cref="ConfigurationException">
/// This exception is thrown when the actor system does not have a <see cref="RemoteActorRefProvider"/> enabled in the configuration.
/// </exception>
public RemoteWatcher(
IFailureDetectorRegistry<Address> failureDetector,
TimeSpan heartbeatInterval,
TimeSpan unreachableReaperInterval,
TimeSpan heartbeatExpectedResponseAfter
)
{
_failureDetector = failureDetector;
_heartbeatExpectedResponseAfter = heartbeatExpectedResponseAfter;
var systemProvider = Context.System.AsInstanceOf<ExtendedActorSystem>().Provider as IRemoteActorRefProvider;
if (systemProvider != null) _remoteProvider = systemProvider;
else throw new ConfigurationException(
$"ActorSystem {Context.System} needs to have a 'RemoteActorRefProvider' enabled in the configuration, current uses {Context.System.AsInstanceOf<ExtendedActorSystem>().Provider.GetType().FullName}");
_heartbeatCancelable = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(heartbeatInterval, heartbeatInterval, Self, HeartbeatTick.Instance, Self);
_failureDetectorReaperCancelable = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(unreachableReaperInterval, unreachableReaperInterval, Self, ReapUnreachableTick.Instance, Self);
}
private readonly IFailureDetectorRegistry<Address> _failureDetector;
private readonly TimeSpan _heartbeatExpectedResponseAfter;
private readonly IScheduler _scheduler = Context.System.Scheduler;
private readonly IRemoteActorRefProvider _remoteProvider;
private readonly HeartbeatRsp _selfHeartbeatRspMsg = new HeartbeatRsp(AddressUidExtension.Uid(Context.System));
/// <summary>
/// Actors that this node is watching, map of watchee --> Set(watchers)
/// </summary>
protected readonly Dictionary<IInternalActorRef, HashSet<IInternalActorRef>> Watching = new Dictionary<IInternalActorRef, HashSet<IInternalActorRef>>();
/// <summary>
/// Nodes that this node is watching, i.e. expecting heartbeats from these nodes. Map of address --> Set(watchee) on this address.
/// </summary>
protected readonly Dictionary<Address, HashSet<IInternalActorRef>> WatcheeByNodes = new Dictionary<Address, HashSet<IInternalActorRef>>();
/// <summary>
/// TBD
/// </summary>
protected ICollection<Address> WatchingNodes => WatcheeByNodes.Keys;
/// <summary>
/// TBD
/// </summary>
protected HashSet<Address> Unreachable { get; } = new HashSet<Address>();
private readonly Dictionary<Address, int> _addressUids = new Dictionary<Address, int>();
private readonly ICancelable _heartbeatCancelable;
private readonly ICancelable _failureDetectorReaperCancelable;
/// <summary>
/// TBD
/// </summary>
protected override void PostStop()
{
base.PostStop();
_heartbeatCancelable.Cancel();
_failureDetectorReaperCancelable.Cancel();
}
/// <summary>
/// TBD
/// </summary>
/// <param name="message">TBD</param>
protected override void OnReceive(object message)
{
if (message is HeartbeatTick) SendHeartbeat();
else if (message is Heartbeat) ReceiveHeartbeat();
else if (message is HeartbeatRsp) ReceiveHeartbeatRsp(((HeartbeatRsp)message).AddressUid);
else if (message is ReapUnreachableTick) ReapUnreachable();
else if (message is ExpectedFirstHeartbeat) TriggerFirstHeartbeat(((ExpectedFirstHeartbeat)message).From);
else if (message is WatchRemote)
{
var watchRemote = (WatchRemote)message;
AddWatching(watchRemote.Watchee, watchRemote.Watcher);
}
else if (message is UnwatchRemote)
{
var unwatchRemote = (UnwatchRemote)message;
RemoveWatch(unwatchRemote.Watchee, unwatchRemote.Watcher);
}
else if (message is Terminated)
{
var t = (Terminated)message;
ProcessTerminated(t.ActorRef.AsInstanceOf<IInternalActorRef>(), t.ExistenceConfirmed, t.AddressTerminated);
}
// test purpose
else if (message is Stats)
{
var watchSet = ImmutableHashSet.Create(Watching.SelectMany(pair =>
{
var list = new List<Tuple<IActorRef, IActorRef>>(pair.Value.Count);
var wee = pair.Key;
list.AddRange(pair.Value.Select(wer => Tuple.Create<IActorRef, IActorRef>(wee, wer)));
return list;
}).ToArray());
Sender.Tell(new Stats(watchSet.Count(), WatchingNodes.Count, watchSet,
ImmutableHashSet.Create(WatchingNodes.ToArray())));
}
else
{
Unhandled(message);
}
}
private void ReceiveHeartbeat()
{
Sender.Tell(_selfHeartbeatRspMsg);
}
private void ReceiveHeartbeatRsp(int uid)
{
var from = Sender.Path.Address;
if (_failureDetector.IsMonitoring(from))
Log.Debug("Received heartbeat rsp from [{0}]", from);
else
Log.Debug("Received first heartbeat rsp from [{0}]", from);
if (WatcheeByNodes.ContainsKey(from) && !Unreachable.Contains(from))
{
if (_addressUids.TryGetValue(from, out int addressUid))
{
if (addressUid != uid)
ReWatch(from);
}
else
ReWatch(from);
_addressUids[from] = uid;
_failureDetector.Heartbeat(from);
}
}
private void ReapUnreachable()
{
foreach (var a in WatchingNodes)
{
if (!Unreachable.Contains(a) && !_failureDetector.IsAvailable(a))
{
Log.Warning("Detected unreachable: [{0}]", a);
var nullableAddressUid =
_addressUids.TryGetValue(a, out int addressUid) ? new int?(addressUid) : null;
Quarantine(a, nullableAddressUid);
PublishAddressTerminated(a);
Unreachable.Add(a);
}
}
}
/// <summary>
/// TBD
/// </summary>
/// <param name="address">TBD</param>
protected virtual void PublishAddressTerminated(Address address)
{
AddressTerminatedTopic.Get(Context.System).Publish(new AddressTerminated(address));
}
/// <summary>
/// TBD
/// </summary>
/// <param name="address">TBD</param>
/// <param name="addressUid">TBD</param>
protected virtual void Quarantine(Address address, int? addressUid)
{
_remoteProvider.Quarantine(address, addressUid);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="watchee">TBD</param>
/// <param name="watcher">TBD</param>
/// <exception cref="InvalidOperationException">TBD</exception>
protected void AddWatching(IInternalActorRef watchee, IInternalActorRef watcher)
{
// TODO: replace with Code Contracts assertion
if(watcher.Equals(Self)) throw new InvalidOperationException("Watcher cannot be the RemoteWatcher!");
Log.Debug("Watching: [{0} -> {1}]", watcher.Path, watchee.Path);
if (Watching.TryGetValue(watchee, out var watching))
watching.Add(watcher);
else
Watching.Add(watchee, new HashSet<IInternalActorRef> { watcher });
WatchNode(watchee);
// add watch from self, this will actually send a Watch to the target when necessary
Context.Watch(watchee);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="watchee">TBD</param>
protected virtual void WatchNode(IInternalActorRef watchee)
{
var watcheeAddress = watchee.Path.Address;
if (!WatcheeByNodes.ContainsKey(watcheeAddress) && Unreachable.Contains(watcheeAddress))
{
// first watch to a node after a previous unreachable
Unreachable.Remove(watcheeAddress);
_failureDetector.Remove(watcheeAddress);
}
if (WatcheeByNodes.TryGetValue(watcheeAddress, out var watchees))
watchees.Add(watchee);
else
WatcheeByNodes.Add(watcheeAddress, new HashSet<IInternalActorRef> { watchee });
}
/// <summary>
/// TBD
/// </summary>
/// <param name="watchee">TBD</param>
/// <param name="watcher">TBD</param>
/// <exception cref="InvalidOperationException">TBD</exception>
protected void RemoveWatch(IInternalActorRef watchee, IInternalActorRef watcher)
{
if (watcher.Equals(Self)) throw new InvalidOperationException("Watcher cannot be the RemoteWatcher!");
Log.Debug($"Unwatching: [{watcher.Path} -> {watchee.Path}]");
if (Watching.TryGetValue(watchee, out var watchers))
{
watchers.Remove(watcher);
if (!watchers.Any())
{
// clean up self watch when no more watchers of this watchee
Log.Debug("Cleanup self watch of [{0}]", watchee.Path);
Context.Unwatch(watchee);
RemoveWatchee(watchee);
}
}
}
/// <summary>
/// TBD
/// </summary>
/// <param name="watchee">TBD</param>
protected void RemoveWatchee(IInternalActorRef watchee)
{
var watcheeAddress = watchee.Path.Address;
Watching.Remove(watchee);
if (WatcheeByNodes.TryGetValue(watcheeAddress, out var watchees))
{
watchees.Remove(watchee);
if (!watchees.Any())
{
// unwatched last watchee on that node
Log.Debug("Unwatched last watchee of node: [{0}]", watcheeAddress);
UnwatchNode(watcheeAddress);
}
}
}
/// <summary>
/// TBD
/// </summary>
/// <param name="watcheeAddress">TBD</param>
protected void UnwatchNode(Address watcheeAddress)
{
WatcheeByNodes.Remove(watcheeAddress);
_addressUids.Remove(watcheeAddress);
_failureDetector.Remove(watcheeAddress);
}
private void ProcessTerminated(IInternalActorRef watchee, bool existenceConfirmed, bool addressTerminated)
{
Log.Debug("Watchee terminated: [{0}]", watchee.Path);
// When watchee is stopped it sends DeathWatchNotification to this RemoteWatcher,
// which will propagate it to all watchers of this watchee.
// addressTerminated case is already handled by the watcher itself in DeathWatch trait
if (!addressTerminated)
{
if (Watching.TryGetValue(watchee, out var watchers))
{
foreach (var watcher in watchers)
{
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
watcher.SendSystemMessage(new DeathWatchNotification(watchee, existenceConfirmed, addressTerminated));
}
}
}
RemoveWatchee(watchee);
}
private void SendHeartbeat()
{
foreach (var a in WatchingNodes)
{
if (!Unreachable.Contains(a))
{
if (_failureDetector.IsMonitoring(a))
{
Log.Debug("Sending Heartbeat to [{0}]", a);
}
else
{
Log.Debug("Sending first Heartbeat to [{0}]", a);
// schedule the expected first heartbeat for later, which will give the
// other side a chance to reply, and also trigger some resends if needed
_scheduler.ScheduleTellOnce(_heartbeatExpectedResponseAfter, Self, new ExpectedFirstHeartbeat(a), Self);
}
Context.ActorSelection(new RootActorPath(a) / Self.Path.Elements).Tell(Heartbeat.Instance);
}
}
}
private void TriggerFirstHeartbeat(Address address)
{
if (WatcheeByNodes.ContainsKey(address) && !_failureDetector.IsMonitoring(address))
{
Log.Debug("Trigger extra expected heartbeat from [{0}]", address);
_failureDetector.Heartbeat(address);
}
}
/// <summary>
/// To ensure that we receive heartbeat messages from the right actor system
/// incarnation we send Watch again for the first HeartbeatRsp (containing
/// the system UID) and if HeartbeatRsp contains a new system UID.
/// Terminated will be triggered if the watchee (including correct Actor UID)
/// does not exist.
/// </summary>
/// <param name="address"></param>
private void ReWatch(Address address)
{
var watcher = Self.AsInstanceOf<IInternalActorRef>();
foreach (var watchee in WatcheeByNodes[address])
{
Log.Debug("Re-watch [{0} -> {1}]", watcher.Path, watchee.Path);
watchee.SendSystemMessage(new Watch(watchee, watcher)); // ➡➡➡ NEVER SEND THE SAME SYSTEM MESSAGE OBJECT TO TWO ACTORS ⬅⬅⬅
}
}
/// <summary>
/// TBD
/// </summary>
protected readonly ILoggingAdapter Log = Context.GetLogger();
}
}
| 37.245098 | 214 | 0.539653 | [
"Apache-2.0"
] | IgorFedchenko/akka.net | src/core/Akka.Remote/RemoteWatcher.cs | 26,607 | C# |
using System;
using System.Collections.Generic;
using System.Data;
namespace LinqToDB.DataProvider.Firebird
{
using Common;
using Data;
using Mapping;
using SqlProvider;
using System.Threading;
using System.Threading.Tasks;
public class FirebirdDataProvider : DynamicDataProviderBase<FirebirdProviderAdapter>
{
public FirebirdDataProvider()
: this(ProviderName.Firebird, new FirebirdMappingSchema(), null)
{
}
public FirebirdDataProvider(ISqlOptimizer sqlOptimizer)
: this(ProviderName.Firebird, new FirebirdMappingSchema(), sqlOptimizer)
{
}
protected FirebirdDataProvider(string name, MappingSchema mappingSchema, ISqlOptimizer? sqlOptimizer)
: base(name, mappingSchema, FirebirdProviderAdapter.GetInstance())
{
SqlProviderFlags.IsIdentityParameterRequired = true;
SqlProviderFlags.IsCommonTableExpressionsSupported = true;
SqlProviderFlags.IsSubQueryOrderBySupported = true;
SqlProviderFlags.IsDistinctSetOperationsSupported = false;
SqlProviderFlags.IsUpdateFromSupported = false;
SetCharField("CHAR", (r,i) => r.GetString(i).TrimEnd(' '));
SetCharFieldToType<char>("CHAR", (r, i) => DataTools.GetChar(r, i));
SetProviderField<IDataReader,TimeSpan,DateTime>((r,i) => r.GetDateTime(i) - new DateTime(1970, 1, 1));
SetProviderField<IDataReader,DateTime,DateTime>((r,i) => GetDateTime(r, i));
_sqlOptimizer = sqlOptimizer ?? new FirebirdSqlOptimizer(SqlProviderFlags);
}
static DateTime GetDateTime(IDataReader dr, int idx)
{
var value = dr.GetDateTime(idx);
if (value.Year == 1970 && value.Month == 1 && value.Day == 1)
return new DateTime(1, 1, 1, value.Hour, value.Minute, value.Second, value.Millisecond);
return value;
}
public override ISqlBuilder CreateSqlBuilder(MappingSchema mappingSchema)
{
return new FirebirdSqlBuilder(this, mappingSchema, GetSqlOptimizer(), SqlProviderFlags);
}
readonly ISqlOptimizer _sqlOptimizer;
public override ISqlOptimizer GetSqlOptimizer()
{
return _sqlOptimizer;
}
public override SchemaProvider.ISchemaProvider GetSchemaProvider()
{
return new FirebirdSchemaProvider();
}
public override bool? IsDBNullAllowed(IDataReader reader, int idx)
{
return true;
}
public override void SetParameter(DataConnection dataConnection, IDbDataParameter parameter, string name, DbDataType dataType, object? value)
{
if (value is bool)
{
value = (bool)value ? "1" : "0";
dataType = dataType.WithDataType(DataType.Char);
}
base.SetParameter(dataConnection, parameter, name, dataType, value);
}
protected override void SetParameterType(DataConnection dataConnection, IDbDataParameter parameter, DbDataType dataType)
{
switch (dataType.DataType)
{
case DataType.SByte : dataType = dataType.WithDataType(DataType.Int16); break;
case DataType.UInt16 : dataType = dataType.WithDataType(DataType.Int32); break;
case DataType.UInt32 : dataType = dataType.WithDataType(DataType.Int64); break;
case DataType.UInt64 : dataType = dataType.WithDataType(DataType.Decimal); break;
case DataType.VarNumeric : dataType = dataType.WithDataType(DataType.Decimal); break;
case DataType.DateTime2 : dataType = dataType.WithDataType(DataType.DateTime); break;
}
base.SetParameterType(dataConnection, parameter, dataType);
}
#region BulkCopy
public override BulkCopyRowsCopied BulkCopy<T>(
ITable<T> table, BulkCopyOptions options, IEnumerable<T> source)
{
return new FirebirdBulkCopy().BulkCopy(
options.BulkCopyType == BulkCopyType.Default ? FirebirdTools.DefaultBulkCopyType : options.BulkCopyType,
table,
options,
source);
}
public override Task<BulkCopyRowsCopied> BulkCopyAsync<T>(
ITable<T> table, BulkCopyOptions options, IEnumerable<T> source, CancellationToken cancellationToken)
{
return new FirebirdBulkCopy().BulkCopyAsync(
options.BulkCopyType == BulkCopyType.Default ? FirebirdTools.DefaultBulkCopyType : options.BulkCopyType,
table,
options,
source,
cancellationToken);
}
#if !NET45 && !NET46
public override Task<BulkCopyRowsCopied> BulkCopyAsync<T>(
ITable<T> table, BulkCopyOptions options, IAsyncEnumerable<T> source, CancellationToken cancellationToken)
{
return new FirebirdBulkCopy().BulkCopyAsync(
options.BulkCopyType == BulkCopyType.Default ? FirebirdTools.DefaultBulkCopyType : options.BulkCopyType,
table,
options,
source,
cancellationToken);
}
#endif
#endregion
}
}
| 33.361702 | 144 | 0.720663 | [
"MIT"
] | SuleymanEngin/linq2db | Source/LinqToDB/DataProvider/Firebird/FirebirdDataProvider.cs | 4,566 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GlobalTimer : MonoBehaviour
{
public GameObject timeDisplay01;
public GameObject timeDisplay02;
public bool isTakingTime = false;
public static int extendScore;
public int seconds = 150;
void Update()
{
extendScore = seconds;
if (isTakingTime == false)
{
StartCoroutine(SubstractSecond());
}
}
IEnumerator SubstractSecond()
{
isTakingTime = true;
seconds -= 1;
timeDisplay01.GetComponent<Text>().text = "" + seconds;
timeDisplay02.GetComponent<Text>().text = "" + seconds;
yield return new WaitForSeconds(1);
isTakingTime = false;
}
}
| 19.9 | 63 | 0.630653 | [
"MIT"
] | JCharlieDev/Platform-Game | Platform Game/Assets/Scripts/GlobalTimer.cs | 798 | C# |
// 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.Linq.Expressions;
using System.Reactive.Concurrency;
using System.Reflection;
namespace ReactiveUI.Fody.Helpers
{
public static class ObservableAsPropertyExtensions
{
public static ObservableAsPropertyHelper<TRet> ToPropertyEx<TObj, TRet>(this IObservable<TRet> @this, TObj source, Expression<Func<TObj, TRet>> property, TRet initialValue = default(TRet), bool deferSubscription = false, IScheduler scheduler = null) where TObj : ReactiveObject
{
var result = @this.ToProperty(source, property, initialValue, deferSubscription, scheduler);
// Now assign the field via reflection.
var propertyInfo = property.GetPropertyInfo();
if (propertyInfo == null)
throw new Exception("Could not resolve expression " + property + " into a property.");
var field = propertyInfo.DeclaringType.GetTypeInfo().GetDeclaredField("$" + propertyInfo.Name);
if (field == null)
throw new Exception("Backing field not found for " + propertyInfo);
field.SetValue(source, result);
return result;
}
static PropertyInfo GetPropertyInfo(this LambdaExpression expression)
{
var current = expression.Body;
var unary = current as UnaryExpression;
if (unary != null)
current = unary.Operand;
var call = (MemberExpression)current;
return (PropertyInfo)call.Member;
}
}
}
| 41.380952 | 285 | 0.662831 | [
"MIT"
] | editor-tools/ReactiveUI | src/ReactiveUI.Fody.Helpers/ObservableAsPropertyExtensions.cs | 1,740 | C# |
using System.Collections.Generic;
using Essensoft.AspNetCore.Payment.Alipay.Response;
namespace Essensoft.AspNetCore.Payment.Alipay.Request
{
/// <summary>
/// AOP API: alipay.open.public.message.label.send
/// </summary>
public class AlipayOpenPublicMessageLabelSendRequest : IAlipayRequest<AlipayOpenPublicMessageLabelSendResponse>
{
/// <summary>
/// 根据标签组发消息接口
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return returnUrl;
}
public void SetTerminalType(string terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return terminalType;
}
public void SetTerminalInfo(string terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return terminalInfo;
}
public void SetProdCode(string prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return prodCode;
}
public string GetApiName()
{
return "alipay.open.public.message.label.send";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.954955 | 115 | 0.586687 | [
"MIT"
] | AkonCoder/Payment | src/Essensoft.AspNetCore.Payment.Alipay/Request/AlipayOpenPublicMessageLabelSendRequest.cs | 2,679 | C# |
// ReSharper disable RedundantNameQualifier
namespace PropertyChangedAnalyzers.Benchmarks.Benchmarks
{
[BenchmarkDotNet.Attributes.MemoryDiagnoser]
public class EqualityAnalyzerBenchmarks
{
private static readonly Gu.Roslyn.Asserts.Benchmark Benchmark = Gu.Roslyn.Asserts.Benchmark.Create(Code.ValidCodeProject, new PropertyChangedAnalyzers.EqualityAnalyzer());
[BenchmarkDotNet.Attributes.Benchmark]
public void RunOnValidCodeProject()
{
Benchmark.Run();
}
}
}
| 33.1875 | 179 | 0.73823 | [
"MIT"
] | jnm2/PropertyChangedAnalyzers | PropertyChangedAnalyzers.Benchmarks/Benchmarks/EqualityAnalyzerBenchmarks.cs | 531 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Newtonsoft.Json;
namespace Nest
{
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
[ContractJsonConverter(typeof(AggregationJsonConverter<GeoDistanceAggregation>))]
public interface IGeoDistanceAggregation : IBucketAggregation
{
[JsonProperty("field")]
Field Field { get; set; }
[JsonProperty("origin")]
GeoLocation Origin { get; set; }
[JsonProperty("unit")]
DistanceUnit? Unit { get; set; }
[JsonProperty("distance_type")]
GeoDistanceType? DistanceType { get; set; }
[JsonProperty("ranges")]
#pragma warning disable 618
IEnumerable<IRange> Ranges { get; set; }
#pragma warning restore 618
}
public class GeoDistanceAggregation : BucketAggregationBase, IGeoDistanceAggregation
{
public Field Field { get; set; }
public GeoLocation Origin { get; set; }
public DistanceUnit? Unit { get; set; }
public GeoDistanceType? DistanceType { get; set; }
#pragma warning disable 618
public IEnumerable<IRange> Ranges { get; set; }
#pragma warning restore 618
internal GeoDistanceAggregation() { }
public GeoDistanceAggregation(string name) : base(name) { }
internal override void WrapInContainer(AggregationContainer c) => c.GeoDistance = this;
}
public class GeoDistanceAggregationDescriptor<T> :
BucketAggregationDescriptorBase<GeoDistanceAggregationDescriptor<T>, IGeoDistanceAggregation, T>
, IGeoDistanceAggregation
where T : class
{
Field IGeoDistanceAggregation.Field { get; set; }
GeoLocation IGeoDistanceAggregation.Origin { get; set; }
DistanceUnit? IGeoDistanceAggregation.Unit { get; set; }
GeoDistanceType? IGeoDistanceAggregation.DistanceType { get; set; }
#pragma warning disable 618
IEnumerable<IRange> IGeoDistanceAggregation.Ranges { get; set; }
#pragma warning restore 618
public GeoDistanceAggregationDescriptor<T> Field(Field field) => Assign(a => a.Field = field);
public GeoDistanceAggregationDescriptor<T> Field(Expression<Func<T, object>> field) => Assign(a => a.Field = field);
public GeoDistanceAggregationDescriptor<T> Origin(double lat, double lon) => Assign(a => a.Origin = new GeoLocation(lat, lon));
public GeoDistanceAggregationDescriptor<T> Origin(GeoLocation geoLocation) => Assign(a => a.Origin = geoLocation);
public GeoDistanceAggregationDescriptor<T> Unit(DistanceUnit unit) => Assign(a => a.Unit = unit);
public GeoDistanceAggregationDescriptor<T> DistanceType(GeoDistanceType? geoDistance) => Assign(a => a.DistanceType = geoDistance);
#pragma warning disable 618
public GeoDistanceAggregationDescriptor<T> Ranges(params Func<RangeDescriptor, IRange>[] ranges) =>
Assign(a => a.Ranges = ranges?.Select(r => r(new RangeDescriptor())));
#pragma warning restore 618
}
}
| 32.413793 | 133 | 0.758156 | [
"Apache-2.0"
] | jslicer/elasticsearch-net | src/Nest/Aggregations/Bucket/GeoDistance/GeoDistanceAggregation.cs | 2,820 | C# |
// 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.Globalization;
using System.Text;
using Microsoft.ML.Internal.Utilities;
using Microsoft.ML.Runtime;
namespace Microsoft.ML.Transforms
{
/// <summary>
/// The lexer. This is effectively a template. Call LexSource to get an Enumerable of tokens.
/// </summary>
[BestFriend]
internal partial class Lexer
{
private readonly NormStr.Pool _pool;
private readonly KeyWordTable _kwt;
/// <summary>
/// The constructor. Caller must provide the name pool and key word table.
/// </summary>
public Lexer(NormStr.Pool pool, KeyWordTable kwt)
{
Contracts.AssertValue(pool);
Contracts.AssertValue(kwt);
_pool = pool;
_kwt = kwt;
}
public IEnumerable<Token> LexSource(CharCursor cursor)
{
Contracts.AssertValue(cursor);
LexerImpl impl = new LexerImpl(this, cursor);
Token tok;
while ((tok = impl.GetNextToken()) != null)
yield return tok;
yield return impl.GetEof();
}
private partial class LexerImpl
{
private readonly Lexer _lex;
private readonly CharCursor _cursor;
private StringBuilder _sb; // Used while building a token.
private int _ichMinTok; // The start of the current token.
private Queue<Token> _queue; // For multiple returns.
#pragma warning disable 414
// This will be used by any pre-processor, so keep it around.
private bool _fLineStart;
#pragma warning restore 414
public LexerImpl(Lexer lex, CharCursor cursor)
{
_lex = lex;
_cursor = cursor;
_sb = new StringBuilder();
_queue = new Queue<Token>(4);
_fLineStart = true;
}
/// <summary>
/// Whether we've hit the end of input yet. If this returns true, ChCur will be zero.
/// </summary>
private bool Eof { get { return _cursor.Eof; } }
/// <summary>
/// The current character. Zero if we've hit the end of input.
/// </summary>
private char ChCur
{
get { return _cursor.ChCur; }
}
/// <summary>
/// Advance to the next character and return it.
/// </summary>
private char ChNext()
{
return _cursor.ChNext();
}
private char ChPeek(int ich)
{
return _cursor.ChPeek(ich);
}
/// <summary>
/// Marks the beginning of the current token.
/// </summary>
private void StartTok()
{
_ichMinTok = _cursor.IchCur;
}
/// <summary>
/// Called to embed an error token in the stream.
/// </summary>
private void ReportError(ErrId eid)
{
ReportError(_ichMinTok, _cursor.IchCur, eid, null);
}
private void ReportError(ErrId eid, params object[] args)
{
ReportError(_ichMinTok, _cursor.IchCur, eid, args);
}
private void ReportError(int ichMin, int ichLim, ErrId eid, params object[] args)
{
// REVIEW: Fix this so the error is marked as nested if appropriate!
ErrorToken err = new ErrorToken(GetTextSpan(ichMin, ichLim), eid, args);
_queue.Enqueue(err);
}
private TextSpan GetSpan()
{
var span = new TextSpan(_ichMinTok, _cursor.IchCur);
StartTok();
return span;
}
private TextSpan GetTextSpan(int ichMin, int ichLim)
{
return new TextSpan(ichMin, ichLim);
}
/// <summary>
/// Form and return the next token. Returns null to signal end of input.
/// </summary>
public Token GetNextToken()
{
// New line tokens and errors can be "nested" inside comments or string literals
// so this code isn't as simple as lexing a single token and returning it.
// Note that we return the outer token before nested ones.
while (_queue.Count == 0)
{
if (Eof)
return null;
Token tokNew = FetchToken();
if (tokNew != null)
return tokNew;
}
// Only new lines and errors should be enqueued.
Token tok = _queue.Dequeue();
Contracts.Assert(tok.Kind == TokKind.NewLine || tok.Kind == TokKind.Error);
return tok;
}
/// <summary>
/// Call once GetNextToken returns null if you need an Eof token.
/// </summary>
public EofToken GetEof()
{
Contracts.Assert(Eof);
return new EofToken(GetTextSpan(_cursor.IchCur, _cursor.IchCur));
}
private Token FetchToken()
{
Contracts.Assert(!Eof);
StartTok();
LexStartKind kind = LexCharUtils.StartKind(ChCur);
if (kind != LexStartKind.Space && kind != LexStartKind.PreProc)
_fLineStart = false;
switch (kind)
{
case LexStartKind.Punc:
return LexPunc();
case LexStartKind.NumLit:
return LexNumLit();
case LexStartKind.StrLit:
return LexStrLit();
case LexStartKind.Verbatim:
if (ChPeek(1) == '"')
return LexStrLit();
if (LexCharUtils.StartKind(ChPeek(1)) == LexStartKind.Ident)
return LexIdent();
ChNext();
ReportError(ErrId.VerbatimLiteralExpected);
return null;
case LexStartKind.Ident:
return LexIdent();
case LexStartKind.Comment:
return LexComment();
case LexStartKind.Space:
return LexSpace();
case LexStartKind.LineTerm:
LexLineTerm();
return null;
case LexStartKind.PreProc:
return LexPreProc();
default:
return LexError();
}
}
/// <summary>
/// Called to lex a punctuator (operator). Asserts the current character lex type
/// is LexCharType.Punc.
/// </summary>
private Token LexPunc()
{
int cchPunc = 0;
TokKind tidPunc = TokKind.None;
_sb.Length = 0;
_sb.Append(ChCur);
for (; ; )
{
TokKind tidCur;
NormStr nstr = _lex._pool.Add(_sb);
if (!_lex._kwt.IsPunctuator(nstr, out tidCur))
break;
if (tidCur != TokKind.None)
{
// This is a real punctuator, not just a prefix.
tidPunc = tidCur;
cchPunc = _sb.Length;
}
char ch = ChPeek(_sb.Length);
if (!LexCharUtils.IsPunc(ch))
break;
_sb.Append(ch);
}
if (cchPunc == 0)
return LexError();
while (--cchPunc >= 0)
ChNext();
return KeyToken.Create(GetSpan(), tidPunc);
}
/// <summary>
/// Called to lex a numeric literal or a Dot token. Asserts the current
/// character lex type is LexCharType.NumLit.
/// </summary>
private Token LexNumLit()
{
Contracts.Assert(LexCharUtils.StartKind(ChCur) == LexStartKind.NumLit);
Contracts.Assert(LexCharUtils.IsDigit(ChCur) || ChCur == '.');
// A dot not followed by a digit is just a Dot. This is a very common case (hence first).
if (ChCur == '.' && !LexCharUtils.IsDigit(ChPeek(1)))
return LexPunc();
// Check for a hex literal. Note that 0x followed by a non-hex-digit is really a 0 followed
// by an identifier.
if (ChCur == '0' && (ChPeek(1) == 'x' || ChPeek(1) == 'X') && LexCharUtils.IsHexDigit(ChPeek(2)))
{
// Advance to first hex digit.
ChNext();
ChNext();
return LexHexInt();
}
// Decimal literal (possible floating point).
Contracts.Assert(LexCharUtils.IsDigit(ChCur) || ChCur == '.' && LexCharUtils.IsDigit(ChPeek(1)));
bool fExp = false;
bool fDot = ChCur == '.';
_sb.Length = 0;
_sb.Append(ChCur);
for (; ; )
{
if (ChNext() == '.')
{
if (fDot || !LexCharUtils.IsDigit(ChPeek(1)))
break;
fDot = true;
}
else if (!LexCharUtils.IsDigit(ChCur))
break;
_sb.Append(ChCur);
}
// Check for an exponent.
if (ChCur == 'e' || ChCur == 'E')
{
char chTmp = ChPeek(1);
if (LexCharUtils.IsDigit(chTmp) || (chTmp == '+' || chTmp == '-') && LexCharUtils.IsDigit(ChPeek(2)))
{
fExp = true;
_sb.Append(ChCur);
_sb.Append(ChNext());
while (LexCharUtils.IsDigit(chTmp = ChNext()))
_sb.Append(chTmp);
}
}
bool fReal = fDot || fExp;
char chSuf = LexRealSuffix(fReal);
if (fReal || chSuf != '\0')
return LexRealNum(chSuf);
// Integer type.
return LexDecInt(LexIntSuffix());
}
/// <summary>
/// Lex a hex literal optionally followed by an integer suffix. Asserts the current
/// character is a hex digit.
/// </summary>
private Token LexHexInt()
{
Contracts.Assert(LexCharUtils.IsHexDigit(ChCur));
ulong u = 0;
bool fOverflow = false;
do
{
if ((u & 0xF000000000000000) != 0 && !fOverflow)
{
ReportError(ErrId.IntOverflow);
fOverflow = true;
}
u = (u << 4) + (ulong)LexCharUtils.GetHexVal(ChCur);
} while (LexCharUtils.IsHexDigit(ChNext()));
if (fOverflow)
u = ulong.MaxValue;
return new IntLitToken(GetSpan(), u, LexIntSuffix() | IntLitKind.Hex);
}
/// <summary>
/// Lex a decimal integer literal. The digits must be in _sb.
/// </summary>
private Token LexDecInt(IntLitKind ilk)
{
// Digits are in _sb.
Contracts.Assert(_sb.Length > 0);
ulong u = 0;
try
{
for (int ich = 0; ich < _sb.Length; ich++)
u = checked(u * 10 + (ulong)LexCharUtils.GetDecVal(_sb[ich]));
}
catch (System.OverflowException)
{
ReportError(ErrId.IntOverflow);
u = ulong.MaxValue;
}
return new IntLitToken(GetSpan(), u, ilk);
}
/// <summary>
/// Lex a real literal (float, double or decimal). The characters should be in _sb.
/// </summary>
private Token LexRealNum(char chSuf)
{
// Digits are in _sb.
Contracts.Assert(_sb.Length > 0);
TextSpan span = GetSpan();
switch (chSuf)
{
default:
Contracts.Assert(chSuf == '\0' || chSuf == 'D');
try
{
double dbl = double.Parse(_sb.ToString(), NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent);
return new DblLitToken(span, dbl, chSuf != 0);
}
catch (OverflowException)
{
ReportError(ErrId.FloatOverflow, "double");
return new DblLitToken(span, double.PositiveInfinity, chSuf != 0);
}
case 'F':
try
{
double dbl = double.Parse(_sb.ToString(), NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent);
return new FltLitToken(span, (float)dbl);
}
catch (OverflowException)
{
ReportError(ErrId.FloatOverflow, "float");
return new FltLitToken(span, float.PositiveInfinity);
}
}
}
/// <summary>
/// Lex an optional integer suffix (U and/or L).
/// </summary>
private IntLitKind LexIntSuffix()
{
IntLitKind ilk = IntLitKind.None;
for (; ; )
{
if (ChCur == 'U' || ChCur == 'u')
{
if ((ilk & IntLitKind.Uns) != 0)
break;
ilk |= IntLitKind.Uns;
}
else if (ChCur == 'L' || ChCur == 'l')
{
if ((ilk & IntLitKind.Lng) != 0)
break;
ilk |= IntLitKind.Lng;
}
else
break;
ChNext();
}
return ilk;
}
/// <summary>
/// Lex an optional real suffix (F, D, M).
/// </summary>
private char LexRealSuffix(bool fKnown)
{
char ch;
switch (ChCur)
{
default:
return '\0';
case 'd':
case 'D':
ch = 'D';
break;
case 'f':
case 'F':
ch = 'F';
break;
case 'l':
case 'L':
if (!fKnown)
return '\0';
ch = 'L';
break;
}
ChNext();
return ch;
}
/// <summary>
/// Lex a string or character literal.
/// </summary>
private Token LexStrLit()
{
char chQuote;
_sb.Length = 0;
if (ChCur == '@')
{
chQuote = '"';
ChNext();
Contracts.Assert(ChCur == '"');
ChNext();
for (; ; )
{
char ch = ChCur;
if (ch == '"')
{
ChNext();
if (ChCur != '"')
break;
ChNext();
}
else if (LexCharUtils.IsLineTerm(ch))
ch = LexLineTerm(_sb);
else if (Eof)
{
ReportError(ErrId.UnterminatedString);
break;
}
else
ChNext();
_sb.Append(ch);
}
}
else
{
Contracts.Assert(ChCur == '"' || ChCur == '\'');
chQuote = ChCur;
ChNext();
for (; ; )
{
char ch = ChCur;
if (ch == chQuote || Eof || LexCharUtils.IsLineTerm(ch))
break;
if (ch == '\\')
{
uint u;
if (!FLexEscChar(false, out u))
continue;
if (u < 0x10000)
ch = (char)u;
else
{
char chT;
if (!ConvertToSurrogatePair(u, out chT, out ch))
continue;
_sb.Append(chT);
}
}
else
ChNext();
_sb.Append(ch);
}
if (ChCur != chQuote)
ReportError(ErrId.NewlineInConst);
else
ChNext();
}
if (chQuote == '"')
return new StrLitToken(GetSpan(), _sb.ToString());
if (_sb.Length != 1)
ReportError(_sb.Length == 0 ? ErrId.CharConstEmpty : ErrId.CharConstTooLong);
return new CharLitToken(GetSpan(), _sb.Length > 0 ? _sb[0] : '\0');
}
/// <summary>
/// Lex a character escape. Returns true if successful (ch is valid).
/// </summary>
private bool FLexEscChar(bool fUniOnly, out uint u)
{
Contracts.Assert(ChCur == '\\');
int ichErr = _cursor.IchCur;
bool fUni;
int cchHex;
switch (ChNext())
{
case 'u':
fUni = true;
cchHex = 4;
goto LHex;
case 'U':
fUni = true;
cchHex = 8;
goto LHex;
default:
if (!fUniOnly)
{
switch (ChCur)
{
default:
goto LBad;
case 'x':
case 'X':
fUni = false;
cchHex = 4;
goto LHex;
case '\'':
u = 0x0027;
break;
case '"':
u = 0x0022;
break;
case '\\':
u = 0x005C;
break;
case '0':
u = 0x0000;
break;
case 'a':
u = 0x0007;
break;
case 'b':
u = 0x0008;
break;
case 'f':
u = 0x000C;
break;
case 'n':
u = 0x000A;
break;
case 'r':
u = 0x000D;
break;
case 't':
u = 0x0009;
break;
case 'v':
u = 0x000B;
break;
}
ChNext();
return true;
}
LBad:
ReportError(ichErr, _cursor.IchCur, ErrId.BadEscape);
u = 0;
return false;
}
LHex:
bool fRet = true;
ChNext();
u = 0;
for (int ich = 0; ich < cchHex; ich++)
{
if (!LexCharUtils.IsHexDigit(ChCur))
{
fRet = (ich > 0);
if (fUni || !fRet)
ReportError(ichErr, _cursor.IchCur, ErrId.BadEscape);
break;
}
u = (u << 4) + (uint)LexCharUtils.GetHexVal(ChCur);
ChNext();
}
return fRet;
}
/// <summary>
/// Convert the pair of characters to a surrogate pair.
/// </summary>
private bool ConvertToSurrogatePair(uint u, out char ch1, out char ch2)
{
Contracts.Assert(u > 0x0000FFFF);
if (u > 0x0010FFFF)
{
ReportError(ErrId.BadEscape);
ch1 = ch2 = '\0';
return false;
}
ch1 = (char)((u - 0x10000) / 0x400 + 0xD800);
ch2 = (char)((u - 0x10000) % 0x400 + 0xDC00);
return true;
}
/// <summary>
/// Lex an identifier.
/// </summary>
private Token LexIdent()
{
bool fVerbatim = false;
if (ChCur == '@')
{
fVerbatim = true;
ChNext();
}
NormStr nstr = LexIdentCore(ref fVerbatim);
if (nstr == null)
{
// Error already reported.
return null;
}
if (!fVerbatim)
{
KeyWordTable.KeyWordKind kind;
if (_lex._kwt.IsKeyWord(nstr, out kind))
return KeyToken.CreateKeyWord(GetSpan(), nstr.Value.ToString(), kind.Kind, kind.IsContextKeyWord);
}
return new IdentToken(GetSpan(), nstr.Value.ToString());
}
private NormStr LexIdentCore(ref bool fVerbatim)
{
Contracts.Assert(LexCharUtils.IsIdentStart(ChCur));
_sb.Length = 0;
for (; ; )
{
char ch;
if (ChCur == '\\')
{
uint u;
int ichErr = _cursor.IchCur;
if (!FLexEscChar(true, out u))
break;
if (u > 0xFFFF || !LexCharUtils.IsIdent(ch = (char)u))
{
ReportError(ichErr, _cursor.IchCur, ErrId.BadChar, LexCharUtils.GetUniEscape(u));
break;
}
fVerbatim = true;
}
else
{
if (!LexCharUtils.IsIdent(ChCur))
break;
ch = ChCur;
ChNext();
}
Contracts.Assert(LexCharUtils.IsIdent(ch));
if (!LexCharUtils.IsFormat(ch))
_sb.Append(ch);
}
if (_sb.Length == 0)
return null;
return _lex._pool.Add(_sb);
}
/// <summary>
/// Lex a comment.
/// </summary>
private Token LexComment()
{
Contracts.Assert(ChCur == '/');
int ichErr = _cursor.IchCur;
switch (ChPeek(1))
{
default:
return LexPunc();
case '/':
// Single line comment.
ChNext();
_sb.Length = 0;
_sb.Append("//");
for (; ; )
{
if (LexCharUtils.IsLineTerm(ChNext()) || Eof)
return new CommentToken(GetSpan(), _sb.ToString(), 0);
_sb.Append(ChCur);
}
case '*':
/* block comment */
ChNext();
_sb.Length = 0;
_sb.Append("/*");
ChNext();
int lines = 0;
for (; ; )
{
if (Eof)
{
ReportError(ichErr, _cursor.IchCur, ErrId.UnterminatedComment);
break;
}
char ch = ChCur;
if (LexCharUtils.IsLineTerm(ch))
{
ch = LexLineTerm(_sb);
lines++;
}
else
ChNext();
_sb.Append(ch);
if (ch == '*' && ChCur == '/')
{
_sb.Append('/');
ChNext();
break;
}
}
// We support comment keywords.
KeyWordTable.KeyWordKind kind;
NormStr nstr = _lex._pool.Add(_sb);
if (_lex._kwt.IsKeyWord(nstr, out kind))
return KeyToken.CreateKeyWord(GetSpan(), nstr.ToString(), kind.Kind, kind.IsContextKeyWord);
return new CommentToken(GetSpan(), _sb.ToString(), lines);
}
}
/// <summary>
/// Lex a sequence of spacing characters.
/// Always returns null.
/// </summary>
private Token LexSpace()
{
Contracts.Assert(LexCharUtils.StartKind(ChCur) == LexStartKind.Space);
while (LexCharUtils.IsSpace(ChNext()))
;
return null;
}
/// <summary>
/// Lex a line termination character. Transforms CRLF into a single LF.
/// Updates the line mapping. When this "drops" a character and sb is not
/// null, it adds the character to sb. It does NOT add the returned character
/// to the sb.
/// </summary>
private char LexLineTerm(StringBuilder sb = null)
{
Contracts.Assert(LexCharUtils.StartKind(ChCur) == LexStartKind.LineTerm);
int ichMin = _cursor.IchCur;
if (ChCur == '\xD' && ChPeek(1) == '\xA')
{
if (sb != null)
sb.Append(ChCur);
ChNext();
}
char ch = ChCur;
ChNext();
if (_ichMinTok == ichMin)
{
// Not nested.
_queue.Enqueue(new NewLineToken(GetSpan(), false));
}
else
{
// Is nested.
_queue.Enqueue(new NewLineToken(GetTextSpan(ichMin, _cursor.IchCur), true));
}
_fLineStart = true;
return ch;
}
private Token LexPreProc()
{
// We don't currently support pre-processing.
return LexError();
}
/// <summary>
/// Skip over an error character. Always returns null.
/// REVIEW: Should we skip over multiple?
/// </summary>
private Token LexError()
{
_sb.Length = 0;
do
{
_sb.AppendFormat("{0}({1})", ChCur, LexCharUtils.GetUniEscape(ChCur));
} while (LexCharUtils.StartKind(ChNext()) == LexStartKind.None && !Eof);
return new ErrorToken(GetSpan(), ErrId.BadChar, _sb.ToString());
}
}
}
}
| 36.170414 | 131 | 0.36844 | [
"MIT"
] | Hyolog/machinelearning | src/Microsoft.ML.Transforms/Expression/Lexer.cs | 30,566 | C# |
/* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using XenAdmin.Dialogs;
using XenAdmin.Dialogs.Network;
using XenAdmin.Dialogs.RestoreSession;
using XenAdmin.Dialogs.WarningDialogs;
using XenAdmin.Dialogs.Wlb;
namespace XenAdminTests.DialogTests.state1_xml.DialogsWithDefaultConstructor
{
public abstract class DialogWithDefaultConstructorTest<T> : DialogTest<T> where T: XenDialogBase, new()
{
protected override T NewDialog()
{
return new T();
}
}
[TestFixture, Category(TestCategories.UICategoryA)]
public class AboutDialogTest : DialogWithDefaultConstructorTest<AboutDialog> { }
[TestFixture, Category(TestCategories.UICategoryA)]
public class BondPropertiesTest : DialogWithDefaultConstructorTest<BondProperties> { }
[TestFixture, Category(TestCategories.UICategoryA)]
public class CloseXenCenterWarningDialogTest : DialogWithDefaultConstructorTest<CloseXenCenterWarningDialog> { }
[TestFixture, Category(TestCategories.UICategoryA)]
public class ConfigureGraphsDialogTest : DialogWithDefaultConstructorTest<GraphDetailsDialog> { }
[TestFixture, Category(TestCategories.UICategoryA)]
public class ConfirmDeconfigureWLBDialogTest : DialogWithDefaultConstructorTest<ConfirmDeconfigureWLBDialog> { }
[TestFixture, Category(TestCategories.UICategoryA)]
public class InputPromptDialogTest : DialogWithDefaultConstructorTest<InputPromptDialog>
{
protected override void RunBeforeShow()
{
dialog.Text = "Foo";
dialog.promptLabel.Text = "Bar";
dialog.textBox1.Text = "stuff";
dialog.HelpID = "NewFolderDialog";
}
}
[TestFixture, Category(TestCategories.UICategoryA)]
public class LegalNoticesDialogTest : DialogWithDefaultConstructorTest<LegalNoticesDialog> { }
[TestFixture, Category(TestCategories.UICategoryA)]
public class LoadSessionDialogTest : DialogWithDefaultConstructorTest<LoadSessionDialog> { }
[TestFixture, Category(TestCategories.UICategoryA)]
public class NameAndConnectionPromptTest : DialogWithDefaultConstructorTest<NameAndConnectionPrompt> { }
[TestFixture, Category(TestCategories.UICategoryA)]
public class PasswordsRequestDialogTest : DialogWithDefaultConstructorTest<PasswordsRequestDialog> { }
[TestFixture, Category(TestCategories.UICategoryA)]
public class SelectHostDialogTest : DialogWithDefaultConstructorTest<SelectHostDialog> { }
[TestFixture, Category(TestCategories.UICategoryA)]
public class SetMasterPasswordDialogTest : DialogWithDefaultConstructorTest<SetMasterPasswordDialog> { }
}
| 42.132653 | 116 | 0.760717 | [
"BSD-2-Clause"
] | wdxgy136/xenadmin-yeesan | XenAdminTests/DialogTests/DialogsWithDefaultConstructor.cs | 4,131 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace CC98.Medal.Migrations
{
public partial class AddMedalCategoryInfo : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Description",
table: "MedalCategories",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "IconUri",
table: "MedalCategories",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Name",
table: "MedalCategories",
maxLength: 100,
nullable: false,
defaultValue: "");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Description",
table: "MedalCategories");
migrationBuilder.DropColumn(
name: "IconUri",
table: "MedalCategories");
migrationBuilder.DropColumn(
name: "Name",
table: "MedalCategories");
}
}
}
| 28.627907 | 71 | 0.528026 | [
"Apache-2.0"
] | ZJU-CC98/CC98.Medal | CC98.Medal/CC98.Medal/Migrations/20200701064527_AddMedalCategoryInfo.cs | 1,233 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.AppPlatform.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Specifications of the Dimension of metrics
/// </summary>
public partial class MetricDimension
{
/// <summary>
/// Initializes a new instance of the MetricDimension class.
/// </summary>
public MetricDimension()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the MetricDimension class.
/// </summary>
/// <param name="name">Name of the dimension</param>
/// <param name="displayName">Localized friendly display name of the
/// dimension</param>
/// <param name="toBeExportedForShoebox">Whether this dimension should
/// be included for the Shoebox export scenario</param>
public MetricDimension(string name = default(string), string displayName = default(string), bool? toBeExportedForShoebox = default(bool?))
{
Name = name;
DisplayName = displayName;
ToBeExportedForShoebox = toBeExportedForShoebox;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets name of the dimension
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets localized friendly display name of the dimension
/// </summary>
[JsonProperty(PropertyName = "displayName")]
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets whether this dimension should be included for the
/// Shoebox export scenario
/// </summary>
[JsonProperty(PropertyName = "toBeExportedForShoebox")]
public bool? ToBeExportedForShoebox { get; set; }
}
}
| 33.732394 | 146 | 0.617537 | [
"MIT"
] | AikoBB/azure-sdk-for-net | sdk/appplatform/Microsoft.Azure.Management.AppPlatform/src/Generated/Models/MetricDimension.cs | 2,395 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using SimplCommerce.Infrastructure;
namespace SimplCommerce.Web.Areas.Admin.ViewModels.SmartTable
{
public static class SmartTableExtension
{
public static SmartTableResult<TResult> ToSmartTableResult<TModel, TResult>(this IQueryable<TModel> query, SmartTableParam param, Func<TModel, TResult> selector)
{
if (param.Pagination.Number <= 0)
{
param.Pagination.Number = 10;
}
var totalRecord = query.Count();
if (!string.IsNullOrWhiteSpace(param.Sort.Predicate))
{
query = query.OrderByName(param.Sort.Predicate, param.Sort.Reverse);
}
else
{
query = query.OrderByName("Id", false);
}
var items = query
.Skip(param.Pagination.Start)
.Take(param.Pagination.Number)
.Select(selector).ToList();
return new SmartTableResult<TResult>
{
Items = items,
TotalRecord = totalRecord,
NumberOfPages = (int)Math.Ceiling((double)totalRecord / param.Pagination.Number)
};
}
}
}
| 30.547619 | 169 | 0.566641 | [
"Apache-2.0"
] | dbraunbock/SimplCommerce | src/SimplCommerce.Web/Areas/Admin/ViewModels/SmartTable/SmartTableExtension.cs | 1,285 | C# |
using UnityEditor;
using UnityEngine;
using UnityEngine.XR.WindowsMR;
namespace UnityEditor.XR.WindowsMR
{
public class WindowsMRRemotingWindow : EditorWindow
{
[MenuItem("Window/XR/Windows XR Plugin Remoting")]
public static void Init()
{
GetWindow<WindowsMRRemotingWindow>(false);
}
static GUIContent s_ConnectionStatusText = EditorGUIUtility.TrTextContent("Connection Status");
static GUIContent s_EmulationModeText = EditorGUIUtility.TrTextContent("Emulation Mode");
static GUIContent s_RemoteMachineText = EditorGUIUtility.TrTextContent("Remote Machine");
static GUIContent s_EnableVideoText = EditorGUIUtility.TrTextContent("Enable Video");
static GUIContent s_EnableAudioText = EditorGUIUtility.TrTextContent("Enable Audio");
static GUIContent s_MaxBitrateText = EditorGUIUtility.TrTextContent("Max Bitrate (kbps)");
static GUIContent s_ConnectionButtonConnectText = EditorGUIUtility.TrTextContent("Connect");
static GUIContent s_ConnectionButtonDisconnectText = EditorGUIUtility.TrTextContent("Disconnect");
static GUIContent s_ConnectionStateDisconnectedText = EditorGUIUtility.TrTextContent("Disconnected");
static GUIContent s_ConnectionStateConnectingText = EditorGUIUtility.TrTextContent("Connecting");
static GUIContent s_ConnectionStateConnectedText = EditorGUIUtility.TrTextContent("Connected");
static GUIContent s_RemotingSettingsReminder = EditorGUIUtility.TrTextContent("The Editor uses player settings from the 'Standalone' platform for play mode and a remoting connection can be established without 'Windows Mixed Reality' enabled.");
ConnectionState previousConnectionState = ConnectionState.Disconnected;
static GUIContent[] s_ModeStrings = new GUIContent[]
{
EditorGUIUtility.TrTextContent("None"),
EditorGUIUtility.TrTextContent("Remote to Device")
};
void OnEnable()
{
titleContent = EditorGUIUtility.TrTextContent("Windows Mixed Reality");
}
void DrawEmulationModeOnGUI()
{
EditorGUI.BeginDisabledGroup(EditorApplication.isPlayingOrWillChangePlaymode);
EditorGUI.BeginChangeCheck();
WindowsMREmulationMode previousMode = WindowsMREmulation.mode;
WindowsMREmulationMode currentMode = (WindowsMREmulationMode)EditorGUILayout.Popup(s_EmulationModeText, (int)previousMode, s_ModeStrings);
if (EditorGUI.EndChangeCheck())
{
if (previousMode == WindowsMREmulationMode.Remoting)
WindowsMRRemoting.Disconnect();
WindowsMREmulation.mode = currentMode;
}
EditorGUI.EndDisabledGroup();
}
string m_RemoteMachineName = "";
void DrawRemotingOnGUI()
{
EditorGUILayout.HelpBox(s_RemotingSettingsReminder);
EditorGUI.BeginDisabledGroup(WindowsMRRemoting.isConnected);
m_RemoteMachineName = EditorGUILayout.TextField(s_RemoteMachineText, m_RemoteMachineName);
WindowsMRRemoting.remoteMachineName = m_RemoteMachineName;
WindowsMRRemoting.isVideoEnabled = EditorGUILayout.Toggle(s_EnableVideoText, WindowsMRRemoting.isVideoEnabled);
WindowsMRRemoting.isAudioEnabled = EditorGUILayout.Toggle(s_EnableAudioText, WindowsMRRemoting.isAudioEnabled);
WindowsMRRemoting.maxBitRateKbps = EditorGUILayout.IntSlider(s_MaxBitrateText, WindowsMRRemoting.maxBitRateKbps, 1024, 99999);
EditorGUI.EndDisabledGroup();
GUIContent labelContent;
GUIContent buttonContent;
ConnectionState connectionState;
if (!WindowsMRRemoting.TryGetConnectionState(out connectionState))
{
Debug.Log("Failed to get connection state! Exiting remoting-window drawing.");
return;
}
if (previousConnectionState == ConnectionState.Connecting && connectionState == ConnectionState.Disconnected)
{
ConnectionFailureReason failureReason;
WindowsMRRemoting.TryGetConnectionFailureReason(out failureReason);
Debug.Log("Connection Failure Reason: " + failureReason);
}
previousConnectionState = connectionState;
switch (connectionState)
{
case ConnectionState.Disconnected:
default:
labelContent = s_ConnectionStateDisconnectedText;
buttonContent = s_ConnectionButtonConnectText;
break;
case ConnectionState.Connecting:
labelContent = s_ConnectionStateConnectingText;
buttonContent = s_ConnectionButtonDisconnectText;
break;
case ConnectionState.Connected:
labelContent = s_ConnectionStateConnectedText;
buttonContent = s_ConnectionButtonDisconnectText;
break;
}
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel(s_ConnectionStatusText, "Button");
float iconSize = EditorGUIUtility.singleLineHeight;
Rect iconRect = GUILayoutUtility.GetRect(iconSize, iconSize, GUILayout.ExpandWidth(false));
EditorGUILayout.LabelField(labelContent);
EditorGUILayout.EndHorizontal();
EditorGUI.BeginDisabledGroup(EditorApplication.isPlayingOrWillChangePlaymode);
bool pressed = EditorGUILayout.DropdownButton(buttonContent, FocusType.Passive, EditorStyles.miniButton);
EditorGUI.EndDisabledGroup();
if (pressed)
{
if (EditorGUIUtility.editingTextField)
{
EditorGUIUtility.editingTextField = false;
GUIUtility.keyboardControl = 0;
}
HandleButtonPress();
}
}
private void HandleButtonPress()
{
if (EditorApplication.isPlayingOrWillChangePlaymode)
{
Debug.LogError("Unable to connect / disconnect remoting while playing.");
return;
}
ConnectionState connectionState;
if (!WindowsMRRemoting.TryGetConnectionState(out connectionState))
{
Debug.LogError("Failed to get connection state - exiting button-press response!");
return;
}
if (connectionState == ConnectionState.Connecting ||
connectionState == ConnectionState.Connected)
WindowsMRRemoting.Disconnect();
else if (!string.IsNullOrEmpty(WindowsMRRemoting.remoteMachineName))
WindowsMRRemoting.Connect();
else
Debug.LogError("Cannot connect without a remote machine name!");
}
void OnGUI()
{
DrawEmulationModeOnGUI();
if (WindowsMREmulation.mode == WindowsMREmulationMode.Remoting)
DrawRemotingOnGUI();
}
}
}
| 44.207317 | 252 | 0.654897 | [
"Apache-2.0"
] | BCBlanka/BeatSaber | Library/PackageCache/com.unity.xr.windowsmr@2.5.2/Editor/WindowsMRRemotingWindow.cs | 7,250 | C# |
using System.Text.Json.Serialization;
namespace Horizon.Payment.Alipay.Domain
{
/// <summary>
/// KoubeiTradeTicketSendCloseModel Data Structure.
/// </summary>
public class KoubeiTradeTicketSendCloseModel : AlipayObject
{
/// <summary>
/// 订单号
/// </summary>
[JsonPropertyName("order_no")]
public string OrderNo { get; set; }
/// <summary>
/// 停止发码原因
/// </summary>
[JsonPropertyName("reason")]
public string Reason { get; set; }
/// <summary>
/// 外部请求流水号
/// </summary>
[JsonPropertyName("request_id")]
public string RequestId { get; set; }
/// <summary>
/// 口碑商品发货单号
/// </summary>
[JsonPropertyName("send_order_no")]
public string SendOrderNo { get; set; }
/// <summary>
/// 凭证发放token
/// </summary>
[JsonPropertyName("send_token")]
public string SendToken { get; set; }
}
}
| 24.609756 | 63 | 0.536174 | [
"Apache-2.0"
] | bluexray/Horizon.Sample | Horizon.Payment.Alipay/Domain/KoubeiTradeTicketSendCloseModel.cs | 1,067 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the config-2014-11-12.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ConfigService.Model
{
/// <summary>
/// This is the response object from the PutStoredQuery operation.
/// </summary>
public partial class PutStoredQueryResponse : AmazonWebServiceResponse
{
private string _queryArn;
/// <summary>
/// Gets and sets the property QueryArn.
/// <para>
/// Amazon Resource Name (ARN) of the query. For example, arn:partition:service:region:account-id:resource-type/resource-id.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=500)]
public string QueryArn
{
get { return this._queryArn; }
set { this._queryArn = value; }
}
// Check to see if QueryArn property is set
internal bool IsSetQueryArn()
{
return this._queryArn != null;
}
}
} | 31.12069 | 133 | 0.639889 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/ConfigService/Generated/Model/PutStoredQueryResponse.cs | 1,805 | C# |
namespace popp
{
public enum LineType
{
Whitespace,
Comment,
Msgctxt,
Msgid,
Msgstr,
StrContinuation,
IncludeStatement
}
}
| 14.642857 | 25 | 0.473171 | [
"MIT"
] | Treer/POpp | popp/LineType.cs | 207 | C# |
// Copyright (c) 2019, WebsitePanel-Support.net.
// Distributed by websitepanel-support.net
// Build and fixed by Key4ce - IT Professionals
// https://www.key4ce.com
//
// Original source:
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
using System.Web.Services.Protocols;
using System.Xml.XPath;
using WebsitePanel.Providers.Common;
using WebsitePanel.Providers.Mail.SM5;
using WebsitePanel.Providers.Utils;
using WebsitePanel.Server.Utils;
using Microsoft.Win32;
namespace WebsitePanel.Providers.Mail
{
public class SmarterMail5 : HostingServiceProviderBase, IMailServer
{
static string[] smListSettings = new string[] {
"description",
"disabled",
"moderator",
"password",
"requirepassword",
"whocanpost",
"prependsubject",
"maxmessagesize",
"maxrecipients",
"replytolist",
"subject"
};
#region Constants
public const string SYSTEM_DOMAIN_ADMIN = "system.domain.admin";
public const string SYSTEM_CATCH_ALL = "system.catch.all";
#endregion
#region Public Properties
protected string AdminUsername
{
get { return ProviderSettings["AdminUsername"]; }
}
protected string AdminPassword
{
get { return ProviderSettings["AdminPassword"]; }
}
protected bool ImportDomainAdmin
{
get
{
bool res;
bool.TryParse(ProviderSettings[Constants.ImportDomainAdmin], out res);
return res;
}
}
protected bool InheritDomainDefaultLimits
{
get
{
bool res;
bool.TryParse(ProviderSettings[Constants.InheritDomainDefaultLimits], out res);
return res;
}
}
protected string DomainsPath
{
get { return FileUtils.EvaluateSystemVariables(ProviderSettings["DomainsPath"]); }
}
protected string ServerIP
{
get
{
string val = ProviderSettings["ServerIPAddress"];
if (String.IsNullOrEmpty(val))
return "127.0.0.1";
string ip = val.Trim();
if (ip.IndexOf(";") > -1)
{
string[] ips = ip.Split(';');
ip = String.IsNullOrEmpty(ips[1]) ? ips[0] : ips[1]; // get internal IP part
}
return ip;
}
}
protected string ServiceUrl
{
get { return ProviderSettings["ServiceUrl"]; }
}
protected string LicenseType
{
get { return ProviderSettings["LicenseType"]; }
}
#endregion
#region Domains
public void CreateDomain(MailDomain domain)
{
try
{
svcDomainAdmin domains = new svcDomainAdmin();
PrepareProxy(domains);
DomainSettingsResult defaultDomainSettings = domains.GetDomainDefaults(AdminUsername, AdminPassword);
SettingsRequestResult defaultRequestedSettings =
domains.GetRequestedDomainDefaults(AdminUsername, AdminPassword, new string[] {
"defaultaltsmtpport",
"defaultaltsmtpportenabled",
"defaultautoresponderrestriction",
"defaultbypassgreylisting",
"defaultenablecatchalls",
"defaultenabledomainkeys",
"defaultenableemailreports",
"defaultenablepopretrieval",
"defaultmaxmessagesperhour",
"defaultmaxmessagesperhourenabled",
"defaultmaxsmtpoutbandwidthperhour",
"defaultmaxsmtpoutbandwidthperhourenabled",
"defaultmaxbouncesreceivedperhour",
"defaultmaxbouncesreceivedperhourenabled",
"defaultmaxpopretrievalaccounts",
"defaultsharedcalendar",
"defaultsharedcontact",
"defaultsharedfolder",
"defaultsharedgal",
"defaultsharednotes",
"defaultsharedtasks",
"defaultshowcalendar",
"defaultshowcontacts",
"defaultshowcontentfilteringmenu",
"defaultshowdomainaliasmenu",
"defaultshowdomainreports",
"defaultshowlistmenu",
"defaultshownotes",
"defaultshowspammenu",
"defaultshowtasks",
"defaultshowuserreports",
"defaultskin",
"defaultspamresponderoption",
"defaultspamforwardoption"
});
string[] requestedDomainDefaults = defaultRequestedSettings.settingValues;
//domain Path is taken from WebsitePanel Service settings
GenericResult result = null;
if (!InheritDomainDefaultLimits)
{
result = domains.AddDomain(AdminUsername, AdminPassword,
domain.Name,
Path.Combine(DomainsPath, domain.Name),
SYSTEM_DOMAIN_ADMIN, // admin username
Guid.NewGuid().ToString("P"), // admin password
"Domain", // admin first name
"Administrator", // admin last name
ServerIP,
defaultDomainSettings.ImapPort,
defaultDomainSettings.PopPort,
defaultDomainSettings.SmtpPort,
domain.MaxAliases,
domain.MaxDomainSizeInMB,
domain.MaxDomainUsers,
domain.MaxMailboxSizeInMB,
domain.MaxMessageSize,
domain.MaxRecipients,
domain.MaxDomainAliases,
domain.MaxLists,
defaultDomainSettings.ShowDomainAliasMenu,
// ShowDomainAliasMenu
defaultDomainSettings.ShowContentFilteringMenu,
// ShowContentFilteringMenu
defaultDomainSettings.ShowSpamMenu, // ShowSpamMenu
defaultDomainSettings.ShowStatsMenu, // ShowStatsMenu
defaultDomainSettings.RequireSmtpAuthentication,
defaultDomainSettings.ShowListMenu, // ShowListMenu
defaultDomainSettings.ListCommandAddress);
}
else
{
result = domains.AddDomain(AdminUsername, AdminPassword,
domain.Name,
Path.Combine(DomainsPath, domain.Name),
SYSTEM_DOMAIN_ADMIN, // admin username
Guid.NewGuid().ToString("P"), // admin password
"Domain", // admin first name
"Administrator", // admin last name
ServerIP,
defaultDomainSettings.ImapPort,
defaultDomainSettings.PopPort,
defaultDomainSettings.SmtpPort,
defaultDomainSettings.MaxAliases,
defaultDomainSettings.MaxDomainSizeInMB,
defaultDomainSettings.MaxDomainUsers,
defaultDomainSettings.MaxMailboxSizeInMB,
defaultDomainSettings.MaxMessageSize,
defaultDomainSettings.MaxRecipients,
defaultDomainSettings.MaxDomainAliases,
defaultDomainSettings.MaxLists,
defaultDomainSettings.ShowDomainAliasMenu,// ShowDomainAliasMenu
defaultDomainSettings.ShowContentFilteringMenu,// ShowContentFilteringMenu
defaultDomainSettings.ShowSpamMenu, // ShowSpamMenu
defaultDomainSettings.ShowStatsMenu, // ShowStatsMenu
defaultDomainSettings.RequireSmtpAuthentication,
defaultDomainSettings.ShowListMenu, // ShowListMenu
defaultDomainSettings.ListCommandAddress);
}
if (!result.Result)
throw new Exception(result.Message);
// update additional settings
result = domains.SetRequestedDomainSettings(AdminUsername, AdminPassword, domain.Name, SetMailDomainDefaultSettings(requestedDomainDefaults));
if (!result.Result)
throw new Exception(result.Message);
}
catch (Exception ex)
{
if (DomainExists(domain.Name))
{
DeleteDomain(domain.Name);
}
Log.WriteError(ex);
throw new Exception("Could not create mail domain", ex);
}
}
/// <summary>
/// Returns domain info
/// </summary>
/// <param name="domainName">Domain name</param>
/// <returns>Domain info</returns>
public MailDomain GetDomain(string domainName)
{
try
{
svcDomainAdmin domains = new svcDomainAdmin();
PrepareProxy(domains);
DomainSettingsResult result = domains.GetDomainSettings(AdminUsername, AdminPassword, domainName);
if (!result.Result)
throw new Exception(result.Message);
// fill domain properties
MailDomain domain = new MailDomain();
domain.Name = domainName;
domain.Path = result.Path;
domain.ServerIP = result.ServerIP;
domain.ImapPort = result.ImapPort;
domain.SmtpPort = result.SmtpPort;
domain.PopPort = result.PopPort;
domain.MaxAliases = result.MaxAliases;
domain.MaxDomainAliases = result.MaxDomainAliases;
domain.MaxLists = result.MaxLists;
domain.MaxDomainSizeInMB = result.MaxDomainSizeInMB;
domain.MaxDomainUsers = result.MaxDomainUsers;
domain.MaxMailboxSizeInMB = result.MaxMailboxSizeInMB;
domain.MaxMessageSize = result.MaxMessageSize;
domain.MaxRecipients = result.MaxRecipients;
domain.RequireSmtpAuthentication = result.RequireSmtpAuthentication;
domain.ListCommandAddress = result.ListCommandAddress;
domain.ShowContentFilteringMenu = result.ShowContentFilteringMenu;
domain.ShowDomainAliasMenu = result.ShowDomainAliasMenu;
domain.ShowListMenu = result.ShowListMenu;
domain.ShowSpamMenu = result.ShowSpamMenu;
// get additional domain settings
string[] requestedSettings = new string[]
{
"catchall",
"enablepopretrieval",
"enablecatchalls",
"isenabled",
"ldapport",
"altsmtpport",
"sharedcalendar",
"sharedcontact",
"sharedfolder",
"sharednotes",
"sharedtasks",
"sharedgal",
"bypassforwardblacklist",
"showdomainreports",
"spamresponderoption",
"spamforwardoption",
"maxmessagesperhour",
"maxmessagesperhourenabled",
"maxsmtpoutbandwidthperhour",
"maxsmtpoutbandwidthperhourenabled",
"maxpopretrievalaccounts",
"maxbouncesreceivedperhour",
"maxbouncesreceivedperhourenabled"
};
SettingsRequestResult addResult = domains.GetRequestedDomainSettings(AdminUsername, AdminPassword, domainName, requestedSettings);
if (!addResult.Result)
throw new Exception(addResult.Message);
FillMailDomainFields(domain, addResult);
// get catch-all address
if (!String.IsNullOrEmpty(domain.CatchAllAccount))
{
// get catch-all group
string groupName = SYSTEM_CATCH_ALL + "@" + domain.Name;
if (GroupExists(groupName))
{
// get the first member of this group
MailGroup group = GetGroup(groupName);
domain.CatchAllAccount = GetAccountName(group.Members[0]);
}
}
//get license information
if (LicenseType == "PRO")
{
domain[MailDomain.SMARTERMAIL_LICENSE_TYPE] = "PRO";
}
if (LicenseType == "ENT")
{
domain[MailDomain.SMARTERMAIL_LICENSE_TYPE] = "ENT";
}
return domain;
}
catch (Exception ex)
{
throw new Exception("Could not get mail domain", ex);
}
}
public void UpdateDomain(MailDomain domain)
{
try
{
// load original domain
MailDomain origDomain = GetDomain(domain.Name);
svcDomainAdmin domains = new svcDomainAdmin();
PrepareProxy(domains);
GenericResult result = domains.UpdateDomain(AdminUsername, AdminPassword,
domain.Name,
origDomain.ServerIP,
domain.ImapPort,
domain.PopPort,
domain.SmtpPort,
domain.MaxAliases,
domain.MaxDomainSizeInMB,
domain.MaxDomainUsers,
domain.MaxMailboxSizeInMB,
domain.MaxMessageSize,
domain.MaxRecipients,
domain.MaxDomainAliases,
domain.MaxLists,
domain.ShowDomainAliasMenu, // ShowDomainAliasMenu
domain.ShowContentFilteringMenu, // ShowContentFilteringMenu
domain.ShowSpamMenu, // ShowSpamMenu
domain.ShowsStatsMenu, // this parameter is no longer used in SM5
origDomain.RequireSmtpAuthentication,
domain.ShowListMenu, // Showlistmenu
origDomain.ListCommandAddress);
if (!result.Result)
throw new Exception(result.Message);
// update catch-all group
UpdateDomainCatchAllGroup(domain.Name, domain.CatchAllAccount);
// update additional settings
result = domains.SetRequestedDomainSettings(AdminUsername, AdminPassword, domain.Name,
new string[] {
"isenabled=" + domain.Enabled,
"catchall=" + (!String.IsNullOrEmpty(domain.CatchAllAccount) ? SYSTEM_CATCH_ALL : ""),
"altsmtpport=" + domain.SmtpPortAlt,
"ldapport=" + domain.LdapPort,
"sharedcalendar=" + domain.SharedCalendars,
"sharedcontact=" + domain.SharedContacts,
"sharedfolder=" + domain.SharedFolders,
"sharednotes=" + domain.SharedNotes,
"sharedtasks=" + domain.SharedTasks,
"sharedgal=" + domain.IsGlobalAddressList,
"enablecatchalls=" + domain[MailDomain.SMARTERMAIL5_CATCHALLS_ENABLED],
"bypassforwardblacklist=" + domain.BypassForwardBlackList,
"showdomainreports=" + domain[MailDomain.SMARTERMAIL5_SHOW_DOMAIN_REPORTS],
"maxmessagesperhour=" + domain[MailDomain.SMARTERMAIL5_MESSAGES_PER_HOUR],
"maxmessagesperhourenabled=" + domain[MailDomain.SMARTERMAIL5_MESSAGES_PER_HOUR_ENABLED],
"maxsmtpoutbandwidthperhour=" + domain[MailDomain.SMARTERMAIL5_BANDWIDTH_PER_HOUR],
"maxsmtpoutbandwidthperhourenabled=" + domain[MailDomain.SMARTERMAIL5_BANDWIDTH_PER_HOUR_ENABLED],
"enablepopretrieval=" + domain[MailDomain.SMARTERMAIL5_POP_RETREIVAL_ENABLED],
"maxpopretrievalaccounts=" + domain[MailDomain.SMARTERMAIL5_POP_RETREIVAL_ACCOUNTS],
"maxbouncesreceivedperhour=" + domain[MailDomain.SMARTERMAIL5_BOUNCES_PER_HOUR],
"maxbouncesreceivedperhourenabled=" + domain[MailDomain.SMARTERMAIL5_BOUNCES_PER_HOUR_ENABLED]
});
/*
string[] requestedSettings = new string[]
{
"maxmessagesperhour",
"maxmessagesperhourenabled",
"maxsmtpoutbandwidthperhour",
"maxsmtpoutbandwidthperhourenabled"
};
SettingsRequestResult addResult =
domains.GetRequestedDomainSettings(AdminUsername, AdminPassword, domain.Name, requestedSettings);
*/
if (!result.Result)
throw new Exception(result.Message);
}
catch (Exception ex)
{
throw new Exception("Could not update mail domain", ex);
}
}
/// <summary>
/// Checks whether the specified domain exists
/// </summary>
/// <param name="domainName">Domain name</param>
/// <returns>true if the specified domain exists, otherwise false</returns>
public bool DomainExists(string domainName)
{
try
{
svcDomainAdmin domains = new svcDomainAdmin();
PrepareProxy(domains);
DomainSettingsResult result = domains.GetDomainSettings(AdminUsername, AdminPassword, domainName);
return result.Result;
}
catch (Exception ex)
{
throw new Exception("Could not check whether mail domain exists", ex);
}
}
/// <summary>
/// Returns a list of all domain names
/// </summary>
/// <returns>Array with domain names</returns>
public string[] GetDomains()
{
try
{
svcDomainAdmin domains = new svcDomainAdmin();
PrepareProxy(domains);
DomainListResult result = domains.GetAllDomains(AdminUsername, AdminPassword);
if (!result.Result)
throw new Exception(result.Message);
return result.DomainNames;
}
catch (Exception ex)
{
throw new Exception("Could not get the list of mail domains", ex);
}
}
/// <summary>
/// Deletes the specified domain
/// </summary>
/// <param name="domainName"></param>
public void DeleteDomain(string domainName)
{
try
{
svcDomainAdmin domains = new svcDomainAdmin();
PrepareProxy(domains);
GenericResult result = domains.DeleteDomain(AdminUsername, AdminPassword,
domainName,
true // delete files
);
if (!result.Result)
throw new Exception(result.Message);
}
catch (Exception ex)
{
throw new Exception("Could not delete mail domain", ex);
}
}
#endregion
#region MailBoxes
public void CreateAccount(MailAccount mailbox)
{
try
{
svcUserAdmin users = new svcUserAdmin();
PrepareProxy(users);
GenericResult result = users.AddUser(AdminUsername, AdminPassword,
mailbox.Name,
mailbox.Password,
GetDomainName(mailbox.Name),
mailbox.FirstName,
mailbox.LastName,
false // domain admin is false
);
if (!result.Result)
throw new Exception(result.Message);
// set forwarding settings
result = users.UpdateUserForwardingInfo(AdminUsername, AdminPassword,
mailbox.Name, mailbox.DeleteOnForward,
(mailbox.ForwardingAddresses != null ? String.Join(", ", mailbox.ForwardingAddresses) : ""));
if (!result.Result)
throw new Exception(result.Message);
// set additional settings
result = users.SetRequestedUserSettings(AdminUsername, AdminPassword,
mailbox.Name,
new string[]
{
"isenabled=" + mailbox.Enabled.ToString(),
"maxsize=" + mailbox.MaxMailboxSize.ToString(),
"lockpassword=" + mailbox.PasswordLocked.ToString(),
"passwordlocked" + mailbox.PasswordLocked.ToString(),
"replytoaddress=" + (mailbox.ReplyTo != null ? mailbox.ReplyTo : ""),
"signature=" + (mailbox.Signature != null ? mailbox.Signature : ""),
"spamforwardoption=none"
});
if (!result.Result)
throw new Exception(result.Message);
// set autoresponder settings
result = users.UpdateUserAutoResponseInfo(AdminUsername, AdminPassword,
mailbox.Name,
mailbox.ResponderEnabled,
(mailbox.ResponderSubject != null ? mailbox.ResponderSubject : ""),
(mailbox.ResponderMessage != null ? mailbox.ResponderMessage : ""));
if (!result.Result)
throw new Exception(result.Message);
}
catch (Exception ex)
{
throw new Exception("Could not create mailbox", ex);
}
}
public bool AccountExists(string mailboxName)
{
try
{
svcUserAdmin users = new svcUserAdmin();
PrepareProxy(users);
UserInfoResult result = users.GetUser(AdminUsername, AdminPassword, mailboxName);
return result.Result;
}
catch (Exception ex)
{
throw new Exception("Could not check whether mailbox exists", ex);
}
}
/// <summary>
/// Returns all users that belong to the specified domain
/// </summary>
/// <param name="domainName">Domain name</param>
/// <returns>Array with user names</returns>
public MailAccount[] GetAccounts(string domainName)
{
try
{
svcUserAdmin users = new svcUserAdmin();
PrepareProxy(users);
UserInfoListResult result = users.GetUsers(AdminUsername, AdminPassword, domainName);
if (!result.Result)
throw new Exception(result.Message);
List<MailAccount> accounts = new List<MailAccount>();
foreach (UserInfo user in result.Users)
{
if (user.IsDomainAdmin && !ImportDomainAdmin)
continue;
MailAccount account = new MailAccount();
account.Name = user.UserName;
account.Password = user.Password;
accounts.Add(account);
}
return accounts.ToArray();
}
catch (Exception ex)
{
throw new Exception("Could not get the list of domain mailboxes", ex);
}
}
public MailAccount GetAccount(string mailboxName)
{
try
{
svcUserAdmin users = new svcUserAdmin();
PrepareProxy(users);
UserInfoResult result = users.GetUser(AdminUsername, AdminPassword, mailboxName);
if (!result.Result)
throw new Exception(result.Message);
MailAccount mailbox = new MailAccount();
mailbox.Name = result.UserInfo.UserName;
mailbox.Password = result.UserInfo.Password;
mailbox.FirstName = result.UserInfo.FirstName;
mailbox.LastName = result.UserInfo.LastName;
mailbox.IsDomainAdmin = result.UserInfo.IsDomainAdmin;
// get additional settings
string[] requestedSettings = new string[]
{
"isenabled",
"maxsize",
"lockpassword",
"replytoaddress",
"signature",
"passwordlocked"
};
SettingsRequestResult addResult = users.GetRequestedUserSettings(AdminUsername, AdminPassword,
mailboxName, requestedSettings);
if (!addResult.Result)
throw new Exception(addResult.Message);
foreach (string pair in addResult.settingValues)
{
string[] parts = pair.Split('=');
if (parts[0] == "isenabled") mailbox.Enabled = Boolean.Parse(parts[1]);
else if (parts[0] == "maxsize") mailbox.MaxMailboxSize = Int32.Parse(parts[1]);
else if (parts[0] == "passwordlocked") mailbox.PasswordLocked = Boolean.Parse(parts[1]);
else if (parts[0] == "replytoaddress") mailbox.ReplyTo = parts[1];
else if (parts[0] == "signature") mailbox.Signature = parts[1];
}
// get forwardings info
UserForwardingInfoResult forwResult = users.GetUserForwardingInfo(AdminUsername, AdminPassword, mailboxName);
if (!forwResult.Result)
throw new Exception(forwResult.Message);
string[] forwAddresses = forwResult.ForwardingAddress.Split(';', ',');
List<string> listForAddresses = new List<string>();
foreach (string forwAddress in forwAddresses)
{
if (!String.IsNullOrEmpty(forwAddress.Trim()))
listForAddresses.Add(forwAddress.Trim());
}
mailbox.ForwardingAddresses = listForAddresses.ToArray();
mailbox.DeleteOnForward = forwResult.DeleteOnForward;
// get autoresponder info
UserAutoResponseResult respResult = users.GetUserAutoResponseInfo(AdminUsername, AdminPassword, mailboxName);
if (!respResult.Result)
throw new Exception(respResult.Message);
mailbox.ResponderEnabled = respResult.Enabled;
mailbox.ResponderSubject = respResult.Subject;
mailbox.ResponderMessage = respResult.Body;
return mailbox;
}
catch (Exception ex)
{
throw new Exception("Could not get mailbox", ex);
}
}
public void UpdateAccount(MailAccount mailbox)
{
try
{
//get original account
MailAccount account = GetAccount(mailbox.Name);
svcUserAdmin users = new svcUserAdmin();
PrepareProxy(users);
string strPassword = mailbox.Password;
//Don't change password. Get it from mail server.
if (!mailbox.ChangePassword)
{
strPassword = account.Password;
}
GenericResult result = users.UpdateUser(AdminUsername, AdminPassword,
mailbox.Name,
strPassword,
mailbox.FirstName,
mailbox.LastName,
account.IsDomainAdmin
);
if (!result.Result)
throw new Exception(result.Message);
// set forwarding settings
result = users.UpdateUserForwardingInfo(AdminUsername, AdminPassword,
mailbox.Name, mailbox.DeleteOnForward,
(mailbox.ForwardingAddresses != null ? String.Join(", ", mailbox.ForwardingAddresses) : ""));
if (!result.Result)
throw new Exception(result.Message);
// set additional settings
result = users.SetRequestedUserSettings(AdminUsername, AdminPassword,
mailbox.Name,
new string[]
{
"isenabled=" + mailbox.Enabled.ToString(),
"maxsize=" + mailbox.MaxMailboxSize.ToString(),
"passwordlocked=" + mailbox.PasswordLocked.ToString(),
"lockpassword=" + mailbox.PasswordLocked.ToString(),
"replytoaddress=" + (mailbox.ReplyTo != null ? mailbox.ReplyTo : ""),
"signature=" + (mailbox.Signature != null ? mailbox.Signature : ""),
"spamforwardoption=none"
});
if (!result.Result)
throw new Exception(result.Message);
// set autoresponder settings
result = users.UpdateUserAutoResponseInfo(AdminUsername, AdminPassword,
mailbox.Name,
mailbox.ResponderEnabled,
(mailbox.ResponderSubject != null ? mailbox.ResponderSubject : ""),
(mailbox.ResponderMessage != null ? mailbox.ResponderMessage : ""));
if (!result.Result)
throw new Exception(result.Message);
}
catch (Exception ex)
{
throw new Exception("Could not update mailbox", ex);
}
}
public void DeleteAccount(string mailboxName)
{
try
{
svcUserAdmin users = new svcUserAdmin();
PrepareProxy(users);
GenericResult result = users.DeleteUser(AdminUsername, AdminPassword,
mailboxName, GetDomainName(mailboxName));
if (!result.Result)
throw new Exception(result.Message);
}
catch (Exception ex)
{
throw new Exception("Could not delete mailbox", ex);
}
}
#endregion
#region Mail Aliases
public bool MailAliasExists(string mailAliasName)
{
try
{
svcAliasAdmin aliases = new svcAliasAdmin();
PrepareProxy(aliases);
AliasInfoResult result = aliases.GetAlias(AdminUsername, AdminPassword, GetDomainName(mailAliasName), mailAliasName);
if ((result.AliasInfo.Name.Equals("Empty")) && (result.AliasInfo.Addresses.Length == 0))
return false;
return true;
}
catch (Exception ex)
{
throw new Exception("Could not check whether mail alias exists", ex);
}
}
public MailAlias[] GetMailAliases(string domainName)
{
try
{
svcAliasAdmin aliases = new svcAliasAdmin();
PrepareProxy(aliases);
AliasInfoListResult result = aliases.GetAliases(AdminUsername, AdminPassword, domainName);
if (!result.Result)
throw new Exception(result.Message);
List<MailAlias> aliasesList = new List<MailAlias>();
foreach (AliasInfo alias in result.AliasInfos)
{
if (alias.Addresses.Length == 1)
{
MailAlias mailAlias = new MailAlias();
mailAlias.Name = alias.Name + "@" + domainName;
mailAlias.ForwardTo = alias.Addresses[0];
aliasesList.Add(mailAlias);
}
}
return aliasesList.ToArray();
}
catch (Exception ex)
{
throw new Exception("Could not get the list of mail aliases", ex);
}
}
public MailAlias GetMailAlias(string mailAliasName)
{
svcAliasAdmin aliases = new svcAliasAdmin();
PrepareProxy(aliases);
MailAlias alias = new MailAlias();
MailAlias newAlias = new MailAlias();
//convert old alliases created as mailboxes
if (!MailAliasExists(mailAliasName))
{
MailAccount account = GetAccount(mailAliasName);
newAlias.Name = account.Name;
newAlias.ForwardTo = account.ForwardingAddresses[0];
DeleteAccount(mailAliasName);
CreateMailAlias(newAlias);
return newAlias;
}
AliasInfoResult result = aliases.GetAlias(AdminUsername, AdminPassword, GetDomainName(mailAliasName), mailAliasName);
alias.Name = result.AliasInfo.Name;
alias.ForwardTo = result.AliasInfo.Addresses[0];
return alias;
}
public void CreateMailAlias(MailAlias mailAlias)
{
try
{
svcAliasAdmin aliases = new svcAliasAdmin();
PrepareProxy(aliases);
GenericResult result = aliases.AddAlias(AdminUsername, AdminPassword,
GetDomainName(mailAlias.Name), mailAlias.Name,
new string[] { mailAlias.ForwardTo });
if (!result.Result)
throw new Exception(result.Message);
}
catch (Exception ex)
{
if (MailAliasExists(mailAlias.Name))
{
DeleteMailAlias(mailAlias.Name);
}
Log.WriteError(ex);
throw new Exception("Could not create mail alias", ex);
}
}
public void UpdateMailAlias(MailAlias mailAlias)
{
try
{
svcAliasAdmin aliases = new svcAliasAdmin();
PrepareProxy(aliases);
GenericResult result = aliases.UpdateAlias(AdminUsername, AdminPassword, GetDomainName(mailAlias.Name),
mailAlias.Name,
new string[] { mailAlias.ForwardTo });
if (!result.Result)
throw new Exception(result.Message);
}
catch (Exception ex)
{
throw new Exception("Could not update mailAlias", ex);
}
}
public void DeleteMailAlias(string mailAliasName)
{
try
{
svcAliasAdmin aliases = new svcAliasAdmin();
PrepareProxy(aliases);
GenericResult result = aliases.DeleteAlias(AdminUsername, AdminPassword, GetDomainName(mailAliasName),
mailAliasName);
if (!result.Result)
throw new Exception(result.Message);
}
catch (Exception ex)
{
throw new Exception("Could not delete mailAlias", ex);
}
}
#endregion
#region Mailing lists
public bool ListExists(string listName)
{
bool exists = false;
try
{
string domain = GetDomainName(listName);
string account = GetAccountName(listName);
svcMailListAdmin lists = new svcMailListAdmin();
PrepareProxy(lists);
MailingListResult result = lists.GetMailingListsByDomain(AdminUsername, AdminPassword, domain);
if (result.Result)
{
foreach (string member in result.listNames)
{
if (string.Compare(member, listName, true) == 0)
{
exists = true;
break;
}
}
}
}
catch (Exception ex)
{
throw new Exception("Couldn't obtain mail list.", ex);
}
return exists;
}
public virtual MailList[] GetLists(string domainName)
{
try
{
svcMailListAdmin svcLists = new svcMailListAdmin();
PrepareProxy(svcLists);
MailingListResult mResult = svcLists.GetMailingListsByDomain(
AdminUsername,
AdminPassword,
domainName
);
if (!mResult.Result)
throw new Exception(mResult.Message);
List<MailList> mailLists = new List<MailList>();
foreach (string listName in mResult.listNames)
{
SettingsRequestResult sResult = svcLists.GetRequestedListSettings(
AdminUsername,
AdminPassword,
domainName,
listName,
smListSettings
);
if (!sResult.Result)
throw new Exception(sResult.Message);
SubscriberListResult rResult = svcLists.GetSubscriberList(
AdminUsername,
AdminPassword,
domainName,
listName
);
if (!rResult.Result)
throw new Exception(rResult.Message);
MailList list = new MailList();
list.Name = string.Concat(listName, "@", domainName);
SetMailListSettings(list, sResult.settingValues);
SetMailListMembers(list, rResult.Subscribers);
mailLists.Add(list);
}
return mailLists.ToArray();
}
catch (Exception ex)
{
throw new Exception("Couldn't obtain domain mail lists.", ex);
}
}
public virtual MailList GetList(string listName)
{
try
{
string domain = GetDomainName(listName);
string account = GetAccountName(listName);
svcMailListAdmin svcLists = new svcMailListAdmin();
PrepareProxy(svcLists);
SettingsRequestResult sResult = svcLists.GetRequestedListSettings(
AdminUsername,
AdminPassword,
domain,
account,
smListSettings
);
if (!sResult.Result)
throw new Exception(sResult.Message);
SubscriberListResult mResult = svcLists.GetSubscriberList(
AdminUsername,
AdminPassword,
domain,
account
);
if (!mResult.Result)
throw new Exception(mResult.Message);
MailList list = new MailList();
list.Name = listName;
SetMailListSettings(list, sResult.settingValues);
SetMailListMembers(list, mResult.Subscribers);
return list;
}
catch (Exception ex)
{
throw new Exception("Couldn't obtain mail list.", ex);
}
}
public void CreateList(MailList list)
{
try
{
string domain = GetDomainName(list.Name);
string account = GetAccountName(list.Name);
svcMailListAdmin lists = new svcMailListAdmin();
PrepareProxy(lists);
GenericResult result = lists.AddList(AdminUsername, AdminPassword,
domain,
account,
list.ModeratorAddress,
list.Description
);
if (!result.Result)
throw new Exception(result.Message);
List<string> settings = new List<string>();
settings.Add(string.Concat("description=", list.Description));
settings.Add(string.Concat("disabled=", !list.Enabled));
settings.Add(string.Concat("moderator=", list.ModeratorAddress));
settings.Add(string.Concat("password=", list.Password));
settings.Add(string.Concat("requirepassword=", list.RequirePassword));
switch (list.PostingMode)
{
case PostingMode.AnyoneCanPost:
settings.Add("whocanpost=anyone");
break;
case PostingMode.MembersCanPost:
settings.Add("whocanpost=subscribersonly");
break;
case PostingMode.ModeratorCanPost:
settings.Add("whocanpost=moderator");
break;
}
settings.Add(string.Concat("prependsubject=", list.EnableSubjectPrefix));
settings.Add(string.Concat("maxmessagesize=", list.MaxMessageSize));
settings.Add(string.Concat("maxrecipients=", list.MaxRecipientsPerMessage));
settings.Add(string.Concat("subject=", list.SubjectPrefix));
switch (list.ReplyToMode)
{
case ReplyTo.RepliesToList:
settings.Add("replytolist=true");
break;
}
result = lists.SetRequestedListSettings(AdminUsername, AdminPassword,
domain,
account,
settings.ToArray()
);
if (!result.Result)
throw new Exception(result.Message);
if (list.Members.Length > 0)
{
result = lists.SetSubscriberList(AdminUsername, AdminPassword,
domain,
account,
list.Members
);
if (!result.Result)
throw new Exception(result.Message);
}
}
catch (Exception ex)
{
throw new Exception("Couldn't create mail list.", ex);
}
}
public void UpdateList(MailList list)
{
try
{
string domain = GetDomainName(list.Name);
string account = GetAccountName(list.Name);
svcMailListAdmin lists = new svcMailListAdmin();
PrepareProxy(lists);
List<string> settings = new List<string>();
settings.Add(string.Concat("description=", list.Description));
settings.Add(string.Concat("disabled=", !list.Enabled));
settings.Add(string.Concat("moderator=", list.ModeratorAddress));
settings.Add(string.Concat("password=", list.Password));
settings.Add(string.Concat("requirepassword=", list.RequirePassword));
switch (list.PostingMode)
{
case PostingMode.AnyoneCanPost:
settings.Add("whocanpost=anyone");
break;
case PostingMode.MembersCanPost:
settings.Add("whocanpost=subscribersonly");
break;
case PostingMode.ModeratorCanPost:
settings.Add("whocanpost=moderator");
break;
}
settings.Add(string.Concat("prependsubject=", list.EnableSubjectPrefix));
settings.Add(string.Concat("maxmessagesize=", list.MaxMessageSize));
settings.Add(string.Concat("maxrecipients=", list.MaxRecipientsPerMessage));
settings.Add(string.Concat("subject=", list.SubjectPrefix));
switch (list.ReplyToMode)
{
case ReplyTo.RepliesToList:
settings.Add("replytolist=true");
break;
case ReplyTo.RepliesToSender:
settings.Add("replytolist=false");
break;
}
GenericResult result = lists.SetRequestedListSettings(AdminUsername, AdminPassword,
domain,
account,
settings.ToArray()
);
if (!result.Result)
throw new Exception(result.Message);
if (list.Members.Length > 0)
{
result = lists.SetSubscriberList(AdminUsername, AdminPassword,
domain,
account,
list.Members
);
if (!result.Result)
throw new Exception(result.Message);
}
}
catch (Exception ex)
{
throw new Exception("Couldn't update mail list.", ex);
}
}
/// <summary>
/// Deletes specified mail list.
/// </summary>
/// <param name="listName">Mail list name.</param>
public void DeleteList(string listName)
{
try
{
svcMailListAdmin svcLists = new svcMailListAdmin();
PrepareProxy(svcLists);
string account = GetAccountName(listName);
string domain = GetDomainName(listName);
GenericResult Result = svcLists.DeleteList(
AdminUsername,
AdminPassword,
domain,
listName
);
if (!Result.Result)
throw new Exception(Result.Message);
}
catch (Exception ex)
{
throw new Exception("Couldn't delete a mail list.", ex);
}
}
#endregion
#region Domain aliases
public virtual bool DomainAliasExists(string domainName, string aliasName)
{
try
{
string[] aliases = GetDomainAliases(domainName);
foreach (string alias in aliases)
{
if (String.Compare(alias, aliasName, true) == 0)
return true;
}
return false;
}
catch (Exception ex)
{
throw new Exception("Could not check whether mail domain alias exists", ex);
}
}
public virtual void AddDomainAlias(string domainName, string aliasName)
{
try
{
svcDomainAliasAdmin aliases = new svcDomainAliasAdmin();
PrepareProxy(aliases);
GenericResult result = aliases.AddDomainAliasWithoutMxCheck(AdminUsername, AdminPassword,
domainName, aliasName);
if (!result.Result)
throw new Exception(result.Message);
}
catch (Exception ex)
{
throw new Exception("Could not add mail domain alias", ex);
}
}
public void DeleteDomainAlias(string domainName, string aliasName)
{
try
{
svcDomainAliasAdmin aliases = new svcDomainAliasAdmin();
PrepareProxy(aliases);
GenericResult result = aliases.DeleteDomainAlias(AdminUsername, AdminPassword,
domainName, aliasName);
if (!result.Result)
throw new Exception(result.Message);
}
catch (Exception ex)
{
throw new Exception("Could not delete mail domain alias", ex);
}
}
/// <summary>
/// Returns all domain aliases that belong to the specified domain
/// </summary>
/// <param name="domainName">Domain name</param>
/// <returns>Array with domain names</returns>
public string[] GetDomainAliases(string domainName)
{
try
{
svcDomainAliasAdmin aliases = new svcDomainAliasAdmin();
PrepareProxy(aliases);
DomainAliasInfoListResult result = aliases.GetAliases(AdminUsername, AdminPassword, domainName);
if (!result.Result)
throw new Exception(result.Message);
return result.DomainAliasNames;
}
catch (Exception ex)
{
throw new Exception("Could not get the list of mail domain aliases", ex);
}
}
#endregion
#region Domain Groups (Aliases)
public bool GroupExists(string groupName)
{
try
{
svcAliasAdmin svcGroups = new svcAliasAdmin();
PrepareProxy(svcGroups);
AliasInfoResult result = svcGroups.GetAlias(AdminUsername, AdminPassword,
GetDomainName(groupName), groupName);
return (result.Result
&& result.AliasInfo.Name != "Empty");
}
catch (Exception ex)
{
throw new Exception("Could not check whether mail domain group exists", ex);
}
}
public MailGroup[] GetGroups(string domainName)
{
try
{
svcAliasAdmin svcGroups = new svcAliasAdmin();
PrepareProxy(svcGroups);
AliasInfoListResult result = svcGroups.GetAliases(AdminUsername, AdminPassword, domainName);
if (!result.Result)
throw new Exception(result.Message);
MailGroup[] groups = new MailGroup[result.AliasInfos.Length];
for (int i = 0; i < groups.Length; i++)
{
groups[i] = new MailGroup();
groups[i].Name = result.AliasInfos[i].Name + "@" + domainName;
groups[i].Members = result.AliasInfos[i].Addresses;
groups[i].Enabled = true; // by default
}
return groups;
}
catch (Exception ex)
{
throw new Exception("Could not get the list of mail domain groups", ex);
}
}
public MailGroup GetGroup(string groupName)
{
try
{
svcAliasAdmin svcGroups = new svcAliasAdmin();
PrepareProxy(svcGroups);
AliasInfoResult result = svcGroups.GetAlias(AdminUsername, AdminPassword,
GetDomainName(groupName), groupName);
if (!result.Result)
throw new Exception(result.Message);
MailGroup group = new MailGroup();
group.Name = groupName;
group.Members = result.AliasInfo.Addresses;
group.Enabled = true; // by default
return group;
}
catch (Exception ex)
{
throw new Exception("Could not get mail domain group", ex);
}
}
public void CreateGroup(MailGroup group)
{
try
{
svcAliasAdmin svcGroups = new svcAliasAdmin();
PrepareProxy(svcGroups);
GenericResult result = svcGroups.AddAlias(AdminUsername, AdminPassword,
GetDomainName(group.Name), group.Name, group.Members);
if (!result.Result)
throw new Exception(result.Message);
}
catch (Exception ex)
{
throw new Exception("Could not create mail domain group", ex);
}
}
public void UpdateGroup(MailGroup group)
{
try
{
svcAliasAdmin svcGroups = new svcAliasAdmin();
PrepareProxy(svcGroups);
GenericResult result = svcGroups.UpdateAlias(AdminUsername, AdminPassword,
GetDomainName(group.Name), group.Name, group.Members);
if (!result.Result)
throw new Exception(result.Message);
}
catch (Exception ex)
{
throw new Exception("Could not update mail domain group", ex);
}
}
public void DeleteGroup(string groupName)
{
try
{
svcAliasAdmin svcGroups = new svcAliasAdmin();
PrepareProxy(svcGroups);
GenericResult result = svcGroups.DeleteAlias(AdminUsername, AdminPassword,
GetDomainName(groupName), groupName);
if (!result.Result)
throw new Exception(result.Message);
}
catch (Exception ex)
{
throw new Exception("Could not delete mail domain group", ex);
}
}
#endregion
#region IHostingServiceProvier methods
public override void ChangeServiceItemsState(ServiceProviderItem[] items, bool enabled)
{
foreach (ServiceProviderItem item in items)
{
if (item is MailDomain)
{
try
{
// enable/disable mail domain
if (DomainExists(item.Name))
{
MailDomain mailDomain = GetDomain(item.Name);
mailDomain.Enabled = enabled;
UpdateDomain(mailDomain);
}
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error switching '{0}' SmarterMail domain", item.Name), ex);
}
}
}
}
public override void DeleteServiceItems(ServiceProviderItem[] items)
{
foreach (ServiceProviderItem item in items)
{
if (item is MailDomain)
{
try
{
// delete mail domain
DeleteDomain(item.Name);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error deleting '{0}' SmarterMail domain", item.Name), ex);
}
}
}
}
public override ServiceProviderItemDiskSpace[] GetServiceItemsDiskSpace(ServiceProviderItem[] items)
{
List<ServiceProviderItemDiskSpace> itemsDiskspace = new List<ServiceProviderItemDiskSpace>();
// update items with diskspace
foreach (ServiceProviderItem item in items)
{
if (item is MailAccount)
{
try
{
svcUserAdmin users = new svcUserAdmin();
PrepareProxy(users);
StatInfoResult userStats = users.GetUserStats(AdminUsername, AdminPassword, item.Name, DateTime.Now, DateTime.Now);
if (!userStats.Result)
{
throw new Exception(userStats.Message);
}
Log.WriteStart(String.Format("Calculating mail account '{0}' size", item.Name));
// calculate disk space
ServiceProviderItemDiskSpace diskspace = new ServiceProviderItemDiskSpace();
diskspace.ItemId = item.Id;
//diskspace.DiskSpace = 0;
diskspace.DiskSpace = userStats.BytesSize;
itemsDiskspace.Add(diskspace);
Log.WriteEnd(String.Format("Calculating mail account '{0}' size", item.Name));
}
catch (Exception ex)
{
Log.WriteError(ex);
}
}
}
return itemsDiskspace.ToArray();
}
public override ServiceProviderItemBandwidth[] GetServiceItemsBandwidth(ServiceProviderItem[] items, DateTime since)
{
ServiceProviderItemBandwidth[] itemsBandwidth = new ServiceProviderItemBandwidth[items.Length];
// update items with diskspace
for (int i = 0; i < items.Length; i++)
{
ServiceProviderItem item = items[i];
// create new bandwidth object
itemsBandwidth[i] = new ServiceProviderItemBandwidth();
itemsBandwidth[i].ItemId = item.Id;
itemsBandwidth[i].Days = new DailyStatistics[0];
if (item is MailDomain)
{
try
{
// get daily statistics
itemsBandwidth[i].Days = GetDailyStatistics(since, item.Name);
}
catch (Exception ex)
{
Log.WriteError(ex);
System.Diagnostics.Debug.WriteLine(ex);
}
}
}
return itemsBandwidth;
}
public DailyStatistics[] GetDailyStatistics(DateTime since, string maildomainName)
{
ArrayList days = new ArrayList();
// read statistics
DateTime now = DateTime.Now;
DateTime date = since;
try
{
while (date < now)
{
svcDomainAdmin domains = new svcDomainAdmin();
PrepareProxy(domains);
StatInfoResult result =
domains.GetDomainStatistics(AdminUsername, AdminPassword, maildomainName, date, date);
if (!result.Result)
throw new Exception(result.Message);
if (result.BytesReceived != 0 | result.BytesSent != 0)
{
DailyStatistics dailyStats = new DailyStatistics();
dailyStats.Year = date.Year;
dailyStats.Month = date.Month;
dailyStats.Day = date.Day;
dailyStats.BytesSent = result.BytesSent;
dailyStats.BytesReceived = result.BytesReceived;
days.Add(dailyStats);
}
// advance day
date = date.AddDays(1);
}
}
catch (Exception ex)
{
Log.WriteError("Could not get SmarterMail domain statistics", ex);
}
return (DailyStatistics[])days.ToArray(typeof(DailyStatistics));
}
#endregion
#region Helper Methods
/*
private string GetProductLicenseInfo()
{
Licensing.ReloadProductLicense();
License productLicense = Licensing.ProductLicense;
return productLicense.FunctionalityKey;
}
*/
private void PrepareProxy(SoapHttpClientProtocol proxy)
{
string smarterUrl = ServiceUrl;
if (String.IsNullOrEmpty(smarterUrl))
smarterUrl = "http://localhost:9998/services/";
int idx = proxy.Url.LastIndexOf("/");
// strip the last slash if any
if (smarterUrl[smarterUrl.Length - 1] == '/')
smarterUrl = smarterUrl.Substring(0, smarterUrl.Length - 1);
proxy.Url = smarterUrl + proxy.Url.Substring(idx);
}
private void SetMailListSettings(MailList list, string[] smSettings)
{
foreach (string setting in smSettings)
{
string[] bunch = setting.Split(new char[] { '=' });
switch (bunch[0])
{
case "description":
list.Description = bunch[1];
break;
case "disabled":
list.Enabled = !Convert.ToBoolean(bunch[1]);
break;
case "moderator":
list.ModeratorAddress = bunch[1];
list.Moderated = !string.IsNullOrEmpty(bunch[1]);
break;
case "password":
list.Password = bunch[1];
break;
case "requirepassword":
list.RequirePassword = Convert.ToBoolean(bunch[1]);
break;
case "whocanpost":
if (string.Compare(bunch[1], "anyone", true) == 0)
list.PostingMode = PostingMode.AnyoneCanPost;
else if (string.Compare(bunch[1], "moderatoronly", true) == 0)
list.PostingMode = PostingMode.ModeratorCanPost;
else
list.PostingMode = PostingMode.MembersCanPost;
break;
case "prependsubject":
list.EnableSubjectPrefix = Convert.ToBoolean(bunch[1]);
break;
case "maxmessagesize":
list.MaxMessageSize = Convert.ToInt32(bunch[1]);
break;
case "maxrecipients":
list.MaxRecipientsPerMessage = Convert.ToInt32(bunch[1]);
break;
case "replytolist":
list.ReplyToMode = string.Compare(bunch[1], "true", true) == 0 ? ReplyTo.RepliesToList : ReplyTo.RepliesToSender;
break;
case "subject":
list.SubjectPrefix = bunch[1];
break;
}
}
}
protected void SetMailListMembers(MailList list, string[] subscribers)
{
List<string> members = new List<string>();
foreach (string subscriber in subscribers)
members.Add(subscriber);
list.Members = members.ToArray();
}
private void UpdateDomainCatchAllGroup(string domainName, string mailboxName)
{
// check if system catch all group exists
string groupName = SYSTEM_CATCH_ALL + "@" + domainName;
if (GroupExists(groupName))
{
// delete group
DeleteGroup(groupName);
}
if (!String.IsNullOrEmpty(mailboxName))
{
// create catch-all group
MailGroup group = new MailGroup();
group.Name = groupName;
group.Enabled = true;
group.Members = new string[] { mailboxName + "@" + domainName };
// create
CreateGroup(group);
}
}
private static string[] SetMailDomainDefaultSettings(string[] defaultSettings)
{
List<string> settings = new List<string>();
foreach (string pair in defaultSettings)
{
string[] parts = pair.Split('=');
switch (parts[0])
{
case "defaultaltsmtpport":
settings.Add("altsmtpport=" + parts[1]);
break;
case "defaultaltsmtpportenabled":
settings.Add("altsmtpportenabled=" + parts[1]);
break;
case "defaultbypassgreylisting":
settings.Add("bypassgreylisting=" + parts[1]);
break;
case "defaultenablecatchalls":
if (String.Equals(parts[1], "Enabled"))
settings.Add("enablecatchalls=True");
if (String.Equals(parts[1], "Disabled"))
settings.Add("enablecatchalls=False");
break;
case "defaultenabledomainkeys":
settings.Add("enabledomainkeys=" + parts[1]);
break;
case "defaultenableemailreports":
settings.Add("enableemailreports=" + parts[1]);
break;
case "defaultenablepopretrieval":
settings.Add("enablepopretrieval=" + parts[1]);
break;
case "defaultautoresponderrestriction":
settings.Add("autoresponderrestriction=" + parts[1]);
break;
case "defaultmaxmessagesperhour":
settings.Add("maxmessagesperhour=" + parts[1]);
break;
case "defaultmaxmessagesperhourenabled":
settings.Add("maxmessagesperhourenabled=" + parts[1]);
break;
case "defaultmaxsmtpoutbandwidthperhour":
settings.Add("maxsmtpoutbandwidthperhour=" + parts[1]);
break;
case "defaultmaxsmtpoutbandwidthperhourenabled":
settings.Add("maxsmtpoutbandwidthperhourenabled=" + parts[1]);
break;
case "defaultmaxbouncesreceivedperhour":
settings.Add("maxbouncesreceivedperhour=" + parts[1]);
break;
case "defaultmaxbouncesreceivedperhourenabled":
settings.Add("maxbouncesreceivedperhourenabled=" + parts[1]);
break;
case "defaultsharedcalendar":
settings.Add("sharedcalendar=" + parts[1]);
break;
case "defaultsharedcontact":
settings.Add("sharedcontact=" + parts[1]);
break;
case "defaultsharedfolder":
settings.Add("sharedfolder=" + parts[1]);
break;
case "defaultsharedgal":
settings.Add("sharedgal=" + parts[1]);
break;
case "defaultsharednotes":
settings.Add("sharednotes=" + parts[1]);
break;
case "defaultsharedtasks":
settings.Add("sharedtasks=" + parts[1]);
break;
case "defaultshowcalendar":
settings.Add("showcalendar=" + parts[1]);
break;
case "defaultshowcontacts":
settings.Add("showcontacts=" + parts[1]);
break;
case "defaultshowcontentfilteringmenu":
settings.Add("showcontentfilteringmenu=" + parts[1]);
break;
case "defaultshowdomainaliasmenu":
settings.Add("showdomainaliasmenu=" + parts[1]);
break;
case "defaultshowdomainreports":
settings.Add("showdomainreports=" + parts[1]);
break;
case "defaultshowlistmenu":
settings.Add("showlistmenu=" + parts[1]);
break;
case "defaultshownotes":
settings.Add("shownotes=" + parts[1]);
break;
case "defaultshowtasks":
settings.Add("showtasks=" + parts[1]);
break;
case "defaultshowuserreports":
settings.Add("showuserreports=" + parts[1]);
break;
case "defaultshowspammenu":
settings.Add("showspammenu=" + parts[1]);
break;
case "defaultspamresponderoption":
settings.Add("spamresponderoption=" + parts[1]);
break;
case "defaultspamforwardoption":
settings.Add("spamforwardoption=" + parts[1]);
break;
// "defaultskin"
}
}
return settings.ToArray();
}
private static void FillMailDomainFields(MailDomain domain, SettingsRequestResult addResult)
{
foreach (string pair in addResult.settingValues)
{
string[] parts = pair.Split('=');
switch (parts[0])
{
case "catchall":
domain.CatchAllAccount = parts[1];
break;
case "enablecatchalls":
if (String.Equals(parts[1], "Enabled"))
domain[MailDomain.SMARTERMAIL5_CATCHALLS_ENABLED] = "True";
if (String.Equals(parts[1], "Disabled"))
domain[MailDomain.SMARTERMAIL5_CATCHALLS_ENABLED] = "False";
break;
case "enablepopretrieval":
domain[MailDomain.SMARTERMAIL5_POP_RETREIVAL_ENABLED] = parts[1];
break;
case "isenabled":
domain.Enabled = Boolean.Parse(parts[1]);
break;
case "ldapport":
domain.LdapPort = int.Parse(parts[1]);
break;
case "altsmtpport":
domain.SmtpPortAlt = int.Parse(parts[1]);
break;
case "sharedcalendar":
domain.SharedCalendars = Boolean.Parse(parts[1]);
break;
case "sharedcontact":
domain.SharedContacts = Boolean.Parse(parts[1]);
break;
case "sharedfolder":
domain.SharedFolders = Boolean.Parse(parts[1]);
break;
case "sharednotes":
domain.SharedNotes = Boolean.Parse(parts[1]);
break;
case "sharedtasks":
domain.SharedTasks = Boolean.Parse(parts[1]);
break;
case "sharedgal":
domain.IsGlobalAddressList = Boolean.Parse(parts[1]);
break;
case "bypassforwardblacklist":
domain.BypassForwardBlackList = Boolean.Parse(parts[1]);
break;
case "showdomainreports":
domain[MailDomain.SMARTERMAIL5_SHOW_DOMAIN_REPORTS] = parts[1];
break;
case "maxmessagesperhour":
domain[MailDomain.SMARTERMAIL5_MESSAGES_PER_HOUR] = parts[1];
break;
case "maxmessagesperhourenabled":
domain[MailDomain.SMARTERMAIL5_MESSAGES_PER_HOUR_ENABLED] = parts[1];
break;
case "maxsmtpoutbandwidthperhour":
domain[MailDomain.SMARTERMAIL5_BANDWIDTH_PER_HOUR] = parts[1];
break;
case "maxsmtpoutbandwidthperhourenabled":
domain[MailDomain.SMARTERMAIL5_BANDWIDTH_PER_HOUR_ENABLED] = parts[1];
break;
case "maxpopretrievalaccounts":
domain[MailDomain.SMARTERMAIL5_POP_RETREIVAL_ACCOUNTS] = parts[1];
break;
case "maxbouncesreceivedperhour":
domain[MailDomain.SMARTERMAIL5_BOUNCES_PER_HOUR] = parts[1];
break;
case "maxbouncesreceivedperhourenabled":
domain[MailDomain.SMARTERMAIL5_BOUNCES_PER_HOUR_ENABLED] = parts[1];
break;
}
}
}
protected string GetDomainName(string email)
{
return email.Substring(email.IndexOf('@') + 1);
}
protected string GetAccountName(string email)
{
return email.Substring(0, email.IndexOf('@'));
}
#endregion
public override bool IsInstalled()
{
string productName = null;
string productVersion = null;
RegistryKey HKLM = Registry.LocalMachine;
RegistryKey key = HKLM.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall");
String[] names = null;
if (key != null)
{
names = key.GetSubKeyNames();
foreach (string s in names)
{
RegistryKey subkey = HKLM.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" + s);
if (subkey != null)
if (!String.IsNullOrEmpty((string)subkey.GetValue("DisplayName")))
{
productName = (string)subkey.GetValue("DisplayName");
}
if (productName != null && productName.Equals("SmarterMail"))
{
if (subkey != null)
productVersion = (string)subkey.GetValue("DisplayVersion");
break;
}
}
if (!String.IsNullOrEmpty(productVersion))
{
string[] split = productVersion.Split(new char[] { '.' });
return split[0].Equals("5");
}
}
//checking x64 platform
key = HKLM.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall");
if (key == null)
{
return false;
}
names = key.GetSubKeyNames();
foreach (string s in names)
{
RegistryKey subkey = HKLM.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\" + s);
if (subkey != null)
if (!String.IsNullOrEmpty((string)subkey.GetValue("DisplayName")))
{
productName = (string)subkey.GetValue("DisplayName");
}
if (productName != null)
if (productName.Equals("SmarterMail"))
{
if (subkey != null) productVersion = (string)subkey.GetValue("DisplayVersion");
break;
}
}
if (!String.IsNullOrEmpty(productVersion))
{
string[] split = productVersion.Split(new[] { '.' });
return split[0].Equals("5");
}
return false;
}
}
}
| 39.901781 | 159 | 0.474214 | [
"BSD-3-Clause"
] | Key4ce/Websitepanel | WebsitePanel/Sources/WebsitePanel.Providers.Mail.SmarterMail5/SmarterMail5.cs | 82,878 | C# |
// Copyright (c) 2019 .NET Foundation and Contributors. All rights reserved.
// 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 full license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using TestHelper;
using Xunit;
namespace ReactiveUI.Fody.Analyzer.Test
{
/// <summary>
/// Unit Tests to check the proper operation of ReactiveObjectAnalyzer.
/// </summary>
public class ReactiveObjectAnalyzerTest : DiagnosticVerifier
{
/// <summary>
/// Unit Test to ensure that we do not flag an empty file with errors.
/// </summary>
[Fact]
public void CheckEmptyFileReturnsNoFailures()
{
var test = string.Empty;
VerifyCSharpDiagnostic(test);
}
/// <summary>
/// Check that a class which does not implement IReactiveObject throws an error, when it uses
/// the [Reactive] attribute in one of its properties.
/// </summary>
[Fact]
public void ShouldGiveAnErrorWhenClassDoesNotImplement()
{
var test = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
namespace ConsoleApplication1
{
public class TypeName
{
[Reactive] public string Prop { get; set; }
}
}";
var expected = new DiagnosticResult
{
Id = "RUI_0001",
Message = "Type 'TypeName' does not implement IReactiveObject",
Severity = DiagnosticSeverity.Error,
Locations =
new[] { new DiagnosticResultLocation("Test0.cs", 15, 14) }
};
VerifyCSharpDiagnostic(test, expected);
}
/// <summary>
/// Check that a class which does inherits ReactiveObject does not throw
/// an error, when it uses the [Reactive] attribute in one of its properties.
/// </summary>
[Fact]
public void ShouldNotGiveAnErrorWhenClassInherits()
{
var test = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
namespace ConsoleApplication1
{
public class TypeName : ReactiveObject
{
[Reactive] public string Prop { get; set; }
}
}";
VerifyCSharpDiagnostic(test);
}
/// <summary>
/// Check that a class which does implements IReactiveObject does not throw
/// an error, when it uses the [Reactive] attribute in one of its properties.
/// </summary>
[Fact]
public void ShouldNotGiveAnErrorWhenClassImplements()
{
var test = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
namespace ConsoleApplication1
{
public class TypeName : IReactiveObject
{
[Reactive] public string Prop { get; set; }
}
}";
VerifyCSharpDiagnostic(test);
}
/// <summary>
/// Check that a class should not be allowed to have a non-auto-property
/// when used with the [Reactive] attribute.
/// </summary>
[Fact]
public void ShouldGiveErrorForNonAutoProperty()
{
var test = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
namespace ConsoleApplication1
{
public class TypeName : IReactiveObject
{
[Reactive] public string Prop
{
get => _prop;
set => _prop = value;
}
private string _prop;
}
}";
var expected = new DiagnosticResult
{
Id = "RUI_0002",
Message = "Property 'Prop' on 'TypeName' should be an auto property",
Severity = DiagnosticSeverity.Error,
Locations =
new[] { new DiagnosticResultLocation("Test0.cs", 15, 14) }
};
VerifyCSharpDiagnostic(test, expected);
}
/// <summary>
/// Returns the Roslyn Analyzer under test.
/// </summary>
/// <returns>ReactiveObjectAnalyzer.</returns>
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new ReactiveObjectAnalyzer();
}
}
}
| 30.260355 | 101 | 0.588189 | [
"MIT"
] | JesperTreetop/ReactiveUI | src/ReactiveUI.Fody.Analyzer.Test/ReactiveObjectAnalyzerTest.cs | 5,116 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.Drs")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Elastic Disaster Recovery Service. Introducing AWS Elastic Disaster Recovery (AWS DRS), a new service that minimizes downtime and data loss with fast, reliable recovery of on-premises and cloud-based applications using affordable storage, minimal compute, and point-in-time recovery.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.7.0.16")] | 50.625 | 363 | 0.75679 | [
"Apache-2.0"
] | raz2017/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/Drs/Properties/AssemblyInfo.cs | 1,620 | C# |
using Heuristics.TechEval.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Heuristics.TechEval.Web.Models
{
public class ViewAll
{
public List<ViewMember> Members { get; set; }
public List<SelectListItem> Categories { get; set; }
}
} | 22.933333 | 60 | 0.715116 | [
"MIT"
] | JohnMoseley/TechEval. | Web/Models/ViewAll.cs | 346 | C# |
using System;
namespace CoreMe.Core.AOP.Attributes
{
[AttributeUsage(AttributeTargets.Method)]
public class CacheableAttribute : Attribute
{
public CacheableAttribute()
{
}
public CacheableAttribute(string cacheKey)
{
CacheKey = cacheKey;
}
public string CacheKey { get; set; }
}
}
| 17.666667 | 50 | 0.595687 | [
"MIT"
] | Memoyu/CoreMe | src/CoreMe.Core/AOP/Attributes/CacheableAttribute.cs | 373 | C# |
using System.Collections.Generic;
using TaskHistory.Api.Labels;
using TaskHistory.Api.Tasks;
namespace TaskHistory.Api.Terminal
{
public interface ITerminalObjectMapper
{
//TODO instead of doing it this way. use attributes
IEnumerable<ITerminalObject> ConvertTasks(IEnumerable<ITask> task);
IEnumerable<ITerminalObject> ConvertLabels(IEnumerable<ILabel> label);
}
} | 26.928571 | 72 | 0.806366 | [
"MIT"
] | rhsu/TaskHistory | TaskHistory.Api/Terminal/ITerminalObjectMapper.cs | 379 | C# |
namespace GDShrapt.Reader
{
public interface IGDKeywordToken
{
string Sequence { get; }
}
} | 16 | 36 | 0.625 | [
"MIT"
] | elamaunt/GDShrapt | src/GDShrapt.Reader/SimpleTokens/Keywords/IGDKeywordToken.cs | 114 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using System;
namespace PlusUltra.OpenTracing.HttpPropagation.Incoming
{
public class IncomingTraceStartupFilter : IStartupFilter
{
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
return app =>
{
app.UseMiddleware<IncomingTraceMiddleware>();
next(app);
};
}
}
}
| 23.7 | 86 | 0.632911 | [
"MIT"
] | alefcarlos/PlusUltra.OpenTracing.HttpPropagation | src/PlusUltra.OpenTracing.HttpPropagation/Incoming/IncomingTraceStartupFilter.cs | 476 | C# |
namespace XCommon.CodeGenerator.Core.DataBase
{
public class DataBaseRelationShip
{
public string SchemaPK { get; set; }
public string SchemaFK { get; set; }
public string TablePK { get; set; }
public string TableFK { get; set; }
public string ColumnPK { get; set; }
public string ColumnFK { get; set; }
public DataBaseRelationShipType Type { get; set; }
public bool Nullable { get; internal set; }
}
}
| 19.681818 | 52 | 0.688222 | [
"MIT"
] | marviobezerra/XCommon | src/XCommon.CodeGenerator/Core/DataBase/DataBaseRelationShip.cs | 435 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Domain
{
/// <summary>
/// KoubeiCateringPosPrintQueryModel Data Structure.
/// </summary>
public class KoubeiCateringPosPrintQueryModel : AlipayObject
{
/// <summary>
/// 门店id
/// </summary>
[JsonPropertyName("shop_id")]
public string ShopId { get; set; }
}
}
| 23.529412 | 64 | 0.62 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Domain/KoubeiCateringPosPrintQueryModel.cs | 406 | C# |
using System;
using System.IO;
using System.Threading;
using UIKit;
using Foundation;
namespace Microsoft.AspNet.SignalR.Client.iOS.Samples
{
public class TextViewWriter : TextWriter
{
private SynchronizationContext _context;
private UITextView _textView;
public TextViewWriter(SynchronizationContext context, UITextView textView)
{
_context = context;
_textView = textView;
}
public override void WriteLine(string value)
{
_context.Post(delegate
{
_textView.Text = _textView.Text + value + Environment.NewLine;
}, state: null);
}
public override void WriteLine(string format, object arg0)
{
this.WriteLine(string.Format(format, arg0));
}
public override void WriteLine(string format, object arg0, object arg1, object arg2)
{
this.WriteLine(string.Format(format, arg0, arg1, arg2));
}
public override void WriteLine(string format, params object[] args)
{
_context.Post(delegate
{
_textView.Text = _textView.Text + string.Format(format, args) + Environment.NewLine;
_textView.ScrollRangeToVisible(new NSRange(_textView.Text.Length, 0));
}, state: null);
}
#region implemented abstract members of TextWriter
public override System.Text.Encoding Encoding
{
get
{
throw new NotImplementedException();
}
}
#endregion
}
}
| 26.177419 | 100 | 0.592113 | [
"MIT"
] | JoeRock11/SignalR-Chat-Client | SignalR_Client/Components/signalr-2.1.2.2/samples/Microsoft.AspNet.SignalR.Client.iOS.Samples/Microsoft.AspNet.SignalR.Client.iOS.Samples/TextViewWriter.cs | 1,623 | C# |
/*-------------------------------------------------------------------------------------------
* Copyright (c) Fuyuno Mikazuki / Natsuneko. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*------------------------------------------------------------------------------------------*/
#if UNITY_EDITOR
using System.Linq;
using UnityEditor.Animations;
namespace Mochizuki.VRChat.Extensions.Unity
{
public static class AnimatorStateTransitionExtensions
{
public static void CloneTo(this AnimatorStateTransition source, AnimatorStateTransition dest)
{
dest.orderedInterruption = source.orderedInterruption;
dest.canTransitionToSelf = source.canTransitionToSelf;
dest.duration = source.duration;
dest.exitTime = source.exitTime;
dest.hasFixedDuration = source.hasFixedDuration;
dest.interruptionSource = source.interruptionSource;
dest.mute = source.mute;
dest.solo = source.solo;
dest.name = source.name;
dest.hideFlags = source.hideFlags;
foreach (var sourceCondition in source.conditions)
dest.AddCondition(sourceCondition.mode, sourceCondition.threshold, sourceCondition.parameter);
// source.destinationState is ignored because it is resolved by parent
// source.destinationStateMachine is ignored because it is resolved by parent
}
public static bool HasCondition(this AnimatorStateTransition obj, string parameter, AnimatorConditionMode mode, float threshold)
{
var condition = new AnimatorCondition { parameter = parameter, mode = mode, threshold = threshold };
return obj.HasCondition(condition);
}
public static bool HasCondition(this AnimatorStateTransition obj, AnimatorCondition condition)
{
var conditions = obj.conditions;
return conditions.Any(w => condition.Equals(w));
}
}
}
#endif | 42.428571 | 136 | 0.618567 | [
"MIT"
] | mika-f/MochizukiExtensionsLibrary | Assets/Mochizuki/VRChat/Extensions/Unity/AnimatorStateTransitionExtensions.cs | 2,081 | C# |
using T04.WildFarm.Contracts;
namespace T04.WildFarm.Models.Animals
{
public class Hen : Bird
{
private const double Modifier = 0.35;
public Hen(string name, double weight, double wingSize)
: base(name, weight, wingSize) { }
public override void Eat(IFood food)
{
BaseEat(Modifier, food.Quantity);
}
public override string ProduceSound() => "Cluck";
}
}
| 22.15 | 63 | 0.600451 | [
"MIT"
] | akdimitrov/CSharp-OOP | 08.Polymorphism-Exercise/T04.WildFarm/Models/Animals/Hen.cs | 445 | C# |
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
// using TravelWithUsService.DBContext.Repositories;
using TravelWithUsService.Models;
namespace TravelWithUsService.Controllers
{ // base address: api/hotel
[Route("api/[controller]")]
[ApiController]
public class HotelController : ControllerBase
{
private DBContext.Repositories.IHotel repo;
public HotelController(DBContext.Repositories.IHotel repo)
{
this.repo = repo;
}
// GET: api/hotel
[HttpGet]
[ProducesResponseType(200, Type = typeof(IEnumerable<Hotel>))]
public async Task<IEnumerable<Hotel>> GetHoteles()
{
return await this.repo.RetrieveAllAsync();
}
// GET: api/hotel/[id]
[HttpGet("{id:int}")]
[ProducesResponseType(200, Type = typeof(Hotel))]
[ProducesResponseType(404)]
public async Task<IActionResult> Get(int id)
{
Hotel hotel = await this.repo.RetrieveAsync(id);
if (hotel == null)
{
return NotFound(); // 404 resource not found
}
else
{
return Ok(hotel);
}
}
// POST: api/hotel
// BODY: Hotel (JSON)
[HttpPost]
[ProducesResponseType(201, Type = typeof(Hotel))]
[ProducesResponseType(400)]
public async Task<IActionResult> Create([FromBody] Hotel hotel)
{
if (hotel == null)
{
return BadRequest(); // 400 Bad Request
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState); // 400 Bad Request
}
Hotel added = await repo.CreateAsync(hotel);
return CreatedAtRoute( // 201 Created
routeName: nameof(this.Get),
routeValues: new { id = added.HotelID },
value: added
);
}
// PUT: api/hotel/[id]
// BODY: Hotel (JSON)
[HttpPut("{id:int}")]
[ProducesResponseType(204)]
[ProducesResponseType(400)]
[ProducesResponseType(404)]
public async Task<IActionResult> Update([FromBody] Hotel hotel, int id)
{
if (hotel == null || hotel.HotelID != id)
{
return BadRequest(); // 400 Bad Request
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState); // 400 Bad request
}
var existing = await this.repo.RetrieveAsync(id);
if (existing == null)
{
return NotFound(); // 404 Resource not found
}
await this.repo.UpdateAsync(id, hotel);
return new NoContentResult(); // 204 No Content
}
// DELETE: api/hotel/[id]
[HttpDelete("{id:int}")]
[ProducesResponseType(204)]
[ProducesResponseType(400)]
[ProducesResponseType(404)]
public async Task<IActionResult> Delete(int id)
{
Hotel hotel = await this.repo.RetrieveAsync(id);
if (hotel == null)
{
return NotFound(); // 404 Resource No Found
}
bool? deleted = await this.repo.DeleteAsync(id);
if (deleted.HasValue && deleted.Value)
{
return new NoContentResult(); // 204 No Content
}
else
{
return BadRequest( // 400 Bad Request
$"Hotel with id {id} was found but failed to delete."
);
}
}
}
}
| 26.131034 | 79 | 0.516495 | [
"MIT"
] | Equipo12-SBDII/TravelWithUs | TravelWithUsService/Controllers/HotelController.cs | 3,789 | C# |
using Crypto.Core.Settings;
using System.Collections.Specialized;
using System.Net;
using System.Security.Cryptography;
using System.Text;
namespace Crypto.Core;
public class Utilities
{
private string apiPath => ApiSettings.ApiPath;
private string? apiPublicKey { get; set; }
private string? apiPrivateKey { get; set; }
public Utilities()
{
}
public Utilities(string apiPublicKey, string apiPrivateKey)
{
this.apiPublicKey = apiPublicKey;
this.apiPrivateKey = apiPrivateKey;
}
/// <summary>
/// Signs a message
/// </summary>
/// <param name="endpoint"></param>
/// <param name="postData"></param>
/// <param name="apiPrivateKey"></param>
/// <returns></returns>
public string SignMessage(string endpoint, string postData)
{
// Step 1: Concatenate postData + endpoint
var message = postData + endpoint;
// Step 2: Hash the result of step 1 with SHA256
byte[]? hash;
using (SHA256 hash256 = SHA256.Create())
{
hash = hash256.ComputeHash(Encoding.UTF8.GetBytes(message));
}
// Step 3: Base64 decode apiPrivateKey
var secretDecoded = Convert.FromBase64String(apiPrivateKey);
// Step 4: Use result of step 3 to hash the resultof step 2 with HMAC-SHA512
var hmacsha512 = new HMACSHA512(secretDecoded);
var hash2 = hmacsha512.ComputeHash(hash);
// Step 5: Base64 encode the result of step 4 and return
return Convert.ToBase64String(hash2);
}
/// <summary>
/// Send a HTTP request
/// </summary>
/// <param name="requestMethod"></param>
/// <param name="endpoint"></param>
/// <param name="apiPath"></param>
/// <param name="apiPublicKey"></param>
/// <param name="apiPrivateKey"></param>
/// <param name="checkCertificate"></param>
/// <param name="postUrl"></param>
/// <param name="postBody"></param>
/// <returns></returns>
public string MakeRequest(string requestMethod, string endpoint, string postUrl = "", string postBody = "")
{
using (var client = new WebClient())
{
var url = apiPath + endpoint + "?" + postUrl;
// Create authentication headers
if (apiPublicKey != null && apiPrivateKey != null)
{
var postData = postUrl + postBody;
var signature = SignMessage(endpoint, postData);
client.Headers.Add("APIKey", apiPublicKey);
client.Headers.Add("Authent", signature);
}
if (requestMethod == "POST" && postBody.Length > 0)
{
NameValueCollection parameters = new();
string[] bodyArray = postBody.Split('&');
foreach (string pair in bodyArray)
{
string[] splitPair = pair.Split('=');
parameters.Add(splitPair[0], splitPair[1]);
}
var response = client.UploadValues(url, "POST", parameters);
return Encoding.UTF8.GetString(response);
}
else
{
return client.DownloadString(url);
}
}
}
public async Task<string> MakeGETRequest(string url)
{
using (HttpResponseMessage response = await ApiHelper.ApiClient.GetAsync(url))
{
if (response.IsSuccessStatusCode)
return response.Content.ReadAsStringAsync().Result;
else
throw new Exception(response.ReasonPhrase);
}
}
public async Task<string> MakePOSTRequest(string endpoint, string postUrl, string postBody)
{
using (var client = ApiHelper.ApiClient)
{
var url = apiPath + endpoint + "?" + postUrl;
// Create authentication headers
if (!string.IsNullOrWhiteSpace(apiPublicKey) && !string.IsNullOrWhiteSpace(apiPrivateKey))
{
var postData = postUrl + postBody;
var signature = SignMessage(endpoint, postData);
client.DefaultRequestHeaders.Add("APIKey", apiPublicKey);
client.DefaultRequestHeaders.Add("Authent", signature);
}
NameValueCollection parameters = new NameValueCollection();
string[] bodyArray = postBody.Split('&');
foreach (string pair in bodyArray)
{
string[] splitPair = pair.Split('=');
parameters.Add(splitPair[0], splitPair[1]);
}
StringContent content = new("");
var response = await client.PostAsync(url, content);
return await response.Content.ReadAsStringAsync();
}
}
}
| 32.890411 | 111 | 0.575802 | [
"MIT"
] | AdisonCavani/Crypto | src/Crypto.Core/Utilities.cs | 4,804 | C# |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
/*
* AvaTax API Client Library
*
* (c) 2004-2019 Avalara, Inc.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Genevieve Conty
* @author Greg Hester
*/
namespace Avalara.AvaTax.RestClient
{
/// <summary>
/// Represents a request for a free trial account for AvaTax.
/// Free trial accounts are only available on the Sandbox environment.
/// </summary>
public class FreeTrialRequestModel
{
/// <summary>
/// The first or given name of the user requesting a free trial.
/// </summary>
public String firstName { get; set; }
/// <summary>
/// The last or family name of the user requesting a free trial.
/// </summary>
public String lastName { get; set; }
/// <summary>
/// The email address of the user requesting a free trial.
/// </summary>
public String email { get; set; }
/// <summary>
/// The company or organizational name for this free trial. If this account is for personal use, it is acceptable
/// to use your full name here.
/// </summary>
public String company { get; set; }
/// <summary>
/// The phone number of the person requesting the free trial.
/// </summary>
public String phone { get; set; }
/// <summary>
/// Campaign identifier for Notification purpose
/// </summary>
public String campaign { get; set; }
/// <summary>
/// The Address information of the account
/// </summary>
public CompanyAddress companyAddress { get; set; }
/// <summary>
/// Website of the company or user requesting a free trial
/// </summary>
public String website { get; set; }
/// <summary>
/// Read Avalara's terms and conditions is necessary for a free trial account
/// </summary>
public Boolean haveReadAvalaraTermsAndConditions { get; set; }
/// <summary>
/// Accept Avalara's terms and conditions is necessary for a free trial
/// </summary>
public Boolean acceptAvalaraTermsAndConditions { get; set; }
/// <summary>
/// Convert this object to a JSON string of itself
/// </summary>
/// <returns>A JSON string of this object</returns>
public override string ToString()
{
return JsonConvert.SerializeObject(this, new JsonSerializerSettings() { Formatting = Formatting.Indented });
}
}
}
| 31.586207 | 122 | 0.586608 | [
"Apache-2.0"
] | avadev/AvaTax-REST-V2-DotNet-SDK | src/models/FreeTrialRequestModel.cs | 2,748 | C# |
// 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.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Completion.Providers
{
internal static partial class ExtensionMethodImportCompletionHelper
{
private class ExtensionMethodSymbolComputer
{
private readonly int _position;
private readonly Document _originatingDocument;
private readonly SemanticModel _originatingSemanticModel;
private readonly ITypeSymbol _receiverTypeSymbol;
private readonly ImmutableArray<string> _receiverTypeNames;
private readonly ISet<string> _namespaceInScope;
private readonly IImportCompletionCacheService<CacheEntry, object> _cacheService;
// This dictionary is used as cache among all projects and PE references.
// The key is the receiver type as in the extension method declaration (symbol retrived from originating compilation).
// The value indicates if we can reduce an extension method with this receiver type given receiver type.
private readonly ConcurrentDictionary<ITypeSymbol, bool> _checkedReceiverTypes;
private Project OriginatingProject => _originatingDocument.Project;
private Solution Solution => OriginatingProject.Solution;
public ExtensionMethodSymbolComputer(
Document document,
SemanticModel semanticModel,
ITypeSymbol receiverTypeSymbol,
int position,
ISet<string> namespaceInScope
)
{
_originatingDocument = document;
_originatingSemanticModel = semanticModel;
_receiverTypeSymbol = receiverTypeSymbol;
_position = position;
_namespaceInScope = namespaceInScope;
var receiverTypeNames = GetReceiverTypeNames(receiverTypeSymbol);
_receiverTypeNames = AddComplexTypes(receiverTypeNames);
_cacheService = GetCacheService(document.Project.Solution.Workspace);
_checkedReceiverTypes = new ConcurrentDictionary<ITypeSymbol, bool>();
}
public static async Task<ExtensionMethodSymbolComputer> CreateAsync(
Document document,
int position,
ITypeSymbol receiverTypeSymbol,
ISet<string> namespaceInScope,
CancellationToken cancellationToken
)
{
var semanticModel = await document
.GetRequiredSemanticModelAsync(cancellationToken)
.ConfigureAwait(false);
return new ExtensionMethodSymbolComputer(
document,
semanticModel,
receiverTypeSymbol,
position,
namespaceInScope
);
}
/// <summary>
/// Force create all relevant indices
/// </summary>
public Task PopulateIndicesAsync(CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<Task>.GetInstance(out var tasks);
foreach (var project in GetAllRelevantProjects())
{
tasks.Add(
Task.Run(
() =>
GetCacheEntryAsync(
project,
loadOnly: false,
_cacheService,
cancellationToken
),
cancellationToken
)
);
}
foreach (var peReference in GetAllRelevantPeReferences())
{
tasks.Add(
Task.Run(
() =>
SymbolTreeInfo
.GetInfoForMetadataReferenceAsync(
Solution,
peReference,
loadOnly: false,
cancellationToken
)
.AsTask(),
cancellationToken
)
);
}
return Task.WhenAll(tasks.ToImmutable());
}
public async Task<(ImmutableArray<IMethodSymbol> symbols, bool isPartialResult)> GetExtensionMethodSymbolsAsync(
bool forceIndexCreation,
CancellationToken cancellationToken
)
{
// Find applicable symbols in parallel
using var _1 = ArrayBuilder<Task<ImmutableArray<IMethodSymbol>?>>.GetInstance(
out var tasks
);
foreach (var peReference in GetAllRelevantPeReferences())
{
tasks.Add(
Task.Run(
() =>
GetExtensionMethodSymbolsFromPeReferenceAsync(
peReference,
forceIndexCreation,
cancellationToken
)
.AsTask(),
cancellationToken
)
);
}
foreach (var project in GetAllRelevantProjects())
{
tasks.Add(
Task.Run(
() =>
GetExtensionMethodSymbolsFromProjectAsync(
project,
forceIndexCreation,
cancellationToken
),
cancellationToken
)
);
}
using var _2 = ArrayBuilder<IMethodSymbol>.GetInstance(out var symbols);
var isPartialResult = false;
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
foreach (var result in results)
{
// `null` indicates we don't have the index ready for the corresponding project/PE.
// returns what we have even it means we only show partial results.
if (result == null)
{
isPartialResult = true;
continue;
}
symbols.AddRange(result);
}
var browsableSymbols = symbols
.ToImmutable()
.FilterToVisibleAndBrowsableSymbols(
_originatingDocument.ShouldHideAdvancedMembers(),
_originatingSemanticModel.Compilation
);
return (browsableSymbols, isPartialResult);
}
// Returns all referenced projects and originating project itself.
private ImmutableArray<Project> GetAllRelevantProjects()
{
var graph = Solution.GetProjectDependencyGraph();
var relevantProjectIds = graph
.GetProjectsThatThisProjectTransitivelyDependsOn(OriginatingProject.Id)
.Concat(OriginatingProject.Id);
return relevantProjectIds
.Select(id => Solution.GetRequiredProject(id))
.Where(p => p.SupportsCompilation)
.ToImmutableArray();
}
// Returns all PEs referenced by originating project.
private ImmutableArray<PortableExecutableReference> GetAllRelevantPeReferences() =>
OriginatingProject.MetadataReferences
.OfType<PortableExecutableReference>()
.ToImmutableArray();
private async Task<ImmutableArray<IMethodSymbol>?> GetExtensionMethodSymbolsFromProjectAsync(
Project project,
bool forceIndexCreation,
CancellationToken cancellationToken
)
{
// By default, don't trigger index creation except for documents in originating project.
var isOriginatingProject = project == OriginatingProject;
forceIndexCreation = forceIndexCreation || isOriginatingProject;
var cacheEntry = await GetCacheEntryAsync(
project,
loadOnly: !forceIndexCreation,
_cacheService,
cancellationToken
)
.ConfigureAwait(false);
if (!cacheEntry.HasValue)
{
// Returns null to indicate index not ready
return null;
}
if (!cacheEntry.Value.ContainsExtensionMethod)
{
return ImmutableArray<IMethodSymbol>.Empty;
}
var originatingAssembly = _originatingSemanticModel.Compilation.Assembly;
var filter = CreateAggregatedFilter(cacheEntry.Value);
var compilation = await project
.GetRequiredCompilationAsync(cancellationToken)
.ConfigureAwait(false);
var assembly = compilation.Assembly;
var internalsVisible = originatingAssembly.IsSameAssemblyOrHasFriendAccessTo(
assembly
);
var matchingMethodSymbols = GetPotentialMatchingSymbolsFromAssembly(
compilation.Assembly,
filter,
internalsVisible,
cancellationToken
);
return isOriginatingProject
? GetExtensionMethodsForSymbolsFromSameCompilation(
matchingMethodSymbols,
cancellationToken
)
: GetExtensionMethodsForSymbolsFromDifferentCompilation(
matchingMethodSymbols,
cancellationToken
);
}
private async ValueTask<ImmutableArray<IMethodSymbol>?> GetExtensionMethodSymbolsFromPeReferenceAsync(
PortableExecutableReference peReference,
bool forceIndexCreation,
CancellationToken cancellationToken
)
{
var index = await SymbolTreeInfo
.GetInfoForMetadataReferenceAsync(
Solution,
peReference,
loadOnly: !forceIndexCreation,
cancellationToken
)
.ConfigureAwait(false);
if (index == null)
{
// Returns null to indicate index not ready
return null;
}
if (
!(
index.ContainsExtensionMethod
&& _originatingSemanticModel.Compilation.GetAssemblyOrModuleSymbol(
peReference
)
is IAssemblySymbol assembly
)
)
{
return ImmutableArray<IMethodSymbol>.Empty;
}
var filter = CreateAggregatedFilter(index);
var internalsVisible =
_originatingSemanticModel.Compilation.Assembly.IsSameAssemblyOrHasFriendAccessTo(
assembly
);
var matchingMethodSymbols = GetPotentialMatchingSymbolsFromAssembly(
assembly,
filter,
internalsVisible,
cancellationToken
);
return GetExtensionMethodsForSymbolsFromSameCompilation(
matchingMethodSymbols,
cancellationToken
);
}
private ImmutableArray<IMethodSymbol> GetExtensionMethodsForSymbolsFromDifferentCompilation(
MultiDictionary<ITypeSymbol, IMethodSymbol> matchingMethodSymbols,
CancellationToken cancellationToken
)
{
using var _ = ArrayBuilder<IMethodSymbol>.GetInstance(out var builder);
// Matching extension method symbols are grouped based on their receiver type.
foreach (var (declaredReceiverType, methodSymbols) in matchingMethodSymbols)
{
cancellationToken.ThrowIfCancellationRequested();
var declaredReceiverTypeInOriginatingCompilation = SymbolFinder
.FindSimilarSymbols(
declaredReceiverType,
_originatingSemanticModel.Compilation,
cancellationToken
)
.FirstOrDefault();
if (declaredReceiverTypeInOriginatingCompilation == null)
{
// Bug: https://github.com/dotnet/roslyn/issues/45404
// SymbolFinder.FindSimilarSymbols would fail if originating and referenced compilation targeting different frameworks say net472 and netstandard respectively.
// Here's SymbolKey for System.String from those two framework as an example:
//
// {1 (D "String" (N "System" 0 (N "" 0 (U (S "netstandard" 4) 3) 2) 1) 0 0 (% 0) 0)}
// {1 (D "String" (N "System" 0 (N "" 0 (U (S "mscorlib" 4) 3) 2) 1) 0 0 (% 0) 0)}
//
// Also we don't use the "ignoreAssemblyKey" option for SymbolKey resolution because its perfermance doesn't meet our requirement.
continue;
}
if (
_checkedReceiverTypes.TryGetValue(
declaredReceiverTypeInOriginatingCompilation,
out var cachedResult
) && !cachedResult
)
{
// If we already checked an extension method with same receiver type before, and we know it can't be applied
// to the receiverTypeSymbol, then no need to proceed methods from this group..
continue;
}
// This is also affected by the symbol resolving issue mentioned above, which means in case referenced projects
// are targeting different framework, we will miss extension methods with any framework type in their signature from those projects.
var isFirstMethod = true;
foreach (
var methodInOriginatingCompilation in methodSymbols
.Select(
s =>
SymbolFinder
.FindSimilarSymbols(
s,
_originatingSemanticModel.Compilation
)
.FirstOrDefault()
)
.WhereNotNull()
)
{
if (isFirstMethod)
{
isFirstMethod = false;
// We haven't seen this receiver type yet. Try to check by reducing one extension method
// to the given receiver type and save the result.
if (!cachedResult)
{
// If this is the first symbol we retrived from originating compilation,
// try to check if we can apply it to given receiver type, and save result to our cache.
// Since method symbols are grouped by their declared receiver type, they are either all matches to the receiver type
// or all mismatches. So we only need to call ReduceExtensionMethod on one of them.
var reducedMethodSymbol =
methodInOriginatingCompilation.ReduceExtensionMethod(
_receiverTypeSymbol
);
cachedResult = reducedMethodSymbol != null;
_checkedReceiverTypes[
declaredReceiverTypeInOriginatingCompilation
] = cachedResult;
// Now, cachedResult being false means method doesn't match the receiver type,
// stop processing methods from this group.
if (!cachedResult)
{
break;
}
}
}
if (
_originatingSemanticModel.IsAccessible(
_position,
methodInOriginatingCompilation
)
)
{
builder.Add(methodInOriginatingCompilation);
}
}
}
return builder.ToImmutable();
}
private ImmutableArray<IMethodSymbol> GetExtensionMethodsForSymbolsFromSameCompilation(
MultiDictionary<ITypeSymbol, IMethodSymbol> matchingMethodSymbols,
CancellationToken cancellationToken
)
{
using var _ = ArrayBuilder<IMethodSymbol>.GetInstance(out var builder);
// Matching extension method symbols are grouped based on their receiver type.
foreach (var (receiverType, methodSymbols) in matchingMethodSymbols)
{
cancellationToken.ThrowIfCancellationRequested();
// If we already checked an extension method with same receiver type before, and we know it can't be applied
// to the receiverTypeSymbol, then no need to proceed further.
if (
_checkedReceiverTypes.TryGetValue(receiverType, out var cachedResult)
&& !cachedResult
)
{
continue;
}
// We haven't seen this type yet. Try to check by reducing one extension method
// to the given receiver type and save the result.
if (!cachedResult)
{
var reducedMethodSymbol = methodSymbols
.First()
.ReduceExtensionMethod(_receiverTypeSymbol);
cachedResult = reducedMethodSymbol != null;
_checkedReceiverTypes[receiverType] = cachedResult;
}
// Receiver type matches the receiver type of the extension method declaration.
// We can add accessible ones to the item builder.
if (cachedResult)
{
foreach (var methodSymbol in methodSymbols)
{
if (_originatingSemanticModel.IsAccessible(_position, methodSymbol))
{
builder.Add(methodSymbol);
}
}
}
}
return builder.ToImmutable();
}
private MultiDictionary<
ITypeSymbol,
IMethodSymbol
> GetPotentialMatchingSymbolsFromAssembly(
IAssemblySymbol assembly,
MultiDictionary<
string,
(string methodName, string receiverTypeName)
> extensionMethodFilter,
bool internalsVisible,
CancellationToken cancellationToken
)
{
var builder = new MultiDictionary<ITypeSymbol, IMethodSymbol>();
// The filter contains all the extension methods that potentially match the receiver type.
// We use it as a guide to selectively retrive container and member symbols from the assembly.
foreach (var (fullyQualifiedContainerName, methodInfo) in extensionMethodFilter)
{
// First try to filter out types from already imported namespaces
var indexOfLastDot = fullyQualifiedContainerName.LastIndexOf('.');
var qualifiedNamespaceName =
indexOfLastDot > 0
? fullyQualifiedContainerName.Substring(0, indexOfLastDot)
: string.Empty;
if (_namespaceInScope.Contains(qualifiedNamespaceName))
{
continue;
}
// Container of extension method (static class in C# and Module in VB) can't be generic or nested.
var containerSymbol = assembly.GetTypeByMetadataName(
fullyQualifiedContainerName
);
if (
containerSymbol == null
|| !containerSymbol.MightContainExtensionMethods
|| !IsAccessible(containerSymbol, internalsVisible)
)
{
continue;
}
// Now we have the container symbol, first try to get member extension method symbols that matches our syntactic filter,
// then further check if those symbols matches semantically.
foreach (var (methodName, receiverTypeName) in methodInfo)
{
cancellationToken.ThrowIfCancellationRequested();
var methodSymbols = containerSymbol
.GetMembers(methodName)
.OfType<IMethodSymbol>();
foreach (var methodSymbol in methodSymbols)
{
if (
MatchExtensionMethod(
methodSymbol,
receiverTypeName,
internalsVisible,
out var receiverType
)
)
{
// Find a potential match.
builder.Add(receiverType!, methodSymbol);
}
}
}
}
return builder;
static bool MatchExtensionMethod(
IMethodSymbol method,
string filterReceiverTypeName,
bool internalsVisible,
out ITypeSymbol? receiverType
)
{
receiverType = null;
if (
!method.IsExtensionMethod
|| method.Parameters.IsEmpty
|| !IsAccessible(method, internalsVisible)
)
{
return false;
}
// We get a match if the receiver type name match.
// For complex type, we would check if it matches with filter on whether it's an array.
if (
filterReceiverTypeName.Length > 0
&& !string.Equals(
filterReceiverTypeName,
GetReceiverTypeName(method.Parameters[0].Type),
StringComparison.Ordinal
)
)
{
return false;
}
receiverType = method.Parameters[0].Type;
return true;
}
// An quick accessibility check based on declared accessibility only, a semantic based check is still required later.
// Since we are dealing with extension methods and their container (top level static class and modules), only public,
// internal and private modifiers are in play here.
// Also, this check is called for a method symbol only when the container was checked and is accessible.
static bool IsAccessible(ISymbol symbol, bool internalsVisible) =>
symbol.DeclaredAccessibility == Accessibility.Public
|| (symbol.DeclaredAccessibility == Accessibility.Internal && internalsVisible);
}
/// <summary>
/// Create a filter for extension methods from source.
/// The filter is a map from fully qualified type name to info of extension methods it contains.
/// </summary>
private MultiDictionary<
string,
(string methodName, string receiverTypeName)
> CreateAggregatedFilter(CacheEntry syntaxIndex)
{
var results = new MultiDictionary<string, (string, string)>();
foreach (var receiverTypeName in _receiverTypeNames)
{
var methodInfos = syntaxIndex.ReceiverTypeNameToExtensionMethodMap[
receiverTypeName
];
if (methodInfos.Count == 0)
{
continue;
}
foreach (var methodInfo in methodInfos)
{
results.Add(
methodInfo.FullyQualifiedContainerName,
(methodInfo.Name, receiverTypeName)
);
}
}
return results;
}
/// <summary>
/// Create filter for extension methods from metadata
/// The filter is a map from fully qualified type name to info of extension methods it contains.
/// </summary>
private MultiDictionary<
string,
(string methodName, string receiverTypeName)
> CreateAggregatedFilter(SymbolTreeInfo symbolInfo)
{
var results = new MultiDictionary<string, (string, string)>();
foreach (var receiverTypeName in _receiverTypeNames)
{
var methodInfos = symbolInfo.GetExtensionMethodInfoForReceiverType(
receiverTypeName
);
if (methodInfos.Count == 0)
{
continue;
}
foreach (var methodInfo in methodInfos)
{
results.Add(
methodInfo.FullyQualifiedContainerName,
(methodInfo.Name, receiverTypeName)
);
}
}
return results;
}
/// <summary>
/// Get the metadata name of all the base types and interfaces this type derived from.
/// </summary>
private static ImmutableArray<string> GetReceiverTypeNames(
ITypeSymbol receiverTypeSymbol
)
{
using var _ = PooledHashSet<string>.GetInstance(out var allTypeNamesBuilder);
AddNamesForTypeWorker(receiverTypeSymbol, allTypeNamesBuilder);
return allTypeNamesBuilder.ToImmutableArray();
static void AddNamesForTypeWorker(
ITypeSymbol receiverTypeSymbol,
PooledHashSet<string> builder
)
{
if (receiverTypeSymbol is ITypeParameterSymbol typeParameter)
{
foreach (var constraintType in typeParameter.ConstraintTypes)
{
AddNamesForTypeWorker(constraintType, builder);
}
}
else
{
builder.Add(GetReceiverTypeName(receiverTypeSymbol));
builder.AddRange(
receiverTypeSymbol.GetBaseTypes().Select(t => t.MetadataName)
);
builder.AddRange(
receiverTypeSymbol
.GetAllInterfacesIncludingThis()
.Select(t => t.MetadataName)
);
// interface doesn't inherit from object, but is implicitly convertible to object type.
if (receiverTypeSymbol.IsInterfaceType())
{
builder.Add(nameof(Object));
}
}
}
}
/// <summary>
/// Add strings represent complex types (i.e. "" for non-array types and "[]" for array types) to the receiver type,
/// so we would include in the filter info about extension methods with complex receiver type.
/// </summary>
private static ImmutableArray<string> AddComplexTypes(
ImmutableArray<string> receiverTypeNames
)
{
using var _ = ArrayBuilder<string>.GetInstance(
receiverTypeNames.Length + 2,
out var receiverTypeNamesBuilder
);
receiverTypeNamesBuilder.AddRange(receiverTypeNames);
receiverTypeNamesBuilder.Add(FindSymbols.Extensions.ComplexReceiverTypeName);
receiverTypeNamesBuilder.Add(FindSymbols.Extensions.ComplexArrayReceiverTypeName);
return receiverTypeNamesBuilder.ToImmutable();
}
private static string GetReceiverTypeName(ITypeSymbol typeSymbol)
{
switch (typeSymbol)
{
case INamedTypeSymbol namedType:
return namedType.MetadataName;
case IArrayTypeSymbol arrayType:
var elementType = arrayType.ElementType;
while (elementType is IArrayTypeSymbol symbol)
{
elementType = symbol.ElementType;
}
var elementTypeName = GetReceiverTypeName(elementType);
// We do not differentiate array of different kinds sicne they are all represented in the indices as "NonArrayElementTypeName[]"
// e.g. int[], int[][], int[,], etc. are all represented as "int[]", whereas array of complex type such as T[] is "[]".
return elementTypeName + FindSymbols.Extensions.ArrayReceiverTypeNameSuffix;
default:
// Complex types are represented by "";
return FindSymbols.Extensions.ComplexReceiverTypeName;
}
}
}
}
}
| 44.325798 | 183 | 0.484115 | [
"MIT"
] | belav/roslyn | src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/ExtensionMethodImportCompletionHelper.ExtensionMethodSymbolComputer.cs | 33,335 | C# |
using Pomodoro.Common;
using Pomodoro.Services;
using System;
using System.Windows.Input;
namespace Pomodoro.ViewModels
{
public interface ICountdownViewModel
{
void Initialize(TimeSpan time, Uri uri);
void RestartTimer();
void StopTimer();
}
public class CountdownViewModel : ObservableObject, ICountdownViewModel
{
public ICommand UpCountdownCommand { get; private set; }
public ICommand DownCountdownCommand { get; private set; }
private ITimerService timer;
private TimeSpan currentTime;
private TimeSpan countdownTime;
public CountdownViewModel(ITimerService work)
{
timer = work ?? throw new ArgumentNullException("work timer service");
timer.SubscribeOnTimerUpdateEvent(OnTimerUpdate);
timer.SubscribeOnCountdownUpdateEvent(OnCountdownUpdate);
timer.SubscribeOnCountdownFinishEvent(OnCountdownFinish);
UpCountdownCommand = new DelegateCommand(UpCountdown);
DownCountdownCommand = new DelegateCommand(DownCountdown);
}
public void Initialize(TimeSpan time, Uri uri)
{
timer.Initialize(time, uri);
}
public void RestartTimer()
{
timer.Stop();
timer.Restart();
}
public void StopTimer()
{
timer.Stop();
}
#region events
private void OnTimerUpdate(TimeSpan time)
{
CurrentTime = time;
}
private void OnCountdownUpdate(TimeSpan time)
{
CountdownTime = time;
}
private void OnCountdownFinish()
{
}
#endregion events
#region commands
public void UpCountdown()
{
timer.UpCountdown();
}
public void DownCountdown()
{
timer.DownCountdown();
}
#endregion commands
#region properties
public TimeSpan CurrentTime
{
get { return currentTime; }
set
{
currentTime = value;
OnPropertyChanged("CurrentTime");
}
}
public TimeSpan CountdownTime
{
get { return countdownTime; }
set
{
countdownTime = value;
OnPropertyChanged("CountdownTime");
}
}
#endregion properties
}
} | 21.546296 | 79 | 0.603782 | [
"Apache-2.0"
] | sszost/pomodoro | source/Pomodoro/ViewModels/CountdownViewModel.cs | 2,329 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using Microsoft.Kusto.ServiceLayer.Connection;
using Microsoft.Kusto.ServiceLayer.Connection.Contracts;
using Microsoft.Kusto.ServiceLayer.DataSource;
using Microsoft.Kusto.ServiceLayer.LanguageServices;
using Moq;
using NUnit.Framework;
namespace Microsoft.Kusto.ServiceLayer.UnitTests.LanguageServices
{
public class ConnectedBindingQueueTests
{
private static IEnumerable<Tuple<ConnectionDetails, string>> ConnectionDetailsSource()
{
var results = new List<Tuple<ConnectionDetails, string>>();
var details1 = new ConnectionDetails
{
ServerName = "ServerName",
DatabaseName = "DatabaseName",
UserName = "UserName",
AuthenticationType = "AuthenticationType",
DatabaseDisplayName = "DisplayName",
GroupId = "GroupId"
};
results.Add(new Tuple<ConnectionDetails, string>(details1, "ServerName_DatabaseName_UserName_AuthenticationType_DisplayName_GroupId"));
var details2 = new ConnectionDetails
{
ServerName = null,
DatabaseName = null,
UserName = null,
AuthenticationType = null,
DatabaseDisplayName = "",
GroupId = ""
};
results.Add(new Tuple<ConnectionDetails, string>(details2, "NULL_NULL_NULL_NULL"));
var details3 = new ConnectionDetails
{
ServerName = null,
DatabaseName = null,
UserName = null,
AuthenticationType = null,
DatabaseDisplayName = null,
GroupId = null
};
results.Add(new Tuple<ConnectionDetails, string>(details3, "NULL_NULL_NULL_NULL"));
return results;
}
[TestCaseSource(nameof(ConnectionDetailsSource))]
public void GetConnectionContextKey_Returns_Key(Tuple<ConnectionDetails, string> tuple)
{
var contextKey = ConnectedBindingQueue.GetConnectionContextKey(tuple.Item1);
Assert.AreEqual(tuple.Item2, contextKey);
}
[Test]
public void AddConnectionContext_Returns_EmptyString_For_NullConnectionInfo()
{
var dataSourceFactory = new Mock<IDataSourceFactory>();
var connectedBindingQueue = new ConnectedBindingQueue(dataSourceFactory.Object);
var connectionKey = connectedBindingQueue.AddConnectionContext(null, false);
Assert.AreEqual(string.Empty, connectionKey);
}
[Test]
public void AddConnectionContext_Returns_ConnectionKey()
{
var connectionDetails = new ConnectionDetails();
var connectionFactory = new Mock<IDataSourceConnectionFactory>();
var connectionInfo = new ConnectionInfo(connectionFactory.Object, "ownerUri", connectionDetails);
var dataSourceFactory = new Mock<IDataSourceFactory>();
var connectedBindingQueue = new ConnectedBindingQueue(dataSourceFactory.Object);
var connectionKey = connectedBindingQueue.AddConnectionContext(connectionInfo, false, "featureName");
Assert.AreEqual("NULL_NULL_NULL_NULL", connectionKey);
}
[Test]
public void AddConnectionContext_Sets_BindingContext()
{
var connectionDetails = new ConnectionDetails
{
AccountToken = "AzureAccountToken"
};
var connectionFactory = new Mock<IDataSourceConnectionFactory>();
var connectionInfo = new ConnectionInfo(connectionFactory.Object, "ownerUri", connectionDetails);
var dataSourceFactory = new Mock<IDataSourceFactory>();
var dataSourceMock = new Mock<IDataSource>();
dataSourceFactory
.Setup(x => x.Create(It.IsAny<ConnectionDetails>(), It.IsAny<string>()))
.Returns(dataSourceMock.Object);
var connectedBindingQueue =
new ConnectedBindingQueue(dataSourceFactory.Object);
var connectionKey =
connectedBindingQueue.AddConnectionContext(connectionInfo, false, "featureName");
var bindingContext = connectedBindingQueue.GetOrCreateBindingContext(connectionKey);
Assert.AreEqual(dataSourceMock.Object, bindingContext.DataSource);
Assert.AreEqual(500, bindingContext.BindingTimeout);
Assert.AreEqual(true, bindingContext.IsConnected);
}
[Test]
public void RemoveBindingContext_Removes_Context()
{
var connectionDetails = new ConnectionDetails();
var connectionFactory = new Mock<IDataSourceConnectionFactory>();
var connectionInfo = new ConnectionInfo(connectionFactory.Object, "ownerUri", connectionDetails);
var dataSourceFactory = new Mock<IDataSourceFactory>();
var connectedBindingQueue = new ConnectedBindingQueue(dataSourceFactory.Object);
var connectionKey = connectedBindingQueue.AddConnectionContext(connectionInfo, false, "featureName");
connectedBindingQueue.RemoveBindingContext(connectionInfo);
Assert.IsFalse(connectedBindingQueue.BindingContextMap.ContainsKey(connectionKey));
}
}
} | 42.323529 | 147 | 0.633252 | [
"MIT"
] | KevinRansom/sqltoolsservice | test/Microsoft.Kusto.ServiceLayer.UnitTests/LanguageServices/ConnectedBindingQueueTests.cs | 5,756 | C# |
using System;
using Aop.Api.Domain;
using System.Collections.Generic;
using Aop.Api.Response;
namespace Aop.Api.Request
{
/// <summary>
/// AOP API: alipay.data.aiservice.smartprice.merchanteffect.query
/// </summary>
public class AlipayDataAiserviceSmartpriceMerchanteffectQueryRequest : IAopRequest<AlipayDataAiserviceSmartpriceMerchanteffectQueryResponse>
{
/// <summary>
/// isv商家效果展示接口
/// </summary>
public string BizContent { get; set; }
#region IAopRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AopObject bizModel;
private Dictionary<string, string> udfParams; //add user-defined text parameters
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return this.needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return this.notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return this.returnUrl;
}
public void SetTerminalType(String terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return this.terminalType;
}
public void SetTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return this.terminalInfo;
}
public void SetProdCode(String prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return this.prodCode;
}
public string GetApiName()
{
return "alipay.data.aiservice.smartprice.merchanteffect.query";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return this.apiVersion;
}
public void PutOtherTextParam(string key, string value)
{
if(this.udfParams == null)
{
this.udfParams = new Dictionary<string, string>();
}
this.udfParams.Add(key, value);
}
public IDictionary<string, string> GetParameters()
{
AopDictionary parameters = new AopDictionary();
parameters.Add("biz_content", this.BizContent);
if(udfParams != null)
{
parameters.AddAll(this.udfParams);
}
return parameters;
}
public AopObject GetBizModel()
{
return this.bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 26.459677 | 145 | 0.57452 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Request/AlipayDataAiserviceSmartpriceMerchanteffectQueryRequest.cs | 3,297 | C# |
using System.ComponentModel.DataAnnotations;
using Abp.MultiTenancy;
namespace WeixinProject.Authorization.Accounts.Dto
{
public class IsTenantAvailableInput
{
[Required]
[StringLength(AbpTenantBase.MaxTenancyNameLength)]
public string TenancyName { get; set; }
}
}
| 23.384615 | 58 | 0.726974 | [
"MIT"
] | Yuexs/WeixinProject | src/WeixinProject.Application/Authorization/Accounts/Dto/IsTenantAvailableInput.cs | 306 | C# |
//-------------------------------------------------------------------
/*! @file Assert.cs
* @brief This file provides a small set of class and related definitions for classes and methods that are useful in constructing assert style operations with programmatically defined behavior.
*
* Copyright (c) Mosaic Systems Inc.
* Copyright (c) 2008 Mosaic Systems Inc.
* Copyright (c) 2007 Mosaic Systems Inc. (C++ library version)
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Runtime.InteropServices;
namespace MosaicLib.Utils
{
/// <summary>
/// Enum defines the behavior of the Assertion when it is triggered or produced.
/// <para/>LogFallback = 0, Log, DebugBreakpoint, ThrowException,
/// <para/>Assert.DefaultAssertType = AssertType.DebugBreakpoint
/// </summary>
public enum AssertType
{
/// <summary>on assert: log message to fall back log. Behavior common to all AssertTypes.</summary>
LogFallback = 0,
/// <summary>on assert: log message from Assert source and to fall back log</summary>
Log,
/// <summary>on assert: log message to fall back log and take breakpoint if code is being run under a debugger</summary>
DebugBreakpoint,
/// <summary>on assert: log message to fall back log and throw AssertException with message</summary>
ThrowException,
/// <summary>The use of this value has been deprecated and is no longer supported</summary>
[Obsolete("The use of this value has been deprecated and is no longer supported (2016-05-28)")]
FatalExit,
};
/// <summary>Provides a specific exception type that is thrown on Asserts with the AssertType of ThrowExecption</summary>
public class AssertException : System.Exception
{
/// <summary>Constructors accepts a message and a StackFrame, from which the file and line are derived.</summary>
public AssertException(string mesg, System.Diagnostics.StackFrame sourceFrame) : base(mesg) { this.sourceFrame = sourceFrame; }
private System.Diagnostics.StackFrame sourceFrame;
/// <summary>Reports the full StackFrame of the Assert related method invocation that failed and/or generated this exception</summary>
public System.Diagnostics.StackFrame SourceFrame { get { return sourceFrame; } }
/// <summary>Reports the file name of the original Assert related method invocation that failed and/or generated this exception</summary>
public string File { get { return sourceFrame.GetFileName(); } }
/// <summary>Reports the file line of the original Assert related method invocation that failed and/or generated this exception</summary>
public int Line { get { return sourceFrame.GetFileLineNumber(); } }
/// <summary>Returns readable/logable version of this exception</summary>
public override string ToString() { return string.Format("Exception:{0} at file:{1}, line:{2}", Message, File, Line); }
}
/// <summary>
/// This static helper class defines a set of static methods that may be used by client code to perform assertion and assertion failure reaction logic in a well defined manner
/// </summary>
/// <remarks>
/// This static helper class was renamed from Assert to Asserts to remove a class/method name collision with the Assert method name in the NUnit.Framework namespace.
/// </remarks>
public static class Asserts
{
#region Standard public methods [standard variations of the normal methods that clients use from this static helper class]
/// <summary>Logs the given condDesc condition description as an assert error message if the given cond condition is not true.</summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void LogIfConditionIsNotTrue(bool cond, string condDesc) { if (!cond) NoteConditionCheckFailed(condDesc, AssertType.Log, new System.Diagnostics.StackFrame(1, true)); }
/// <summary>Logs the given condDesc as an assert Condition Failed error message.</summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void LogThatConditionCheckFailed(string condDesc) { NoteConditionCheckFailed(condDesc, AssertType.Log, new System.Diagnostics.StackFrame(1, true)); }
/// <summary>Logs the given faultDesc as an Assert Fault error message</summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void LogFaultOccurance(string faultDesc) { NoteFaultOccurance(faultDesc, null, AssertType.Log, new System.Diagnostics.StackFrame(1, true)); }
/// <summary>Logs the given faultDesc as an Assert Fault error message with the given faultDesc fault description and the given ex exception.</summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void LogFaultOccurance(string faultDesc, System.Exception ex) { NoteFaultOccurance(faultDesc, ex, AssertType.Log, new System.Diagnostics.StackFrame(1, true)); }
/// <summary>Takes a debugger breakpoint if the given cond condition is not true. Also logs a Condition Failed message for the given condition description in this case.</summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void TakeBreakpointIfConditionIsNotTrue(bool cond, string condDesc) { if (!cond) NoteConditionCheckFailed(condDesc, AssertType.DebugBreakpoint, new System.Diagnostics.StackFrame(1, true)); }
/// <summary>Takss a debugger breakpoint and logs a Condition Failed message for the given condDesc condition description</summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void TakeBreakpointAfterConditionCheckFailed(string condDesc) { NoteConditionCheckFailed(condDesc, AssertType.DebugBreakpoint, new System.Diagnostics.StackFrame(1, true)); }
/// <summary>Takes a debugger breakpoint and logs an Assert Fault message for the given faultDesc fault description.</summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void TakeBreakpointAfterFault(string faultDesc) { NoteFaultOccurance(faultDesc, null, AssertType.DebugBreakpoint, new System.Diagnostics.StackFrame(1, true)); }
/// <summary>Takes a debugger breakpoint and logs an Assert Fault message for the given faultDesc fault description and ex exception.</summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void TakeBreakpointAfterFault(string faultDesc, System.Exception ex) { NoteFaultOccurance(faultDesc, ex, AssertType.DebugBreakpoint, new System.Diagnostics.StackFrame(1, true)); }
/// <summary>Throws an <see cref="AssertException"/> if the given condition is not true. </summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void ThrowIfConditionIsNotTrue(bool cond, string condDesc) { if (!cond) NoteConditionCheckFailed(condDesc, AssertType.ThrowException, new System.Diagnostics.StackFrame(1, true)); }
/// <summary>Throws an <see cref="AssertException"/>. </summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void ThrowAfterFault(string faultDesc) { NoteFaultOccurance(faultDesc, null, AssertType.ThrowException, new System.Diagnostics.StackFrame(1, true)); }
/// <summary>Throws an <see cref="AssertException"/> with the given ex as the inner exception. </summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void ThrowAfterFault(string faultDesc, System.Exception ex) { NoteFaultOccurance(faultDesc, ex, AssertType.ThrowException, new System.Diagnostics.StackFrame(1, true)); }
/// <summary>Defines the default assert type for the following non-typed assert methods. defaults to AssertType.DebugBreakpoint</summary>
public static AssertType DefaultAssertType = AssertType.DebugBreakpoint;
/// <summary>Asserts that the given cond condition is true. If not then it uses the DefaultAssertType to define what action is taken.</summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void CheckIfConditionIsNotTrue(bool cond, string condDesc) { if (!cond) NoteConditionCheckFailed(condDesc, DefaultAssertType, new System.Diagnostics.StackFrame(1, true)); }
/// <summary>Asserts that the described condition (condDesc) test has failed. Uses the DefaultAssertType to define what action is taken.</summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void NoteConditionCheckFailed(string condDesc) { NoteConditionCheckFailed(condDesc, DefaultAssertType, new System.Diagnostics.StackFrame(1, true)); }
/// <summary>Asserts that a described fault (faultDesc) has occurred. Uses the DefaultAssertType to define what action is taken.</summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void NoteFaultOccurance(string faultDesc) { NoteFaultOccurance(faultDesc, null, DefaultAssertType, new System.Diagnostics.StackFrame(1, true)); }
/// <summary>Asserts that a described fault (faultDesc) and exception has occurred. Uses the DefaultAssertType to define what action is taken.</summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void NoteFaultOccurance(string faultDesc, System.Exception ex) { NoteFaultOccurance(faultDesc, ex, DefaultAssertType, new System.Diagnostics.StackFrame(1, true)); }
/// <summary>Asserts that the given cond condition is true. Action taken when the condition is not true is determined by the given assertType value.</summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void CheckIfConditionIsNotTrue(bool cond, string condDesc, AssertType assertType) { if (!cond) NoteConditionCheckFailed(condDesc, assertType, new System.Diagnostics.StackFrame(1, true)); }
/// <summary>Reports that the given condDesc described condition test failed. Action taken when the condition is not true is determined by the given assertType value.</summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void NoteConditionCheckFailed(string condDesc, AssertType assertType) { NoteConditionCheckFailed(condDesc, assertType, new System.Diagnostics.StackFrame(1, true)); }
/// <summary>Reports that the faultDesc described fault has occurred. Action taken when the condition is not true is determined by the given assertType value.</summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void NoteFaultOccurance(string faultDesc, AssertType assertType) { NoteFaultOccurance(faultDesc, null, assertType, new System.Diagnostics.StackFrame(1, true)); }
/// <summary>Reports that the faultDesc described fault and the ex Exception has occurred. Action taken when the condition is not true is determined by the given assertType value.</summary>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void NoteFaultOccurance(string faultDesc, System.Exception ex, AssertType assertType) { NoteFaultOccurance(faultDesc, ex, assertType, new System.Diagnostics.StackFrame(1, true)); }
#endregion
#region Public adapter/formatter methods
/// <summary>Common implementation method for Noting that a condition test failed.</summary>
public static void NoteConditionCheckFailed(string condDesc, AssertType assertType, System.Diagnostics.StackFrame sourceFrame)
{
AssertCommon(Fcns.CheckedFormat("AssertCondition:[{0}] Failed", condDesc), assertType, sourceFrame);
}
/// <summary>Common implementation method for Noting that Fault has occurred, with or without a related System.Exception ex.</summary>
public static void NoteFaultOccurance(string faultDesc, System.Exception ex, AssertType assertType, System.Diagnostics.StackFrame sourceFrame)
{
if (ex == null)
AssertCommon(Fcns.CheckedFormat("AssertFault:{0}", faultDesc), assertType, sourceFrame);
else
AssertCommon(Fcns.CheckedFormat("AssertFault:{0} with exception:{1}", faultDesc, ex.Message), assertType, sourceFrame);
}
/// <summary>Defines the default Logging.MesgType used for logging asserts into log distribution (either directly or via QueuedLogger. defaults to Logging.MesgType.Error</summary>
public static Logging.MesgType DefaultAssertLoggingMesgType = Logging.MesgType.Error;
/// <summary>Set this property to true if you would like non-log only assertions (such as DebugBreakpoint) to take a debug breakpoint. defaults to false</summary>
public static bool EnableAssertDebugBreakpoints { get; set; }
/// <summary>Set this property to true if you would like Asserts to generate BasicFallbackLogging output. defaults to false</summary>
public static bool EnableBasicFallbackLogging { get; set; }
#endregion
#region Private methods
private static Logging.ILogger assertLogger = null;
private static Logging.ILogger queuedAssertLogger = null;
/// <summary> This is the inner-most implementation method for the Assert helper class. It implements all of the assertType specific behavior for all assertions that get triggered.</summary>
private static void AssertCommon(string mesg, AssertType assertType, System.Diagnostics.StackFrame sourceFrame)
{
// always log all triggered asserts to the BasicFallbackLog
string logStr = Fcns.CheckedFormat("{0} at file:'{1}', line:{2}", mesg, sourceFrame.GetFileName(), sourceFrame.GetFileLineNumber());
if (assertType != AssertType.Log)
{
if (EnableBasicFallbackLogging)
Logging.BasicFallbackLogging.LogError(logStr);
if (queuedAssertLogger == null) // in an MT world we might create a few of these simultaneously. This is not a problem as the distribution engine supports such a construct so locking is not required here in order to get valid behavior.
queuedAssertLogger = new Logging.QueuedLogger("MosaicLib.Utils.Assert");
queuedAssertLogger.Emitter(DefaultAssertLoggingMesgType).Emit(logStr);
}
bool ignoreFault = false; // intended to be used by debug user to ignore such asserts on a case by case basis
if (assertType == AssertType.Log)
{
if (assertLogger == null) // in an MT world we might create a few of these simultaneously. This is not a problem as the distribution engine supports such a construct so locking is not required here in order to get valid behavior.
assertLogger = new Logging.Logger("MosaicLib.Utils.Assert");
assertLogger.Emitter(DefaultAssertLoggingMesgType).Emit(logStr);
return;
}
else if (assertType == AssertType.LogFallback)
{
return; // already done
}
else if (assertType == AssertType.ThrowException)
{
if (!ignoreFault)
throw new AssertException(mesg, sourceFrame);
return;
}
if (!ignoreFault)
{
// the remaining types always trigger a breakpoint if a debugger is attached and the hosting environment has set the EnabledAssertDebugBreakpoints flag
if (System.Diagnostics.Debugger.IsAttached && EnableAssertDebugBreakpoints)
System.Diagnostics.Debugger.Break();
}
}
#endregion
}
}
//-------------------------------------------------------------------
| 69.15415 | 259 | 0.728338 | [
"ECL-2.0",
"Apache-2.0"
] | mosaicsys/MosaicLibCS | Base/Utils/Assert.cs | 17,496 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace evaluare
{
class Camera
{
String nume;
public String Nume { get { return nume; } }
public Camera(String nume)
{
this.nume = nume;
}
}
}
| 18.210526 | 52 | 0.566474 | [
"MIT"
] | BUG95/tap2020-e01 | bug95/src/evaluare/evaluare/Camera.cs | 348 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Clarity.Common.CodingUtilities;
using Clarity.Common.Numericals;
using Clarity.Common.Numericals.Algebra;
using Clarity.Common.Numericals.Geometry;
namespace Clarity.Ext.Simulation.Fluids
{
public class LevelSet
{
private const int ParticleMaskRadius = 4;
public IntSize3 Size { get; }
public float CellSize { get; }
private double[] phi;
private double[] backPhi;
private float[] mass;
private float[] backMass;
private NavierStokesCellState[] states;
private float[] particleMass;
private bool[] particleMask;
private readonly object backWriteLock = new object();
public double[] AllPhi => phi;
public float[] AllMasses => mass;
public bool[] AllParticleMasks => particleMask;
public ref double Phi(int i, int j) => ref phi[j * Size.Width + i];
public ref double BackPhi(int i, int j) => ref backPhi[j * Size.Width + i];
public ref float Mass(int i, int j) => ref mass[j * Size.Width + i];
public ref float BackMass(int i, int j) => ref backMass[j * Size.Width + i];
public ref NavierStokesCellState State(int i, int j) => ref states[j * Size.Width + i];
public ref float ParticleMass(int i, int j) => ref particleMass[j * Size.Width + i];
public ref bool ParticleMask(int i, int j) => ref particleMask[j * Size.Width + i];
public LevelSet(IntSize3 size, float cellSize, INavierStokesGrid grid)
{
Size = size;
CellSize = cellSize;
phi = new double[size.Volume()];
backPhi = new double[size.Volume()];
mass = new float[size.Volume()];
backMass = new float[size.Volume()];
states = new NavierStokesCellState[size.Volume()];
particleMass = new float[size.Volume()];
particleMask = new bool[size.Volume()];
for (int j = 0; j < Size.Height - 1; j++)
for (int i = 0; i < Size.Width - 1; i++)
{
var point = new Vector3(i, j, 0) * CellSize;
State(i, j) = grid.StateAtPoint(point);
}
}
public void TransferPhi(float deltaT, INavierStokesGrid grid)
{
/*
Parallel.For(0, Size.Volume(), index =>
{
var j = index / Size.Width;
var i = index - j * Size.Width;
if (i < 1 || i >= Size.Width - 1 || j < 1 || j >= Size.Height - 1)
return;
var dpdx = (Phi(i + 1, j) - Phi(i - 1, j)) / (2 * CellSize);
var dpdy = (Phi(i, j + 1) - Phi(i, j - 1)) / (2 * CellSize);
var point = CellSize * (new Vector3(i, j, 0) + new Vector3(0.5f, 0.5f, 0.5f));
var u = grid.GetVelocityAt(point) * deltaT;
var deltaPhi = -u.X * dpdx - u.Y * dpdy;
BackPhi(i, j) = Phi(i, j) + deltaPhi;
});*/
/*
for (int j = 1; j < Size.Height - 1; j++)
for (int i = 1; i < Size.Width - 1; i++)
{
var dpdx = (Phi(i + 1, j) - Phi(i - 1, j)) / (2 * CellSize);
var dpdy = (Phi(i, j + 1) - Phi(i, j - 1)) / (2 * CellSize);
var point = CellSize * (new Vector3(i, j, 0) + new Vector3(0.5f, 0.5f, 0.5f));
var u = grid.GetVelocityAt(point) * deltaT;
var deltaPhi = -u.X * dpdx - u.Y * dpdy;
BackPhi(i, j) = Phi(i, j) + deltaPhi;
}*/
Array.Clear(backPhi, 0, backPhi.Length);
var halfVector = new Vector3(0.5f, 0.5f, 0.5f);
var cornerOffset = CellSize * halfVector;
Parallel.For(0, Size.Volume(), index =>
{
var j = index / Size.Width;
var i = index - j * Size.Width;
if (i < 1 || i >= Size.Width - 1 || j < 1 || j >= Size.Height - 1)
return;
var remainingDeltaT = deltaT;
var point = CellSize * (new Vector3(i, j, 0) + halfVector);
while (remainingDeltaT > 0)
{
var v = grid.GetVelocityAt(point);
var vlen = v.Length();
var localDeltaT = vlen * remainingDeltaT > CellSize ? CellSize / vlen : remainingDeltaT;
var potentialPoint = point + v * localDeltaT;
var potentialCorner = potentialPoint - cornerOffset;
var normPotentialCorner = potentialCorner / CellSize;
var npci = (int)normPotentialCorner.X;
var npcj = (int)normPotentialCorner.Y;
if (State(npci, npcj) == NavierStokesCellState.Object)
break;
point = potentialPoint;
remainingDeltaT -= localDeltaT;
}
var corner = point - cornerOffset;
//var centerPoint = new Vector3(Size.Width, Size.Height, 0) * CellSize / 2;
//while (grid.StateAtPoint(corner) == NavierStokesCellState.Object)
//{
// corner = Vector3.Lerp(corner, centerPoint, 0.05f);
//}
var ti = (int)(corner.X / CellSize);
var tj = (int)(corner.Y / CellSize);
var intCorner = new Vector3(ti, tj, 0) * CellSize;
var rightVolume = (corner.X - intCorner.X) / CellSize;
var upVolume = (corner.Y - intCorner.Y) / CellSize;
var leftVolume = 1 - rightVolume;
var downVolume = 1 - upVolume;
var originalMass = Phi(i, j);
var a00 = originalMass * leftVolume * downVolume;
var a01 = originalMass * leftVolume * upVolume;
var a10 = originalMass * rightVolume * downVolume;
var a11 = originalMass * rightVolume * upVolume;
lock (backWriteLock)
{
BackPhi(ti, tj) += a00;
BackPhi(ti + 1, tj) += a10;
BackPhi(ti, tj + 1) += a01;
BackPhi(ti + 1, tj + 1) += a11;
}
});
CodingHelper.Swap(ref phi, ref backPhi);
}
public void InitPhi()
{
for (int j = 0; j < Size.Height; j++)
for (int i = 0; i < Size.Width; i++)
{
var currMass = Mass(i, j) + ParticleMass(i, j);
Phi(i, j) = currMass > 0f ? -float.MaxValue : float.MaxValue;
}
var positiveBorderPoints = new List<Vector2>();
var negativeBorderPoints = new List<Vector2>();
for (int j = 1; j < Size.Height - 1; j++)
for (int i = 1; i < Size.Width - 1; i++)
{
var curr = Phi(i, j);
var left = Phi(i - 1, j);
var right = Phi(i + 1, j);
var down = Phi(i, j - 1);
var up = Phi(i, j + 1);
if (curr > 0 && (left < 0 || right < 0 || down < 0 || up < 0))
positiveBorderPoints.Add(PointForCoords(i, j).Xy);
else if (curr < 0 && (left > 0 || right > 0 || down > 0 || up > 0))
negativeBorderPoints.Add(PointForCoords(i, j).Xy);
}
Parallel.For(0, Size.Width * Size.Height, index =>
{
var j = index / Size.Width;
var i = (index - j * Size.Width);
var currPoint = PointForCoords(i, j).Xy;
var distSq = float.MaxValue;
if (Phi(i, j) > 0)
{
foreach (var point in negativeBorderPoints)
{
var newLength = (currPoint - point).LengthSquared();
if (newLength < distSq)
distSq = newLength;
}
Phi(i, j) = Math.Sqrt(distSq);
}
else
{
foreach (var point in positiveBorderPoints)
{
var newLength = (currPoint - point).LengthSquared();
if (newLength < distSq)
distSq = newLength;
}
Phi(i, j) = -Math.Sqrt(distSq);
}
});
/*
for (int j = 1; j < Size.Height - 1; j++)
for (int i = 1; i < Size.Width - 1; i++)
{
ref var curr = ref Phi(i, j);
var prevI = Phi(i - 1, j);
var nextI = Phi(i + 1, j);
var prevJ = Phi(i, j - 1);
var nextJ = Phi(i, j + 1);
if (curr == largestDist)
{
if (prevI < 0 || nextI < 0 || prevJ < 0 || nextJ < 0)
curr = 1;
}
else if (curr == -largestDist)
{
if (prevI > 0 || nextI > 0 || prevJ > 0 || nextJ > 0)
curr = -1;
}
}
for (int j = 1; j < Size.Height - 1; j++)
for (int i = 1; i < Size.Width - 1; i++)
{
ref var curr = ref Phi(i, j);
var prevI = Phi(i - 1, j);
var nextI = Phi(i + 1, j);
var prevJ = Phi(i, j - 1);
var nextJ = Phi(i, j + 1);
if (curr == largestDist)
{
if (prevI == 1 || nextI == 1 || prevJ == 1 || nextJ == 1)
curr = 2;
}
else if (curr == -largestDist)
{
if (prevI == -1 || nextI == -1 || prevJ == -1 || nextJ == -1)
curr = -2;
}
}*/
}
public float Curvature(int i, int j)
{
var point = CellSize * (new Vector3(i, j, 0) + new Vector3(0.5f, 0.5f, 0.5f));
return Curvature(point);
}
public float Curvature(Vector3 point)
{
var gradLeft = GradPhiAt(new Vector3(point.X - CellSize, point.Y, point.Z)).Normalize();
var gradRight = GradPhiAt(new Vector3(point.X + CellSize, point.Y, point.Z)).Normalize();
var gradBottom = GradPhiAt(new Vector3(point.X, point.Y - CellSize, point.Z)).Normalize();
var gradTop = GradPhiAt(new Vector3(point.X, point.Y + CellSize, point.Z)).Normalize();
var div = gradRight.X - gradLeft.X + gradTop.Y - gradBottom.Y;
return div;
}
public Vector2 GradPhiAt(Vector3 point)
{
var phiLeft = PhiAt(new Vector3(point.X - CellSize, point.Y, point.Z));
var phiRight = PhiAt(new Vector3(point.X + CellSize, point.Y, point.Z));
var phiBottom = PhiAt(new Vector3(point.X, point.Y - CellSize, point.Z));
var phiTop = PhiAt(new Vector3(point.X, point.Y + CellSize, point.Z));
var dpdx = (phiRight - phiLeft) / (2 * CellSize);
var dpdy = (phiTop - phiBottom) / (2 * CellSize);
return new Vector2((float)dpdx, (float)dpdy);
}
public double PhiAt(Vector3 point)
{
var normPoint = point / CellSize - new Vector3(0.5f, 0.5f, 0.5f);
int i = (int)normPoint.X;
int j = (int)normPoint.Y;
var phi1 = Phi(i, j);
var phi2 = Phi(i + 1, j);
var phi3 = Phi(i, j + 1);
var phi4 = Phi(i + 1, j + 1);
var amountI = normPoint.X - i;
var amountJ = normPoint.Y - j;
var phi12 = MathHelper.Lerp(phi1, phi2, amountI);
var phi34 = MathHelper.Lerp(phi3, phi4, amountI);
return MathHelper.Lerp(phi12, phi34, amountJ);
}
public void ClearParticleMask()
{
Array.Clear(particleMask, 0, particleMask.Length);
}
public bool AddParticleIfHavePlace(Vector3 point)
{
CoordsForPoint(point, out var i, out var j);
return AddParticleIfHavePlace(i, j);
}
public bool AddParticleIfHavePlace(int i, int j)
{
if (ParticleMask(i, j))
return false;
for (int mi = -ParticleMaskRadius + 1; mi < ParticleMaskRadius; mi++)
for (int mj = -ParticleMaskRadius + 1; mj < ParticleMaskRadius; mj++)
ParticleMask(i + mi, j + mj) = true;
return true;
}
public Vector3 PointForCoords(int i, int j)
{
return CellSize * (new Vector3(i, j, 0) + new Vector3(0.5f, 0.5f, 0.5f));
}
public void CoordsForPoint(Vector3 point, out int i, out int j)
{
var normPoint = point / CellSize - new Vector3(0.5f, 0.5f, 0.5f);
i = (int)normPoint.X;
j = (int)normPoint.Y;
}
}
} | 39.528358 | 108 | 0.46496 | [
"MIT"
] | Zulkir/ClarityWorlds | Source/Clarity.Ext.Simulation.Fluids/LevelSet.cs | 13,244 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using Ultraviolet.Content;
using Ultraviolet.Core;
using Ultraviolet.OpenGL.Bindings;
namespace Ultraviolet.OpenGL.Graphics
{
/// <summary>
/// Represents shader source code after processing has been performed.
/// </summary>
public sealed class ShaderSource
{
/// <summary>
/// Initializes a new instance of the <see cref="ShaderSource"/> class.
/// </summary>
/// <param name="source">The source code for this shader.</param>
/// <param name="metadata">The metadata for this shader.</param>
private ShaderSource(String source, ShaderSourceMetadata metadata)
{
this.Source = source;
this.Metadata = metadata;
}
/// <summary>
/// Processes raw shader source into a new <see cref="ShaderSource"/> object.
/// </summary>
/// <param name="manager">The <see cref="ContentManager"/> that is loading the shader source.</param>
/// <param name="metadata">The content processor metadata for the shader source that is being loaded.</param>
/// <param name="source">The raw shader source to process.</param>
/// <returns>A <see cref="ShaderSource"/> object that represents the processed shader source.</returns>
public static ShaderSource ProcessRawSource(ContentManager manager, IContentProcessorMetadata metadata, String source)
{
var ssmd = new ShaderSourceMetadata();
return ProcessInternal(ssmd, source, (line, output) =>
{
if (ProcessIncludeDirective(manager, metadata, line, output, ssmd))
return true;
if (ProcessIncludeResourceDirective(manager, metadata, line, output, ssmd))
return true;
if (ProcessIfVerDirective(manager, metadata, line, output, ssmd))
return true;
if (ProcessSamplerDirective(manager, metadata, line, output, ssmd))
return true;
if (ProcessParamDirective(manager, metadata, line, output, ssmd))
return true;
if (ProcessCameraDirective(manager, metadata, line, output, ssmd))
return true;
return false;
});
}
/// <summary>
/// Processes a <see cref="ShaderSource"/> instance to produce a new <see cref="ShaderSource"/> instance
/// with expanded #extern definitions. Externs which do not exist in <paramref name="externs"/> are removed from
/// the shader source entirely, and if <paramref name="externs"/> is <see langword="null"/>, all externs are removed.
/// </summary>
/// <param name="source">The source instance to process.</param>
/// <param name="externs">The collection of defined extern values, or <see langword="null"/>.</param>
/// <returns>A new <see cref="ShaderSource"/> instance with expanded #extern definitions.</returns>
public static ShaderSource ProcessExterns(ShaderSource source, Dictionary<String, String> externs)
{
Contract.Require(source, nameof(source));
return ProcessInternal(source.Metadata, source.Source, (line, output) =>
{
if (ProcessExternDirective(line, output, source.Metadata, externs))
return true;
return false;
});
}
/// <summary>
/// Implicitly converts a <see cref="String"/> object to a new <see cref="ShaderSource"/> instance.
/// </summary>
/// <param name="source">The underlying source string of the <see cref="ShaderSource"/> object to create.</param>
public static implicit operator ShaderSource(String source) => new ShaderSource(source, new ShaderSourceMetadata());
/// <summary>
/// Gets the processed shader source.
/// </summary>
public String Source { get; }
/// <summary>
/// Gets the metadata for this shader.
/// </summary>
public ShaderSourceMetadata Metadata { get; }
/// <summary>
/// Performs line-by-line processing of raw shader source code.
/// </summary>
private static ShaderSource ProcessInternal(ShaderSourceMetadata ssmd, String source, Func<String, StringBuilder, Boolean> processor)
{
var output = new StringBuilder();
var line = default(String);
using (var reader = new StringReader(source))
{
var insideComment = false;
while ((line = reader.ReadLine()) != null)
{
TrackComments(line, ref insideComment);
if (!insideComment)
{
if (processor(line, output))
continue;
}
output.AppendLine(line);
}
}
return new ShaderSource(output.ToString(), ssmd);
}
/// <summary>
/// Parses a line of GLSL for comments and keeps track of whether we're
/// currently inside of one that spans multiple lines.
/// </summary>
private static void TrackComments(String line, ref Boolean insideComment)
{
var ixCurrent = 0;
// If we're inside of a C-style comment, look for a */ somewhere on this line...
if (insideComment)
{
var ixCStyleEndToken = line.IndexOf("*/");
if (ixCStyleEndToken >= 0)
{
ixCurrent = ixCStyleEndToken + "*/".Length;
insideComment = false;
}
}
if (insideComment)
return;
// Remove any complete C-style comments from the line
var cStyleComments = regexCStyleComment.Matches(line, ixCurrent);
if (cStyleComments.Count > 0)
{
var lastMatch = cStyleComments[cStyleComments.Count - 1];
ixCurrent = lastMatch.Index + lastMatch.Length;
}
// Look for comments that finish out the line
var ixCppCommentToken = line.IndexOf("//", ixCurrent);
var ixCStyleStartToken = line.IndexOf("/*", ixCurrent);
if (ixCStyleStartToken >= 0 && (ixCppCommentToken < 0 || ixCStyleStartToken < ixCppCommentToken))
{
line = line.Substring(0, ixCStyleStartToken);
insideComment = true;
}
}
/// <summary>
/// Processes #extern directives.
/// </summary>
private static Boolean ProcessExternDirective(String line, StringBuilder output, ShaderSourceMetadata ssmd, Dictionary<String, String> externs)
{
var externMatch = regexExternDirective.Match(line);
if (externMatch.Success)
{
var externName = externMatch.Groups["name"].Value;
if (String.IsNullOrWhiteSpace(externName))
throw new InvalidOperationException(OpenGLStrings.ShaderExternHasInvalidName);
var externValue = String.Empty;
if (externs?.TryGetValue(externName, out externValue) ?? false)
{
output.AppendLine($"#define {externName} {externValue}");
}
return true;
}
return false;
}
/// <summary>
/// Processes #include directives.
/// </summary>
private static Boolean ProcessIncludeDirective(ContentManager manager, IContentProcessorMetadata metadata, String line, StringBuilder output, ShaderSourceMetadata ssmd)
{
var includeMatch = regexIncludeDirective.Match(line);
if (includeMatch.Success)
{
if (manager == null || metadata == null)
throw new InvalidOperationException(OpenGLStrings.CannotIncludeShaderHeadersInStream);
var includePath = includeMatch.Groups["file"].Value;
includePath = ContentManager.NormalizeAssetPath(Path.Combine(Path.GetDirectoryName(metadata.AssetPath), includePath));
metadata.AddAssetDependency(includePath);
var includeSrc = manager.Load<ShaderSource>(includePath, metadata.AssetDensity, false, metadata.IsLoadedFromSolution);
ssmd.Concat(includeSrc.Metadata);
output.AppendLine(includeSrc.Source);
return true;
}
return false;
}
/// <summary>
/// Processes #includeres directives.
/// </summary>
private static Boolean ProcessIncludeResourceDirective(ContentManager manager, IContentProcessorMetadata metadata, String line, StringBuilder output, ShaderSourceMetadata ssmd)
{
var includeResourceMatch = regexincludeResourceDirective.Match(line);
if (includeResourceMatch.Success)
{
var includeResource = includeResourceMatch.Groups["resource"].Value;
var includeAsm = includeResourceMatch.Groups["asm"]?.Value ?? "entry";
var asm =
String.Equals("entry", includeAsm, StringComparison.OrdinalIgnoreCase) ? Assembly.GetEntryAssembly() :
String.Equals("executing", includeAsm, StringComparison.OrdinalIgnoreCase) ? Assembly.GetExecutingAssembly() : null;
var info = asm.GetManifestResourceInfo(includeResource);
if (info == null)
throw new InvalidOperationException(OpenGLStrings.InvalidIncludedResource.Format(includeResource));
using (var resStream = asm.GetManifestResourceStream(includeResource))
using (var resReader = new StreamReader(resStream))
{
var includeSrc = ProcessRawSource(manager, metadata, resReader.ReadToEnd());
ssmd.Concat(includeSrc.Metadata);
output.Append(includeSrc.Source);
if (!includeSrc.Source.EndsWith("\n"))
output.AppendLine();
}
return true;
}
return false;
}
/// <summary>
/// Processes #ifver directives.
/// </summary>
private static Boolean ProcessIfVerDirective(ContentManager manager, IContentProcessorMetadata metadata, String line, StringBuilder output, ShaderSourceMetadata ssmd)
{
var ifVerMatch = regexIfVerDirective.Match(line);
if (ifVerMatch.Success)
{
var source = ifVerMatch.Groups["source"].Value;
var dirVersionIsGLES = !String.IsNullOrEmpty(ifVerMatch.Groups["gles"].Value);
var dirVersionMajor = Int32.Parse(ifVerMatch.Groups["version_maj"].Value);
var dirVersionMinor = Int32.Parse(ifVerMatch.Groups["version_min"].Value);
var dirVersion = new Version(dirVersionMajor, dirVersionMinor);
var dirSatisfied = false;
var uvVersionIsGLES = gl.IsGLES;
var uvVersionMajor = gl.MajorVersion;
var uvVersionMinor = gl.MinorVersion;
var uvVersion = new Version(uvVersionMajor, uvVersionMinor);
if (dirVersionIsGLES != uvVersionIsGLES)
return true;
switch (ifVerMatch.Groups["op"].Value)
{
case "ifver":
dirSatisfied = (uvVersion == dirVersion);
break;
case "ifver_lt":
dirSatisfied = (uvVersion < dirVersion);
break;
case "ifver_lte":
dirSatisfied = (uvVersion <= dirVersion);
break;
case "ifver_gt":
dirSatisfied = (uvVersion > dirVersion);
break;
case "ifver_gte":
dirSatisfied = (uvVersion >= dirVersion);
break;
}
if (dirSatisfied)
{
var includedSource = ProcessRawSource(manager, metadata, source);
ssmd.Concat(includedSource.Metadata);
output.Append(includedSource.Source);
if (!includedSource.Source.EndsWith("\n"))
output.AppendLine();
}
return true;
}
return false;
}
/// <summary>
/// Processes #sampler directives.
/// </summary>
private static Boolean ProcessSamplerDirective(ContentManager manager, IContentProcessorMetadata metadata, String line, StringBuilder output, ShaderSourceMetadata ssmd)
{
var samplerMatch = regexSamplerDirective.Match(line);
if (samplerMatch.Success)
{
var sampler = Int32.Parse(samplerMatch.Groups["sampler"].Value);
var uniform = samplerMatch.Groups["uniform"].Value;
ssmd.AddPreferredSamplerIndex(uniform, sampler);
return true;
}
return false;
}
/// <summary>
/// Processes #param directives.
/// </summary>
private static Boolean ProcessParamDirective(ContentManager manager, IContentProcessorMetadata metadata, String line, StringBuilder output, ShaderSourceMetadata ssmd)
{
var paramMatch = regexParamDirective.Match(line);
if (paramMatch.Success)
{
var parameter = paramMatch.Groups["parameter"].Value;
ssmd.AddParameterHint(parameter);
return true;
}
return false;
}
/// <summary>
/// Processes #camera directives.
/// </summary>
private static Boolean ProcessCameraDirective(ContentManager manager, IContentProcessorMetadata metadata, String line, StringBuilder output, ShaderSourceMetadata ssmd)
{
var cameraMatch = regexCameraDirective.Match(line);
if (cameraMatch.Success)
{
var parameter = cameraMatch.Groups["parameter"].Value;
var uniform = cameraMatch.Groups["uniform"].Value;
ssmd.AddCameraHint(parameter, uniform);
return true;
}
return false;
}
// Regular expressions used to identify directives
private static readonly Regex regexCStyleComment =
new Regex(@"/\*.*?\*/", RegexOptions.Compiled);
private static readonly Regex regexExternDirective =
new Regex(@"^\s*(\/\/)?#extern(\s+""(?<name>.*)""\s*)?$", RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly Regex regexIncludeDirective =
new Regex(@"^\s*(\/\/)?#include\s+""(?<file>.*)""\s*$", RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly Regex regexincludeResourceDirective =
new Regex(@"^\s*(\/\/)?#includeres\s+""(?<resource>.*)""\s*(?<asm>entry|executing)?\s*$", RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly Regex regexIfVerDirective =
new Regex(@"^\s*(\/\/)?#(?<op>ifver(_gt|_gte|_lt|_lte)?)\s+\""(?<gles>es)?(?<version_maj>\d+).(?<version_min>\d+)\""\s+\{\s*(?<source>.+)\s*\}\s*$", RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly Regex regexSamplerDirective =
new Regex(@"^\s*(\/\/)?#sampler\s+(?<sampler>\d+)\s+""(?<uniform>.*)""\s*$", RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly Regex regexParamDirective =
new Regex(@"^\s*(\/\/)?#param\s+""(?<parameter>.*?)""\s*$", RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly Regex regexCameraDirective =
new Regex(@"^\s*(\/\/)?#camera\((?<parameter>\w+)\)\s*""(?<uniform>\w+)""\s*$", RegexOptions.Singleline | RegexOptions.Compiled);
}
}
| 42.929688 | 210 | 0.573127 | [
"Apache-2.0",
"MIT"
] | MicroWorldwide/ultraviolet | Source/Ultraviolet.OpenGL/Shared/Graphics/ShaderSource.cs | 16,487 | C# |
using Fan.Blog.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace Fan.Web.ViewComponents
{
/// <summary>
/// The BlogArchives view component.
/// </summary>
public class BlogArchivesViewComponent : ViewComponent
{
private readonly IStatsService _statsSvc;
public BlogArchivesViewComponent(IStatsService statsService)
{
_statsSvc = statsService;
}
public async Task<IViewComponentResult> InvokeAsync()
{
var years = await _statsSvc.GetArchivesAsync();
return View(years);
}
}
} | 26.541667 | 68 | 0.651491 | [
"Apache-2.0"
] | tamil1809/Fanray | src/Fan.Web/ViewComponents/BlogArchivesViewComponent.cs | 639 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CNC Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Io Engineering")]
[assembly: AssemblyProduct("CNC Core")]
[assembly: AssemblyCopyright("Copyright © 2019 Io Engineering")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f245ff89-a838-4d6e-aa40-92cfd3d072d3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
| 38.324324 | 84 | 0.745416 | [
"BSD-3-Clause"
] | Jmerk523/Grbl-GCode-Sender | CNC Core/CNC Core/Properties/AssemblyInfo.cs | 1,421 | C# |
namespace Steamworks
{
public enum EDenyReason
{
k_EDenyInvalid,
k_EDenyInvalidVersion,
k_EDenyGeneric,
k_EDenyNotLoggedOn,
k_EDenyNoLicense,
k_EDenyCheater,
k_EDenyLoggedInElseWhere,
k_EDenyUnknownText,
k_EDenyIncompatibleAnticheat,
k_EDenyMemoryCorruption,
k_EDenyIncompatibleSoftware,
k_EDenySteamConnectionLost,
k_EDenySteamConnectionError,
k_EDenySteamResponseTimedOut,
k_EDenySteamValidationStalled,
k_EDenySteamOwnerLeftGuestUser
}
}
| 20.695652 | 32 | 0.834034 | [
"MIT"
] | undancer/oni-data | Managed/firstpass/Steamworks/EDenyReason.cs | 476 | C# |
namespace Test.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.Migrations;
public partial class InitialMigrations : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.AbpAuditLogs",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
ServiceName = c.String(maxLength: 256),
MethodName = c.String(maxLength: 256),
Parameters = c.String(maxLength: 1024),
ExecutionTime = c.DateTime(nullable: false),
ExecutionDuration = c.Int(nullable: false),
ClientIpAddress = c.String(maxLength: 64),
ClientName = c.String(maxLength: 128),
BrowserInfo = c.String(maxLength: 512),
Exception = c.String(maxLength: 2000),
ImpersonatorUserId = c.Long(),
ImpersonatorTenantId = c.Int(),
CustomData = c.String(maxLength: 2000),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpBackgroundJobs",
c => new
{
Id = c.Long(nullable: false, identity: true),
JobType = c.String(nullable: false, maxLength: 512),
JobArgs = c.String(nullable: false),
TryCount = c.Short(nullable: false),
NextTryTime = c.DateTime(nullable: false),
LastTryTime = c.DateTime(),
IsAbandoned = c.Boolean(nullable: false),
Priority = c.Byte(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
})
.PrimaryKey(t => t.Id)
.Index(t => new { t.IsAbandoned, t.NextTryTime });
CreateTable(
"dbo.AbpFeatures",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 128),
Value = c.String(nullable: false, maxLength: 2000),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
EditionId = c.Int(),
Discriminator = c.String(nullable: false, maxLength: 128),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_EditionFeatureSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_FeatureSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_TenantFeatureSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpEditions", t => t.EditionId, cascadeDelete: true)
.Index(t => t.EditionId);
CreateTable(
"dbo.AbpEditions",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 32),
DisplayName = c.String(nullable: false, maxLength: 64),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpLanguages",
c => new
{
Id = c.Int(nullable: false, identity: true),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 10),
DisplayName = c.String(nullable: false, maxLength: 64),
Icon = c.String(maxLength: 128),
IsDisabled = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpLanguageTexts",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
LanguageName = c.String(nullable: false, maxLength: 10),
Source = c.String(nullable: false, maxLength: 128),
Key = c.String(nullable: false, maxLength: 256),
Value = c.String(nullable: false),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpNotifications",
c => new
{
Id = c.Guid(nullable: false),
NotificationName = c.String(nullable: false, maxLength: 96),
Data = c.String(),
DataTypeName = c.String(maxLength: 512),
EntityTypeName = c.String(maxLength: 250),
EntityTypeAssemblyQualifiedName = c.String(maxLength: 512),
EntityId = c.String(maxLength: 96),
Severity = c.Byte(nullable: false),
UserIds = c.String(),
ExcludedUserIds = c.String(),
TenantIds = c.String(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpNotificationSubscriptions",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
NotificationName = c.String(maxLength: 96),
EntityTypeName = c.String(maxLength: 250),
EntityTypeAssemblyQualifiedName = c.String(maxLength: 512),
EntityId = c.String(maxLength: 96),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.Index(t => new { t.NotificationName, t.EntityTypeName, t.EntityId, t.UserId });
CreateTable(
"dbo.AbpOrganizationUnits",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
ParentId = c.Long(),
Code = c.String(nullable: false, maxLength: 95),
DisplayName = c.String(nullable: false, maxLength: 128),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpOrganizationUnits", t => t.ParentId)
.Index(t => t.ParentId);
CreateTable(
"dbo.AbpPermissions",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 128),
IsGranted = c.Boolean(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
RoleId = c.Int(),
UserId = c.Long(),
Discriminator = c.String(nullable: false, maxLength: 128),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_PermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_RolePermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_UserPermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.ForeignKey("dbo.AbpRoles", t => t.RoleId, cascadeDelete: true)
.Index(t => t.RoleId)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpRoles",
c => new
{
Id = c.Int(nullable: false, identity: true),
Description = c.String(),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 32),
DisplayName = c.String(nullable: false, maxLength: 64),
IsStatic = c.Boolean(nullable: false),
IsDefault = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUsers",
c => new
{
Id = c.Long(nullable: false, identity: true),
AuthenticationSource = c.String(maxLength: 64),
UserName = c.String(nullable: false, maxLength: 256),
TenantId = c.Int(),
EmailAddress = c.String(nullable: false, maxLength: 256),
Name = c.String(nullable: false, maxLength: 32),
Surname = c.String(nullable: false, maxLength: 32),
Password = c.String(nullable: false, maxLength: 128),
EmailConfirmationCode = c.String(maxLength: 328),
PasswordResetCode = c.String(maxLength: 328),
LockoutEndDateUtc = c.DateTime(),
AccessFailedCount = c.Int(nullable: false),
IsLockoutEnabled = c.Boolean(nullable: false),
PhoneNumber = c.String(maxLength: 32),
IsPhoneNumberConfirmed = c.Boolean(nullable: false),
SecurityStamp = c.String(maxLength: 128),
IsTwoFactorEnabled = c.Boolean(nullable: false),
IsEmailConfirmed = c.Boolean(nullable: false),
IsActive = c.Boolean(nullable: false),
LastLoginTime = c.DateTime(),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUserClaims",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
ClaimType = c.String(maxLength: 256),
ClaimValue = c.String(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserClaim_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpUserLogins",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 256),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserLogin_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpUserRoles",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
RoleId = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserRole_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpSettings",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
Name = c.String(nullable: false, maxLength: 256),
Value = c.String(maxLength: 2000),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Setting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpTenantNotifications",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
NotificationName = c.String(nullable: false, maxLength: 96),
Data = c.String(),
DataTypeName = c.String(maxLength: 512),
EntityTypeName = c.String(maxLength: 250),
EntityTypeAssemblyQualifiedName = c.String(maxLength: 512),
EntityId = c.String(maxLength: 96),
Severity = c.Byte(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpTenants",
c => new
{
Id = c.Int(nullable: false, identity: true),
EditionId = c.Int(),
TenancyName = c.String(nullable: false, maxLength: 64),
Name = c.String(nullable: false, maxLength: 128),
ConnectionString = c.String(maxLength: 1024),
IsActive = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpEditions", t => t.EditionId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.Index(t => t.EditionId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUserAccounts",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
UserLinkId = c.Long(),
UserName = c.String(maxLength: 256),
EmailAddress = c.String(maxLength: 256),
LastLoginTime = c.DateTime(),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserAccount_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpUserLoginAttempts",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
TenancyName = c.String(maxLength: 64),
UserId = c.Long(),
UserNameOrEmailAddress = c.String(maxLength: 255),
ClientIpAddress = c.String(maxLength: 64),
ClientName = c.String(maxLength: 128),
BrowserInfo = c.String(maxLength: 512),
Result = c.Byte(nullable: false),
CreationTime = c.DateTime(nullable: false),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserLoginAttempt_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.Index(t => new { t.UserId, t.TenantId })
.Index(t => new { t.TenancyName, t.UserNameOrEmailAddress, t.Result });
CreateTable(
"dbo.AbpUserNotifications",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
TenantNotificationId = c.Guid(nullable: false),
State = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.Index(t => new { t.UserId, t.State, t.CreationTime });
CreateTable(
"dbo.AbpUserOrganizationUnits",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
OrganizationUnitId = c.Long(nullable: false),
IsDeleted = c.Boolean(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_UserOrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
}
public override void Down()
{
DropForeignKey("dbo.AbpTenants", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpTenants", "EditionId", "dbo.AbpEditions");
DropForeignKey("dbo.AbpTenants", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpTenants", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpPermissions", "RoleId", "dbo.AbpRoles");
DropForeignKey("dbo.AbpRoles", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpRoles", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpRoles", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpSettings", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserRoles", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpPermissions", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserLogins", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserClaims", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpOrganizationUnits", "ParentId", "dbo.AbpOrganizationUnits");
DropForeignKey("dbo.AbpFeatures", "EditionId", "dbo.AbpEditions");
DropIndex("dbo.AbpUserNotifications", new[] { "UserId", "State", "CreationTime" });
DropIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" });
DropIndex("dbo.AbpUserLoginAttempts", new[] { "UserId", "TenantId" });
DropIndex("dbo.AbpTenants", new[] { "CreatorUserId" });
DropIndex("dbo.AbpTenants", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpTenants", new[] { "DeleterUserId" });
DropIndex("dbo.AbpTenants", new[] { "EditionId" });
DropIndex("dbo.AbpSettings", new[] { "UserId" });
DropIndex("dbo.AbpUserRoles", new[] { "UserId" });
DropIndex("dbo.AbpUserLogins", new[] { "UserId" });
DropIndex("dbo.AbpUserClaims", new[] { "UserId" });
DropIndex("dbo.AbpUsers", new[] { "CreatorUserId" });
DropIndex("dbo.AbpUsers", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpUsers", new[] { "DeleterUserId" });
DropIndex("dbo.AbpRoles", new[] { "CreatorUserId" });
DropIndex("dbo.AbpRoles", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpRoles", new[] { "DeleterUserId" });
DropIndex("dbo.AbpPermissions", new[] { "UserId" });
DropIndex("dbo.AbpPermissions", new[] { "RoleId" });
DropIndex("dbo.AbpOrganizationUnits", new[] { "ParentId" });
DropIndex("dbo.AbpNotificationSubscriptions", new[] { "NotificationName", "EntityTypeName", "EntityId", "UserId" });
DropIndex("dbo.AbpFeatures", new[] { "EditionId" });
DropIndex("dbo.AbpBackgroundJobs", new[] { "IsAbandoned", "NextTryTime" });
DropTable("dbo.AbpUserOrganizationUnits",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_UserOrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserNotifications",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserLoginAttempts",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserLoginAttempt_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserAccounts",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserAccount_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpTenants",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpTenantNotifications",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpSettings",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Setting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserRoles",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserRole_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserLogins",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserLogin_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUserClaims",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_UserClaim_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpUsers",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpRoles",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpPermissions",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_PermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_RolePermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_UserPermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpOrganizationUnits",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpNotificationSubscriptions",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpNotifications");
DropTable("dbo.AbpLanguageTexts",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpLanguages",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpEditions",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpFeatures",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_EditionFeatureSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_FeatureSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_TenantFeatureSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpBackgroundJobs");
DropTable("dbo.AbpAuditLogs",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
}
}
}
| 53.519481 | 141 | 0.499043 | [
"MIT"
] | davidbandinelli/Abp52MvcJQueryDemo | src/Test.EntityFramework/Migrations/201809270654064_InitialMigrations.cs | 37,089 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.API;
using osu.Game.Online.Placeholders;
namespace osu.Game.Online
{
/// <summary>
/// A <see cref="Container"/> for displaying online content which require a local user to be logged in.
/// Shows its children only when the local user is logged in and supports displaying a placeholder if not.
/// </summary>
public class OnlineViewContainer : Container
{
protected LoadingSpinner LoadingSpinner { get; private set; }
protected override Container<Drawable> Content { get; } = new Container { RelativeSizeAxes = Axes.Both };
private readonly string placeholderMessage;
private Drawable placeholder;
private const double transform_duration = 300;
[Resolved]
protected IAPIProvider API { get; private set; }
/// <summary>
/// Construct a new instance of an online view container.
/// </summary>
/// <param name="placeholderMessage">The message to display when not logged in. If empty, no button will display.</param>
public OnlineViewContainer(string placeholderMessage)
{
this.placeholderMessage = placeholderMessage;
}
private readonly IBindable<APIState> apiState = new Bindable<APIState>();
[BackgroundDependencyLoader]
private void load(IAPIProvider api)
{
InternalChildren = new[]
{
Content,
placeholder = string.IsNullOrEmpty(placeholderMessage) ? Empty() : new LoginPlaceholder(placeholderMessage),
LoadingSpinner = new LoadingSpinner
{
Alpha = 0,
}
};
apiState.BindTo(api.State);
apiState.BindValueChanged(onlineStateChanged, true);
}
private void onlineStateChanged(ValueChangedEvent<APIState> state) => Schedule(() =>
{
switch (state.NewValue)
{
case APIState.Offline:
PopContentOut(Content);
placeholder.ScaleTo(0.8f).Then().ScaleTo(1, 3 * transform_duration, Easing.OutQuint);
placeholder.FadeInFromZero(2 * transform_duration, Easing.OutQuint);
LoadingSpinner.Hide();
break;
case APIState.Online:
PopContentIn(Content);
placeholder.FadeOut(transform_duration / 2, Easing.OutQuint);
LoadingSpinner.Hide();
break;
case APIState.Failing:
case APIState.Connecting:
PopContentOut(Content);
LoadingSpinner.Show();
placeholder.FadeOut(transform_duration / 2, Easing.OutQuint);
break;
}
});
/// <summary>
/// Applies a transform to the online content to make it hidden.
/// </summary>
protected virtual void PopContentOut(Drawable content) => content.FadeOut(transform_duration / 2, Easing.OutQuint);
/// <summary>
/// Applies a transform to the online content to make it visible.
/// </summary>
protected virtual void PopContentIn(Drawable content) => content.FadeIn(transform_duration, Easing.OutQuint);
}
}
| 38.479592 | 130 | 0.591355 | [
"MIT"
] | 02Naitsirk/osu | osu.Game/Online/OnlineViewContainer.cs | 3,676 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.DocumentDB.Inputs
{
/// <summary>
/// Cosmos DB SQL database resource object
/// </summary>
public sealed class SqlDatabaseResourceArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Name of the Cosmos DB SQL database
/// </summary>
[Input("id", required: true)]
public Input<string> Id { get; set; } = null!;
public SqlDatabaseResourceArgs()
{
}
}
}
| 26.37931 | 81 | 0.643137 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/DocumentDB/Inputs/SqlDatabaseResourceArgs.cs | 765 | C# |
using System;
namespace FUR10N.NullContracts.FlowAnalysis
{
public enum ExpressionStatus
{
Assigned,
ReassignedAfterCondition,
NotAssigned,
AssignedWithUnneededConstraint
}
public static class ExpressionStatusExtensions
{
public static bool IsAssigned(this ExpressionStatus status)
{
return status == ExpressionStatus.Assigned || status == ExpressionStatus.AssignedWithUnneededConstraint;
}
}
}
| 23.333333 | 116 | 0.679592 | [
"MIT"
] | FUR10N/NullContracts | src/FUR10N.NullContracts/FlowAnalysis/ExpressionStatus.cs | 492 | C# |
using LinqToLdap.Collections;
using LinqToLdap.Mapping.PropertyMappingBuilders;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq.Expressions;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
namespace LinqToLdap.Mapping
{
public abstract partial class ClassMap<T>
{
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<bool> Map(Expression<Func<T, bool>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<bool>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<bool?> Map(Expression<Func<T, bool?>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<bool?>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<byte[][]> Map(Expression<Func<T, byte[][]>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<byte[][]>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<byte[]> Map(Expression<Func<T, byte[]>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<byte[]>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<ICollection<byte[]>> Map(Expression<Func<T, ICollection<byte[]>>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<ICollection<byte[]>>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<Collection<byte[]>> Map(Expression<Func<T, Collection<byte[]>>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<Collection<byte[]>>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IDateTimePropertyMappingBuilder<T, DateTime> Map(Expression<Func<T, DateTime>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map(new DateTimePropertyMappingBuilder<T, DateTime>(propertyInfo));
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IDateTimePropertyMappingBuilder<T, DateTime?> Map(Expression<Func<T, DateTime?>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map(new DateTimePropertyMappingBuilder<T, DateTime?>(propertyInfo));
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<Enum> Map(Expression<Func<T, Enum>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<Enum>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<TProperty> Map<TProperty>(Expression<Func<T, TProperty>> property) where TProperty : struct, IConvertible
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<TProperty>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<TProperty?> Map<TProperty>(Expression<Func<T, TProperty?>> property) where TProperty : struct, IConvertible
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<TProperty?>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<Guid> Map(Expression<Func<T, Guid>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<Guid>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<Guid?> Map(Expression<Func<T, Guid?>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<Guid?>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<Int16> Map(Expression<Func<T, Int16>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<Int16>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<Int16?> Map(Expression<Func<T, Int16?>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<Int16?>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<UInt16> Map(Expression<Func<T, UInt16>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<UInt16>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<UInt16?> Map(Expression<Func<T, UInt16?>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<UInt16?>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<Int32> Map(Expression<Func<T, Int32>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<Int32>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<Int32?> Map(Expression<Func<T, Int32?>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<Int32?>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<UInt32> Map(Expression<Func<T, UInt32>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<UInt32>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<UInt32?> Map(Expression<Func<T, UInt32?>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<UInt32?>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<Int64> Map(Expression<Func<T, Int64>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<Int64>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<Int64?> Map(Expression<Func<T, Int64?>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<Int64?>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<UInt64> Map(Expression<Func<T, UInt64>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<UInt64>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<UInt64?> Map(Expression<Func<T, UInt64?>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<UInt64?>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<byte> Map(Expression<Func<T, byte>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<byte>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<byte?> Map(Expression<Func<T, byte?>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<byte?>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<decimal> Map(Expression<Func<T, decimal>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<decimal>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<decimal?> Map(Expression<Func<T, decimal?>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<decimal?>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<double> Map(Expression<Func<T, double>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<double>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<double?> Map(Expression<Func<T, double?>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<double?>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<float> Map(Expression<Func<T, float>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<float>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<float?> Map(Expression<Func<T, float?>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<float?>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<sbyte> Map(Expression<Func<T, sbyte>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<sbyte>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<sbyte?> Map(Expression<Func<T, sbyte?>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<sbyte?>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<SecurityIdentifier> Map(Expression<Func<T, SecurityIdentifier>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<SecurityIdentifier>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<string[]> Map(Expression<Func<T, string[]>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<string[]>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<DateTime[]> Map(Expression<Func<T, DateTime[]>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<DateTime[]>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<DateTime?[]> Map(Expression<Func<T, DateTime?[]>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<DateTime?[]>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<Collection<string>> Map(Expression<Func<T, Collection<string>>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<Collection<string>>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<ICollection<string>> Map(Expression<Func<T, ICollection<string>>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<ICollection<string>>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<string> Map(Expression<Func<T, string>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<string>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<X509Certificate> Map(Expression<Func<T, X509Certificate>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<X509Certificate>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<X509Certificate2> Map(Expression<Func<T, X509Certificate2>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<X509Certificate2>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<X509Certificate[]> Map(Expression<Func<T, X509Certificate[]>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<X509Certificate[]>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<SecurityIdentifier[]> Map(Expression<Func<T, SecurityIdentifier[]>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<SecurityIdentifier[]>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<X509Certificate2[]> Map(Expression<Func<T, X509Certificate2[]>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<X509Certificate2[]>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<Collection<X509Certificate>> Map(Expression<Func<T, Collection<X509Certificate>>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<Collection<X509Certificate>>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<ICollection<X509Certificate>> Map(Expression<Func<T, ICollection<X509Certificate>>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<ICollection<X509Certificate>>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<Collection<X509Certificate2>> Map(Expression<Func<T, Collection<X509Certificate2>>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<Collection<X509Certificate2>>(propertyInfo);
}
/// <summary>
/// Create a property mapping.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected IPropertyMapperGeneric<ICollection<X509Certificate2>> Map(Expression<Func<T, ICollection<X509Certificate2>>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
return Map<ICollection<X509Certificate2>>(propertyInfo);
}
/// <summary>
/// Create a property mapping to catch all attributes.
/// </summary>
/// <param name="property">Property to map</param>
/// <example>
/// Map(x => x.Name);
/// </example>
protected void CatchAll(Expression<Func<T, IDirectoryAttributes>> property)
{
var propertyInfo = GetPropertyInfo(property.Body);
CatchAll(propertyInfo);
}
}
} | 32.518868 | 148 | 0.540926 | [
"MIT"
] | madhatter22/LinqToLdap | LinqToLdap/Mapping/ClassMapMapMethods.cs | 24,131 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Nerula.Data
{
public enum WipState
{
New = 10,
Billed = 50
}
}
| 13.5 | 33 | 0.634921 | [
"Unlicense"
] | jahav/Nerula | Nerula.Wip/WipState.cs | 191 | C# |
using System;
using NetOffice;
namespace NetOffice.WordApi.Enums
{
/// <summary>
/// SupportByVersion Word 14, 15, 16
/// </summary>
///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff835791.aspx </remarks>
[SupportByVersionAttribute("Word", 14,15,16)]
[EntityTypeAttribute(EntityType.IsEnum)]
public enum XlBarShape
{
/// <summary>
/// SupportByVersion Word 14, 15, 16
/// </summary>
/// <remarks>0</remarks>
[SupportByVersionAttribute("Word", 14,15,16)]
xlBox = 0,
/// <summary>
/// SupportByVersion Word 14, 15, 16
/// </summary>
/// <remarks>1</remarks>
[SupportByVersionAttribute("Word", 14,15,16)]
xlPyramidToPoint = 1,
/// <summary>
/// SupportByVersion Word 14, 15, 16
/// </summary>
/// <remarks>2</remarks>
[SupportByVersionAttribute("Word", 14,15,16)]
xlPyramidToMax = 2,
/// <summary>
/// SupportByVersion Word 14, 15, 16
/// </summary>
/// <remarks>3</remarks>
[SupportByVersionAttribute("Word", 14,15,16)]
xlCylinder = 3,
/// <summary>
/// SupportByVersion Word 14, 15, 16
/// </summary>
/// <remarks>4</remarks>
[SupportByVersionAttribute("Word", 14,15,16)]
xlConeToPoint = 4,
/// <summary>
/// SupportByVersion Word 14, 15, 16
/// </summary>
/// <remarks>5</remarks>
[SupportByVersionAttribute("Word", 14,15,16)]
xlConeToMax = 5
}
} | 25.781818 | 119 | 0.627645 | [
"MIT"
] | Engineerumair/NetOffice | Source/Word/Enums/XlBarShape.cs | 1,418 | C# |
/*
* PagarmeCoreApi.Standard
*
* This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
*/
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using PagarmeCoreApi.Standard;
using PagarmeCoreApi.Standard.Utilities;
namespace PagarmeCoreApi.Standard.Models
{
public class UpdateMetadataRequest : BaseModel
{
// These fields hold the values for the public properties.
private Dictionary<string, string> metadata;
/// <summary>
/// Metadata
/// </summary>
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata
{
get
{
return this.metadata;
}
set
{
this.metadata = value;
onPropertyChanged("Metadata");
}
}
}
} | 25 | 83 | 0.587907 | [
"MIT"
] | pagarme/pagarme-core-api-dotnet-standard | PagarmeCoreApi.Standard/Models/UpdateMetadataRequest.cs | 1,075 | C# |
using System;
using Xunit;
using MultiBracketValidation;
namespace MultiBracketValidatorTest
{
public class MultiBracketValidationTest
{
[Fact]
public void HappyPath()
{
string test = "()[]{}";
Assert.True(MultiBracket.MultiBracketValidation(test));
}
[Fact]
public void ShouldFail()
{
string str = "(})";
Assert.False(MultiBracket.MultiBracketValidation(str));
}
[Fact]
public void LongString()
{
string str = "(abcd(cfrt)({{[o]}})hjvghjkkopoht)";
Assert.True(MultiBracket.MultiBracketValidation(str));
}
[Fact]
public void SmallString()
{
string str = "(";
Assert.False(MultiBracket.MultiBracketValidation(str));
}
[Fact]
public void NoBrackets()
{
string str = "Askjbhj";
Assert.True(MultiBracket.MultiBracketValidation(str));
}
[Fact]
public void OneChar()
{
string str = "a";
Assert.True(MultiBracket.MultiBracketValidation(str));
}
[Fact]
public void ExtraOpen()
{
string str = "((abc)";
Assert.False(MultiBracket.MultiBracketValidation(str));
}
[Fact]
public void ExtraClose()
{
string str = "(abc))";
Assert.False(MultiBracket.MultiBracketValidation(str));
}
[Fact]
public void EmptyString()
{
string str = "";
Assert.Throws<NullReferenceException>(() => MultiBracket.MultiBracketValidation(str));
}
}
}
| 26.101449 | 99 | 0.500833 | [
"MIT"
] | daviddicken/data-structures-and-algorithms | dotnet/codeChallenges/MultiBracketValidatorTest/MultiBarachetValidationTest.cs | 1,801 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\shared\d3dkmddi.h(3254,9)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential)]
public partial struct _DXGK_QUERYADAPTERINFOFLAGS__union_0__struct_0
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public byte[] __bits;
public uint VirtualMachineData { get => InteropRuntime.GetUInt32(__bits, 0, 1); set { if (__bits == null) __bits = new byte[4]; InteropRuntime.SetUInt32(value, __bits, 0, 1); } }
public uint SecureVirtualMachine { get => InteropRuntime.GetUInt32(__bits, 1, 1); set { if (__bits == null) __bits = new byte[4]; InteropRuntime.SetUInt32(value, __bits, 1, 1); } }
public uint Reserved { get => InteropRuntime.GetUInt32(__bits, 2, 30); set { if (__bits == null) __bits = new byte[4]; InteropRuntime.SetUInt32(value, __bits, 2, 30); } }
}
}
| 58.5 | 189 | 0.698006 | [
"MIT"
] | Steph55/DirectN | DirectN/DirectN/Generated/_DXGK_QUERYADAPTERINFOFLAGS__union_0__struct_0.cs | 1,055 | C# |
using System;
using AppRopio.Models.Filters.Responses;
using System.Collections.Generic;
using AppRopio.Base.Filters.Core.Services;
using MvvmCross.Platform;
using MvvmCross.Plugins.Messenger;
using AppRopio.Base.Filters.Core.ViewModels.Filters.Messages;
namespace AppRopio.Base.Filters.Core.ViewModels.Filters.Items.Selection
{
public abstract class BaseSelectionFiVm : FiltersItemVm, IBaseSelectionFiVm
{
#region Fields
private MvxSubscriptionToken _subscribtionToken;
#endregion
#region Properties
public override ApplyedFilter SelectedValue { get; protected set; }
protected List<FilterValue> Values { get; set; }
protected List<ApplyedFilterValue> ApplyedFilterValues { get; set; }
#endregion
#region Services
protected IFiltersNavigationVmService NavigationVmService { get { return Mvx.Resolve<IFiltersNavigationVmService>(); } }
#endregion
#region Constructor
protected BaseSelectionFiVm(Filter filter, List<ApplyedFilterValue> applyedFilterValues)
: base(filter)
{
Values = filter.Values;
ApplyedFilterValues = applyedFilterValues;
}
#region Protected
protected abstract void OnSelectionMessageReceived(FiltersSelectionChangedMessage msg);
#endregion
#endregion
#region Public
#region IBaseSelectionFiVm implementation
public void OnSelected()
{
if (_subscribtionToken == null)
_subscribtionToken = Messenger.Subscribe<FiltersSelectionChangedMessage>(OnSelectionMessageReceived);
NavigationVmService.NavigateToSelection(new Models.Bundle.SelectionBundle(this.Id, this.Name, this.WidgetType, Values, SelectedValue?.Values));
}
#endregion
#endregion
}
}
| 27.246377 | 155 | 0.695745 | [
"Apache-2.0"
] | cryptobuks/AppRopio.Mobile | src/app-ropio/AppRopio.Base/Filters/Core/ViewModels/Filters/Items/Selection/BaseSelectionFiVm.cs | 1,882 | C# |
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class OpenFileName {
public int structSize = 0;
public IntPtr dlgOwner = IntPtr.Zero;
public IntPtr instance = IntPtr.Zero;
public String filter = null;
public String customFilter = null;
public int maxCustFilter = 0;
public int filterIndex = 0;
public String file = null;
public int maxFile = 0;
public String fileTitle = null;
public int maxFileTitle = 0;
public String initialDir = null;
public String title = null;
public int flags = 0;
public short fileOffset = 0;
public short fileExtension = 0;
public String defExt = null;
public IntPtr custData = IntPtr.Zero;
public IntPtr hook = IntPtr.Zero;
public String templateName = null;
public IntPtr reservedPtr = IntPtr.Zero;
public int reservedInt = 0;
public int flagsEx = 0;
}
public class DllTest {
[DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
public static extern bool GetOpenFileName([In, Out] OpenFileName ofn);
public static bool GetOpenFileName1([In, Out] OpenFileName ofn) {
return GetOpenFileName(ofn);
}
} | 33 | 103 | 0.710526 | [
"MIT"
] | Danruc/Scape_to_Space | ScapeToSpace/Assets/Scripts/Level2/Quest2/Tutorial/OpenFileName.cs | 1,256 | C# |
using SimpleIdentityServer.Core.Jwt.Serializer;
using SimpleIdentityServer.Core.Jwt.Signature;
namespace SimpleIdentityServer.Core.Jwt
{
public class JwsGeneratorFactory
{
public IJwsGenerator BuildJwsGenerator()
{
ICreateJwsSignature createJwsSignature;
#if NET461
createJwsSignature = new CreateJwsSignature(new CngKeySerializer());
#else
createJwsSignature = new CreateJwsSignature();
#endif
return new JwsGenerator(createJwsSignature);
}
}
} | 27.947368 | 80 | 0.706215 | [
"Apache-2.0"
] | appkins/SimpleIdentityServer | SimpleIdentityServer/src/Apis/SimpleIdServer/SimpleIdentityServer.Core.Jwt/JwsGeneratorFactory.cs | 533 | C# |
namespace JiraAssistant.Domain.Ui
{
public interface IToolbarItem
{
}
} | 13.5 | 34 | 0.703704 | [
"MIT"
] | sceeter89/jira-client | JiraAssistant.Domain/Ui/IToolbarItem.cs | 83 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using ManagedLzma.Testing;
using ManagedCoder = ManagedLzma.LZMA.Helper;
using ManagedCoder2 = ManagedLzma.LZMA.Helper2;
using NativeCoder = ManagedLzma.LZMA.Reference.Native.Helper;
using NativeCoder2 = ManagedLzma.LZMA.Reference.Native.Helper2;
namespace ManagedLzma.LZMA
{
[Serializable]
public class TestSettings : SharedSettings
{
public int Seed;
public int DatLen;
public int RunLen;
public TestSettings() { }
public TestSettings(TestSettings other)
: base(other)
{
this.Seed = other.Seed;
this.DatLen = other.DatLen;
this.RunLen = other.RunLen;
}
}
public static class TestRunner
{
private static IHelper CreateHelper(Guid id, bool managed, SharedSettings s)
{
if (managed)
{
if (s.UseV2)
return new ManagedCoder2(id);
else
return new ManagedCoder(id);
}
else
{
if (s.UseV2)
return new NativeCoder2(id);
else
return new NativeCoder(id);
}
}
private static void GenData(int seed, int runlen, byte[] buffer)
{
var rnd = new Random(seed);
byte val = (byte)rnd.Next(256);
for (int i = 0; i < buffer.Length; i++)
{
if (rnd.Next(runlen) == 0)
val = (byte)rnd.Next(32);
buffer[i] = val;
}
}
private static TestSettings Pack(Guid id, bool managed, TestSettings s)
{
s.Dst = new PZ(new byte[s.DatLen * 2]);
s.Src = new PZ(new byte[s.DatLen]);
GenData(s.Seed, s.RunLen, s.Src.Buffer);
using (var coder = CreateHelper(id, managed, s))
coder.LzmaCompress(s);
return s;
}
private static TestSettings Unpack(Guid id, bool managed, TestSettings t)
{
var s = new TestSettings(t)
{
Dst = new PZ(new byte[t.Src.Length]),
Src = t.Dst,
Enc = t.Enc,
};
using (var coder = CreateHelper(id, managed, s))
coder.LzmaUncompress(s);
if (s.WrittenSize != t.Src.Length)
throw new InvalidOperationException();
if (s.UsedSize != t.WrittenSize)
throw new InvalidOperationException();
return s;
}
public static void RunPackTest(ref TestSettings settings)
{
TestSettings r1 = null;
TestSettings r2 = null;
using (var nativeManager = new LocalManager())
{
Guid id = Guid.NewGuid();
var nativeResult = nativeManager.BeginInvoke(typeof(TestRunner), "Pack", id, false, settings);
using (var managedManager = new InprocManager())
r2 = (TestSettings)managedManager.Invoke(typeof(TestRunner), "Pack", id, true, settings);
r1 = (TestSettings)nativeManager.EndInvoke(nativeResult);
}
if (r1.WrittenSize != r2.WrittenSize)
throw new InvalidOperationException();
for (int i = 0; i < r1.WrittenSize; i++)
if (r1.Dst[i] != r2.Dst[i])
throw new InvalidOperationException();
if (r1.Enc.Length != r1.Enc.Length)
throw new InvalidOperationException();
for (int i = 0; i < r1.Enc.Length; i++)
if (r1.Enc[i] != r1.Enc[i])
throw new InvalidOperationException();
settings = r1;
}
public static void RunUnpackTest(ref TestSettings settings)
{
TestSettings r1 = null;
TestSettings r2 = null;
using (var nativeManager = new LocalManager())
{
Guid id = Guid.NewGuid();
var nativeResult = nativeManager.BeginInvoke(typeof(TestRunner), "Unpack", id, false, settings);
using (var managedManager = new InprocManager())
r2 = (TestSettings)managedManager.Invoke(typeof(TestRunner), "Unpack", id, true, settings);
r1 = (TestSettings)nativeManager.EndInvoke(nativeResult);
}
if (r1.WrittenSize != r2.WrittenSize)
throw new InvalidOperationException();
if (r1.UsedSize != r2.UsedSize)
throw new InvalidOperationException();
for (int i = 0; i < r1.WrittenSize; i++)
if (r1.Dst[i] != r2.Dst[i])
throw new InvalidOperationException();
settings = r1;
}
private static void RunTestInternal(TestSettings test)
{
RunPackTest(ref test);
GC.Collect();
GC.WaitForPendingFinalizers();
RunUnpackTest(ref test);
}
public static void RunTest(TestSettings test)
{
try
{
RunTestInternal(test);
}
finally
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}
}
| 30.430108 | 113 | 0.49894 | [
"MIT"
] | mostlyuseful/managed-lzma | sandbox/TestRunner.cs | 5,662 | C# |
/*************************************************
----Author: Cyy
----CreateDate: 2022-04-02 11:20:21
----Desc: Create By BM
**************************************************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using BmFramework.Core;
namespace Bm.Lerp
{
public class BmLerpAnimationClip : BmLerpBase
{
public AnimationClip clip;
protected override void _Lerp(float _per)
{
clip.SampleAnimation(gameObject, Mathf.Lerp(0, clip.length, _per));
}
}
}
| 23.36 | 91 | 0.513699 | [
"MIT"
] | corle-bell/MineSweeping | Assets/BmFramework/Commpent/LerpTween/BmLerpAnimationClip.cs | 584 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.Reflection.Tests
{
// System.Reflection.FieldInfo.GetValue(System.Object)
public class FieldInfoGetValue1
{
// Positive Test 1: Test a general field in a system defined class
[Fact]
public void PosTest1()
{
string str = "Test String Value";
Type type = typeof(System.String);
FieldInfo fieldinfo = type.GetField("Empty");
object obj = fieldinfo.GetValue(str);
Assert.Equal("", obj.ToString());
}
// Positive Test 2: Test a string field in a customized class
[Fact]
public void PosTest2()
{
string argu_str1 = "ArgumentString1";
string argu_str2 = "ArgumentString2";
TestClassA str = new TestClassA(argu_str1, argu_str2);
Type type = typeof(TestClassA);
FieldInfo fieldinfo = type.GetField("str1");
object obj = fieldinfo.GetValue(str);
Assert.Equal(argu_str1, obj.ToString());
}
// Positive Test 3: Test a field of a sub class derived from its base class
[Fact]
public void PosTest3()
{
int int1 = new Random().Next(int.MinValue, int.MaxValue);
subclass sub = new subclass(int1);
Type type = typeof(subclass);
FieldInfo fieldinfo = type.GetField("v_int", BindingFlags.NonPublic | BindingFlags.Instance);
object obj = fieldinfo.GetValue(sub);
Assert.Equal(int1, (int)obj);
}
// Positive Test 4: Test a nullable type field in a customized class
[Fact]
public void PosTest4()
{
TestClassA str = new TestClassA();
Type type = typeof(TestClassA);
FieldInfo fieldinfo = type.GetField("v_null_int");
object obj = fieldinfo.GetValue(str);
Assert.Null(obj);
}
// Positive Test 5: Get the object of a customized class type
[Fact]
public void PosTest5()
{
TestClassA str = new TestClassA();
Type type = typeof(TestClassA);
FieldInfo fieldinfo = type.GetField("tc");
object obj = fieldinfo.GetValue(str);
int int1 = (obj as TypeClass).value;
Assert.Equal(1000, int1);
}
// Positive Test 6: Test a generic type field
[Fact]
public void PosTest6()
{
genClass<int> str = new genClass<int>(12345);
Type type = typeof(genClass<int>);
FieldInfo fieldinfo = type.GetField("t");
object obj = fieldinfo.GetValue(str);
Assert.Equal(12345, (int)obj);
}
// Positive Test 7: Test a static field
[Fact]
public void PosTest7()
{
Type type = typeof(TestClassA);
TestClassA.sta_int = -99;
FieldInfo fieldinfo = type.GetField("sta_int");
object obj = fieldinfo.GetValue(null);
Assert.Equal(-99, (int)obj);
}
// Negative Test 1: The argument object is null reference
[Fact]
public void NegTest1()
{
genClass<int> str = new genClass<int>(12345);
Type type = typeof(genClass<int>);
FieldInfo fieldinfo = type.GetField("t");
// System.Reflection.TargetException not visible at the moment.
Exception e = Assert.ThrowsAny<Exception>(() => fieldinfo.GetValue(null));
Assert.Equal("System.Reflection.TargetException", e.GetType().FullName);
}
#region Test helper classes
public class TestClassA
{
public string str1;
public string str2;
public TestClassA(string a, string b)
{
str1 = a;
str2 = b;
}
public TestClassA()
{
v_null_int = null;
tc = new TypeClass();
_vpri = 100;
}
protected int v_int;
public int? v_null_int;
public TypeClass tc;
public static int sta_int;
private int _vpri;
public void usingv()
{
int a = _vpri;
}
}
public class subclass : TestClassA
{
public subclass(int c)
: base(null, null)
{
v_int = c;
}
}
public class genClass<T>
{
public T t;
public genClass(T value)
{
t = value;
}
}
public class TypeClass
{
public TypeClass()
{
value = 1000;
}
public int value;
}
#endregion
}
} | 31.841772 | 105 | 0.521566 | [
"MIT"
] | 690486439/corefx | src/System.Reflection.TypeExtensions/tests/FieldInfo/FieldInfoGetValue1.cs | 5,031 | C# |
using BingImageSearchSample.Services.BingService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Template10.Mvvm;
using Template10.Services.NavigationService;
using Windows.UI.Xaml.Navigation;
namespace BingImageSearchSample.ViewModels
{
public class DetailPageViewModel : BingImageSearchSample.Mvvm.ViewModelBase
{
public DetailPageViewModel()
{
//if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
// Value = "Designtime value";
}
private BingImage _image;
public BingImage Image { get { return _image; } set { Set(ref _image, value); } }
public override Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> state)
{
if (state.ContainsKey(nameof(Image)))
{
Image = state[nameof(Image)] as BingImage;
state.Clear();
}
else
{
Image = parameter as BingImage;
}
return Task.CompletedTask;
}
public override Task OnNavigatedFromAsync(IDictionary<string, object> state, bool suspending)
{
if (suspending)
{
state[nameof(Image)] = Image;
}
return Task.CompletedTask;
}
}
}
| 28.36 | 121 | 0.610014 | [
"Apache-2.0"
] | gsantopaolo/BingImageSearchSample | BingImageSearchSample/ViewModels/DetailPageViewModel.cs | 1,418 | C# |
namespace SFA.DAS.Events.Api.Client.Configuration
{
public interface IEventsApiClientConfiguration
{
string BaseUrl { get; }
string ClientToken { get; }
}
} | 23.125 | 50 | 0.664865 | [
"MIT"
] | SkillsFundingAgency/das-events | src/SFA.DAS.Events.Api.Client/Configuration/IEventsApiClientConfiguration.cs | 187 | C# |
using System;
namespace WebApiBasics.WebApp.Areas.HelpPage
{
/// <summary>
/// This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class.
/// </summary>
public class TextSample
{
public TextSample(string text)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
Text = text;
}
public string Text { get; private set; }
public override bool Equals(object obj)
{
TextSample other = obj as TextSample;
return other != null && Text == other.Text;
}
public override int GetHashCode()
{
return Text.GetHashCode();
}
public override string ToString()
{
return Text;
}
}
} | 24.189189 | 140 | 0.536313 | [
"MIT"
] | paulboocock/WebApiBasics | WebApiBasics.WebApp/Areas/HelpPage/SampleGeneration/TextSample.cs | 895 | C# |
// 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.Diagnostics;
namespace Cake.Core.IO.Globbing.Nodes;
[DebuggerDisplay("**")]
internal sealed class RecursiveWildcardNode : MatchableNode
{
[DebuggerStepThrough]
public override void Accept(GlobVisitor globber, GlobVisitorContext context)
{
globber.VisitRecursiveWildcardSegment(this, context);
}
public override bool IsMatch(string value)
{
return true;
}
} | 28.227273 | 80 | 0.73591 | [
"MIT"
] | ecampidoglio/cake | src/Cake.Core/IO/Globbing/Nodes/RecursiveWildcardNode.cs | 623 | C# |
namespace GitVersion.VersionCalculation.BaseVersionCalculators
{
using System;
using System.Collections.Generic;
using System.Linq;
using LibGit2Sharp;
/// <summary>
/// Version is extracted from all tags on the branch which are valid, and not newer than the current commit.
/// BaseVersionSource is the tag's commit.
/// Increments if the tag is not the current commit.
/// </summary>
public class TaggedCommitVersionStrategy : BaseVersionStrategy
{
public override IEnumerable<BaseVersion> GetVersions(GitVersionContext context)
{
return GetTaggedVersions(context, context.CurrentBranch, context.CurrentCommit.When());
}
public IEnumerable<BaseVersion> GetTaggedVersions(GitVersionContext context, Branch currentBranch, DateTimeOffset? olderThan)
{
var allTags = context.Repository.Tags
.Where(tag => !olderThan.HasValue || ((Commit) tag.PeeledTarget()).When() <= olderThan.Value)
.ToList();
var tagsOnBranch = currentBranch
.Commits
.SelectMany(commit => { return allTags.Where(t => IsValidTag(t, commit)); })
.Select(t =>
{
SemanticVersion version;
if (SemanticVersion.TryParse(t.FriendlyName, context.Configuration.GitTagPrefix, out version))
{
var commit = t.PeeledTarget() as Commit;
if (commit != null)
return new VersionTaggedCommit(commit, version, t.FriendlyName);
}
return null;
})
.Where(a => a != null)
.ToList();
return tagsOnBranch.Select(t => CreateBaseVersion(context, t));
}
BaseVersion CreateBaseVersion(GitVersionContext context, VersionTaggedCommit version)
{
var shouldUpdateVersion = version.Commit.Sha != context.CurrentCommit.Sha;
var baseVersion = new BaseVersion(context, FormatSource(version), shouldUpdateVersion, version.SemVer, version.Commit, null);
return baseVersion;
}
protected virtual string FormatSource(VersionTaggedCommit version)
{
return string.Format("Git tag '{0}'", version.Tag);
}
protected virtual bool IsValidTag(Tag tag, Commit commit)
{
return tag.PeeledTarget() == commit;
}
protected class VersionTaggedCommit
{
public string Tag;
public Commit Commit;
public SemanticVersion SemVer;
public VersionTaggedCommit(Commit commit, SemanticVersion semVer, string tag)
{
Tag = tag;
Commit = commit;
SemVer = semVer;
}
}
}
} | 39.381579 | 138 | 0.56866 | [
"MIT"
] | clairernovotny/GitVersion | src/GitVersionCore/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs | 2,920 | C# |
using Sandbox;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using VRP.Items.UI;
using VRP.Player;
namespace VRP.Items
{
public partial class VrpItemEntity : ModelEntity, IUse
{
private static readonly List<VrpItemEntity> ITEMS = new List<VrpItemEntity>();
private float _dataDirtyTime = 0f;
private Dictionary<ulong, float> _dataLastSent = new Dictionary<ulong, float>();
public VrpItemEntity()
{
ITEMS.Add( this );
}
[Net]
public VrpItem Item { get; set; }
[Event.Tick]
public void OnTick()
{
if ( Host.IsClient )
{
return;
}
if ( this.Item == null )
{
Log.Warning( "VrpItemEntity deleted for missing _item!" );
this.Delete();
return;
}
var itemModel = this.Item.GetModelPath();
if ( this.GetModelName() != itemModel )
{
this.SetModel( itemModel );
//this.SetupPhysicsFromModel
}
this.ProcessClientDataUpdates();
this.Item.Tick( this );
}
[Event.Frame]
public void OnFrame()
{
// TODO: Check this is only called when entity is rendered
if ( this.Item != null && this.Item.DisplayHint && Local.Pawn is VrpPlayer player )
{
var tr = player.GetEyeTrace();
if ( tr.Entity == this && tr.Distance <= this.Item.DisplayHintDistance )
{
VrpItemHintPanel.CreateHintIfNotExists( this );
}
else
{
VrpItemHintPanel.RemoveHint( this );
}
}
}
public void InitializeItem( VrpItem item )
{
if ( this.Item != null )
{
this.Item.OnDataSet -= this.OnItemDataSet;
}
this.Item = item;
this.Item.OnDataSet += this.OnItemDataSet;
this.SetModel( item.GetModelPath() );
if ( item.DataTemplates != null )
{
foreach ( var req in item.DataTemplates )
{
if ( !item.HasData( req.Key ) )
{
item.SetData( req.Key, req.DefaultValue );
}
}
}
this.Item.Initialize( this );
}
public static VrpItemEntity[] GetItems()
{
return ITEMS.ToArray();
}
public void NetworkData()
{
this.NetworkData( To.Everyone );
}
public void NetworkData( To to )
{
var data = this.Item.SerializeData();
this.RpcNetworkData( to, data );
}
[ClientRpc]
public void RpcNetworkData( string serializedData )
{
var data = this.Item.DeserializeData( serializedData );
this.Item.Data = data;
}
private void ProcessClientDataUpdates()
{
foreach ( var cl in Client.All )
{
if ( !_dataLastSent.TryGetValue( cl.SteamId, out var lastUpdated ) )
{
lastUpdated = -1f;
}
if ( lastUpdated < _dataDirtyTime )
{
this.UpdateClientData( cl );
}
}
}
private void UpdateClientData( Client client )
{
if ( _dataLastSent.ContainsKey( client.SteamId ) )
{
_dataLastSent.Remove( client.SteamId );
}
_dataLastSent.Add( client.SteamId, Time.Now );
this.NetworkData( To.Single( client ) );
}
private void OnItemDataSet( string key, object value )
{
_dataDirtyTime = Time.Now;
}
}
}
| 19.27673 | 86 | 0.639804 | [
"MIT"
] | civilgamers/vrp | code/Items/VrpItemEntity.cs | 3,067 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("04.Text Filter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("04.Text Filter")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6ffd2d7c-d2c9-4bac-b2be-c708defea506")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.351351 | 84 | 0.7463 | [
"Apache-2.0"
] | Gab42/C-sharp-Advanced | C_Sharp_Adv_Homework4/04.Text Filter/Properties/AssemblyInfo.cs | 1,422 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Ship_Game.Ships;
namespace Ship_Game
{
/// <summary>
/// This contains multiple simple yet useful extension algorithms for different data structures
/// The goal is to increase performance by specializing for concrete container types,
/// which helps to eliminate virtual dispatch, greatly speeding up iteration times
///
/// As much as possible, we try to avoid any kind of IEnumerable or foreach loops, because
/// they have appalling performance and .NET JIT fails to optimize most of our use cases.
///
/// We don't benefit from lazy evaluation either, because most of the algorithms are very data-heavy,
/// with no way to exclude elements.
///
/// If you find these extensions repetitive, then yes, this is your worst nightmare --- however,
/// all of this repetitive looping provides the best possible performance on .NET JIT. It's just not good enough.
/// </summary>
public static class CollectionFindClosestTo
{
public static Ship FindClosestTo(this Array<Ship> ships, Planet toPlanet)
{
return FindClosestTo(ships.GetInternalArrayItems(), ships.Count, toPlanet.Center);
}
public static Ship FindClosestTo(this Ship[] ships, Planet toPlanet)
{
return FindClosestTo(ships, ships.Length, toPlanet.Center);
}
public static Ship FindClosestTo(this Ship[] ships, int count, Planet toPlanet)
{
return FindClosestTo(ships, count, toPlanet.Center);
}
public static Ship FindClosestTo(this Ship[] ships, int count, Vector2 to)
{
if (count <= 0)
return null;
Ship found = ships[0];
float min = to.SqDist(found.Center);
for (int i = 1; i < count; ++i)
{
Ship ship = ships[i];
float distance = to.SqDist(ship.Center);
if (distance < min)
{
min = distance;
found = ship;
}
}
return found;
}
public static Planet FindClosestTo(this Array<Planet> planets, Planet toPlanet)
{
return FindClosestTo(planets.GetInternalArrayItems(), planets.Count, toPlanet.Center);
}
public static Planet FindClosestTo(this Planet[] planets, Planet toPlanet)
{
return FindClosestTo(planets, planets.Length, toPlanet.Center);
}
public static Planet FindClosestTo(this Planet[] planets, int count, Planet toPlanet)
{
return FindClosestTo(planets, count, toPlanet.Center);
}
public static Planet FindClosestTo(this Planet[] planets, Ship toShip)
{
return FindClosestTo(planets, planets.Length, toShip.Center);
}
public static Planet FindClosestTo(this Array<Planet> planets, Ship toShip)
{
return FindClosestTo(planets.ToArray(), planets.Count, toShip.Center);
}
public static Planet FindClosestTo(this Planet[] planets, int count, Vector2 to)
{
if (count <= 0)
return null;
Planet found = planets[0];
float min = to.SqDist(found.Center);
for (int i = 1; i < count; ++i)
{
Planet ship = planets[i];
float distance = to.SqDist(ship.Center);
if (distance < min)
{
min = distance;
found = ship;
}
}
return found;
}
public static Ship FindClosestTo(this Ship[] ships, Planet to, Predicate<Ship> filter)
{
return FindClosestTo(ships, ships.Length, to.Center, filter);
}
public static Ship FindClosestTo(this Array<Ship> ships, Planet to, Predicate<Ship> filter)
{
return FindClosestTo(ships.GetInternalArrayItems(), ships.Count, to.Center, filter);
}
public static Ship FindClosestTo(this Ship[] ships, int count, Planet toPlanet, Predicate<Ship> filter)
{
return FindClosestTo(ships, count, toPlanet.Center, filter);
}
public static Ship FindClosestTo(this Ship[] ships, int count, Vector2 to, Predicate<Ship> filter)
{
if (count <= 0 || !ships.FindFirstValid(count, filter, out int i, out Ship found))
return null; // no elements passed the filter!
float min = to.SqDist(found.Center);
for (; i < count; ++i)
{
Ship ship = ships[i];
if (filter(ship))
{
float value = to.SqDist(ship.Center);
if (value < min)
{
min = value;
found = ship;
}
}
}
return found;
}
public static SolarSystem FindClosestTo(this Array<SolarSystem> systems, SolarSystem toPlanet)
{
return FindClosestTo(systems.GetInternalArrayItems(), systems.Count, toPlanet.Position);
}
public static SolarSystem FindClosestTo(this SolarSystem[] systems, SolarSystem toPlanet)
{
return FindClosestTo(systems, systems.Length, toPlanet.Position);
}
public static SolarSystem FindClosestTo(this SolarSystem[] systems, int count, SolarSystem toPlanet)
{
return FindClosestTo(systems, count, toPlanet.Position);
}
public static SolarSystem FindClosestTo(this SolarSystem[] systems, Ship toShip)
{
return FindClosestTo(systems, systems.Length, toShip.Center);
}
public static SolarSystem FindClosestTo(this Array<SolarSystem> systems, Ship toShip)
{
return FindClosestTo(systems.ToArray(), systems.Count, toShip.Center);
}
public static SolarSystem FindClosestTo(this Array<SolarSystem> systems, Vector2 position)
{
return FindClosestTo(systems.ToArray(), systems.Count, position);
}
public static SolarSystem FindClosestTo(this SolarSystem[] systems, int count, Vector2 to)
{
if (count <= 0)
return null;
SolarSystem found = systems[0];
float min = to.SqDist(found.Position);
for (int i = 1; i < count; ++i)
{
SolarSystem target = systems[i];
float distance = to.SqDist(target.Position);
if (distance < min)
{
min = distance;
found = target;
}
}
return found;
}
}
}
| 36.755102 | 118 | 0.554137 | [
"MIT"
] | UnGaucho/StarDrive | Ship_Game/ExtensionMethods/CollectionFindClosestTo.cs | 7,206 | C# |
namespace CafeLib.Cryptography.BouncyCastle.Asn1
{
public class BerSequence
: DerSequence
{
public static new readonly BerSequence Empty = new BerSequence();
public static new BerSequence FromVector(
Asn1EncodableVector v)
{
return v.Count < 1 ? Empty : new BerSequence(v);
}
/**
* create an empty sequence
*/
public BerSequence()
{
}
/**
* create a sequence containing one object
*/
public BerSequence(
Asn1Encodable obj)
: base(obj)
{
}
public BerSequence(
params Asn1Encodable[] v)
: base(v)
{
}
/**
* create a sequence containing a vector of objects.
*/
public BerSequence(
Asn1EncodableVector v)
: base(v)
{
}
/*
*/
internal override void Encode(
DerOutputStream derOut)
{
if (derOut is Asn1OutputStream || derOut is BerOutputStream)
{
derOut.WriteByte(Asn1Tags.Sequence | Asn1Tags.Constructed);
derOut.WriteByte(0x80);
foreach (Asn1Encodable o in this)
{
derOut.WriteObject(o);
}
derOut.WriteByte(0x00);
derOut.WriteByte(0x00);
}
else
{
base.Encode(derOut);
}
}
}
}
| 16.2 | 67 | 0.638448 | [
"MIT"
] | chrissolutions/CafeLib | Cryptography/CafeLib.Cryptography.BouncyCastle/Asn1/BerSequence.cs | 1,134 | C# |
using UnityEngine;
using System.Collections;
using MalbersAnimations.Scriptables;
#if UNITY_EDITOR
using UnityEditorInternal;
using UnityEditor;
#endif
namespace MalbersAnimations.Utilities
{
[AddComponentMenu("Malbers/Events/Messages")]
public class Messages : MonoBehaviour
{
public MesssageItem[] messages; //Store messages to send it when Enter the animation State
public bool UseSendMessage = true;
public bool SendToChildren = true;
public bool debug = true;
public bool nextFrame = false;
public Component Pinned;
/// <summary> Send all the messages to a gameobject </summary>
public virtual void SendMessage(GameObject component) => SendMessage(component.transform);
/// <summary> Store the Receiver of the messages</summary>
public virtual void Pin_Receiver(GameObject component) => Pinned = component.transform;
/// <summary> Store the Receiver of the messages</summary>
public virtual void Pin_Receiver(Component component) => Pinned = component;
/// <summary>Send a message by its index to the stored receiver</summary>
public virtual void SendMessage(int index)
{
if (nextFrame)
this.Delay_Action(() => Deliver(messages[index], Pinned));
else
Deliver(messages[index], Pinned);
}
public virtual void SendMessageByIndex(int index) => SendMessage(index);
public virtual void SendMessage(Component go)
{
Pinned = go;
foreach (var m in messages)
{
if (nextFrame)
this.Delay_Action(() => Deliver(m, Pinned));
else
Deliver(m, Pinned);
}
}
private void Deliver(MesssageItem m, Component go)
{
if (UseSendMessage)
m.DeliverMessage(go, SendToChildren, debug);
else
{
IAnimatorListener[] listeners;
if (SendToChildren)
listeners = go.GetComponentsInChildren<IAnimatorListener>();
else
listeners = go.GetComponents<IAnimatorListener>();
if (listeners != null && listeners.Length > 0)
{
foreach (var animListeners in listeners)
m.DeliverAnimListener(animListeners,debug);
}
}
}
//#if UNITY_EDITOR
// private void OnDrawGizmosSelected()
// {
// DrawInteration(true);
// }
// private void OnDrawGizmos()
// {
// DrawInteration(false);
// }
// private void DrawInteration(bool Selected)
// {
// foreach (var msg in messages)
// {
// Transform t = null;
// if (msg.typeM == TypeMessage.Transform && !msg.transformValue.gameObject.IsPrefab()) t = msg.transformValue;
// else if (msg.typeM == TypeMessage.Component && !msg.ComponentValue.gameObject.IsPrefab()) t = msg.ComponentValue.transform;
// else if (msg.typeM == TypeMessage.GameObject && !msg.GoValue.IsPrefab()) t = msg.GoValue.transform;
// if (t) MalbersEditor.DrawInteraction(transform.position, t.position, Selected, Color.white);
// }
// }
//#endif
}
[System.Serializable]
public class MesssageItem
{
public string message;
public TypeMessage typeM;
public bool boolValue;
public int intValue;
public float floatValue;
public string stringValue;
public IntVar intVarValue;
public Transform transformValue;
public GameObject GoValue;
public Component ComponentValue;
public float time;
public bool sent;
public bool Active = true;
public MesssageItem()
{
message = string.Empty;
Active = true;
}
public bool IsActive => Active && !string.IsNullOrEmpty(message);
public void DeliverAnimListener(IAnimatorListener listener, bool debug = false)
{
if (!IsActive) return; //Mean the Message cannot be sent
string val = "";
bool succesful = false;
switch (typeM)
{
case TypeMessage.Bool:
succesful = listener.OnAnimatorBehaviourMessage(message, boolValue);
val = boolValue.ToString();
break;
case TypeMessage.Int:
succesful = listener.OnAnimatorBehaviourMessage(message, intValue);
val = intValue.ToString();
break;
case TypeMessage.Float:
succesful = listener.OnAnimatorBehaviourMessage(message, floatValue);
val = floatValue.ToString();
break;
case TypeMessage.String:
succesful = listener.OnAnimatorBehaviourMessage(message, stringValue);
val = stringValue.ToString();
break;
case TypeMessage.Void:
succesful = listener.OnAnimatorBehaviourMessage(message, null);
val = "Void";
break;
case TypeMessage.IntVar:
succesful = listener.OnAnimatorBehaviourMessage(message, (int)intVarValue);
val = intVarValue.name.ToString();
break;
case TypeMessage.Transform:
succesful = listener.OnAnimatorBehaviourMessage(message, transformValue);
val = transformValue.name.ToString();
break;
case TypeMessage.GameObject:
succesful = listener.OnAnimatorBehaviourMessage(message, GoValue);
val = GoValue.name.ToString();
break;
case TypeMessage.Component:
succesful = listener.OnAnimatorBehaviourMessage(message, ComponentValue);
val = GoValue.name.ToString();
break;
default:
break;
}
if (debug && succesful) Debug.Log($"<b>[AnimMsg: {message}->{val}] [{typeM}]</b> T:{Time.time:F3}"); //Debug
}
/// <summary> Using Message to the Monovehaviours asociated to this animator delivery with Send Message </summary>
public void DeliverMessage(Component anim, bool SendToChildren, bool debug = false)
{
if (!IsActive) return; //Mean the Message cannot be sent
switch (typeM)
{
case TypeMessage.Bool:
SendMessage(anim, message, boolValue, SendToChildren);
break;
case TypeMessage.Int:
SendMessage(anim, message, intValue, SendToChildren);
break;
case TypeMessage.Float:
SendMessage(anim, message, floatValue, SendToChildren);
break;
case TypeMessage.String:
SendMessage(anim, message, stringValue, SendToChildren);
break;
case TypeMessage.Void:
SendMessageVoid(anim, message, SendToChildren);
break;
case TypeMessage.IntVar:
SendMessage(anim, message, (int)intVarValue, SendToChildren);
break;
case TypeMessage.Transform:
SendMessage(anim, message, transformValue, SendToChildren);
break;
case TypeMessage.GameObject:
SendMessage(anim, message, GoValue, SendToChildren);
break;
case TypeMessage.Component:
SendMessage(anim, message, ComponentValue, SendToChildren);
break;
default:
break;
}
if (debug) Debug.Log($"<b>[Send Msg: {message}->] [{typeM}]</b> T:{Time.time:F3}", anim); //Debug
}
private void SendMessage(Component anim, string message, object value, bool SendToChildren)
{
if (SendToChildren)
anim.BroadcastMessage(message, value, SendMessageOptions.DontRequireReceiver);
else
anim.SendMessage(message, value, SendMessageOptions.DontRequireReceiver);
}
private void SendMessageVoid(Component anim, string message, bool SendToChildren)
{
if (SendToChildren)
anim.BroadcastMessage(message, SendMessageOptions.DontRequireReceiver);
else
anim.SendMessage(message, SendMessageOptions.DontRequireReceiver);
}
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(MesssageItem))]
public class MessageDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
// position.y += 2;
EditorGUI.BeginProperty(position, label, property);
//GUI.Box(position, GUIContent.none, EditorStyles.helpBox);
var indent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
//var height = EditorGUIUtility.singleLineHeight;
//PROPERTIES
var Active = property.FindPropertyRelative("Active");
var message = property.FindPropertyRelative("message");
var typeM = property.FindPropertyRelative("typeM");
var rect = new Rect(position);
rect.y += 2;
Rect R_0 = new Rect(rect.x, rect.y, 15, EditorGUIUtility.singleLineHeight);
EditorGUI.PropertyField(R_0, Active, GUIContent.none);
Rect R_1 = new Rect(rect.x + 15, rect.y, (rect.width / 3) + 15, EditorGUIUtility.singleLineHeight);
EditorGUI.PropertyField(R_1, message, GUIContent.none);
Rect R_3 = new Rect(rect.x + ((rect.width) / 3) + 5 + 30, rect.y, ((rect.width) / 3) - 5 - 15, EditorGUIUtility.singleLineHeight);
EditorGUI.PropertyField(R_3, typeM, GUIContent.none);
Rect R_5 = new Rect(rect.x + ((rect.width) / 3) * 2 + 5 + 15, rect.y, ((rect.width) / 3) - 5 - 15, EditorGUIUtility.singleLineHeight);
var TypeM = (TypeMessage)typeM.intValue;
SerializedProperty messageValue = property.FindPropertyRelative("boolValue");
switch (TypeM)
{
case TypeMessage.Bool:
messageValue.boolValue = EditorGUI.ToggleLeft(R_5, messageValue.boolValue ? " True" : " False", messageValue.boolValue);
break;
case TypeMessage.Int:
messageValue = property.FindPropertyRelative("intValue");
break;
case TypeMessage.Float:
messageValue = property.FindPropertyRelative("floatValue");
break;
case TypeMessage.String:
messageValue = property.FindPropertyRelative("stringValue");
break;
case TypeMessage.IntVar:
messageValue = property.FindPropertyRelative("intVarValue");
break;
case TypeMessage.Transform:
messageValue = property.FindPropertyRelative("transformValue");
break;
case TypeMessage.Void:
break;
case TypeMessage.GameObject:
messageValue = property.FindPropertyRelative("GoValue");
break;
case TypeMessage.Component:
messageValue = property.FindPropertyRelative("ComponentValue");
break;
default:
break;
}
if (TypeM != TypeMessage.Void && TypeM != TypeMessage.Bool)
{
EditorGUI.PropertyField(R_5, messageValue, GUIContent.none);
}
EditorGUI.indentLevel = indent;
EditorGUI.EndProperty();
}
}
//INSPECTOR
[CustomEditor(typeof(Messages))]
public class MessagesEd : Editor
{
private ReorderableList list;
// private Messages MMessage;
private SerializedProperty sp_messages, debug, nextFrame, SendToChildren, UseSendMessage;
private void OnEnable()
{
sp_messages = serializedObject.FindProperty("messages");
debug = serializedObject.FindProperty("debug");
SendToChildren = serializedObject.FindProperty("SendToChildren");
UseSendMessage = serializedObject.FindProperty("UseSendMessage");
nextFrame = serializedObject.FindProperty("nextFrame");
list = new ReorderableList(serializedObject, sp_messages, true, true, true, true)
{
drawHeaderCallback = HeaderCallbackDelegate1,
drawElementCallback = ( rect, index, isActive, isFocused) =>
{
EditorGUI.PropertyField(rect, sp_messages.GetArrayElementAtIndex(index), GUIContent.none);
}
};
}
public override void OnInspectorGUI()
{
serializedObject.Update();
MalbersEditor.DrawDescription("Send messages to scripts with the [IAnimatorListener] interface. " +
"Enable [SendMessage] to use Component.SendMessage() instead.");
EditorGUILayout.BeginVertical(MTools.StyleGray);
{
list.DoLayoutList();
EditorGUILayout.BeginHorizontal();
var currentGUIColor = GUI.color;
GUI.color = SendToChildren.boolValue ? (Color.green) : currentGUIColor;
SendToChildren.boolValue = GUILayout.Toggle(SendToChildren.boolValue,
new GUIContent("Children", "The Messages will be sent also to the gameobject children"), EditorStyles.miniButton);
GUI.color = UseSendMessage.boolValue ? (Color.green) : currentGUIColor;
UseSendMessage.boolValue = GUILayout.Toggle(UseSendMessage.boolValue,
new GUIContent("SendMessage()", "Uses the SendMessage() method, instead of checking for IAnimator Listener Interfaces"), EditorStyles.miniButton);
GUI.color = currentGUIColor;
if (nextFrame != null)
{
GUI.color = nextFrame.boolValue ? (Color.green) : currentGUIColor;
nextFrame.boolValue = GUILayout.Toggle(nextFrame.boolValue,
new GUIContent("Next Frame", "Waits for the next frame to send the messages"), EditorStyles.miniButton);
GUI.color = currentGUIColor;
}
MalbersEditor.DrawDebugIcon(debug);
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndVertical();
serializedObject.ApplyModifiedProperties();
}
static void HeaderCallbackDelegate1(Rect rect)
{
var width = (rect.width / 3);
var height = EditorGUIUtility.singleLineHeight;
Rect R_1 = new Rect(rect.x + 10, rect.y, width + 30, height);
EditorGUI.LabelField(R_1, "Message");
Rect R_3 = new Rect(rect.x + 10 + width + 5 + 30, rect.y, width - 20, height);
EditorGUI.LabelField(R_3, "Type");
Rect R_5 = new Rect(rect.x + 10 + width * 2 + 20, rect.y, width - 20, height);
EditorGUI.LabelField(R_5, "Value");
}
}
#endif
} | 38.116667 | 166 | 0.559748 | [
"MIT"
] | alfonsoquartny/Sherlocked | The Sherlocked/Assets/Malbers Animations/Common/Scripts/Events/Messages.cs | 16,011 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwitchComponent : MonoBehaviour
{
public GameObject component;
public Sprite newSprite;
public bool HasToCut;
private SpriteRenderer spriteRenderer;
private AudioSource sound;
private bool hasSwitchedState = false;
private void Start()
{
spriteRenderer = GetComponent<SpriteRenderer>();
sound = GetComponent<AudioSource>();
}
private void SwitchState()
{
if (!hasSwitchedState)
{
sound.Play();
component.SetActive(false);
spriteRenderer.sprite = newSprite;
hasSwitchedState = true;
}
}
private void PlayerCut(Collider2D other)
{
if (other.gameObject.CompareTag("Player"))
{
if (!HasToCut)
{
SwitchState();
return;
}
var animation = other.gameObject.GetComponent<Animator>().GetCurrentAnimatorStateInfo(0);
if (animation.IsName("PlayerAttackKnife"))
{
SwitchState();
}
}
}
private void OnTriggerEnter2D(Collider2D other)
{
PlayerCut(other);
}
private void OnTriggerStay2D(Collider2D other)
{
PlayerCut(other);
}
}
| 22.031746 | 101 | 0.569885 | [
"Apache-2.0"
] | gaziduc/catch-me-if-you-can | Assets/Scripts/UI/SwitchComponent.cs | 1,388 | C# |
/* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Runtime.Serialization;
using OpenSearch.Net;
namespace OpenSearch.Client
{
[StringEnum]
public enum DateMathTimeUnit
{
[EnumMember(Value = "s")]
Second,
[EnumMember(Value = "m")]
Minute,
[EnumMember(Value = "h")]
Hour,
[EnumMember(Value = "d")]
Day,
[EnumMember(Value = "w")]
Week,
[EnumMember(Value = "M")]
Month,
[EnumMember(Value = "y")]
Year
}
public static class DateMathTimeUnitExtensions
{
public static string GetStringValue(this DateMathTimeUnit value)
{
switch (value)
{
case DateMathTimeUnit.Second:
return "s";
case DateMathTimeUnit.Minute:
return "m";
case DateMathTimeUnit.Hour:
return "h";
case DateMathTimeUnit.Day:
return "d";
case DateMathTimeUnit.Week:
return "w";
case DateMathTimeUnit.Month:
return "M";
case DateMathTimeUnit.Year:
return "y";
default:
throw new ArgumentOutOfRangeException(nameof(value), value, null);
}
}
}
}
| 24.458824 | 71 | 0.712362 | [
"Apache-2.0"
] | opensearch-project/opensearch-net | src/OpenSearch.Client/CommonOptions/DateMath/DateMathTimeUnit.cs | 2,079 | C# |
// <auto-generated />
using System;
using System.Reflection;
using System.Resources;
using System.Threading;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging;
namespace Microsoft.EntityFrameworkCore.InMemory.Internal
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public static class InMemoryStrings
{
private static readonly ResourceManager _resourceManager
= new ResourceManager("Microsoft.EntityFrameworkCore.InMemory.Properties.InMemoryStrings", typeof(InMemoryStrings).Assembly);
/// <summary>
/// Cannot apply DefaultIfEmpty after a client-evaluated projection.
/// </summary>
public static string DefaultIfEmptyAppliedAfterProjection
=> GetString("DefaultIfEmptyAppliedAfterProjection");
/// <summary>
/// 'UpdateEntityType' called with '{derivedType}' which is not derived type of '{entityType}'.
/// </summary>
public static string InvalidDerivedTypeInEntityProjection([CanBeNull] object derivedType, [CanBeNull] object entityType)
=> string.Format(
GetString("InvalidDerivedTypeInEntityProjection", nameof(derivedType), nameof(entityType)),
derivedType, entityType);
/// <summary>
/// Invalid {state} encountered.
/// </summary>
public static string InvalidStateEncountered([CanBeNull] object state)
=> string.Format(
GetString("InvalidStateEncountered", nameof(state)),
state);
/// <summary>
/// There is no query string because the in-memory provider does not use a string-based query language.
/// </summary>
public static string NoQueryStrings
=> GetString("NoQueryStrings");
/// <summary>
/// Unable to bind '{memberType}' '{member}' to entity projection of '{entityType}'.
/// </summary>
public static string UnableToBindMemberToEntityProjection([CanBeNull] object memberType, [CanBeNull] object member, [CanBeNull] object entityType)
=> string.Format(
GetString("UnableToBindMemberToEntityProjection", nameof(memberType), nameof(member), nameof(entityType)),
memberType, member, entityType);
/// <summary>
/// Attempted to update or delete an entity that does not exist in the store.
/// </summary>
public static string UpdateConcurrencyException
=> GetString("UpdateConcurrencyException");
/// <summary>
/// Conflicts were detected for instance of entity type '{entityType}' on the concurrency token properties {properties}. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting values.
/// </summary>
public static string UpdateConcurrencyTokenException([CanBeNull] object entityType, [CanBeNull] object properties)
=> string.Format(
GetString("UpdateConcurrencyTokenException", nameof(entityType), nameof(properties)),
entityType, properties);
/// <summary>
/// Conflicts were detected for instance of entity type '{entityType}' with the key value '{keyValue}' on the concurrency token property values {conflictingValues}, with corresponding database values {databaseValues}.
/// </summary>
public static string UpdateConcurrencyTokenExceptionSensitive([CanBeNull] object entityType, [CanBeNull] object keyValue, [CanBeNull] object conflictingValues, [CanBeNull] object databaseValues)
=> string.Format(
GetString("UpdateConcurrencyTokenExceptionSensitive", nameof(entityType), nameof(keyValue), nameof(conflictingValues), nameof(databaseValues)),
entityType, keyValue, conflictingValues, databaseValues);
private static string GetString(string name, params string[] formatterNames)
{
var value = _resourceManager.GetString(name);
for (var i = 0; i < formatterNames.Length; i++)
{
value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}");
}
return value;
}
}
}
namespace Microsoft.EntityFrameworkCore.InMemory.Internal
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public static class InMemoryResources
{
private static readonly ResourceManager _resourceManager
= new ResourceManager("Microsoft.EntityFrameworkCore.InMemory.Properties.InMemoryStrings", typeof(InMemoryResources).Assembly);
/// <summary>
/// Saved {count} entities to in-memory store.
/// </summary>
public static EventDefinition<int> LogSavedChanges([NotNull] IDiagnosticsLogger logger)
{
var definition = ((Diagnostics.Internal.InMemoryLoggingDefinitions)logger.Definitions).LogSavedChanges;
if (definition == null)
{
definition = LazyInitializer.EnsureInitialized<EventDefinitionBase>(
ref ((Diagnostics.Internal.InMemoryLoggingDefinitions)logger.Definitions).LogSavedChanges,
() => new EventDefinition<int>(
logger.Options,
InMemoryEventId.ChangesSaved,
LogLevel.Information,
"InMemoryEventId.ChangesSaved",
level => LoggerMessage.Define<int>(
level,
InMemoryEventId.ChangesSaved,
_resourceManager.GetString("LogSavedChanges"))));
}
return (EventDefinition<int>)definition;
}
/// <summary>
/// Transactions are not supported by the in-memory store. See http://go.microsoft.com/fwlink/?LinkId=800142
/// </summary>
public static EventDefinition LogTransactionsNotSupported([NotNull] IDiagnosticsLogger logger)
{
var definition = ((Diagnostics.Internal.InMemoryLoggingDefinitions)logger.Definitions).LogTransactionsNotSupported;
if (definition == null)
{
definition = LazyInitializer.EnsureInitialized<EventDefinitionBase>(
ref ((Diagnostics.Internal.InMemoryLoggingDefinitions)logger.Definitions).LogTransactionsNotSupported,
() => new EventDefinition(
logger.Options,
InMemoryEventId.TransactionIgnoredWarning,
LogLevel.Warning,
"InMemoryEventId.TransactionIgnoredWarning",
level => LoggerMessage.Define(
level,
InMemoryEventId.TransactionIgnoredWarning,
_resourceManager.GetString("LogTransactionsNotSupported"))));
}
return (EventDefinition)definition;
}
}
}
| 50.248408 | 231 | 0.640639 | [
"Apache-2.0"
] | 0b01/efcore | src/EFCore.InMemory/Properties/InMemoryStrings.Designer.cs | 7,889 | C# |
//-----------------------------------------------------------------------
// <copyright file="ManyRecoveriesSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Linq;
using Akka.Actor;
using Akka.Configuration;
using Akka.TestKit;
using Akka.TestKit.TestActors;
using Akka.Util.Internal;
using FluentAssertions;
using Xunit;
namespace Akka.Persistence.Tests
{
public class ManyRecoveriesSpec : PersistenceSpec
{
public class TestPersistentActor : UntypedPersistentActor
{
public override string PersistenceId { get; }
public TestLatch Latch { get; }
public static Props Props(string name, TestLatch latch) =>
Actor.Props.Create(() => new TestPersistentActor(name, latch));
public TestPersistentActor(string name, TestLatch latch)
{
PersistenceId = name;
Latch = latch;
}
protected override void OnRecover(object message)
{
if (message is Evt)
{
Latch?.Ready(TimeSpan.FromSeconds(10));
}
}
protected override void OnCommand(object message)
{
if (message is Cmd cmd)
{
Persist(new Evt(cmd.Data), _ =>
{
Sender.Tell($"{PersistenceId}-{cmd.Data}-{LastSequenceNr}", Self);
});
}
else if (message is "stop")
{
Context.Stop(Self);
}
}
}
public ManyRecoveriesSpec() : base(ConfigurationFactory.ParseString(@"
akka.actor.default-dispatcher.Type = ForkJoinDispatcher
akka.actor.default-dispatcher.dedicated-thread-pool.thread-count = 5
akka.persistence.max-concurrent-recoveries = 3
akka.persistence.journal.plugin = ""akka.persistence.journal.inmem""
# snapshot store plugin is NOT defined, things should still work
akka.persistence.snapshot-store.plugin = ""akka.persistence.no-snapshot-store""
akka.persistence.snapshot-store.local.dir = ""target/snapshots-" + typeof(ManyRecoveriesSpec).FullName + "/"))
{
}
[Fact]
public void Many_persistent_actors_must_be_able_to_recover_without_overloading()
{
Enumerable.Range(1, 100).ForEach(n =>
{
Sys.ActorOf(TestPersistentActor.Props($"a{n}", null)).Tell(new Cmd("A"));
ExpectMsg($"a{n}-A-1");
});
// This would starve (block) all threads without max-concurrent-recoveries
var latch = new TestLatch();
Enumerable.Range(1, 100).ForEach(n =>
{
Sys.ActorOf(TestPersistentActor.Props($"a{n}", latch)).Tell(new Cmd("B"));
});
// This should be able to progress even though above is blocking, 2 remaining non-blocked threads
Enumerable.Range(1, 10).ForEach(n =>
{
Sys.ActorOf(EchoActor.Props(this)).Tell(n);
ExpectMsg(n);
});
latch.CountDown();
ReceiveN(100).ShouldAllBeEquivalentTo(Enumerable.Range(1, 100).Select(n => $"a{n}-B-2"));
}
}
}
| 36.31 | 122 | 0.536216 | [
"Apache-2.0"
] | Flubik/akka.net | src/core/Akka.Persistence.Tests/ManyRecoveriesSpec.cs | 3,633 | C# |
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Models;
using Services;
using Services.Interfaces;
namespace FinalProject.Controllers
{
[Route("Api/[controller]")]
public class ClienteController : ControllerBase
{
private readonly ICrudService<Cliente> ClienteServices;
public ClienteController(ICrudService<Cliente> crudService)
{
ClienteServices = crudService;
}
[HttpPost]
public IActionResult Create([FromBody] Cliente model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
ClienteServices.Add(model);
return Ok();
}
[HttpDelete]
[Route("{id}")]
public IActionResult Delete(int id)
{
var result = ClienteServices.Delete(id);
if (result) return NoContent();
return BadRequest("no existe el empleado");
}
[HttpPut]
public IActionResult Update([FromBody] Cliente model)
{
if (!ModelState.IsValid)
{
return BadRequest("no se actualizo");
}
ClienteServices.Add(model);
return Ok();
}
[HttpGet]
[Route("{id}")]
public IActionResult GetById(int id)
{
var result = ClienteServices.Get(id);
return Ok(result);
}
[HttpGet]
public IActionResult GetAll()
{
var result = ClienteServices.GetAll();
return Ok(result);
}
}
}
| 24.911765 | 67 | 0.551358 | [
"MIT"
] | carlosdz4/ApiTaller | FinalProject/FinalProject/Controllers/ClienteController.cs | 1,696 | C# |
using System;
namespace ExRandom.Continuous {
public class InverseGaussRandom : Random {
readonly MT19937 mt;
readonly NormalRandom nd;
readonly double mu, lambda;
public InverseGaussRandom(MT19937 mt, double lambda = 1, double mu = 1) {
if (mt is null) {
throw new ArgumentNullException(nameof(mt));
}
if (!(mu > 0)) {
throw new ArgumentOutOfRangeException(nameof(mu));
}
if (!(lambda > 0)) {
throw new ArgumentOutOfRangeException(nameof(lambda));
}
this.mt = mt;
this.nd = new NormalRandom(mt);
this.mu = mu;
this.lambda = lambda;
}
public override double Next() {
double x, y, z, w;
x = nd.Next();
y = x * x * mu;
z = mt.NextDouble();
w = mu - (0.5 * mu / lambda) * (Math.Sqrt(y * (y + 4.0 * lambda)) - y);
return (z < (mu / (mu + w))) ? w : (mu * mu / w);
}
}
}
| 28.342105 | 83 | 0.467967 | [
"MIT"
] | tk-yoshimura/ExRandom | ExRandom/Continuous/InverseGaussRandom.cs | 1,079 | C# |
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.OData;
using Microsoft.Azure.Mobile.Server;
using XamarinBackendService.DataObjects;
using XamarinBackendService.Models;
using XamarinBackendService.Helpers;
namespace XamarinBackendService.Controllers
{
public class WeaponController : TableController<Weapon>
{
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
XamarinBackendContext context = new XamarinBackendContext();
DomainManager = new EntityDomainManager<Weapon>(context, Request);
}
// GET tables/Weapon
[QueryableExpand("Characters")]
public IQueryable<Weapon> GetAllWeapons()
{
return Query();
}
// GET tables/Weapon/48D68C86-6EA6-4C25-AA33-223FC9A27959
[QueryableExpand("Characters")]
public SingleResult<Weapon> GetWeapon(string id)
{
return Lookup(id);
}
// PATCH tables/Weapon/48D68C86-6EA6-4C25-AA33-223FC9A27959
//public Task<Weapon> PatchWeapon(string id, Delta<Weapon> patch)
//{
// return UpdateAsync(id, patch);
//}
// POST tables/Weapon
//public async Task<IHttpActionResult> PostWeapon(Weapon item)
//{
// Weapon current = await InsertAsync(item);
// return CreatedAtRoute("Tables", new { id = current.Id }, current);
//}
// DELETE tables/Weapon/48D68C86-6EA6-4C25-AA33-223FC9A27959
//public Task DeleteWeapon(string id)
//{
// return DeleteAsync(id);
//}
}
} | 31.781818 | 83 | 0.642449 | [
"MIT"
] | Floris-Dox/xamarinA | Challenge 3/src/XamarinBackend/XamarinBackendService/Controllers/WeaponController.cs | 1,750 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System.Management.Automation;
using Microsoft.Azure.Management.DataFactory.Models;
namespace Microsoft.Azure.Commands.DataFactoryV2.Models
{
public class PSManagedIntegrationRuntime : PSIntegrationRuntime
{
public PSManagedIntegrationRuntime(
IntegrationRuntimeResource integrationRuntime,
string resourceGroupName,
string factoryName)
: base(integrationRuntime, resourceGroupName, factoryName)
{
if (IntegrationRuntime.Properties == null)
{
IntegrationRuntime.Properties = new ManagedIntegrationRuntime();
}
if (ManagedIntegrationRuntime == null)
{
throw new PSArgumentException("The resource is not a valid managed integration runtime.");
}
}
private ManagedIntegrationRuntime ManagedIntegrationRuntime => IntegrationRuntime.Properties as ManagedIntegrationRuntime;
public string Location => ManagedIntegrationRuntime.ComputeProperties?.Location;
public string NodeSize => ManagedIntegrationRuntime.ComputeProperties?.NodeSize;
public int? NodeCount => ManagedIntegrationRuntime.ComputeProperties?.NumberOfNodes;
public int? MaxParallelExecutionsPerNode => ManagedIntegrationRuntime.ComputeProperties?.MaxParallelExecutionsPerNode;
public string CatalogServerEndpoint => ManagedIntegrationRuntime.SsisProperties?.CatalogInfo?.CatalogServerEndpoint;
public string CatalogAdminUserName => ManagedIntegrationRuntime.SsisProperties?.CatalogInfo?.CatalogAdminUserName;
public string CatalogAdminPassword => ManagedIntegrationRuntime.SsisProperties?.CatalogInfo?.CatalogAdminPassword?.Value;
public string CatalogPricingTier => ManagedIntegrationRuntime.SsisProperties?.CatalogInfo?.CatalogPricingTier;
public string VNetId => ManagedIntegrationRuntime.ComputeProperties?.VNetProperties?.VNetId;
public string Subnet => ManagedIntegrationRuntime.ComputeProperties?.VNetProperties?.Subnet;
public string State => ManagedIntegrationRuntime.State;
public string LicenseType => ManagedIntegrationRuntime.SsisProperties?.LicenseType;
public string SetupScriptContainerSasUri => ManagedIntegrationRuntime.SsisProperties?.CustomSetupScriptProperties?.BlobContainerUri + ManagedIntegrationRuntime.SsisProperties?.CustomSetupScriptProperties?.SasToken?.Value;
public string Edition => ManagedIntegrationRuntime.SsisProperties?.Edition;
}
}
| 47.690141 | 230 | 0.702599 | [
"MIT"
] | Acidburn0zzz/azure-powershell | src/ResourceManager/DataFactoryV2/Commands.DataFactoryV2/Models/PSManagedIntegrationRuntime.cs | 3,318 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace SBTCustomerManager.Models.AccountViewModels
{
public class LoginWithRecoveryCodeViewModel
{
[Required]
[DataType(DataType.Text)]
[Display(Name = "Recovery Code")]
public string RecoveryCode { get; set; }
}
}
| 25.764706 | 54 | 0.666667 | [
"MIT"
] | seanpconkie/SBTCustomerManager | Models/AccountViewModels/LoginWithRecoveryCodeViewModel.cs | 440 | C# |
using System;
using System.Collections.Generic;
internal class C<TFirst>
{
internal struct VSlot<T>
{
public readonly T Value;
public VSlot (T value)
{
Value = value;
}
}
internal IEnumerable<V> GetEnumerable<V> (IEnumerable<VSlot<V>> input)
{
foreach (var v in input)
yield return v.Value;
}
}
class C
{
public static int Main ()
{
var c = new C<long> ();
string value = null;
foreach (var v in c.GetEnumerable (new[] { new C<long>.VSlot<string> ("foo") })) {
value = v;
}
if (value != "foo")
return 1;
return 0;
}
}
| 14.538462 | 84 | 0.620811 | [
"Apache-2.0"
] | 121468615/mono | mcs/tests/gtest-iter-15.cs | 567 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.Models;
namespace Azure.ResourceManager.CosmosDB.Models
{
/// <summary> Parameters to create and update Cosmos DB MongoDB collection. </summary>
public partial class MongoDBCollectionCreateUpdateData : TrackedResourceData
{
/// <summary> Initializes a new instance of MongoDBCollectionCreateUpdateData. </summary>
/// <param name="location"> The location. </param>
/// <param name="resource"> The standard JSON format of a MongoDB collection. </param>
/// <exception cref="ArgumentNullException"> <paramref name="resource"/> is null. </exception>
public MongoDBCollectionCreateUpdateData(AzureLocation location, MongoDBCollectionResource resource) : base(location)
{
if (resource == null)
{
throw new ArgumentNullException(nameof(resource));
}
Resource = resource;
}
/// <summary> Initializes a new instance of MongoDBCollectionCreateUpdateData. </summary>
/// <param name="id"> The id. </param>
/// <param name="name"> The name. </param>
/// <param name="type"> The type. </param>
/// <param name="systemData"> The systemData. </param>
/// <param name="tags"> The tags. </param>
/// <param name="location"> The location. </param>
/// <param name="resource"> The standard JSON format of a MongoDB collection. </param>
/// <param name="options"> A key-value pair of options to be applied for the request. This corresponds to the headers sent with the request. </param>
internal MongoDBCollectionCreateUpdateData(ResourceIdentifier id, string name, ResourceType type, SystemData systemData, IDictionary<string, string> tags, AzureLocation location, MongoDBCollectionResource resource, CreateUpdateOptions options) : base(id, name, type, systemData, tags, location)
{
Resource = resource;
Options = options;
}
/// <summary> The standard JSON format of a MongoDB collection. </summary>
public MongoDBCollectionResource Resource { get; set; }
/// <summary> A key-value pair of options to be applied for the request. This corresponds to the headers sent with the request. </summary>
public CreateUpdateOptions Options { get; set; }
}
}
| 48.188679 | 302 | 0.671887 | [
"MIT"
] | KurnakovMaksim/azure-sdk-for-net | sdk/cosmosdb/Azure.ResourceManager.CosmosDB/src/Generated/Models/MongoDBCollectionCreateUpdateData.cs | 2,554 | C# |
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
using Newtonsoft.Json;
namespace DSCore.Api
{
internal static class Utils
{
internal static bool CheckDatabase()
{
if (System.IO.File.Exists(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"FLData.db")))
return true;
return false;
}
internal static string GetDatabase()
{
return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"FLData.db");
}
internal static string ReturnJson(object obj, params Errors[] errors)
{
List<string> stringErrors = new List<string>();
foreach (var item in errors)
stringErrors.Add(item.ToString());
return JsonConvert.SerializeObject(new JsonWrapper() { Result = obj, Errors = stringErrors }, Formatting.Indented);
}
}
public enum Errors
{
DatabaseNotFound,
InvalidDatabaseStructure,
ValueNotFound,
Null
}
}
| 27.348837 | 131 | 0.628401 | [
"MIT"
] | Dannyps/DSCore | DSCore.Api/Utils.cs | 1,178 | C# |
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// Copyright (C) 2016-2017 Sebastian Grams <https://github.com/sebastian-dev>
// Copyright (C) 2016-2017 Aqua Computer <https://github.com/aquacomputer, info@aqua-computer.de>
using System.Collections.Generic;
namespace HardwareProviders.CPU.Ryzen
{
public class RyzenNumaNode
{
private readonly AmdCpu17 _cpu;
public RyzenNumaNode(AmdCpu17 cpu, int id)
{
Cores = new List<RyzenCore>();
NodeId = id;
_cpu = cpu;
}
public int NodeId { get; }
public List<RyzenCore> Cores { get; }
public void AppendThread(CpuId thread, int core_id)
{
RyzenCore ryzenCore = null;
foreach (var c in Cores)
if (c.CoreId == core_id)
ryzenCore = c;
if (ryzenCore == null)
{
ryzenCore = new RyzenCore(_cpu, core_id);
Cores.Add(ryzenCore);
}
if (thread != null)
ryzenCore.Threads.Add(thread);
}
#region UpdateSensors
public void UpdateSensors()
{
}
#endregion
}
} | 27.979592 | 98 | 0.560175 | [
"MPL-2.0"
] | Mjollnirs/HardwareProviders | HardwareProviders.CPU.Standard/Ryzen/RyzenNumaNode.cs | 1,373 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the iot-2015-05-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.IoT.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.IoT.Model.Internal.MarshallTransformations
{
/// <summary>
/// CloudwatchAlarmAction Marshaller
/// </summary>
public class CloudwatchAlarmActionMarshaller : IRequestMarshaller<CloudwatchAlarmAction, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(CloudwatchAlarmAction requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetAlarmName())
{
context.Writer.WritePropertyName("alarmName");
context.Writer.Write(requestObject.AlarmName);
}
if(requestObject.IsSetRoleArn())
{
context.Writer.WritePropertyName("roleArn");
context.Writer.Write(requestObject.RoleArn);
}
if(requestObject.IsSetStateReason())
{
context.Writer.WritePropertyName("stateReason");
context.Writer.Write(requestObject.StateReason);
}
if(requestObject.IsSetStateValue())
{
context.Writer.WritePropertyName("stateValue");
context.Writer.Write(requestObject.StateValue);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static CloudwatchAlarmActionMarshaller Instance = new CloudwatchAlarmActionMarshaller();
}
} | 33.25 | 116 | 0.656015 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/IoT/Generated/Model/Internal/MarshallTransformations/CloudwatchAlarmActionMarshaller.cs | 2,660 | C# |
// Copyright 2020 New Relic, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using System.Linq;
using NewRelic.Agent.IntegrationTestHelpers;
using NewRelic.Agent.IntegrationTestHelpers.Models;
using Xunit;
using Xunit.Abstractions;
namespace NewRelic.Agent.IntegrationTests.CSP
{
[NetCoreTest]
public class AspNetCoreLocalHSMDisabledAndServerSideHSMDisabledTests : NewRelicIntegrationTest<RemoteServiceFixtures.AspNetCoreMvcBasicRequestsFixture>
{
private const string QueryStringParameterValue = @"my thing";
private readonly RemoteServiceFixtures.AspNetCoreMvcBasicRequestsFixture _fixture;
public AspNetCoreLocalHSMDisabledAndServerSideHSMDisabledTests(RemoteServiceFixtures.AspNetCoreMvcBasicRequestsFixture fixture, ITestOutputHelper output)
: base(fixture)
{
_fixture = fixture;
_fixture.TestLogger = output;
_fixture.Actions
(
setupConfiguration: () =>
{
var configPath = fixture.DestinationNewRelicConfigFilePath;
var configModifier = new NewRelicConfigModifier(configPath);
configModifier.ForceTransactionTraces();
CommonUtils.ModifyOrCreateXmlAttributeInNewRelicConfig(configPath, new[] { "configuration", "log" }, "level", "debug");
CommonUtils.ModifyOrCreateXmlAttributeInNewRelicConfig(configPath, new[] { "configuration", "requestParameters" }, "enabled", "true");
CommonUtils.ModifyOrCreateXmlAttributeInNewRelicConfig(configPath, new[] { "configuration", "service" }, "ssl", "false");
CommonUtils.ModifyOrCreateXmlAttributeInNewRelicConfig(configPath, new[] { "configuration", "transactionTracer" }, "recordSql", "raw");
CommonUtils.ModifyOrCreateXmlAttributeInNewRelicConfig(configPath, new[] { "configuration", "highSecurity" }, "enabled", "false");
},
exerciseApplication: () => _fixture.GetWithData(QueryStringParameterValue)
);
_fixture.Initialize();
}
[Fact]
public void Test()
{
var expectedAttributes = new Dictionary<string, string>
{
{ "request.parameters.data", QueryStringParameterValue },
};
var transactionSample = _fixture.AgentLog.GetTransactionSamples().FirstOrDefault();
Assertions.TransactionTraceHasAttributes(expectedAttributes, TransactionTraceAttributeType.Agent, transactionSample);
}
}
}
| 45.101695 | 161 | 0.67531 | [
"Apache-2.0"
] | JoshuaColeman/newrelic-dotnet-agent | tests/Agent/IntegrationTests/IntegrationTests/CSP/AspNetCoreLocalHSMDisabledAndServerSideHSMDisabledTests.cs | 2,661 | C# |
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using Palmmedia.ReportGenerator.Core.Common;
using Palmmedia.ReportGenerator.Core.Properties;
namespace Palmmedia.ReportGenerator.Core.Parser.FileReading
{
/// <summary>
/// File reader with caching.
/// Local files are read from disk. Remote files get downloaded and cached for a given period of time.
/// </summary>
internal class CachingFileReader : IFileReader
{
/// <summary>
/// The HttpClient to retrieve remote files.
/// </summary>
private static readonly HttpClient HttpClient = new HttpClient();
/// <summary>
/// The caching duration of code files that are downloaded from remote servers in minutes.
/// </summary>
private readonly int cachingDuringOfRemoteFilesInMinutes;
/// <summary>
/// Initializes a new instance of the <see cref="CachingFileReader" /> class.
/// </summary>
/// <param name="cachingDuringOfRemoteFilesInMinutes">The caching duration of code files that are downloaded from remote servers in minutes.</param>
public CachingFileReader(int cachingDuringOfRemoteFilesInMinutes)
{
this.cachingDuringOfRemoteFilesInMinutes = cachingDuringOfRemoteFilesInMinutes;
}
/// <summary>
/// Loads the file with the given path.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="error">Error message if file reading failed, otherwise <code>null</code>.</param>
/// <returns><code>null</code> if an error occurs, otherwise the lines of the file.</returns>
public string[] LoadFile(string path, out string error)
{
try
{
if (path.StartsWith("http://") || path.StartsWith("https://"))
{
string cacheDirectory = Path.Combine(Path.GetTempPath(), "ReportGenerator_Cache");
// GetHashCode does not produce same hash on every run (See: https://andrewlock.net/why-is-string-gethashcode-different-each-time-i-run-my-program-in-net-core/)
string cachedFile = Path.Combine(cacheDirectory, GetSha1Hash(path) + ".txt");
try
{
if (!Directory.Exists(cacheDirectory))
{
Directory.CreateDirectory(cacheDirectory);
}
if (File.Exists(cachedFile)
&& File.GetLastWriteTime(cachedFile).AddMinutes(this.cachingDuringOfRemoteFilesInMinutes) > DateTime.Now)
{
error = null;
string[] cachedLines = File.ReadAllLines(cachedFile);
return cachedLines;
}
}
catch
{
// Ignore error, file gets downloaded in next step
}
string content = HttpClient.GetStringAsync(path).Result;
string[] lines = content.Split('\n').Select(l => l.TrimEnd('\r')).ToArray();
try
{
if (this.cachingDuringOfRemoteFilesInMinutes > 0)
{
File.WriteAllLines(cachedFile, lines);
}
}
catch
{
// Ignore error, caching is not important
}
error = null;
return lines;
}
else
{
if (!File.Exists(path))
{
error = string.Format(CultureInfo.InvariantCulture, " " + Resources.FileDoesNotExist, path);
return null;
}
string[] lines = File.ReadAllLines(path);
error = null;
return lines;
}
}
catch (Exception ex)
{
error = string.Format(CultureInfo.InvariantCulture, " " + Resources.ErrorDuringReadingFile, path, ex.GetExceptionMessageForDisplay());
return null;
}
}
private static string GetSha1Hash(string input)
{
return string.Concat(new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(input)).Select(x => x.ToString("x2")).ToArray());
}
}
}
| 39.425 | 180 | 0.523568 | [
"Apache-2.0"
] | SeppPenner/ReportGenerator | src/ReportGenerator.Core/Parser/FileReading/CachingFileReader.cs | 4,733 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Sc.Giphy")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Sc.Giphy")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5ce506ed-65cc-4da5-bd3d-0e2b76791cf7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.540541 | 84 | 0.742261 | [
"MIT"
] | GuitarRich/sitecore-live-blog | src/Sc.Giphy/Properties/AssemblyInfo.cs | 1,392 | C# |
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace H.ReactiveUI.Apps.Views;
public partial class MainView : Window
{
public MainView()
{
InitializeComponent();
#if DEBUG
this.AttachDevTools();
#endif
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
| 16.045455 | 38 | 0.671388 | [
"MIT"
] | HavenDV/H.ReactiveUI.CommonInteractions | src/apps/H.ReactiveUI.Apps.Avalonia/Views/MainView.axaml.cs | 353 | C# |
using System;
using System.Data;
using System.Data.SqlClient;
using lmDatasets;
namespace atriumDAL
{
/// <summary>
/// Class generated by sgen
/// based on ADMSPAppeal table
/// in atrium database
/// on 11/26/2012
/// </summary>
public partial class ADMSPAppealDAL:atDAL.ObjectDAL
{
internal ADMSPAppealDAL(atriumDALManager pDALManager) :base(pDALManager)
{
Init();
}
private void Init()
{
this.sqlDa.TableMappings.AddRange(new System.Data.Common.DataTableMapping[] {
new System.Data.Common.DataTableMapping("Table", "ADMSPAppeal", new System.Data.Common.DataColumnMapping[] {
new System.Data.Common.DataColumnMapping("Id", "Id"),
new System.Data.Common.DataColumnMapping("SSTFileNumber", "SSTFileNumber"),
new System.Data.Common.DataColumnMapping("AppealLevelId", "AppealLevelId"),
new System.Data.Common.DataColumnMapping("AtriumUser", "AtriumUser"),
new System.Data.Common.DataColumnMapping("AppealLevelDate", "AppealLevelDate"),
new System.Data.Common.DataColumnMapping("ClientId", "ClientId"),
new System.Data.Common.DataColumnMapping("FirstName", "FirstName"),
new System.Data.Common.DataColumnMapping("LastName", "LastName"),
new System.Data.Common.DataColumnMapping("IdentifierNumber", "IdentifierNumber"),
new System.Data.Common.DataColumnMapping("TransferStatus", "TransferStatus"),
new System.Data.Common.DataColumnMapping("ActionStatus", "ActionStatus"),
new System.Data.Common.DataColumnMapping("entryUser", "entryUser"),
new System.Data.Common.DataColumnMapping("entryDate", "entryDate"),
new System.Data.Common.DataColumnMapping("updateUser", "updateUser"),
new System.Data.Common.DataColumnMapping("updateDate", "updateDate"),
new System.Data.Common.DataColumnMapping("ts", "ts"),
})});
//
// sqlSelect
//
this.sqlSelect.CommandType = System.Data.CommandType.StoredProcedure;
this.sqlSelect.Connection=myDALManager.SqlCon;
this.sqlSelectAll.CommandText = "[ADMSPAppealSelect]";
this.sqlSelectAll.CommandType = System.Data.CommandType.StoredProcedure;
this.sqlSelectAll.Connection=myDALManager.SqlCon;
this.sqlSelectAll.Parameters.Add(new System.Data.SqlClient.SqlParameter("@RETURN_VALUE", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.ReturnValue, false, ((System.Byte)(10)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null));
//
// sqlInsert
//
this.sqlInsert.CommandText = "[ADMSPAppealInsert]";
this.sqlInsert.CommandType = System.Data.CommandType.StoredProcedure;
this.sqlInsert.Connection=myDALManager.SqlCon;
this.sqlInsert.Parameters.Add(new SqlParameter("@RETURN_VALUE", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.ReturnValue, false, ((System.Byte)(10)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null));
this.sqlInsert.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 10, "Id"));
this.sqlInsert.Parameters["@Id"].SourceVersion=DataRowVersion.Current;
this.sqlInsert.Parameters.Add(new SqlParameter("@SSTFileNumber", SqlDbType.NVarChar, 12, "SSTFileNumber"));
this.sqlInsert.Parameters["@SSTFileNumber"].SourceVersion=DataRowVersion.Current;
this.sqlInsert.Parameters.Add(new SqlParameter("@AppealLevelId", SqlDbType.Int, 10, "AppealLevelId"));
this.sqlInsert.Parameters["@AppealLevelId"].SourceVersion=DataRowVersion.Current;
this.sqlInsert.Parameters.Add(new SqlParameter("@AtriumUser", SqlDbType.NVarChar, 80, "AtriumUser"));
this.sqlInsert.Parameters["@AtriumUser"].SourceVersion=DataRowVersion.Current;
this.sqlInsert.Parameters.Add(new SqlParameter("@AppealLevelDate", SqlDbType.DateTime, 24, "AppealLevelDate"));
this.sqlInsert.Parameters["@AppealLevelDate"].SourceVersion=DataRowVersion.Current;
this.sqlInsert.Parameters.Add(new SqlParameter("@ClientId", SqlDbType.Int, 10, "ClientId"));
this.sqlInsert.Parameters["@ClientId"].SourceVersion=DataRowVersion.Current;
this.sqlInsert.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar, 100, "FirstName"));
this.sqlInsert.Parameters["@FirstName"].SourceVersion=DataRowVersion.Current;
this.sqlInsert.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar, 100, "LastName"));
this.sqlInsert.Parameters["@LastName"].SourceVersion=DataRowVersion.Current;
this.sqlInsert.Parameters.Add(new SqlParameter("@IdentifierNumber", SqlDbType.NVarChar, 12, "IdentifierNumber"));
this.sqlInsert.Parameters["@IdentifierNumber"].SourceVersion=DataRowVersion.Current;
this.sqlInsert.Parameters.Add(new SqlParameter("@TransferStatus", SqlDbType.NVarChar, 30, "TransferStatus"));
this.sqlInsert.Parameters["@TransferStatus"].SourceVersion=DataRowVersion.Current;
this.sqlInsert.Parameters.Add(new SqlParameter("@ActionStatus", SqlDbType.NVarChar, 100, "ActionStatus"));
this.sqlInsert.Parameters["@ActionStatus"].SourceVersion=DataRowVersion.Current;
this.sqlInsert.Parameters.Add(new SqlParameter("@entryUser", SqlDbType.NVarChar, 20, "entryUser"));
this.sqlInsert.Parameters["@entryUser"].SourceVersion=DataRowVersion.Current;
this.sqlInsert.Parameters.Add(new SqlParameter("@entryDate", SqlDbType.SmallDateTime, 24, "entryDate"));
this.sqlInsert.Parameters["@entryDate"].SourceVersion=DataRowVersion.Current;
this.sqlInsert.Parameters.Add(new SqlParameter("@updateUser", SqlDbType.NVarChar, 20, "updateUser"));
this.sqlInsert.Parameters["@updateUser"].SourceVersion=DataRowVersion.Current;
this.sqlInsert.Parameters.Add(new SqlParameter("@updateDate", SqlDbType.SmallDateTime, 24, "updateDate"));
this.sqlInsert.Parameters["@updateDate"].SourceVersion=DataRowVersion.Current;
this.sqlInsert.Parameters.Add(new SqlParameter("@ts", SqlDbType.Timestamp, 50, "ts"));
this.sqlInsert.Parameters["@ts"].SourceVersion=DataRowVersion.Current;
//
// sqlUpdate
//
this.sqlUpdate.CommandText = "[ADMSPAppealUpdate]";
this.sqlUpdate.CommandType = System.Data.CommandType.StoredProcedure;
this.sqlUpdate.Connection=myDALManager.SqlCon;
this.sqlUpdate.Parameters.Add(new System.Data.SqlClient.SqlParameter("@RETURN_VALUE", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.ReturnValue, false, ((System.Byte)(10)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null));
this.sqlUpdate.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 10, "Id"));
this.sqlUpdate.Parameters["@Id"].SourceVersion=DataRowVersion.Current;
this.sqlUpdate.Parameters.Add(new SqlParameter("@SSTFileNumber", SqlDbType.NVarChar, 12, "SSTFileNumber"));
this.sqlUpdate.Parameters["@SSTFileNumber"].SourceVersion=DataRowVersion.Current;
this.sqlUpdate.Parameters.Add(new SqlParameter("@AppealLevelId", SqlDbType.Int, 10, "AppealLevelId"));
this.sqlUpdate.Parameters["@AppealLevelId"].SourceVersion=DataRowVersion.Current;
this.sqlUpdate.Parameters.Add(new SqlParameter("@AtriumUser", SqlDbType.NVarChar, 80, "AtriumUser"));
this.sqlUpdate.Parameters["@AtriumUser"].SourceVersion=DataRowVersion.Current;
this.sqlUpdate.Parameters.Add(new SqlParameter("@AppealLevelDate", SqlDbType.DateTime, 24, "AppealLevelDate"));
this.sqlUpdate.Parameters["@AppealLevelDate"].SourceVersion=DataRowVersion.Current;
this.sqlUpdate.Parameters.Add(new SqlParameter("@ClientId", SqlDbType.Int, 10, "ClientId"));
this.sqlUpdate.Parameters["@ClientId"].SourceVersion=DataRowVersion.Current;
this.sqlUpdate.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar, 100, "FirstName"));
this.sqlUpdate.Parameters["@FirstName"].SourceVersion=DataRowVersion.Current;
this.sqlUpdate.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar, 100, "LastName"));
this.sqlUpdate.Parameters["@LastName"].SourceVersion=DataRowVersion.Current;
this.sqlUpdate.Parameters.Add(new SqlParameter("@IdentifierNumber", SqlDbType.NVarChar, 12, "IdentifierNumber"));
this.sqlUpdate.Parameters["@IdentifierNumber"].SourceVersion=DataRowVersion.Current;
this.sqlUpdate.Parameters.Add(new SqlParameter("@TransferStatus", SqlDbType.NVarChar, 30, "TransferStatus"));
this.sqlUpdate.Parameters["@TransferStatus"].SourceVersion=DataRowVersion.Current;
this.sqlUpdate.Parameters.Add(new SqlParameter("@ActionStatus", SqlDbType.NVarChar, 100, "ActionStatus"));
this.sqlUpdate.Parameters["@ActionStatus"].SourceVersion=DataRowVersion.Current;
this.sqlUpdate.Parameters.Add(new SqlParameter("@entryUser", SqlDbType.NVarChar, 20, "entryUser"));
this.sqlUpdate.Parameters["@entryUser"].SourceVersion=DataRowVersion.Current;
this.sqlUpdate.Parameters.Add(new SqlParameter("@entryDate", SqlDbType.SmallDateTime, 24, "entryDate"));
this.sqlUpdate.Parameters["@entryDate"].SourceVersion=DataRowVersion.Current;
this.sqlUpdate.Parameters.Add(new SqlParameter("@updateUser", SqlDbType.NVarChar, 20, "updateUser"));
this.sqlUpdate.Parameters["@updateUser"].SourceVersion=DataRowVersion.Current;
this.sqlUpdate.Parameters.Add(new SqlParameter("@updateDate", SqlDbType.SmallDateTime, 24, "updateDate"));
this.sqlUpdate.Parameters["@updateDate"].SourceVersion=DataRowVersion.Current;
this.sqlUpdate.Parameters.Add(new SqlParameter("@ts", SqlDbType.Timestamp, 50, "ts"));
this.sqlUpdate.Parameters["@ts"].SourceVersion=DataRowVersion.Current;
//
// sqlDelete
//
this.sqlDelete.CommandText = "[ADMSPAppealDelete]";
this.sqlDelete.CommandType = System.Data.CommandType.StoredProcedure;
this.sqlDelete.Connection=myDALManager.SqlCon;
this.sqlDelete.Parameters.Add(new System.Data.SqlClient.SqlParameter("@RETURN_VALUE", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.ReturnValue, false, ((System.Byte)(10)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null));
this.sqlDelete.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Id", System.Data.SqlDbType.Int, 4, "Id"));
this.sqlDelete.Parameters["@Id"].SourceVersion=DataRowVersion.Original;
this.sqlDelete.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ts", System.Data.SqlDbType.Timestamp, 50, "ts"));
this.sqlDelete.Parameters["@ts"].SourceVersion=DataRowVersion.Original;
}
public SST.ADMSPAppealDataTable Load()
{
this.sqlDa.SelectCommand=sqlSelectAll;
SST.ADMSPAppealDataTable dt=new SST.ADMSPAppealDataTable();
Fill(dt);
return dt;
}
public SST.ADMSPAppealDataTable Load(int Id)
{
this.sqlDa.SelectCommand=sqlSelect;
this.sqlSelect.Parameters.Clear();
this.sqlSelect.CommandText = "[ADMSPAppealSelectById]";
this.sqlSelect.Parameters.Add(new System.Data.SqlClient.SqlParameter("@RETURN_VALUE", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.ReturnValue, false, ((System.Byte)(10)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null));
this.sqlSelect.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Id", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.Input, false, ((System.Byte)(10)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null));
this.sqlSelect.Parameters["@Id"].Value=Id;
SST.ADMSPAppealDataTable dt=new SST.ADMSPAppealDataTable();
Fill(dt);
return dt;
}
public SST.ADMSPAppealDataTable LoadByFileNumber(string SSTFileNumber)
{
this.sqlDa.SelectCommand = sqlSelect;
this.sqlSelect.Parameters.Clear();
this.sqlSelect.CommandText = "[ADMSPAppealSelectBySSTFileNumber]";
this.sqlSelect.Parameters.Add(new System.Data.SqlClient.SqlParameter("@RETURN_VALUE", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.ReturnValue, false, ((System.Byte)(10)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null));
this.sqlSelect.Parameters.Add(new System.Data.SqlClient.SqlParameter("@SSTFileNumber", System.Data.SqlDbType.NVarChar, 12));
this.sqlSelect.Parameters["@SSTFileNumber"].Value = SSTFileNumber;
SST.ADMSPAppealDataTable dt = new SST.ADMSPAppealDataTable();
Fill(dt);
return dt;
}
}
}
| 60.217822 | 267 | 0.754522 | [
"MIT"
] | chris-weekes/atrium | atriumDAL/ADMSPAppeal_DAL.cs | 12,164 | C# |
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.IO;
namespace Xenko.Graphics
{
public static class TextureExtensions
{
public static Texture ToTextureView(this Texture texture, ViewType type, int arraySlice, int mipLevel)
{
var viewDescription = texture.ViewDescription;
viewDescription.Type = type;
viewDescription.ArraySlice = arraySlice;
viewDescription.MipLevel = mipLevel;
return texture.ToTextureView(viewDescription);
}
/// <summary>
/// Gets a view on this depth stencil texture as a readonly depth stencil texture.
/// </summary>
/// <returns>A new texture object that is bouded to the requested view.</returns>
public static Texture ToDepthStencilReadOnlyTexture(this Texture texture)
{
if (!texture.IsDepthStencil)
throw new NotSupportedException("This texture is not a valid depth stencil texture");
var viewDescription = texture.ViewDescription;
viewDescription.Flags = TextureFlags.DepthStencilReadOnly;
return texture.ToTextureView(viewDescription);
}
/// <summary>
/// Creates a new texture that can be used as a ShaderResource from an existing depth texture.
/// </summary>
/// <returns></returns>
public static Texture CreateDepthTextureCompatible(this Texture texture)
{
if (!texture.IsDepthStencil)
throw new NotSupportedException("This texture is not a valid depth stencil texture");
var description = texture.Description;
description.Format = Texture.ComputeShaderResourceFormatFromDepthFormat(description.Format); // TODO: review this
if (description.Format == PixelFormat.None)
throw new NotSupportedException("This depth stencil format is not supported");
description.Flags = TextureFlags.ShaderResource;
return Texture.New(texture.GraphicsDevice, description);
}
public static Texture EnsureRenderTarget(this Texture texture)
{
if (texture != null && !texture.IsRenderTarget)
{
throw new ArgumentException("Texture must be a RenderTarget", "texture");
}
return texture;
}
/// <summary>
/// Creates a texture from an image file data (png, dds, ...).
/// </summary>
/// <param name="graphicsDevice">The graphics device in which to create the texture</param>
/// <param name="data">The image file data</param>
/// <returns>The texture</returns>
public static Texture FromFileData(GraphicsDevice graphicsDevice, byte[] data)
{
Texture result;
var loadAsSRgb = graphicsDevice.ColorSpace == ColorSpace.Linear;
using (var imageStream = new MemoryStream(data))
{
using (var image = Image.Load(imageStream, loadAsSRgb))
{
result = Texture.New(graphicsDevice, image);
}
}
result.Reload = graphicsResource =>
{
using (var imageStream = new MemoryStream(data))
{
using (var image = Image.Load(imageStream, loadAsSRgb))
{
((Texture)graphicsResource).Recreate(image.ToDataBox());
}
}
};
return result;
}
}
}
| 38.927835 | 125 | 0.6009 | [
"MIT"
] | Aminator/xenko | sources/engine/Xenko.Graphics/Texture.Extensions.cs | 3,776 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.