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.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Uxnet.Web.Module.Common;
namespace eIVOGo.Module.SYS
{
public partial class UserMenuList : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
gvEntity.DataBound += new EventHandler(gvEntity_DataBound);
editItem.Done += new EventHandler(editItem_Done);
}
void editItem_Done(object sender, EventArgs e)
{
gvEntity.DataBind();
}
void gvEntity_DataBound(object sender, EventArgs e)
{
gvEntity.SetPageIndex("pagingList", dsEntity.CurrentView.LastSelectArguments.TotalRowCount);
}
protected void PageIndexChanged(object source, PageChangedEventArgs e)
{
gvEntity.PageIndex = e.NewPageIndex;
gvEntity.DataBind();
}
protected void gvEntity_RowCommand(object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "Modify":
break;
case "Delete":
delete((String)e.CommandArgument);
break;
case "Create":
editItem.Show();
break;
}
}
private void delete(String keyValue)
{
var key = keyValue.Split(',').Select(s => int.Parse(s)).ToArray();
dsEntity.CreateDataManager().DeleteAny(r => r.RoleID == key[0] && r.CategoryID == key[1] && r.MenuID == key[2]);
gvEntity.DataBind();
}
}
} | 27.545455 | 124 | 0.558856 | [
"MIT"
] | uxb2bralph/IFS-EIVO03 | eIVOGo/Module/SYS/UserMenuList.ascx.cs | 1,820 | C# |
namespace Hexio.DineroClient.Models.PurchaseVouchers
{
public class CreatePurchaseVoucherLineModel
{
public long AccountNumber { get; set; }
public string Description { get; set; }
public decimal Amount { get; set; }
public string VatCode { get; set; }
}
} | 30 | 52 | 0.656667 | [
"MIT"
] | HexioDK/Hexio.DineroClient | Hexio.DineroClient/Models/PurchaseVouchers/CreatePurchaseVoucherLineModel.cs | 300 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** 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.AzureAD.Inputs
{
public sealed class ApplicationOptionalClaimsAccessTokenGetArgs : Pulumi.ResourceArgs
{
[Input("additionalProperties")]
private InputList<string>? _additionalProperties;
/// <summary>
/// List of additional properties of the claim. If a property exists in this list, it modifies the behaviour of the optional claim.
/// </summary>
public InputList<string> AdditionalProperties
{
get => _additionalProperties ?? (_additionalProperties = new InputList<string>());
set => _additionalProperties = value;
}
/// <summary>
/// Whether the claim specified by the client is necessary to ensure a smooth authorization experience.
/// </summary>
[Input("essential")]
public Input<bool>? Essential { get; set; }
/// <summary>
/// The name of the optional claim.
/// </summary>
[Input("name", required: true)]
public Input<string> Name { get; set; } = null!;
/// <summary>
/// The source of the claim. If `source` is absent, the claim is a predefined optional claim. If `source` is `user`, the value of `name` is the extension property from the user object.
/// </summary>
[Input("source")]
public Input<string>? Source { get; set; }
public ApplicationOptionalClaimsAccessTokenGetArgs()
{
}
}
}
| 35.62 | 192 | 0.636159 | [
"ECL-2.0",
"Apache-2.0"
] | AaronFriel/pulumi-azuread | sdk/dotnet/Inputs/ApplicationOptionalClaimsAccessTokenGetArgs.cs | 1,781 | C# |
#if !NETSTANDARD13
/*
* 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 chime-2018-05-01.normal.json service model.
*/
using Amazon.Runtime;
namespace Amazon.Chime.Model
{
/// <summary>
/// Paginator for the ListMeetings operation
///</summary>
public interface IListMeetingsPaginator
{
/// <summary>
/// Enumerable containing all full responses for the operation
/// </summary>
IPaginatedEnumerable<ListMeetingsResponse> Responses { get; }
}
}
#endif | 32.342857 | 104 | 0.678445 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Chime/Generated/Model/_bcl45+netstandard/IListMeetingsPaginator.cs | 1,132 | C# |
using System;
using System.Drawing;
namespace KaptchaNET.Extensions
{
public static class BitmapExtensions
{
public static Bitmap Apply(this Bitmap btmp, Func<int, int, Color, Color> func)
{
var img = btmp.Clone() as Bitmap;
for (int y = 0; y < img.Height; ++y)
{
for (int x = 0; x < img.Width; ++x)
{
Color z = img.GetPixel(x, y); // old
Color c = func(x, y, z); // new
img.SetPixel(x, y, c);
}
}
return img;
}
public static Color GetColorSample(this Bitmap img, int x, int y)
{
int uvx = TrimValue(x, 0, img.Width - 1);
int uvy = TrimValue(y, 0, img.Height - 1);
return img.GetPixel(uvx, uvy);
}
private static int TrimValue(int x, int min, int max)
{
if (x < min)
{
return min;
}
else if (x > max)
{
return max;
}
else
{
return x;
}
}
}
}
| 24.8125 | 87 | 0.4089 | [
"MIT"
] | meysamda/Kaptcha.NET | src/Kaptcha.NET/Extensions/BitmapExtensions.cs | 1,193 | C# |
using EmbyStat.Services.Models.Stat;
namespace EmbyStat.Services.Models.Show
{
public class ShowGeneral
{
public Card<int> ShowCount { get; set; }
public Card<int> EpisodeCount { get; set; }
public Card<int> MissingEpisodeCount { get; set; }
public TimeSpanCard TotalPlayableTime { get; set; }
public ShowPoster HighestRatedShow { get; set; }
public ShowPoster LowestRatedShow { get; set; }
public ShowPoster ShowWithMostEpisodes { get; set; }
public ShowPoster OldestPremieredShow { get; set; }
public ShowPoster YoungestPremieredShow { get; set; }
public ShowPoster YoungestAddedShow{ get; set; }
}
}
| 36.684211 | 61 | 0.66858 | [
"MIT"
] | trizzone52/EmbyStat | EmbyStat.Services/Models/Show/ShowGeneral.cs | 699 | 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.Collections.Generic;
using System.IO;
using System.Linq;
using Cake.Common.IO;
using Cake.Common.IO.Paths;
using Cake.Common.Tests.Fixtures.IO;
using Cake.Core;
using Cake.Core.IO;
using Cake.Testing;
using NSubstitute;
using Xunit;
using LogLevel = Cake.Core.Diagnostics.LogLevel;
using Verbosity = Cake.Core.Diagnostics.Verbosity;
namespace Cake.Common.Tests.Unit.IO;
public sealed class FileAliasesTests
{
public sealed class TheFileMethod
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given
const string path = "./file.txt";
// When
var result = Record.Exception(() => FileAliases.File(null, path));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_Path_Is_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
// When
var result = Record.Exception(() => FileAliases.File(context, null));
// Then
AssertEx.IsArgumentNullException(result, "path");
}
[Fact]
public void Should_Return_A_Convertable_File_Path()
{
// Given
var context = Substitute.For<ICakeContext>();
// When
var result = FileAliases.File(context, "./file.txt");
// Then
Assert.IsType<ConvertableFilePath>(result);
}
}
public sealed class TheCopyToDirectoryMethod
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given, When
var result = Record.Exception(() =>
FileAliases.CopyFileToDirectory(null, "./file.txt", "./target"));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_File_Path_Is_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
// When
var result = Record.Exception(() =>
FileAliases.CopyFileToDirectory(context, null, "./target"));
// Then
AssertEx.IsArgumentNullException(result, "filePath");
}
[Fact]
public void Should_Throw_If_Target_Directory_Path_Is_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
// When
var result = Record.Exception(() =>
FileAliases.CopyFileToDirectory(context, "./file.txt", null));
// Then
AssertEx.IsArgumentNullException(result, "targetDirectoryPath");
}
[Fact]
public void Should_Copy_File()
{
// Given
var fixture = new FileCopyFixture();
// When
FileAliases.CopyFileToDirectory(fixture.Context, "./file1.txt", "./target");
// Then
fixture.TargetFiles[0].Received(1).Copy(
Arg.Is<FilePath>(p => p.FullPath == "/Working/target/file1.txt"), true);
}
}
public sealed class TheCopyFileMethod
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given, When
var result = Record.Exception(() =>
FileAliases.CopyFile(null, "./file.txt", "./target"));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_File_Path_Is_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
// When
var result = Record.Exception(() =>
FileAliases.CopyFile(context, null, "./target"));
// Then
AssertEx.IsArgumentNullException(result, "filePath");
}
[Fact]
public void Should_Throw_If_Target_File_Path_Is_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
// When
var result = Record.Exception(() =>
FileAliases.CopyFile(context, "./file.txt", null));
// Then
AssertEx.IsArgumentNullException(result, "targetFilePath");
}
[Fact]
public void Should_Throw_If_Target_Directory_Do_Not_Exist()
{
// Given
var fixture = new FileCopyFixture();
fixture.TargetDirectory = Substitute.For<IDirectory>();
fixture.TargetDirectory.Exists.Returns(false);
// When
var result = Record.Exception(() =>
FileAliases.CopyFile(fixture.Context, "./file1.txt", "./target/file1.txt"));
// Then
Assert.IsType<DirectoryNotFoundException>(result);
Assert.Equal("The directory '/Working/target' does not exist.", result?.Message);
}
[Fact]
public void Should_Throw_If_File_Do_Not_Exist()
{
// Given
var fixture = new FileCopyFixture();
fixture.TargetFiles[0] = Substitute.For<IFile>();
fixture.TargetFiles[0].Exists.Returns(false);
// When
var result = Record.Exception(() =>
FileAliases.CopyFile(fixture.Context, "./file1.txt", "./target/file1.txt"));
// Then
Assert.IsType<FileNotFoundException>(result);
Assert.Equal("The file '/Working/file1.txt' does not exist.", result?.Message);
}
[Fact]
public void Should_Copy_File()
{
// Given
var fixture = new FileCopyFixture();
// When
FileAliases.CopyFile(fixture.Context, "./file1.txt", "./target/file1.txt");
// Then
fixture.TargetFiles[0].Received(1).Copy(
Arg.Is<FilePath>(p => p.FullPath == "/Working/target/file1.txt"), true);
}
[Fact]
public void Should_Log_Verbose_Message_With_Correct_Target()
{
// Given
var fixture = new FileCopyFixture();
// When
FileAliases.CopyFile(fixture.Context, "./file1.txt", "./target/file1.txt");
// Then
Assert.Contains(fixture.Log.Entries,
entry =>
entry.Level == LogLevel.Verbose && entry.Verbosity == Verbosity.Verbose &&
entry.Message == "Copying file file1.txt to /Working/target/file1.txt");
}
}
public sealed class TheCopyFilesMethod
{
public sealed class WithFilePaths
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given
var fixture = new FileCopyFixture();
// When
var result = Record.Exception(() =>
FileAliases.CopyFiles(null, fixture.SourceFilePaths, "./target"));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_File_Paths_Are_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
// When
var result = Record.Exception(() =>
FileAliases.CopyFiles(context, (IEnumerable<FilePath>)null, "./target"));
// Then
AssertEx.IsArgumentNullException(result, "filePaths");
}
[Fact]
public void Should_Throw_If_Target_Directory_Path_Is_Null()
{
// Given
var fixture = new FileCopyFixture();
// When
var result = Record.Exception(() =>
FileAliases.CopyFiles(fixture.Context, fixture.SourceFilePaths, null));
// Then
AssertEx.IsArgumentNullException(result, "targetDirectoryPath");
}
[Fact]
public void Should_Throw_If_Any_Target_Directory_Do_Not_Exist()
{
// Given
var fixture = new FileCopyFixture();
fixture.TargetDirectory = Substitute.For<IDirectory>();
fixture.TargetDirectory.Exists.Returns(false);
// When
var result = Record.Exception(() =>
FileAliases.CopyFiles(fixture.Context, fixture.SourceFilePaths, "./target"));
// Then
Assert.IsType<DirectoryNotFoundException>(result);
Assert.Equal("The directory '/Working/target' does not exist.", result?.Message);
}
[Fact]
public void Should_Throw_If_Any_File_Do_Not_Exist()
{
// Given
var fixture = new FileCopyFixture();
fixture.TargetFiles[1] = Substitute.For<IFile>();
fixture.TargetFiles[1].Exists.Returns(false);
// When
var result = Record.Exception(() =>
FileAliases.CopyFiles(fixture.Context, fixture.SourceFilePaths, "./target"));
// Then
Assert.IsType<FileNotFoundException>(result);
Assert.Equal("The file '/Working/file2.txt' does not exist.", result?.Message);
}
[Fact]
public void Should_Keep_Folder_Structure()
{
// Given
var fixture = new FileCopyFixture();
// When
FileAliases.CopyFiles(fixture.Context, fixture.SourceFilePaths, "./target");
// Then
fixture.TargetFiles[0].Received(1).Copy(Arg.Any<FilePath>(), true);
fixture.TargetFiles[1].Received(1).Copy(Arg.Any<FilePath>(), true);
}
[Fact]
public void Should_Copy_Files()
{
// Given
var fixture = new FileCopyFixture();
// When
FileAliases.CopyFiles(fixture.Context, fixture.SourceFilePaths, "./target");
// Then
fixture.TargetFiles[0].Received(1).Copy(Arg.Any<FilePath>(), true);
fixture.TargetFiles[1].Received(1).Copy(Arg.Any<FilePath>(), true);
}
}
public sealed class WithStrings
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given
var fixture = new FileCopyFixture();
var filePaths = fixture.SourceFilePaths.Select(x => x.FullPath);
// When
var result = Record.Exception(() =>
FileAliases.CopyFiles(null, filePaths, "./target"));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_File_Paths_Are_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
// When
var result = Record.Exception(() =>
FileAliases.CopyFiles(context, (IEnumerable<string>)null, "./target"));
// Then
AssertEx.IsArgumentNullException(result, "filePaths");
}
[Fact]
public void Should_Throw_If_Target_Directory_Path_Is_Null()
{
// Given
var fixture = new FileCopyFixture();
var filePaths = fixture.SourceFilePaths.Select(x => x.FullPath);
// When
var result = Record.Exception(() =>
FileAliases.CopyFiles(fixture.Context, filePaths, null));
// Then
AssertEx.IsArgumentNullException(result, "targetDirectoryPath");
}
[Fact]
public void Should_Throw_If_Any_Target_Directory_Do_Not_Exist()
{
// Given
var fixture = new FileCopyFixture();
var filePaths = fixture.SourceFilePaths.Select(x => x.FullPath);
fixture.TargetDirectory = Substitute.For<IDirectory>();
fixture.TargetDirectory.Exists.Returns(false);
// When
var result = Record.Exception(() =>
FileAliases.CopyFiles(fixture.Context, filePaths, "./target"));
// Then
Assert.IsType<DirectoryNotFoundException>(result);
Assert.Equal("The directory '/Working/target' does not exist.", result?.Message);
}
[Fact]
public void Should_Throw_If_Any_File_Do_Not_Exist()
{
// Given
var fixture = new FileCopyFixture();
var filePaths = fixture.SourceFilePaths.Select(x => x.FullPath);
fixture.TargetFiles[1] = Substitute.For<IFile>();
fixture.TargetFiles[1].Exists.Returns(false);
// When
var result = Record.Exception(() =>
FileAliases.CopyFiles(fixture.Context, filePaths, "./target"));
// Then
Assert.IsType<FileNotFoundException>(result);
Assert.Equal("The file '/Working/file2.txt' does not exist.", result?.Message);
}
[Fact]
public void Should_Keep_Folder_Structure()
{
// Given
var fixture = new FileCopyFixture();
var filePaths = fixture.SourceFilePaths.Select(x => x.FullPath);
// When
FileAliases.CopyFiles(fixture.Context, filePaths, "./target");
// Then
fixture.TargetFiles[0].Received(1).Copy(Arg.Any<FilePath>(), true);
fixture.TargetFiles[1].Received(1).Copy(Arg.Any<FilePath>(), true);
}
[Fact]
public void Should_Copy_Files()
{
// Given
var fixture = new FileCopyFixture();
var filePaths = fixture.SourceFilePaths.Select(x => x.FullPath);
// When
FileAliases.CopyFiles(fixture.Context, filePaths, "./target");
// Then
fixture.TargetFiles[0].Received(1).Copy(Arg.Any<FilePath>(), true);
fixture.TargetFiles[1].Received(1).Copy(Arg.Any<FilePath>(), true);
}
}
public sealed class WithGlobExpression
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given, When
var result = Record.Exception(() =>
FileAliases.CopyFiles(null, "", "./target"));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_Glob_Expression_Is_Null()
{
// Given
var fixture = new FileCopyFixture();
// When
var result = Record.Exception(() =>
FileAliases.CopyFiles(fixture.Context, (string)null, "./target"));
// Then
AssertEx.IsArgumentNullException(result, "pattern");
}
[Fact]
public void Should_Throw_If_Target_Directory_Path_Is_Null()
{
// Given
var fixture = new FileCopyFixture();
// When
var result = Record.Exception(() =>
FileAliases.CopyFiles(fixture.Context, "*", null));
// Then
AssertEx.IsArgumentNullException(result, "targetDirectoryPath");
}
[Fact]
public void Should_Throw_If_Any_Target_Directory_Do_Not_Exist()
{
// Given
var fixture = new FileCopyFixture();
fixture.TargetDirectory = Substitute.For<IDirectory>();
fixture.TargetDirectory.Exists.Returns(false);
// When
var result = Record.Exception(() =>
FileAliases.CopyFiles(fixture.Context, "*", "./target"));
// Then
Assert.IsType<DirectoryNotFoundException>(result);
Assert.Equal("The directory '/Working/target' does not exist.", result?.Message);
}
[Fact]
public void Should_Throw_If_Any_File_Do_Not_Exist()
{
// Given
var fixture = new FileCopyFixture();
fixture.TargetFiles[1] = Substitute.For<IFile>();
fixture.TargetFiles[1].Exists.Returns(false);
// When
var result = Record.Exception(() =>
FileAliases.CopyFiles(fixture.Context, "*", "./target"));
// Then
Assert.IsType<FileNotFoundException>(result);
Assert.Equal("The file '/Working/file2.txt' does not exist.", result?.Message);
}
[Fact]
public void Should_Keep_Folder_Structure()
{
// Given
var fixture = new FileCopyFixture();
// When
FileAliases.CopyFiles(fixture.Context, "*", "./target", true);
// Then
fixture.TargetFiles[0].Received(1).Copy(Arg.Any<FilePath>(), true);
fixture.TargetFiles[1].Received(1).Copy(Arg.Any<FilePath>(), true);
}
[Fact]
public void Should_Copy_Files()
{
// Given
var fixture = new FileCopyFixture();
// When
FileAliases.CopyFiles(fixture.Context, "*", "./target");
// Then
fixture.TargetFiles[0].Received(1).Copy(Arg.Any<FilePath>(), true);
fixture.TargetFiles[1].Received(1).Copy(Arg.Any<FilePath>(), true);
}
}
}
public sealed class TheDeleteFileMethod
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given
var filePath = new FilePath("./file.txt");
// When
var result = Record.Exception(() =>
FileAliases.DeleteFile(null, filePath));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_File_Path_Is_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
// When
var result = Record.Exception(() =>
FileAliases.DeleteFile(context, null));
// Then
AssertEx.IsArgumentNullException(result, "filePath");
}
[Fact]
public void Should_Throw_If_File_Do_Not_Exist()
{
// Given
var fixture = new FileDeleteFixture();
// When
var result = Record.Exception(() =>
FileAliases.DeleteFile(fixture.Context, "/file.txt"));
// Then
Assert.IsType<FileNotFoundException>(result);
Assert.Equal("The file '/file.txt' does not exist.", result?.Message);
}
[Fact]
public void Should_Make_Relative_File_Path_Absolute()
{
// Given
var fixture = new FileDeleteFixture();
// When
FileAliases.DeleteFile(fixture.Context, "file1.txt");
// Then
fixture.FileSystem.Received(1).GetFile(Arg.Is<FilePath>(
p => p.FullPath == "/Working/file1.txt"));
}
[Fact]
public void Should_Delete_File()
{
// Given
var fixture = new FileDeleteFixture();
// When
FileAliases.DeleteFile(fixture.Context, fixture.Paths[0]);
// Then
fixture.Files[0].Received(1).Delete();
}
}
public sealed class TheDeleteFilesMethod
{
public sealed class WithFilePaths
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given
var filePaths = new FilePath[] { };
// When
var result = Record.Exception(() =>
FileAliases.DeleteFiles(null, filePaths));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_File_Paths_Are_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
// When
var result = Record.Exception(() =>
FileAliases.DeleteFiles(context, (IEnumerable<FilePath>)null));
// Then
AssertEx.IsArgumentNullException(result, "filePaths");
}
[Fact]
public void Should_Delete_Files()
{
// Given
var fixture = new FileDeleteFixture();
// When
FileAliases.DeleteFiles(fixture.Context, fixture.Paths);
// Then
fixture.Files[0].Received(1).Delete();
fixture.Files[1].Received(1).Delete();
}
}
public sealed class WithGlobExpression
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given, When
var result = Record.Exception(() =>
FileAliases.DeleteFiles(null, "*"));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_Glob_Expression_Is_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
// When
var result = Record.Exception(() =>
FileAliases.DeleteFiles(context, (string)null));
// Then
AssertEx.IsArgumentNullException(result, "pattern");
}
[Fact]
public void Should_Delete_Files()
{
// Given
var fixture = new FileDeleteFixture();
// When
FileAliases.DeleteFiles(fixture.Context, "*");
// Then
fixture.Files[0].Received(1).Delete();
fixture.Files[1].Received(1).Delete();
}
}
}
public sealed class TheMoveFileToDirectory
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given, When
var source = new FilePath("./source.txt");
var target = new DirectoryPath("./target");
var result = Record.Exception(() =>
FileAliases.MoveFileToDirectory(null, source, target));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_Source_File_Path_Is_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
var target = new DirectoryPath("./target");
// When
var result = Record.Exception(() =>
FileAliases.MoveFileToDirectory(context, null, target));
// Then
AssertEx.IsArgumentNullException(result, "filePath");
}
[Fact]
public void Should_Throw_If_Target_File_Path_Is_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
var source = new FilePath("./source.txt");
// When
var result = Record.Exception(() =>
FileAliases.MoveFileToDirectory(context, source, null));
// Then
AssertEx.IsArgumentNullException(result, "targetDirectoryPath");
}
[Fact]
public void Should_Move_File()
{
// Given
var fixture = new FileCopyFixture();
// When
FileAliases.MoveFileToDirectory(fixture.Context, "./file1.txt", "./target");
// Then
fixture.TargetFiles[0].Received(1).Move(
Arg.Is<FilePath>(p => p.FullPath == "/Working/target/file1.txt"));
}
}
public sealed class TheMoveFilesMethod
{
public sealed class WithFilePaths
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given
var fixture = new FileCopyFixture();
// When
var result = Record.Exception(() =>
FileAliases.MoveFiles(null, fixture.SourceFilePaths, "./target"));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_File_Paths_Are_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
// When
var result = Record.Exception(() =>
FileAliases.MoveFiles(context, (IEnumerable<FilePath>)null, "./target"));
// Then
AssertEx.IsArgumentNullException(result, "filePaths");
}
[Fact]
public void Should_Throw_If_Target_Directory_Path_Is_Null()
{
// Given
var fixture = new FileCopyFixture();
// When
var result = Record.Exception(() =>
FileAliases.MoveFiles(fixture.Context, fixture.SourceFilePaths, null));
// Then
AssertEx.IsArgumentNullException(result, "targetDirectoryPath");
}
[Fact]
public void Should_Throw_If_Target_Directory_Do_Not_Exist()
{
// Given
var fixture = new FileCopyFixture();
fixture.TargetDirectory = Substitute.For<IDirectory>();
fixture.TargetDirectory.Exists.Returns(false);
// When
var result = Record.Exception(() =>
FileAliases.MoveFiles(fixture.Context, fixture.SourceFilePaths, "./target"));
// Then
Assert.IsType<DirectoryNotFoundException>(result);
Assert.Equal("The directory '/Working/target' does not exist.", result?.Message);
}
[Fact]
public void Should_Throw_If_Any_File_Do_Not_Exist()
{
// Given
var fixture = new FileCopyFixture();
fixture.TargetFiles[1] = Substitute.For<IFile>();
fixture.TargetFiles[1].Exists.Returns(false);
// When
var result = Record.Exception(() =>
FileAliases.MoveFiles(fixture.Context, fixture.SourceFilePaths, "./target"));
// Then
Assert.IsType<FileNotFoundException>(result);
Assert.Equal("The file '/Working/file2.txt' does not exist.", result?.Message);
}
[Fact]
public void Should_Move_Files()
{
// Given
var fixture = new FileCopyFixture();
// When
FileAliases.MoveFiles(fixture.Context, fixture.SourceFilePaths, "./target");
// Then
fixture.TargetFiles[0].Received(1).Move(Arg.Any<FilePath>());
fixture.TargetFiles[1].Received(1).Move(Arg.Any<FilePath>());
}
}
public sealed class WithGlobExpression
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given, When
var result = Record.Exception(() =>
FileAliases.MoveFiles(null, "", "./target"));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_Glob_Expression_Is_Null()
{
// Given
var fixture = new FileCopyFixture();
// When
var result = Record.Exception(() =>
FileAliases.MoveFiles(fixture.Context, (string)null, "./target"));
// Then
AssertEx.IsArgumentNullException(result, "pattern");
}
[Fact]
public void Should_Throw_If_Target_Directory_Path_Is_Null()
{
// Given
var fixture = new FileCopyFixture();
// When
var result = Record.Exception(() =>
FileAliases.MoveFiles(fixture.Context, "*", null));
// Then
AssertEx.IsArgumentNullException(result, "targetDirectoryPath");
}
[Fact]
public void Should_Throw_If_Target_Directory_Do_Not_Exist()
{
// Given
var fixture = new FileCopyFixture();
fixture.TargetDirectory = Substitute.For<IDirectory>();
fixture.TargetDirectory.Exists.Returns(false);
// When
var result = Record.Exception(() =>
FileAliases.MoveFiles(fixture.Context, "*", "./target"));
// Then
Assert.IsType<DirectoryNotFoundException>(result);
Assert.Equal("The directory '/Working/target' does not exist.", result?.Message);
}
[Fact]
public void Should_Throw_If_Any_File_Do_Not_Exist()
{
// Given
var fixture = new FileCopyFixture();
fixture.TargetFiles[1] = Substitute.For<IFile>();
fixture.TargetFiles[1].Exists.Returns(false);
// When
var result = Record.Exception(() =>
FileAliases.MoveFiles(fixture.Context, "*", "./target"));
// Then
Assert.IsType<FileNotFoundException>(result);
Assert.Equal("The file '/Working/file2.txt' does not exist.", result?.Message);
}
[Fact]
public void Should_Move_Files()
{
// Given
var fixture = new FileCopyFixture();
// When
FileAliases.MoveFiles(fixture.Context, "*", "./target");
// Then
fixture.TargetFiles[0].Received(1).Move(Arg.Any<FilePath>());
fixture.TargetFiles[1].Received(1).Move(Arg.Any<FilePath>());
}
}
}
public sealed class TheMoveFileMethod
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given, When
var source = new FilePath("./source.txt");
var target = new FilePath("./target.txt");
var result = Record.Exception(() =>
FileAliases.MoveFile(null, source, target));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_Source_File_Path_Is_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
var target = new FilePath("./target.txt");
// When
var result = Record.Exception(() =>
FileAliases.MoveFile(context, null, target));
// Then
AssertEx.IsArgumentNullException(result, "filePath");
}
[Fact]
public void Should_Throw_If_Target_File_Path_Is_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
var source = new FilePath("./source.txt");
// When
var result = Record.Exception(() =>
FileAliases.MoveFile(context, source, null));
// Then
AssertEx.IsArgumentNullException(result, "targetFilePath");
}
[Fact]
public void Should_Throw_If_Target_Directory_Do_Not_Exist()
{
// Given
var fixture = new FileCopyFixture();
fixture.TargetDirectory = Substitute.For<IDirectory>();
fixture.TargetDirectory.Exists.Returns(false);
// When
var result = Record.Exception(() =>
FileAliases.MoveFile(fixture.Context, "./file1.txt", "./target/file1.txt"));
// Then
Assert.IsType<DirectoryNotFoundException>(result);
Assert.Equal("The directory '/Working/target' does not exist.", result?.Message);
}
[Fact]
public void Should_Throw_If_File_Do_Not_Exist()
{
// Given
var fixture = new FileCopyFixture();
fixture.TargetFiles[0] = Substitute.For<IFile>();
fixture.TargetFiles[0].Exists.Returns(false);
// When
var result = Record.Exception(() =>
FileAliases.MoveFile(fixture.Context, "./file1.txt", "./target/file1.txt"));
// Then
Assert.IsType<FileNotFoundException>(result);
Assert.Equal("The file '/Working/file1.txt' does not exist.", result?.Message);
}
[Fact]
public void Should_Move_File()
{
// Given
var fixture = new FileCopyFixture();
// When
FileAliases.MoveFile(fixture.Context, "./file1.txt", "./target/file1.txt");
// Then
fixture.TargetFiles[0].Received(1).Move(
Arg.Is<FilePath>(p => p.FullPath == "/Working/target/file1.txt"));
}
}
public sealed class TheFileExistsMethod
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given, When
var result = Record.Exception(() => FileAliases.FileExists(null, "some file"));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_Path_Is_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
// When
var result = Record.Exception(() => FileAliases.FileExists(context, null));
// Then
AssertEx.IsArgumentNullException(result, "filePath");
}
[Fact]
public void Should_Return_False_If_Directory_Does_Not_Exist()
{
// Given
var context = Substitute.For<ICakeContext>();
var environment = FakeEnvironment.CreateUnixEnvironment();
var fileSystem = new FakeFileSystem(environment);
context.FileSystem.Returns(fileSystem);
context.Environment.Returns(environment);
// When
var result = FileAliases.FileExists(context, "non-existent-file.txt");
// Then
Assert.False(result);
}
[Fact]
public void Should_Return_True_If_Relative_Path_Exist()
{
// Given
var context = Substitute.For<ICakeContext>();
var environment = FakeEnvironment.CreateUnixEnvironment();
environment.WorkingDirectory = "/Working";
var fileSystem = new FakeFileSystem(environment);
fileSystem.CreateFile("/Working/some file.txt");
context.FileSystem.Returns(fileSystem);
context.Environment.Returns(environment);
// When
var result = FileAliases.FileExists(context, "some file.txt");
// Then
Assert.True(result);
}
[Fact]
public void Should_Return_True_If_Absolute_Path_Exist()
{
// Given
var context = Substitute.For<ICakeContext>();
var environment = FakeEnvironment.CreateUnixEnvironment();
environment.WorkingDirectory = "/Working/target";
var fileSystem = new FakeFileSystem(environment);
fileSystem.CreateFile("/Working/target/some file.txt");
context.FileSystem.Returns(fileSystem);
context.Environment.Returns(environment);
// When
var result = FileAliases.FileExists(context, "/Working/target/some file.txt");
// Then
Assert.True(result);
}
}
public sealed class TheMakeAbsoluteMethod
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given, When
var result = Record.Exception(() => FileAliases.MakeAbsolute(null, "./build.txt"));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_Path_Is_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
// When
var result = Record.Exception(() => FileAliases.MakeAbsolute(context, null));
// Then
AssertEx.IsArgumentNullException(result, "filePath");
}
[Fact]
public void Should_Return_Absolute_Directory_Path()
{
// Given
var context = Substitute.For<ICakeContext>();
context.Environment.WorkingDirectory.Returns(d => "/Working");
// When
var result = FileAliases.MakeAbsolute(context, "./build.txt");
// Then
Assert.Equal("/Working/build.txt", result.FullPath);
}
}
public sealed class TheFileSizeMethod
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given, When
var result = Record.Exception(() => FileAliases.FileSize(null, "some file"));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_Path_Is_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
// When
var result = Record.Exception(() => FileAliases.FileSize(context, null));
// Then
AssertEx.IsArgumentNullException(result, "filePath");
}
[Fact]
public void Should_Throw_If_Directory_Does_Not_Exist()
{
// Given
var context = Substitute.For<ICakeContext>();
var environment = FakeEnvironment.CreateUnixEnvironment();
var fileSystem = new FakeFileSystem(environment);
context.FileSystem.Returns(fileSystem);
context.Environment.Returns(environment);
// When / Then
Assert.Throws<FileNotFoundException>(() => FileAliases.FileSize(context, "non-existent-file.txt"));
}
[Theory]
[InlineData("/Working", "/Working/some file.txt")]
[InlineData("/Working/target", "/Working/target/some file.txt")]
public void Should_Return_Size_If_Path_Exist(string workingDirectory, string filePath)
{
// Given
var context = Substitute.For<ICakeContext>();
var environment = FakeEnvironment.CreateUnixEnvironment();
environment.WorkingDirectory = workingDirectory;
var fileSystem = new FakeFileSystem(environment);
fileSystem.CreateFile(filePath, new byte[] { 1, 2, 3, 4 });
context.FileSystem.Returns(fileSystem);
context.Environment.Returns(environment);
// When
var result = FileAliases.FileSize(context, filePath);
// Then
Assert.Equal(result, 4);
}
}
public sealed class TheExpandEnvironmentVariablesMethod
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given, When
var result = Record.Exception(() => FileAliases.ExpandEnvironmentVariables(null, "some file"));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_Path_Is_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
// When
var result = Record.Exception(() => FileAliases.ExpandEnvironmentVariables(context, null));
// Then
AssertEx.IsArgumentNullException(result, "filePath");
}
[Fact]
public void Should_Expand_Existing_Environment_Variables()
{
// Given
var context = Substitute.For<ICakeContext>();
var environment = FakeEnvironment.CreateWindowsEnvironment();
environment.SetEnvironmentVariable("FOO", "bar");
context.Environment.Returns(environment);
// When
var result = FileAliases.ExpandEnvironmentVariables(context, "/%FOO%/baz.qux");
// Then
Assert.Equal("/bar/baz.qux", result.FullPath);
}
}
} | 32.515601 | 111 | 0.522802 | [
"MIT"
] | ecampidoglio/cake | src/Cake.Common.Tests/Unit/IO/FileAliasesTests.cs | 41,687 | 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.Reservations
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for AzureReservationAPIClient.
/// </summary>
public static partial class AzureReservationAPIClientExtensions
{
/// <summary>
/// Get the regions and skus that are available for RI purchase for the
/// specified Azure subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionId'>
/// Id of the subscription
/// </param>
/// <param name='reservedResourceType'>
/// The type of the resource for which the skus should be provided.
/// </param>
/// <param name='location'>
/// Filters the skus based on the location specified in this parameter. This
/// can be an azure region or global
/// </param>
public static IList<Catalog> GetCatalog(this IAzureReservationAPIClient operations, string subscriptionId, string reservedResourceType, string location = default(string))
{
return operations.GetCatalogAsync(subscriptionId, reservedResourceType, location).GetAwaiter().GetResult();
}
/// <summary>
/// Get the regions and skus that are available for RI purchase for the
/// specified Azure subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionId'>
/// Id of the subscription
/// </param>
/// <param name='reservedResourceType'>
/// The type of the resource for which the skus should be provided.
/// </param>
/// <param name='location'>
/// Filters the skus based on the location specified in this parameter. This
/// can be an azure region or global
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<Catalog>> GetCatalogAsync(this IAzureReservationAPIClient operations, string subscriptionId, string reservedResourceType, string location = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetCatalogWithHttpMessagesAsync(subscriptionId, reservedResourceType, location, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get list of applicable `Reservation`s.
/// </summary>
/// <remarks>
/// Get applicable `Reservation`s that are applied to this subscription.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionId'>
/// Id of the subscription
/// </param>
public static AppliedReservations GetAppliedReservationList(this IAzureReservationAPIClient operations, string subscriptionId)
{
return operations.GetAppliedReservationListAsync(subscriptionId).GetAwaiter().GetResult();
}
/// <summary>
/// Get list of applicable `Reservation`s.
/// </summary>
/// <remarks>
/// Get applicable `Reservation`s that are applied to this subscription.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionId'>
/// Id of the subscription
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AppliedReservations> GetAppliedReservationListAsync(this IAzureReservationAPIClient operations, string subscriptionId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetAppliedReservationListWithHttpMessagesAsync(subscriptionId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| 44.20339 | 265 | 0.58934 | [
"MIT"
] | 0xced/azure-sdk-for-net | src/SDKs/Reservations/Management.Reservations/Generated/AzureReservationAPIClientExtensions.cs | 5,216 | C# |
namespace Machete
{
using System;
using Cursors;
using Internals.Extensions;
public static class ParsedCursorExtensions
{
/// <summary>
/// Creates a <see cref="Cursor{T}"/> used to query the parsed result.
/// </summary>
/// <param name="entityResult">The parsed result</param>
/// <typeparam name="TSchema">The schema type</typeparam>
/// <returns>A new cursor, positioned at the start of the parsed result.</returns>
public static Cursor<TSchema> GetCursor<TSchema>(this EntityResult<TSchema> entityResult)
where TSchema : Entity
{
return new EntityResultCursor<TSchema>(entityResult);
}
/// <summary>
/// Parse the parsed input from the beginning, create a new cursor, building the query on the fly
/// </summary>
/// <param name="entityResult"></param>
/// <param name="buildQuery"></param>
/// <typeparam name="TSchema"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <returns></returns>
public static Result<Cursor<TSchema>, TResult> Query<TSchema, TResult>(this EntityResult<TSchema> entityResult, QueryBuilderCallback<TSchema, TResult> buildQuery)
where TSchema : Entity
{
var query = Query<TSchema>.Create(entityResult.Schema, buildQuery);
var cursor = entityResult.GetCursor();
return query.Parse(cursor);
}
/// <summary>
/// Parse the parsed input from the beginning, create a new cursor, building the query on the fly
/// </summary>
/// <param name="entityResult"></param>
/// <param name="query">The query parser</param>
/// <typeparam name="TSchema"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <returns></returns>
public static Result<Cursor<TSchema>, TResult> Query<TSchema, TResult>(this EntityResult<TSchema> entityResult, IParser<TSchema, TResult> query)
where TSchema : Entity
{
var cursor = entityResult.GetCursor();
return query.Parse(cursor);
}
/// <summary>
/// Parse the parsed input from the beginning, create a new cursor, building the query on the fly
/// </summary>
/// <param name="entityResult"></param>
/// <param name="selector">The layout selector</param>
/// <param name="options"></param>
/// <typeparam name="TSchema"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <returns></returns>
public static Result<Cursor<TSchema>, TResult> Query<TSchema, TResult>(this EntityResult<TSchema> entityResult, QueryLayoutSelector<TSchema, TResult> selector,
LayoutParserOptions options = LayoutParserOptions.None)
where TSchema : Entity
where TResult : Layout
{
ILayoutParserFactory<TResult, TSchema> layout;
if (!entityResult.Schema.TryGetLayout(out layout))
throw new ArgumentException($"The layout was not found: {TypeCache<TResult>.ShortName}");
IParser<TSchema, TResult> query = entityResult.CreateQuery(q => layout.CreateParser(options, q));
var cursor = entityResult.GetCursor();
return query.Parse(cursor);
}
}
} | 41.790123 | 170 | 0.611817 | [
"Apache-2.0"
] | amccool/Machete | src/Machete/Querying/ParsedCursorExtensions.cs | 3,387 | C# |
//-------------------------------------------------------------------------
// Copyright © 2019 Province of British Columbia
//
// 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.
//-------------------------------------------------------------------------
namespace HealthGateway.Common.Models.BCMailPlus
{
using System.Collections.Generic;
using System.Text.Json.Serialization;
/// <summary>
/// The BC Mail Plus asset query model.
/// </summary>
public class BcmpAssetQuery
{
/// <summary>
/// Gets or sets the ID of the job corresponding to the asset to retrieve.
/// </summary>
[JsonPropertyName("job")]
public string JobId { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the asset type that should be retrieved.
/// </summary>
[JsonPropertyName("asset")]
public string AssetType { get; set; } = string.Empty;
}
}
| 37.025641 | 82 | 0.59903 | [
"Apache-2.0"
] | bcgov/healthgateway | Apps/Common/src/Models/BCMailPlus/BcmpAssetQuery.cs | 1,445 | C# |
// *** WARNING: this file was generated by crd2pulumi. ***
// *** 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.Kubernetes.Types.Inputs.Monitoring.V1
{
/// <summary>
/// Maps a string key to a path within a volume.
/// </summary>
public class AlertmanagerSpecVolumesConfigMapItemsArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The key to project.
/// </summary>
[Input("key", required: true)]
public Input<string> Key { get; set; } = null!;
/// <summary>
/// Optional: mode bits to use on this file, must be a value between 0 and 0777. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.
/// </summary>
[Input("mode")]
public Input<int>? Mode { get; set; }
/// <summary>
/// The relative path of the file to map the key to. May not be an absolute path. May not contain the path element '..'. May not start with the string '..'.
/// </summary>
[Input("path", required: true)]
public Input<string> Path { get; set; } = null!;
public AlertmanagerSpecVolumesConfigMapItemsArgs()
{
}
}
}
| 36.02439 | 272 | 0.631686 | [
"Apache-2.0"
] | pulumi/pulumi-kubernetes-crds | operators/prometheus/dotnet/Kubernetes/Crds/Operators/Prometheus/Monitoring/V1/Inputs/AlertmanagerSpecVolumesConfigMapItemsArgs.cs | 1,477 | C# |
//
// System.Runtime.InteropServices.ComVisibleAttribute.cs
//
// Author:
// Nick Drochak (ndrochak@gol.com)
//
// (C) 2002 Nick Drochak
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace System.Runtime.InteropServices {
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class
| AttributeTargets.Struct | AttributeTargets.Enum |
AttributeTargets.Method | AttributeTargets.Property |
AttributeTargets.Field | AttributeTargets.Interface |
AttributeTargets.Delegate, Inherited=false)]
[ComVisible (true)]
public sealed class ComVisibleAttribute : Attribute {
private bool Visible = false;
public ComVisibleAttribute (bool visibility)
{
Visible = visibility;
}
public bool Value {
get { return Visible; }
}
}
}
| 32.929825 | 73 | 0.750666 | [
"Apache-2.0"
] | OpenPSS/psm-mono | mcs/class/corlib/System.Runtime.InteropServices/ComVisible.cs | 1,877 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DPA_Musicsheets.enums
{
enum NoteItem
{
Kruis,
Mol,
Geen
}
}
| 14.0625 | 33 | 0.657778 | [
"MIT"
] | JoostVermeulen11/dpamuziekgenerator | DPA_Musicsheets/enums/NoteItem.cs | 227 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shaolinq.AsyncRewriter.Tests
{
public partial interface IFoo
{
[RewriteAsync]
int Bar(string s);
}
public partial class Foo : IFoo
{
[RewriteAsync]
public int Bar(string s)
{
return 0;
}
public Foo Other(int x)
{
return null;
}
}
public partial class ConditionalAccess<T>
{
public class Car
{
public void Toot(bool value)
{
}
}
public Foo foo;
private Foo GetCurrentFoo()
{
return null;
}
[RewriteAsync]
public IQueryable<T> GetAll()
{
return null;
}
[RewriteAsync]
public IQueryable<U> GetBalls<U>()
{
return null;
}
public async void Test3Async()
{
if (true)
{
var q = await this.GetAllAsync();
q.Where(c => true);
var x = q.Where(c => true).ToList();
if (true)
{
var q2 = await this.GetAllAsync();
q2.Where(c => true).ToList();
}
}
}
}
}
| 13.25974 | 42 | 0.606268 | [
"MIT"
] | asizikov/Shaolinq | tests/Shaolinq.AsyncRewriter.Tests/RewriteTests/ConditionalAccess.cs | 1,023 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Kekonn.TagHelpers.Core.Assets
{
public enum AssetType
{
Script,
Stylesheet,
Library
}
} | 15.538462 | 39 | 0.653465 | [
"MIT"
] | bloodsplatter/TagHelpers | Kekonn.TagHelpers.Core.Assets/AssetType.cs | 204 | C# |
namespace <%- namespaceContext %>.Core
{
using System;
using Loymax.Core;
using Loymax.Core.Modules;
using Loymax.Core.Settings.Client;
public class CoreApp : App
{
public override Type MainViewModelType => typeof(Loymax.Module.Offers.ViewModels.OffersViewModel);
protected override IClientEnvironmentSettings CreateClientSettings()
{
return new ClientEnvironmentSettings(typeof(CoreApp).Assembly,
#if DEBUG
BuildEnvironmentType.Development
#elif ADHOC
BuildEnvironmentType.Staging
#else
BuildEnvironmentType.Production
#endif
);
}
public override void LoadModules(ILxModuleManager moduleManager)
{
base.LoadModules(moduleManager);
<%- coreAppContext %>
}
}
} | 26.34375 | 106 | 0.642942 | [
"Apache-2.0"
] | loymax/MobileTemplate | XLoyalty.Core/CoreApp.cs | 843 | C# |
using System;
using UnityEngine;
namespace GameSettings
{
[CreateAssetMenu(fileName = "PixelLightCountSetting", menuName = "Game Settings/Quality/Pixel Light Count")]
public class PixelLightCountSetting : IntSetting
{
public const int min = 0;
public override string settingName => "Pixel Light Count";
public override int value
{
get => QualitySettings.pixelLightCount;
set => QualitySettings.pixelLightCount = Mathf.Max(value, min);
}
}
}
| 26.25 | 112 | 0.659048 | [
"MIT"
] | Casey-Hofland/GameSettings | Runtime/Quality/PixelLightCountSetting.cs | 527 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace TestStack.White.ScreenObjects.Services
{
public class ServiceCalls : List<ServiceCall>
{
public ServiceCalls(IEnumerable entities) : base(entities.OfType<ServiceCall>()) {}
public ServiceCalls() {}
public virtual ServiceCalls Matching(ServiceCall match)
{
return new ServiceCalls(FindAll(obj => obj.Equals(match)));
}
}
} | 28.941176 | 92 | 0.662602 | [
"Apache-2.0",
"MIT"
] | DaveWeath/White | src/TestStack.White.ScreenObjects/Services/ServiceCalls.cs | 476 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace EventManagementSystem
{
public partial class notificationPage
{
/// <summary>
/// gvnotification control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.GridView gvnotification;
}
}
| 28.703704 | 84 | 0.490323 | [
"MIT"
] | RakeshThakur26/Assignment4 | EventManagement/EventManagement/notificationPage.aspx.designer.cs | 777 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using SuperSocket.SocketBase.Metadata;
using SuperSocket.ProtoBase;
namespace SuperSocket.Dlr
{
class DynamicCommand<TAppSession, TRequestInfo> : ICommand<TAppSession, TRequestInfo>, ICommandFilterProvider
where TAppSession : IAppSession, IAppSession<TAppSession, TRequestInfo>, new()
where TRequestInfo : IPackageInfo
{
private Action<TAppSession, TRequestInfo> m_DynamicExecuteCommand;
private IEnumerable<CommandFilterAttribute> m_Filters;
public DynamicCommand(ScriptRuntime scriptRuntime, IScriptSource source)
{
Source = source;
Name = source.Name;
var scriptEngine = scriptRuntime.GetEngineByFileExtension(source.LanguageExtension);
var scriptScope = scriptEngine.CreateScope();
var scriptSource = scriptEngine.CreateScriptSourceFromString(source.GetScriptCode(), SourceCodeKind.File);
var compiledCode = scriptSource.Compile();
compiledCode.Execute(scriptScope);
Action<TAppSession, TRequestInfo> dynamicMethod;
if (!scriptScope.TryGetVariable<Action<TAppSession, TRequestInfo>>("execute", out dynamicMethod))
throw new Exception("Failed to find a command execution method in source: " + source.Tag);
Func<IEnumerable<CommandFilterAttribute>> filtersAction;
if (scriptScope.TryGetVariable<Func<IEnumerable<CommandFilterAttribute>>>("getFilters", out filtersAction))
m_Filters = filtersAction();
CompiledTime = DateTime.Now;
m_DynamicExecuteCommand = dynamicMethod;
}
#region ICommand<TAppSession,TRequestInfo> Members
public virtual void ExecuteCommand(TAppSession session, TRequestInfo requestInfo)
{
m_DynamicExecuteCommand(session, requestInfo);
}
#endregion
public IScriptSource Source { get; private set; }
public DateTime CompiledTime { get; private set; }
#region ICommand Members
public string Name { get; private set; }
#endregion
public override string ToString()
{
return Source.Tag;
}
public IEnumerable<CommandFilterAttribute> GetFilters()
{
return m_Filters;
}
}
}
| 32.3 | 119 | 0.686146 | [
"Apache-2.0"
] | cnsuhao/SuperSocket | Dlr/DynamicCommand.cs | 2,586 | C# |
using System;
using System.Data;
using CMS.CustomTables;
using CMS.DataEngine;
using CMS.Helpers;
using CMS.SiteProvider;
using CMS.UIControls;
public partial class CMSModules_AdminControls_Controls_Class_ClassSites : CMSUserControl
{
private int mClassId;
private string mTitleString;
private bool mCheckLicense = true;
private string currentValues = String.Empty;
#region "Public properties"
/// <summary>
/// Gets or sets the value that indicates whether license should be chcecked.
/// </summary>
public bool CheckLicense
{
get
{
return mCheckLicense;
}
set
{
mCheckLicense = value;
}
}
/// <summary>
/// Gets or sets class id.
/// </summary>
public int ClassId
{
get
{
return mClassId;
}
set
{
mClassId = value;
}
}
/// <summary>
/// Gets or sets the title at the top of the page.
/// </summary>
public string TitleString
{
get
{
return mTitleString;
}
set
{
mTitleString = value;
}
}
#endregion
/// <summary>
/// Page load.
/// </summary>
protected void Page_Load(object sender, EventArgs e)
{
if (ClassId > 0)
{
// initializes labels
headTitle.Text = TitleString;
// Get the user sites
currentValues = GetClassSites();
if (!RequestHelper.IsPostBack())
{
usSites.Value = currentValues;
}
usSites.OnSelectionChanged += usSites_OnSelectionChanged;
}
else
{
// Hide control if not properly set
Visible = false;
}
}
/// <summary>
/// Returns string with class sites.
/// </summary>
private string GetClassSites()
{
DataSet ds = ClassSiteInfoProvider.GetClassSites().WhereEquals("ClassID", ClassId).Column("SiteID");
if (!DataHelper.DataSourceIsEmpty(ds))
{
return TextHelper.Join(";", DataHelper.GetStringValues(ds.Tables[0], "SiteID"));
}
return String.Empty;
}
/// <summary>
/// Handles site selector selection change event.
/// </summary>
protected void usSites_OnSelectionChanged(object sender, EventArgs e)
{
SaveSites();
}
protected void SaveSites()
{
// Remove old items
string newValues = ValidationHelper.GetString(usSites.Value, null);
string items = DataHelper.GetNewItemsInList(newValues, currentValues);
if (!String.IsNullOrEmpty(items))
{
string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
if (newItems != null)
{
// Add all new items to site
foreach (string item in newItems)
{
int siteId = ValidationHelper.GetInteger(item, 0);
ClassSiteInfoProvider.RemoveClassFromSite(ClassId, siteId);
}
}
}
// Add new items
items = DataHelper.GetNewItemsInList(currentValues, newValues);
if (!String.IsNullOrEmpty(items))
{
string[] newItems = items.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
bool falseValues = false;
// Add all new items to site
foreach (string item in newItems)
{
int siteId = ValidationHelper.GetInteger(item, 0);
SiteInfo si = SiteInfoProvider.GetSiteInfo(siteId);
if (si != null)
{
// Check license
if (CheckLicense && !CustomTableItemProvider.LicenseVersionCheck(si.DomainName, ObjectActionEnum.Insert))
{
if (ClassSiteInfoProvider.GetClassSiteInfo(ClassId, siteId) == null)
{
// Show error message
ShowError(GetString("LicenseVersion.CustomTables"));
falseValues = true;
continue;
}
}
try
{
ClassSiteInfoProvider.AddClassToSite(ClassId, siteId);
}
catch (Exception ex)
{
// Show error message
ShowError(ex.Message);
return;
}
}
}
// If some of sites could not be assigned reload selector value
if (falseValues)
{
usSites.Value = GetClassSites();
usSites.Reload(true);
}
}
if (CheckLicense)
{
CustomTableItemProvider.ClearLicensesCount(true);
}
// Show message
ShowChangesSaved();
}
} | 26.636816 | 126 | 0.485805 | [
"MIT"
] | CMeeg/kentico-contrib | src/CMS/CMSModules/AdminControls/Controls/Class/ClassSites.ascx.cs | 5,356 | C# |
using System;
using System.Linq;
using Sitecore.Data;
using Sitecore.Links;
using Sitecore.Data.Items;
using Sitecore.Publishing;
using Sitecore.Data.Fields;
using Sitecore.Diagnostics;
using Sitecore.Data.Managers;
using Sitecore.Resources.Media;
using System.Collections.Generic;
namespace Sitecore.Foundation.SitecoreExtensions.Extensions
{
public static class ItemExtensions
{
/// <summary>
/// Common re-usable GetMediaItemImage() extension method
/// </summary>
/// <param name="mediaItem"></param>
/// <param name="imageCss"></param>
/// <returns>The Image Html string from the mediaItem Item object</returns>
public static string GetMediaItemImage(this MediaItem mediaItem, string imageCss = "")
{
var imgSrcUrl = mediaItem == null ? string.Empty : StringUtil.EnsurePrefix('/', MediaManager.GetMediaUrl(mediaItem));
var imgAlt = mediaItem == null ? string.Empty : mediaItem.Alt.Trim();
return $@"<img class'{imageCss}' src='{imgSrcUrl}' alt='{imgAlt}' />";
}
/// <summary>
/// Common re-usable ImageUrl() extension method
/// </summary>
/// <param name="imageField"></param>
/// <returns>The Image Url string value from the imageField Item object</returns>
[Obsolete]
public static string ImageUrl(this ImageField imageField)
{
if (imageField?.MediaItem == null)
{
throw new ArgumentNullException(nameof(imageField));
}
var options = MediaUrlOptions.Empty;
if (int.TryParse(imageField.Width, out var width))
{
options.Width = width;
}
if (int.TryParse(imageField.Height, out var height))
{
options.Height = height;
}
return imageField.ImageUrl(options);
}
/// <summary>
/// Common re-usable ImageUrl() extension method with options
/// </summary>
/// <param name="imageField"></param>
/// <param name="options"></param>
/// <returns>The Image Url string value from the imageField Item object</returns>
[Obsolete]
public static string ImageUrl(this ImageField imageField, MediaUrlOptions options)
{
if (imageField?.MediaItem == null)
{
throw new ArgumentNullException(nameof(imageField));
}
return options == null ? imageField.ImageUrl() : HashingUtils.ProtectAssetUrl(MediaManager.GetMediaUrl(imageField.MediaItem, options));
}
/// <summary>
/// Common re-usable IsChecked() extension method
/// </summary>
/// <param name="checkboxField"></param>
/// <returns>The IsChecked boolean status from the checkboxField object</returns>
public static bool IsChecked(this Field checkboxField)
{
if (checkboxField == null)
{
throw new ArgumentNullException(nameof(checkboxField));
}
return MainUtil.GetBool(checkboxField.Value, false);
}
/// <summary>
/// Common re-usable Url() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="options"></param>
/// <returns>The Url string value from the contextItem Item object</returns>
[Obsolete]
public static string Url(this Item contextItem, UrlOptions options = null)
{
if (contextItem == null)
{
throw new ArgumentNullException(nameof(contextItem));
}
if (options != null)
{
return LinkManager.GetItemUrl(contextItem, options);
}
return !contextItem.Paths.IsMediaItem ? LinkManager.GetItemUrl(contextItem) : MediaManager.GetMediaUrl(contextItem);
}
/// <summary>
/// Common re-usable ImageUrl() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="imageFieldId"></param>
/// <param name="options"></param>
/// <returns>The ImageUrl string value from the contextItem Item object</returns>
[Obsolete]
public static string ImageUrl(this Item contextItem, ID imageFieldId, MediaUrlOptions options = null)
{
if (contextItem == null)
{
throw new ArgumentNullException(nameof(contextItem));
}
var imageField = FieldExtensions.GetImageField(contextItem, imageFieldId);
return imageField?.MediaItem == null ? string.Empty : imageField.ImageUrl(options);
}
/// <summary>
/// Common re-usable ImageUrl() extension method
/// </summary>
/// <param name="mediaItem"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns>The ImageUrl string value from the mediaItem Item object</returns>
[Obsolete]
public static string ImageUrl(this MediaItem mediaItem, int width, int height)
{
if (mediaItem == null)
{
throw new ArgumentNullException(nameof(mediaItem));
}
var options = new MediaUrlOptions { Height = height, Width = width };
var url = MediaManager.GetMediaUrl(mediaItem, options);
var cleanUrl = StringUtil.EnsurePrefix('/', url);
var hashedUrl = HashingUtils.ProtectAssetUrl(cleanUrl);
return hashedUrl;
}
/// <summary>
/// Common re-usable TargetItem() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="linkFieldId"></param>
/// <returns>The TargetItem Item object from the mediaItem Item object</returns>
public static Item TargetItem(this Item contextItem, ID linkFieldId)
{
if (contextItem == null)
{
throw new ArgumentNullException(nameof(contextItem));
}
if (contextItem.Fields[linkFieldId] == null || !contextItem.Fields[linkFieldId].HasValue)
{
return null;
}
var linkField = (LinkField)contextItem.Fields[linkFieldId];
var referenceField = (ReferenceField)contextItem.Fields[linkFieldId];
return linkField.TargetItem ?? referenceField.TargetItem;
}
/// <summary>
/// Common re-usable MediaUrl() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="mediaFieldId"></param>
/// <param name="options"></param>
/// <returns>The MediaUrl string value from the contextItem Item object</returns>
[Obsolete]
public static string MediaUrl(this Item contextItem, ID mediaFieldId, MediaUrlOptions options = null)
{
var targetItem = contextItem.TargetItem(mediaFieldId);
return targetItem == null ? string.Empty : (MediaManager.GetMediaUrl(targetItem) ?? string.Empty);
}
/// <summary>
/// Common re-usable IsImage() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <returns>The IsImage boolean status from the contextItem Item object</returns>
public static bool IsImage(this Item contextItem)
{
return new MediaItem(contextItem).MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase);
}
/// <summary>
/// Common re-usable IsVideo() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <returns>The IsVideo boolean status from the contextItem Item object</returns>
public static bool IsVideo(this Item contextItem)
{
return new MediaItem(contextItem).MimeType.StartsWith("video/", StringComparison.InvariantCultureIgnoreCase);
}
/// <summary>
/// Common re-usable GetAncestorOrSelfOfTemplate() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="templateId"></param>
/// <returns>The AncestorOrSelfOfTemplate Item object from the contextItem Item object</returns>
public static Item GetAncestorOrSelfOfTemplate(this Item contextItem, ID templateId)
{
if (contextItem == null)
{
throw new ArgumentNullException(nameof(contextItem));
}
return contextItem.IsDerived(templateId) ? contextItem : contextItem.Axes.GetAncestors().LastOrDefault(i => i.IsDerived(templateId));
}
/// <summary>
/// Common re-usable GetAncestorsAndSelfOfTemplate() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="templateId"></param>
/// <returns>The List of AncestorOrSelfOfTemplate Items from the contextItem Item object</returns>
public static IList<Item> GetAncestorsAndSelfOfTemplate(this Item contextItem, ID templateId)
{
if (contextItem == null)
{
throw new ArgumentNullException(nameof(contextItem));
}
var returnValue = new List<Item>();
if (contextItem.IsDerived(templateId))
{
returnValue.Add(contextItem);
}
returnValue.AddRange(contextItem.Axes.GetAncestors().Reverse().Where(i => i.IsDerived(templateId)));
return returnValue;
}
/// <summary>
/// Common re-usable LinkFieldUrl() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="fieldId"></param>
/// <returns>The LinkFieldUrl string value from the contextItem Item object</returns>
public static string LinkFieldUrl(this Item contextItem, ID fieldId)
{
if (contextItem == null)
{
throw new ArgumentNullException(nameof(contextItem));
}
if (ID.IsNullOrEmpty(fieldId))
{
throw new ArgumentNullException(nameof(fieldId));
}
var linkField = FieldExtensions.GetLinkField(contextItem, fieldId);
if (linkField == null)
{
return string.Empty;
}
switch (linkField.LinkType.ToLower())
{
case "internal":
// Use LinkMananger for internal links, if link is not empty
return linkField.TargetItem != null ? LinkManager.GetItemUrl(linkField.TargetItem) : string.Empty;
case "media":
// Use MediaManager for media links, if link is not empty
return linkField.TargetItem != null ? MediaManager.GetMediaUrl(linkField.TargetItem) : string.Empty;
case "external":
// Just return external links
return linkField.Url;
case "anchor":
// Prefix anchor link with # if link if not empty
return !string.IsNullOrEmpty(linkField.Anchor) ? "#" + linkField.Anchor : string.Empty;
case "mailto":
// Just return mailto link
return linkField.Url;
case "javascript":
// Just return javascript
return linkField.Url;
default:
// Just please the compiler, this
// condition will never be met
return linkField.Url;
}
}
/// <summary>
/// Common re-usable LinkFieldTarget() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="fieldId"></param>
/// <returns>The LinkFieldTarget string value from the contextItem Item object</returns>
public static string LinkFieldTarget(this Item contextItem, ID fieldId)
{
return contextItem.LinkFieldOptions(fieldId, LinkFieldOption.Target);
}
/// <summary>
/// Common re-usable LinkFieldOptions() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="fieldId"></param>
/// <param name="option"></param>
/// <returns>The LinkFieldOptions string value from the contextItem Item object</returns>
public static string LinkFieldOptions(this Item contextItem, ID fieldId, LinkFieldOption option)
{
XmlField field = contextItem.Fields[fieldId];
switch (option)
{
case LinkFieldOption.Text:
return field?.GetAttribute("text");
case LinkFieldOption.LinkType:
return field?.GetAttribute("linktype");
case LinkFieldOption.Class:
return field?.GetAttribute("class");
case LinkFieldOption.Alt:
return field?.GetAttribute("title");
case LinkFieldOption.Target:
return field?.GetAttribute("target");
case LinkFieldOption.QueryString:
return field?.GetAttribute("querystring");
default:
throw new ArgumentOutOfRangeException(nameof(option), option, null);
}
}
/// <summary>
/// Common re-usable HasLayout() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <returns>The HasLayout boolean status from the contextItem Item object</returns>
public static bool HasLayout(this Item contextItem)
{
return contextItem?.Visualization?.Layout != null;
}
/// <summary>
/// Common re-usable IsDerived() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="templateId"></param>
/// <returns>The IsDerived boolean status from the contextItem Item object</returns>
public static bool IsDerived(this Item contextItem, ID templateId)
{
if (contextItem == null)
{
return false;
}
return !templateId.IsNull && contextItem.IsDerived(contextItem.Database.Templates[templateId]);
}
/// <summary>
/// Common re-usable IsDerived() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="templateItem"></param>
/// <returns>The IsDerived boolean status from the contextItem Item object</returns>
private static bool IsDerived(this Item contextItem, Item templateItem)
{
if (contextItem == null)
{
return false;
}
if (templateItem == null)
{
return false;
}
var itemTemplate = TemplateManager.GetTemplate(contextItem);
return itemTemplate != null && (itemTemplate.ID == templateItem.ID || itemTemplate.DescendsFrom(templateItem.ID));
}
/// <summary>
/// Common re-usable FieldHasValue() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="fieldKey"></param>
/// <returns>The FieldHasValue boolean status from the contextItem Item object</returns>
public static bool FieldHasValue(this Item contextItem, string fieldKey)
{
return FieldExtensions.IsValidFieldValueByKeyHasValue(contextItem, fieldKey);
}
/// <summary>
/// Common re-usable FieldHasValue() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="fieldId"></param>
/// <returns>The FieldHasValue boolean status from the contextItem Item object</returns>
public static bool FieldHasValue(this Item contextItem, ID fieldId)
{
return FieldExtensions.IsValidFieldValueByKeyHasValue(contextItem, fieldId);
}
/// <summary>
/// Common re-usable GetInteger() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="fieldKey"></param>
/// <returns>The Field Item's Integer value from the contextItem Item object</returns>
public static int GetInteger(this Item contextItem, string fieldKey)
{
int.TryParse(FieldExtensions.GetFieldValueByKey(contextItem, fieldKey), out var result);
return result;
}
/// <summary>
/// Common re-usable GetInteger() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="fieldId"></param>
/// <returns>The Field Item's Integer value from the contextItem Item object</returns>
public static int GetInteger(this Item contextItem, ID fieldId)
{
int.TryParse(FieldExtensions.GetFieldValueByKey(contextItem, fieldId), out var result);
return result;
}
/// <summary>
/// Common re-usable GetMultiListValueItems() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="fieldKey"></param>
/// <returns>The List of MultiListValueItems from the contextItem Item object</returns>
public static IEnumerable<Item> GetMultiListValueItems(this Item contextItem, string fieldKey)
{
return FieldExtensions.IsValidFieldValueByKeyHasValue(contextItem, fieldKey)
? FieldExtensions.GetMultiListField(contextItem, fieldKey).GetItems().ToList()
: new List<Item>();
}
/// <summary>
/// Common re-usable GetMultiListValueItems() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="fieldId"></param>
/// <returns>The List of MultiListValueItems from the contextItem Item object</returns>
public static IEnumerable<Item> GetMultiListValueItems(this Item contextItem, ID fieldId)
{
return FieldExtensions.IsValidFieldValueByKeyHasValue(contextItem, fieldId)
? FieldExtensions.GetMultiListField(contextItem, fieldId).GetItems().ToList()
: new List<Item>();
}
/// <summary>
/// Common re-usable GetImageFieldItem() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="fieldKey"></param>
/// <returns>The List of GetImageFieldItem from the contextItem Item object</returns>
public static ImageField GetImageFieldItem(this Item contextItem, string fieldKey)
{
return FieldExtensions.GetImageField(contextItem, fieldKey);
}
/// <summary>
/// Common re-usable GetImageFieldItem() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="fieldId"></param>
/// <returns>The List of GetImageFieldItem from the contextItem Item object</returns>
public static ImageField GetImageFieldItem(this Item contextItem, ID fieldId)
{
return FieldExtensions.GetImageField(contextItem, fieldId);
}
/// <summary>
/// Common re-usable HasContextLanguage() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <returns>The HasContextLanguage from the contextItem Item object</returns>
public static bool HasContextLanguage(this Item contextItem)
{
var latestVersion = contextItem.Versions.GetLatestVersion();
return latestVersion?.Versions.Count > 0;
}
/// <summary>
/// Common re-usable ReferencedFieldItem() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="fieldKey"></param>
/// <returns>The ReferencedFieldItem object from the contextItem Item object</returns>
public static Item ReferencedFieldItem(this Item contextItem, string fieldKey)
{
Item targetItem = null;
var referenceField = FieldExtensions.GetReferenceField(contextItem, fieldKey);
if (referenceField?.TargetItem != null)
{
targetItem = referenceField.TargetItem;
}
return targetItem;
}
/// <summary>
/// Common re-usable ReferencedFieldItem() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="fieldId"></param>
/// <returns>The ReferencedFieldItem object from the contextItem Item object</returns>
public static Item ReferencedFieldItem(this Item contextItem, ID fieldId)
{
Item targetItem = null;
var referenceField = FieldExtensions.GetReferenceField(contextItem, fieldId);
if (referenceField?.TargetItem != null)
{
targetItem = referenceField.TargetItem;
}
return targetItem;
}
/// <summary>
/// Common re-usable FirstChildDerivedFromTemplate() extension method
/// </summary>
/// <param name="contextItem"></param>
/// <param name="templateId"></param>
/// <returns>The FirstChildDerivedFromTemplate Item or null object from the contextItem Item object</returns>
public static Item FirstChildDerivedFromTemplate(this Item contextItem, ID templateId)
{
if (contextItem == null || contextItem.HasChildren != true)
{
return null;
}
foreach (Item child in contextItem.Children)
{
if (child.IsDerived(templateId) == true)
{
return child;
}
}
return null;
}
/// <summary>
/// Common re-usable PublishItem() extension method
/// </summary>
/// <param name="item"></param>
/// <param name="publishMode"></param>
/// <param name="dbTarget"></param>
/// <param name="publishAsync"></param>
/// <param name="deepPublish"></param>
/// <param name="publishRelatedItems"></param>
/// <param name="compareRevisions"></param>
public static void PublishItem(this Item item, PublishMode publishMode, string dbTarget, bool publishAsync = false, bool deepPublish = false, bool publishRelatedItems = false, bool compareRevisions = false)
{
try
{
var publishOptions = new PublishOptions(item.Database, Database.GetDatabase(dbTarget), publishMode, item.Language, DateTime.Now)
{
RootItem = item,
Deep = deepPublish,
PublishRelatedItems = publishRelatedItems,
CompareRevisions = compareRevisions
};
var publisher = new Publisher(publishOptions);
if (publishAsync)
{
publisher.PublishAsync();
}
else
{
publisher.Publish();
}
}
catch (Exception ex)
{
LogExt.LogApiResponseMessages(Helpers.GetMethodName(), $@"Exception Error: {ex.Message}. {ex.StackTrace}.", "", true);
}
}
}
/// <summary>
/// LinkFieldOption enum object
/// </summary>
public enum LinkFieldOption
{
Text,
LinkType,
Class,
Alt,
Target,
QueryString
}
} | 33.97615 | 208 | 0.698255 | [
"MIT"
] | ppatel-sitecore/headstart | src/Middleware/src/Sitecore.Foundation.SitecoreExtensions/code/Extensions/ItemExtensions.cs | 19,946 | C# |
// ---------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ---------------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Xml.Linq;
using Windows.Storage;
using Windows.UI.Xaml.Media.Imaging;
namespace FamilyNotes
{
/// <summary>
/// Represents the settings for the FamilyNotes app.
/// This class is designed to be serializable.
/// BindableBase is part of a collection of task snippets
/// that you can freely use in your code.
/// See https://github.com/Microsoft/Windows-task-snippets/blob/master/tasks/Data-binding-change-notification.md
/// </summary>
public class Settings : BindableBase
{
/// <summary>
/// The wallpaper bitmap to use for the background
/// </summary>
[IgnoreDataMemberAttribute]
public BitmapImage FamilyNotesWallPaper
{
get
{
return _familyNotesWallPaper;
}
set
{
SetProperty(ref _familyNotesWallPaper, value);
}
}
/// <summary>
/// Your key for the Microsoft Face API that allows you to use the service
/// </summary>
[DataMember]
public string FaceApiKey
{
get
{
return _faceApiKey;
}
set
{
SetProperty(ref _faceApiKey, value);
}
}
/// <summary>
/// The default CameraID
/// </summary>
[DataMember]
public string DefaultCameraID
{
get
{
return _defaultCameraID;
}
set
{
SetProperty(ref _defaultCameraID, value);
}
}
/// <summary>
/// Gets or sets whether the app background should be the Bing image of the day or not.
/// </summary>
[DataMember]
public bool UseBingImageOfTheDay
{
get
{
return _useBingImageOfTheDay;
}
set
{
if (value != _useBingImageOfTheDay)
{
_useBingImageOfTheDay = value;
var fireAndForget = ChangeWallPaperAsync(value); // binding will update the UI when the FamilyNotesWallpaper gets set
OnPropertyChanged(nameof(UseBingImageOfTheDay)); // notifies UI that is binding to property that it has changed.
}
}
}
/// <summary>
/// Gets or sets a flag to determine if this is the very first time the app has been launched
/// </summary>
[DataMember]
public bool LaunchedPreviously
{
get
{
return _launchedPreviously;
}
set
{
SetProperty(ref _launchedPreviously, value);
}
}
/// <summary>
/// Save app settings. These settings will roam.
/// </summary>
public void SaveSettings()
{
ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
settings.Values[WALLPAPER] = UseBingImageOfTheDay;
settings.Values[MICRFOSOFT_FACESERVICE_KEY] = FaceApiKey;
settings.Values[NOTFIRSTLAUNCH] = true;
settings.Values[DEFAULTCAMERAID] = DefaultCameraID;
}
/// <summary>
/// Load app settings.
/// </summary>
public void LoadSettings()
{
ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
bool? useBingImage = (bool?)settings.Values[WALLPAPER];
UseBingImageOfTheDay = useBingImage.HasValue ? useBingImage.Value : false;
string faceApiKey = (string)settings.Values[MICRFOSOFT_FACESERVICE_KEY];
FaceApiKey = faceApiKey != null ? faceApiKey : "";
bool? notFirstLaunch = (bool?)settings.Values[NOTFIRSTLAUNCH];
LaunchedPreviously = notFirstLaunch.HasValue ? notFirstLaunch.Value : false;
string defaultCameraID = (string)settings.Values[DEFAULTCAMERAID];
DefaultCameraID = defaultCameraID != null ? defaultCameraID : "";
}
/// <summary>
/// Set the wallpaper (either the bing image of the day or the default brushed steel)
/// </summary>
/// <param name="useBingImageOfTheDay">True = use the Bing image of the day; False = use the brushed steel wallpaper</param>
private async Task ChangeWallPaperAsync(bool useBingImageOfTheDay)
{
if (useBingImageOfTheDay == true)
{
try
{
FamilyNotesWallPaper = new BitmapImage(await GetBingImageOfTheDayUriAsync());
return;
}
catch (System.Net.Http.HttpRequestException)
{
// Fall through to use the default brush steel image instead.
}
}
// When we aren't using the bing image of the day, default to the brush steel background appearance
FamilyNotesWallPaper = new BitmapImage(new Uri(new Uri("ms-appx://"), "Assets/brushed_metal_texture.jpg"));
}
private enum Resolution { Unspecified, _800x600, _1024x768, _1366x768, _1920x1080, _1920x1200 }
/// <summary>
/// Gets the Uri for the Bing imageof the day.
/// Note that this task snippet is available on GitHub at https://github.com/Microsoft/Windows-task-snippets
/// </summary>
/// <param name="resolution"></param>
/// <param name="market"></param>
/// <returns></returns>
private async Task<Uri> GetBingImageOfTheDayUriAsync(
Resolution resolution = Resolution.Unspecified,
string market = "en-ww")
{
var request = new Uri($"http://www.bing.com/hpimagearchive.aspx?n=1&mkt={market}");
string result = null;
using (var httpClient = new HttpClient())
{
result = await httpClient.GetStringAsync(request);
}
var targetElement = resolution == Resolution.Unspecified ? "url" : "urlBase";
var pathString = XDocument.Parse(result).Descendants(targetElement).First().Value;
var resolutionString = resolution == Resolution.Unspecified ? "" : $"{resolution}.jpg";
return new Uri($"http://www.bing.com{pathString}{resolutionString}");
}
private bool _useBingImageOfTheDay;
private bool _launchedPreviously;
private string _defaultCameraID;
private string _faceApiKey = "";
private BitmapImage _familyNotesWallPaper = new BitmapImage(new Uri(new Uri("ms-appx://"), "Assets/brushed_metal_texture.jpg")); // Before the user has decided on the background, use the brushed steel.
private const string WALLPAPER = "UseBingImageOfTheDay";
private const string MICRFOSOFT_FACESERVICE_KEY = "MicrosoftFaceServiceKey";
private const string NOTFIRSTLAUNCH = "NotTheAppFirstLaunch";
private const string DEFAULTCAMERAID = "DefaultCameraID";
}
} | 39.977064 | 209 | 0.591738 | [
"MIT"
] | Bhaskers-Blu-Org2/Windows-appsample-familynotes | FamilyNotes/Settings.cs | 8,717 | 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("MicroJSON")]
[assembly: AssemblyDescription("JSON library for .Net Micro Framework")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MicroJSON")]
[assembly: AssemblyCopyright("Mario Vernari Copyright © 2014")]
[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("fbdce615-0a1d-483b-a00a-304b58ca7bd1")]
// 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.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| 38.972973 | 84 | 0.747573 | [
"Apache-2.0"
] | ppatierno/microjson | MicroJSON/Properties/AssemblyInfo.cs | 1,445 | 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.SecretsManager")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Secrets Manager. AWS Secrets Manager enables you to easily create and manage the secrets that you use in your customer-facing apps. Instead of embedding credentials into your source code, you can dynamically query Secrets Manager from your app whenever you need credentials. You can automatically and frequently rotate your secrets without having to deploy updates to your apps. All secret values are encrypted when they're at rest with AWS KMS, and while they're in transit with HTTPS and TLS.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2019 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.3.101.23")] | 58.0625 | 578 | 0.764801 | [
"Apache-2.0"
] | jiabiao/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/SecretsManager/Properties/AssemblyInfo.cs | 1,858 | C# |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
using MoreMountains.Tools;
using MoreMountains.Feedbacks;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace MoreMountains.Tools
{
/// <summary>
/// Add this class to a camera and you'll be able to pilot it using the horizontal/vertical axis, and up/down controls set via its inspector.
/// It's got an activation button, a run button, and an option to slow down time (this will require a MMTimeManager present in the scene)
/// </summary>
[AddComponentMenu("More Mountains/Tools/Camera/MMGhostCamera")]
public class MMGhostCamera : MonoBehaviour
{
[Header("Speed")]
/// the camera's movement speed
public float MovementSpeed = 10f;
/// the factor by which to multiply the speed when "running"
public float RunFactor = 4f;
/// the movement's acceleration
public float Acceleration = 5f;
/// the movement's deceleration
public float Deceleration = 5f;
/// the speed at which the camera rotates
public float RotationSpeed = 40f;
[Header("Controls")]
/// the button used to toggle the camera on/off
public KeyCode ActivateButton = KeyCode.RightShift;
/// the name of the InputManager's horizontal axis
public string HorizontalAxisName = "Horizontal";
/// the name of the InputManager's vertical axis
public string VerticalAxisName = "Vertical";
/// the button to use to go up
public KeyCode UpButton = KeyCode.Space;
/// the button to use to go down
public KeyCode DownButton = KeyCode.C;
/// the button to use to switch between mobile and desktop control mode
public KeyCode ControlsModeSwitch = KeyCode.M;
/// the button used to modify the timescale
public KeyCode TimescaleModificationButton = KeyCode.F;
/// the button used to run while it's pressed
public KeyCode RunButton = KeyCode.LeftShift;
/// the mouse's sensitivity
public float MouseSensitivity = 0.02f;
/// the right stick sensitivity
public float MobileStickSensitivity = 2f;
[Header("Timescale Modification")]
/// the amount to modify the timescale by when pressing the timescale button
public float TimescaleModifier = 0.5f;
[Header("Settings")]
/// whether or not this camera should activate on start
public bool AutoActivation = true;
/// whether or not movement (up/down/left/right/forward/backward) is enabled
public bool MovementEnabled = true;
// whether or not rotation is enabled
public bool RotationEnabled = true;
[MMReadOnly]
/// whether this camera is active or not right now
public bool Active = false;
[MMReadOnly]
/// whether time is being altered right now or not
public bool TimeAltered = false;
[Header("Virtual Joysticks")]
public bool UseMobileControls;
[MMCondition("UseMobileControls", true)]
public GameObject LeftStickContainer;
[MMCondition("UseMobileControls", true)]
public GameObject RightStickContainer;
[MMCondition("UseMobileControls", true)]
public MMTouchJoystick LeftStick;
[MMCondition("UseMobileControls", true)]
public MMTouchJoystick RightStick;
protected Vector3 _currentInput;
protected Vector3 _lerpedInput;
protected Vector3 _normalizedInput;
protected float _acceleration;
protected float _deceleration;
protected Vector3 _movementVector = Vector3.zero;
protected float _speedMultiplier;
protected Vector3 _newEulerAngles;
/// <summary>
/// On start, activate our camera if needed
/// </summary>
protected virtual void Start()
{
if (AutoActivation)
{
ToggleFreeCamera();
}
}
/// <summary>
/// On Update we grab our input and move accordingly
/// </summary>
protected virtual void Update()
{
if (Input.GetKeyDown(ActivateButton))
{
ToggleFreeCamera();
}
if (!Active)
{
return;
}
GetInput();
Translate();
Rotate();
Move();
HandleMobileControls();
}
/// <summary>
/// Grabs and stores the various input values
/// </summary>
protected virtual void GetInput()
{
if (!UseMobileControls || (LeftStick == null))
{
_currentInput.x = Input.GetAxis("Horizontal");
_currentInput.y = 0f;
_currentInput.z = Input.GetAxis("Vertical");
}
else
{
_currentInput.x = LeftStick._joystickValue.x;
_currentInput.y = 0f;
_currentInput.z = LeftStick._joystickValue.y;
}
if (Input.GetKey(UpButton))
{
_currentInput.y = 1f;
}
if (Input.GetKey(DownButton))
{
_currentInput.y = -1f;
}
_speedMultiplier = Input.GetKey(RunButton) ? RunFactor : 1f;
_normalizedInput = _currentInput.normalized;
if (Input.GetKeyDown(TimescaleModificationButton))
{
ToggleSlowMotion();
}
}
/// <summary>
/// Turns controls to mobile if needed
/// </summary>
protected virtual void HandleMobileControls()
{
if (Input.GetKeyDown(ControlsModeSwitch))
{
UseMobileControls = !UseMobileControls;
}
if (UseMobileControls)
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
else if (Active)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
if (LeftStickContainer != null)
{
LeftStickContainer?.SetActive(UseMobileControls);
}
if (RightStickContainer != null)
{
RightStickContainer?.SetActive(UseMobileControls);
}
}
/// <summary>
/// Computes the new position
/// </summary>
protected virtual void Translate()
{
if (!MovementEnabled)
{
return;
}
if ((Acceleration == 0) || (Deceleration == 0))
{
_lerpedInput = _currentInput;
}
else
{
if (_normalizedInput.magnitude == 0)
{
_acceleration = Mathf.Lerp(_acceleration, 0f, Deceleration * Time.deltaTime);
_lerpedInput = Vector3.Lerp(_lerpedInput, _lerpedInput * _acceleration, Time.deltaTime * Deceleration);
}
else
{
_acceleration = Mathf.Lerp(_acceleration, 1f, Acceleration * Time.deltaTime);
_lerpedInput = Vector3.ClampMagnitude(_normalizedInput, _acceleration);
}
}
_movementVector = _lerpedInput;
_movementVector *= MovementSpeed * _speedMultiplier;
if (_movementVector.magnitude > MovementSpeed * _speedMultiplier)
{
_movementVector = Vector3.ClampMagnitude(_movementVector, MovementSpeed * _speedMultiplier);
}
}
/// <summary>
/// Computes the new rotation
/// </summary>
protected virtual void Rotate()
{
if (!RotationEnabled)
{
return;
}
_newEulerAngles = this.transform.eulerAngles;
if (!UseMobileControls || (LeftStick == null))
{
_newEulerAngles.x += -Input.GetAxis("Mouse Y") * 359f * MouseSensitivity;
_newEulerAngles.y += Input.GetAxis("Mouse X") * 359f * MouseSensitivity;
}
else
{
_newEulerAngles.x += -RightStick._joystickValue.y * MobileStickSensitivity;
_newEulerAngles.y += RightStick._joystickValue.x * MobileStickSensitivity;
}
_newEulerAngles = Vector3.Lerp(this.transform.eulerAngles, _newEulerAngles, Time.deltaTime * RotationSpeed);
}
/// <summary>
/// Modifies the camera's transform's position and rotation
/// </summary>
protected virtual void Move()
{
transform.eulerAngles = _newEulerAngles;
transform.position += transform.rotation * _movementVector * Time.deltaTime;
}
/// <summary>
/// Toggles the timescale modification
/// </summary>
protected virtual void ToggleSlowMotion()
{
TimeAltered = !TimeAltered;
if (TimeAltered)
{
MMTimeScaleEvent.Trigger(MMTimeScaleMethods.For, TimescaleModifier, 1f, true, 5f, true);
}
else
{
MMTimeScaleEvent.Trigger(MMTimeScaleMethods.Unfreeze, 1f, 0f, false, 0f, false);
}
}
/// <summary>
/// Toggles the camera's active state
/// </summary>
protected virtual void ToggleFreeCamera()
{
Active = !Active;
Cursor.lockState = Active ? CursorLockMode.Locked : CursorLockMode.None;
Cursor.visible = !Active;
}
}
} | 34.07931 | 146 | 0.557523 | [
"MIT"
] | random-agile/slowmo_mobile | Assets/Amazing Assets/Feel/MMTools/ToolsForMMFeedbacks/Tools/Camera/MMGhostCamera.cs | 9,883 | C# |
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using MelonLoader;
namespace Bitzophrenia
{
public class BasicInjection
{
[DllImport("kernel32.dll")]
public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress,
uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out UIntPtr lpNumberOfBytesWritten);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr CreateRemoteThread(IntPtr hProcess,
IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
const int PROCESS_CREATE_THREAD = 0x0002;
const int PROCESS_QUERY_INFORMATION = 0x0400;
const int PROCESS_VM_OPERATION = 0x0008;
const int PROCESS_VM_WRITE = 0x0020;
const int PROCESS_VM_READ = 0x0010;
const uint MEM_COMMIT = 0x00001000;
const uint MEM_RESERVE = 0x00002000;
const uint PAGE_READWRITE = 4;
public static int Main()
{
inject("PhasBypass.dll");
return 0;
}
private static void inject(String filename) {
Process[] targetProcesses = Process.GetProcessesByName("Phasmophobia");
MelonLogger.Msg("Found " + targetProcesses.Length + " Phasmophobia processes.");
Process targetProcess = targetProcesses[0];
IntPtr procHandle = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, targetProcess.Id);
IntPtr loadLibraryAddr = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
string dllName = Directory.GetCurrentDirectory()+ "\\" + filename;
IntPtr allocMemAddress = VirtualAllocEx(procHandle, IntPtr.Zero, (uint)((dllName.Length + 1) * Marshal.SizeOf(typeof(char))), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
UIntPtr bytesWritten;
MelonLogger.Msg("Injecting: " + filename);
if(WriteProcessMemory(procHandle, allocMemAddress, Encoding.Default.GetBytes(dllName), (uint)((dllName.Length + 1) * Marshal.SizeOf(typeof(char))), out bytesWritten))
{
MelonLogger.Msg("Success!");
CreateRemoteThread(procHandle, IntPtr.Zero, 0, loadLibraryAddr, allocMemAddress, 0, IntPtr.Zero);
}
else
{
MelonLogger.Msg("Failed!");
}
}
}
} | 45.521127 | 180 | 0.675743 | [
"MIT"
] | XenoSnowFox/bitzophrenia-phasma-mod | src/Utils/BasicInjection.cs | 3,232 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Lib.Exceptions{
public class EmailAlreadyExistsException : Pd2TradeApiException
{
public EmailAlreadyExistsException(string message) : base(message) { }
}
}
| 23.272727 | 78 | 0.75 | [
"BSD-3-Clause"
] | PD2tech/pd2-trade-api | src/Lib/Exceptions/EmailAlreadyExistsException.cs | 258 | C# |
namespace AngleSharp.Html.Dom
{
using AngleSharp.Attributes;
using AngleSharp.Dom;
using System;
/// <summary>
/// Represents the HTML applet element.
/// </summary>
[DomHistorical]
sealed class HtmlAppletElement : HtmlElement
{
public HtmlAppletElement(Document owner, String prefix = null)
: base(owner, TagNames.Applet, prefix, NodeFlags.Special | NodeFlags.Scoped)
{
}
}
}
| 23.947368 | 88 | 0.632967 | [
"MIT"
] | AlexDombrovsky/AngleSharp | src/AngleSharp/Html/Dom/Internal/HtmlAppletElement.cs | 457 | C# |
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Threading;
namespace Material.Ripple {
public class RippleEffect : ContentControl
{
// ReSharper disable once InconsistentNaming
private Canvas PART_RippleCanvasRoot;
private Ripple _last;
private byte _pointers;
public RippleEffect()
{
AddHandler(PointerReleasedEvent, PointerReleasedHandler);
AddHandler(PointerPressedEvent, PointerPressedHandler);
AddHandler(PointerCaptureLostEvent, PointerCaptureLostHandler);
}
private void PointerPressedHandler(object sender, PointerPressedEventArgs e)
{
if (_pointers == 0)
{
// Only first pointer can arrive a ripple
_pointers++;
var r = CreateRipple(e, RaiseRippleCenter);
_last = r;
// Attach ripple instance to canvas
PART_RippleCanvasRoot.Children.Add(r);
r.RunFirstStep();
}
}
private void PointerReleasedHandler(object sender, PointerReleasedEventArgs e)
{
RemoveLastRipple();
}
private void PointerCaptureLostHandler(object sender, PointerCaptureLostEventArgs e)
{
RemoveLastRipple();
}
private void RemoveLastRipple()
{
if (_last == null)
return;
_pointers--;
// This way to handle pointer released is pretty tricky
// could have more better way to improve
OnReleaseHandler(_last);
_last = null;
}
private void OnReleaseHandler(Ripple r)
{
// Fade out ripple
r.RunSecondStep();
void RemoveRippleTask(Task arg1, object arg2)
{
Dispatcher.UIThread.InvokeAsync(delegate
{
PART_RippleCanvasRoot.Children.Remove(r);
});
}
// Remove ripple from canvas to finalize ripple instance
Task.Delay(Ripple.Duration).ContinueWith(RemoveRippleTask, null);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e) {
base.OnApplyTemplate(e);
// Find canvas host
PART_RippleCanvasRoot = e.NameScope.Find<Canvas>(nameof(PART_RippleCanvasRoot));
}
private Ripple CreateRipple(PointerPressedEventArgs e, bool center)
{
var w = Bounds.Width;
var h = Bounds.Height;
var r = new Ripple(w, h)
{
Fill = RippleFill
};
if (center) r. Margin = new Thickness(w / 2, h / 2,0,0);
else r.SetupInitialValues(e, this);
return r;
}
#region Styled properties
public static readonly StyledProperty<IBrush> RippleFillProperty =
AvaloniaProperty.Register<RippleEffect, IBrush>(nameof(RippleFill), SolidColorBrush.Parse("#FFF"));
public IBrush RippleFill {
get => GetValue(RippleFillProperty);
set => SetValue(RippleFillProperty, value);
}
public static readonly StyledProperty<double> RippleOpacityProperty =
AvaloniaProperty.Register<RippleEffect, double>(nameof(RippleOpacity), 0.6);
public double RippleOpacity {
get => GetValue(RippleOpacityProperty);
set => SetValue(RippleOpacityProperty, value);
}
public static readonly StyledProperty<bool> RaiseRippleCenterProperty =
AvaloniaProperty.Register<RippleEffect, bool>(nameof(RaiseRippleCenter));
public bool RaiseRippleCenter {
get => GetValue(RaiseRippleCenterProperty);
set => SetValue(RaiseRippleCenterProperty, value);
}
#endregion Styled properties
}
} | 31.770992 | 111 | 0.578808 | [
"MIT"
] | Al-Dyachkov/Material.Avalonia | Material.Ripple/RippleEffect.cs | 4,164 | C# |
using System;
using System.Net.Mail;
namespace ArpmarService.Services
{
public class MailService : IDisposable
{
private readonly LogService _logService;
public SmtpClient Client { get; }
public string From { private get; set; }
public string To { private get; set; }
public MailService(LogService logService)
{
_logService = logService;
Client = new SmtpClient
{
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false
};
}
public void SendMail(string bodyOfMail)
{
using (var mail = new MailMessage(From, To)
{
Subject = "arpMAR - ARP table changed",
Body = bodyOfMail
})
{
try
{
Client?.Send(mail);
}
catch (Exception e)
{
_logService.WriteWarning(e.Message);
}
}
}
public void Dispose()
=> Client?.Dispose();
}
} | 24.744681 | 60 | 0.474635 | [
"MIT"
] | Xandev/arpmar | ArpmarService/Services/MailService.cs | 1,165 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Q02_Advertising_Message
{
class Program
{
static void Main(string[] args)
{
int numberOfOutputs = int.Parse(Console.ReadLine());
string[] phrases = {
"Excellent product.",
"Such a great product.",
"I always use that product.",
"Best product of its category.",
"Exceptional product.",
"I can’t live without this product." };
string[] events = {
" Now I feel good.",
" I have succeeded with this product.",
" Makes miracles.I am happy of the results!",
" I cannot believe but now I feel awesome.",
" Try it yourself, I am very satisfied.",
" I feel great!"};
string[] author = {
" Diana -",
" Petya -",
" Stella -",
" Elena -",
" Katya -",
" Iva -",
" Annie -",
" Eva -"};
string[] cities = {
" Burgas",
" Sofia",
" Plovdiv",
" Varna",
" Ruse"};
Random rnd = new Random();
for (int i = 0; i < numberOfOutputs; i++)
{
string output = string.Empty;
int phrasesPieceIndex = rnd.Next(0, phrases.Length);
string phrasesPiece = phrases[phrasesPieceIndex];
output += phrasesPiece;
int eventsPieceIndex = rnd.Next(0, events.Length);
string eventsPiece = events[eventsPieceIndex];
output += eventsPiece;
int authorPieceIndex = rnd.Next(0, author.Length);
string authorPiece = author[authorPieceIndex];
output += authorPiece;
int cityPieceIndex = rnd.Next(0, cities.Length);
string cityPiece = cities[cityPieceIndex];
output += cityPiece;
Console.WriteLine(output);
}
}
}
}
| 30.118421 | 68 | 0.459152 | [
"MIT"
] | Uendy/Tech-Module | L07 Classes, Objects/L07 Exercises/Exercises/Q02 Advertising Message/Program.cs | 2,293 | C# |
using System.Collections;
using UnityEngine;
public interface FSMState
{
void Update (FSM fsm, GameObject gameObject);
}
| 15.875 | 49 | 0.76378 | [
"MIT"
] | Over42/uGOAP | FSM/FSMState.cs | 127 | C# |
namespace XTemplate.Templating
{
/// <summary>代码块类型</summary>
internal enum BlockType
{
/// <summary>指令</summary>
Directive,
/// <summary>成员</summary>
Member,
/// <summary>模版文本</summary>
Text,
/// <summary>语句</summary>
Statement,
/// <summary>表达式</summary>
Expression
}
} | 16.954545 | 35 | 0.506702 | [
"MIT"
] | EnhWeb/DC.Framework | src/Ding.XTemplate/Templating/BlockType.cs | 411 | C# |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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 Aurora-Sim Project 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 DEVELOPERS ``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 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 OpenMetaverse;
using Aurora.Framework;
namespace Aurora.Modules.Terrain.FloodBrushes
{
public class FlattenArea : ITerrainFloodEffect
{
#region ITerrainFloodEffect Members
public void FloodEffect(ITerrainChannel map, UUID userID, float north,
float west, float south, float east, float strength)
{
float sum = 0;
float steps = 0;
int x, y;
for (x = (int) west; x < (int) east; x++)
{
for (y = (int) south; y < (int) north; y++)
{
if (!map.Scene.Permissions.CanTerraformLand(userID, new Vector3(x, y, 0)))
continue;
sum += map[x, y];
steps += 1;
}
}
float avg = sum/steps;
float str = 0.1f*strength; // == 0.2 in the default client
for (x = (int) west; x < (int) east; x++)
{
for (y = (int) south; y < (int) north; y++)
{
if (!map.Scene.Permissions.CanTerraformLand(userID, new Vector3(x, y, 0)))
continue;
map[x, y] = (map[x, y]*(1 - str)) + (avg*str);
}
}
}
#endregion
}
} | 42.458333 | 95 | 0.596336 | [
"BSD-3-Clause"
] | BillyWarrhol/Aurora-Sim | Aurora/Modules/World/Terrain/FloodBrushes/FlattenArea.cs | 3,057 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.Interaction.Toolkit;
public class XRGrabInteractable_Offset : XRGrabInteractable
{
private Vector3 initialAttachLocalPos;
private Quaternion initialAttachLocalRot;
// Start is called before the first frame update
void Start()
{
//Create attach point
if (!attachTransform)
{
GameObject grab = new GameObject("Grab Pivot");
grab.transform.SetParent(transform, false);
attachTransform = grab.transform;
}
initialAttachLocalPos = attachTransform.localPosition;
initialAttachLocalRot = attachTransform.localRotation;
}
protected override void OnSelectEntered(XRBaseInteractor interactor)
{
if (interactor is XRDirectInteractor)
{
attachTransform.position = interactor.transform.position;
attachTransform.rotation = interactor.transform.rotation;
}
else
{
attachTransform.localPosition = initialAttachLocalPos;
attachTransform.localRotation = initialAttachLocalRot;
}
base.OnSelectEntered(interactor);
}
} | 29.261905 | 72 | 0.6786 | [
"Apache-2.0"
] | rafa-s-7/turn-off-the-lights | Assets/[Oculus]/Scripts/XRGrabInteractable_Offset.cs | 1,229 | C# |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
namespace Maticsoft.Web.dafen_jieguo
{
public partial class Show : Page
{
public string strid="";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.Params["id"] != null && Request.Params["id"].Trim() != "")
{
strid = Request.Params["id"];
int id=(Convert.ToInt32(strid));
ShowInfo(id);
}
}
}
private void ShowInfo(int id)
{
Maticsoft.BLL.dafen_jieguo bll=new Maticsoft.BLL.dafen_jieguo();
Maticsoft.Model.dafen_jieguo model=bll.GetModel(id);
this.lblid.Text=model.id.ToString();
this.lblshangke_id.Text=model.shangke_id.ToString();
this.lblfenzu_id.Text=model.fenzu_id.ToString();
this.lblfenshu.Text=model.fenshu.ToString();
this.lblneirong.Text=model.neirong;
this.lbldafen_xuhao.Text=model.dafen_xuhao.ToString();
}
}
}
| 24.869565 | 74 | 0.703671 | [
"Unlicense"
] | nature-track/wenCollege-CSharp | Web/dafen_jieguo/Show.aspx.cs | 1,146 | C# |
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Roslynator.CSharp.Analysis
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class RemoveEmptyStatementAnalyzer : BaseDiagnosticAnalyzer
{
private static ImmutableArray<DiagnosticDescriptor> _supportedDiagnostics;
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
if (_supportedDiagnostics.IsDefault)
Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.RemoveEmptyStatement);
return _supportedDiagnostics;
}
}
public override void Initialize(AnalysisContext context)
{
base.Initialize(context);
context.RegisterSyntaxNodeAction(f => AnalyzeEmptyStatement(f), SyntaxKind.EmptyStatement);
}
private static void AnalyzeEmptyStatement(SyntaxNodeAnalysisContext context)
{
SyntaxNode emptyStatement = context.Node;
SyntaxNode parent = emptyStatement.Parent;
if (parent == null)
return;
SyntaxKind kind = parent.Kind();
if (kind == SyntaxKind.LabeledStatement)
return;
if (CSharpFacts.CanHaveEmbeddedStatement(kind))
return;
DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.RemoveEmptyStatement, emptyStatement);
}
}
}
| 32.2 | 160 | 0.673066 | [
"Apache-2.0"
] | JosefPihrt/Roslynator | src/Analyzers/CSharp/Analysis/RemoveEmptyStatementAnalyzer.cs | 1,773 | C# |
using System.Collections.Generic;
namespace BeanstalkSeeder.Models
{
public class WorkerMessage
{
public string JsonPayload { get; set; }
public Dictionary<string, string> Headers { get; set; }
public string ReceiptHandle { get; set; }
}
} | 25.090909 | 63 | 0.666667 | [
"MIT"
] | gabrielweyer/beanstalk-seeder | src/BeanstalkSeeder/Models/WorkerMessage.cs | 276 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using Microsoft.VisualStudio.R.Package.Commands;
using Microsoft.VisualStudio.R.Package.Plots.Definitions;
using Microsoft.VisualStudio.R.Package.Shell;
namespace Microsoft.VisualStudio.R.Package.Plots.Commands {
internal sealed class ExportPlotAsPdfCommand : PlotWindowCommand {
public ExportPlotAsPdfCommand(IPlotHistory plotHistory) :
base(plotHistory, RPackageCommandId.icmdExportPlotAsPdf) {
}
protected override void SetStatus() {
Enabled = PlotHistory.ActivePlotIndex >= 0;
}
protected override void Handle() {
string destinationFilePath = VsAppShell.Current.BrowseForFileSave(IntPtr.Zero, Resources.PlotExportAsPdfFilter, null, Resources.ExportPlotAsPdfDialogTitle);
if (!string.IsNullOrEmpty(destinationFilePath)) {
PlotHistory.PlotContentProvider.ExportAsPdf(destinationFilePath);
}
}
}
}
| 40.851852 | 168 | 0.727108 | [
"MIT"
] | AlexanderSher/RTVS-Old | src/Package/Impl/Plots/Commands/ExportPlotAsPdfCommand.cs | 1,105 | C# |
using AutoFixture.Xunit2;
using FluentValidation.TestHelper;
using Moq;
using NHSD.GPIT.BuyingCatalogue.ServiceContracts.AssociatedServices;
using NHSD.GPIT.BuyingCatalogue.Test.Framework.AutoFixtureCustomisations;
using NHSD.GPIT.BuyingCatalogue.WebApp.Areas.Admin.Models.AssociatedServices;
using NHSD.GPIT.BuyingCatalogue.WebApp.Areas.Admin.Validators;
using Xunit;
namespace NHSD.GPIT.BuyingCatalogue.WebApp.UnitTests.Areas.Admin.Validators
{
public static class AddAssociatedServiceModelValidatorTests
{
[Theory]
[CommonAutoData]
public static void Validate_DuplicateNameForSupplier_SetsModelError(
[Frozen] Mock<IAssociatedServicesService> associatedServicesService,
AddAssociatedServiceModel model,
AddAssociatedServiceModelValidator validator)
{
associatedServicesService.Setup(s => s.AssociatedServiceExistsWithNameForSupplier(model.Name, model.SolutionId.SupplierId, default))
.ReturnsAsync(true);
var result = validator.TestValidate(model);
result.ShouldHaveValidationErrorFor(m => m.Name)
.WithErrorMessage("Associated Service name already exists. Enter a different name");
}
[Theory]
[CommonAutoData]
public static void Validate_ValidName_NoModelError(
[Frozen] Mock<IAssociatedServicesService> associatedServicesService,
AddAssociatedServiceModel model,
AddAssociatedServiceModelValidator validator)
{
associatedServicesService.Setup(s => s.AssociatedServiceExistsWithNameForSupplier(model.Name, model.SolutionId.SupplierId, default))
.ReturnsAsync(false);
var result = validator.TestValidate(model);
result.ShouldNotHaveAnyValidationErrors();
}
}
}
| 40.326087 | 144 | 0.723989 | [
"MIT"
] | nhs-digital-gp-it-futures/GPITBuyingCatalogue | tests/NHSD.GPIT.BuyingCatalogue.WebApp.UnitTests/Areas/Admin/Validators/AddAssociatedServiceModelValidatorTests.cs | 1,857 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Core;
using Azure.ResourceManager.Sql.Models;
namespace Azure.ResourceManager.Sql
{
/// <summary> A class representing collection of ServerSecurityAlertPolicy and their operations over its parent. </summary>
public partial class ServerSecurityAlertPolicyCollection : ArmCollection, IEnumerable<ServerSecurityAlertPolicy>, IAsyncEnumerable<ServerSecurityAlertPolicy>
{
private readonly ClientDiagnostics _serverSecurityAlertPolicyClientDiagnostics;
private readonly ServerSecurityAlertPoliciesRestOperations _serverSecurityAlertPolicyRestClient;
/// <summary> Initializes a new instance of the <see cref="ServerSecurityAlertPolicyCollection"/> class for mocking. </summary>
protected ServerSecurityAlertPolicyCollection()
{
}
/// <summary> Initializes a new instance of the <see cref="ServerSecurityAlertPolicyCollection"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the parent resource that is the target of operations. </param>
internal ServerSecurityAlertPolicyCollection(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_serverSecurityAlertPolicyClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Sql", ServerSecurityAlertPolicy.ResourceType.Namespace, DiagnosticOptions);
TryGetApiVersion(ServerSecurityAlertPolicy.ResourceType, out string serverSecurityAlertPolicyApiVersion);
_serverSecurityAlertPolicyRestClient = new ServerSecurityAlertPoliciesRestOperations(Pipeline, DiagnosticOptions.ApplicationId, BaseUri, serverSecurityAlertPolicyApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != SqlServer.ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, SqlServer.ResourceType), nameof(id));
}
/// <summary>
/// Creates or updates a threat detection policy.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}
/// Operation Id: ServerSecurityAlertPolicies_CreateOrUpdate
/// </summary>
/// <param name="waitUntil"> "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="securityAlertPolicyName"> The name of the threat detection policy. </param>
/// <param name="parameters"> The server security alert policy. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="parameters"/> is null. </exception>
public virtual async Task<ArmOperation<ServerSecurityAlertPolicy>> CreateOrUpdateAsync(WaitUntil waitUntil, SecurityAlertPolicyName securityAlertPolicyName, ServerSecurityAlertPolicyData parameters, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(parameters, nameof(parameters));
using var scope = _serverSecurityAlertPolicyClientDiagnostics.CreateScope("ServerSecurityAlertPolicyCollection.CreateOrUpdate");
scope.Start();
try
{
var response = await _serverSecurityAlertPolicyRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, securityAlertPolicyName, parameters, cancellationToken).ConfigureAwait(false);
var operation = new SqlArmOperation<ServerSecurityAlertPolicy>(new ServerSecurityAlertPolicyOperationSource(Client), _serverSecurityAlertPolicyClientDiagnostics, Pipeline, _serverSecurityAlertPolicyRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, securityAlertPolicyName, parameters).Request, response, OperationFinalStateVia.Location);
if (waitUntil == WaitUntil.Completed)
await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Creates or updates a threat detection policy.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}
/// Operation Id: ServerSecurityAlertPolicies_CreateOrUpdate
/// </summary>
/// <param name="waitUntil"> "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="securityAlertPolicyName"> The name of the threat detection policy. </param>
/// <param name="parameters"> The server security alert policy. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="parameters"/> is null. </exception>
public virtual ArmOperation<ServerSecurityAlertPolicy> CreateOrUpdate(WaitUntil waitUntil, SecurityAlertPolicyName securityAlertPolicyName, ServerSecurityAlertPolicyData parameters, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(parameters, nameof(parameters));
using var scope = _serverSecurityAlertPolicyClientDiagnostics.CreateScope("ServerSecurityAlertPolicyCollection.CreateOrUpdate");
scope.Start();
try
{
var response = _serverSecurityAlertPolicyRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, securityAlertPolicyName, parameters, cancellationToken);
var operation = new SqlArmOperation<ServerSecurityAlertPolicy>(new ServerSecurityAlertPolicyOperationSource(Client), _serverSecurityAlertPolicyClientDiagnostics, Pipeline, _serverSecurityAlertPolicyRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, securityAlertPolicyName, parameters).Request, response, OperationFinalStateVia.Location);
if (waitUntil == WaitUntil.Completed)
operation.WaitForCompletion(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Get a server's security alert policy.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}
/// Operation Id: ServerSecurityAlertPolicies_Get
/// </summary>
/// <param name="securityAlertPolicyName"> The name of the security alert policy. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<ServerSecurityAlertPolicy>> GetAsync(SecurityAlertPolicyName securityAlertPolicyName, CancellationToken cancellationToken = default)
{
using var scope = _serverSecurityAlertPolicyClientDiagnostics.CreateScope("ServerSecurityAlertPolicyCollection.Get");
scope.Start();
try
{
var response = await _serverSecurityAlertPolicyRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, securityAlertPolicyName, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new ServerSecurityAlertPolicy(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Get a server's security alert policy.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}
/// Operation Id: ServerSecurityAlertPolicies_Get
/// </summary>
/// <param name="securityAlertPolicyName"> The name of the security alert policy. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<ServerSecurityAlertPolicy> Get(SecurityAlertPolicyName securityAlertPolicyName, CancellationToken cancellationToken = default)
{
using var scope = _serverSecurityAlertPolicyClientDiagnostics.CreateScope("ServerSecurityAlertPolicyCollection.Get");
scope.Start();
try
{
var response = _serverSecurityAlertPolicyRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, securityAlertPolicyName, cancellationToken);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new ServerSecurityAlertPolicy(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Get the server's threat detection policies.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/securityAlertPolicies
/// Operation Id: ServerSecurityAlertPolicies_ListByServer
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="ServerSecurityAlertPolicy" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<ServerSecurityAlertPolicy> GetAllAsync(CancellationToken cancellationToken = default)
{
async Task<Page<ServerSecurityAlertPolicy>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _serverSecurityAlertPolicyClientDiagnostics.CreateScope("ServerSecurityAlertPolicyCollection.GetAll");
scope.Start();
try
{
var response = await _serverSecurityAlertPolicyRestClient.ListByServerAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new ServerSecurityAlertPolicy(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<ServerSecurityAlertPolicy>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _serverSecurityAlertPolicyClientDiagnostics.CreateScope("ServerSecurityAlertPolicyCollection.GetAll");
scope.Start();
try
{
var response = await _serverSecurityAlertPolicyRestClient.ListByServerNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new ServerSecurityAlertPolicy(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Get the server's threat detection policies.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/securityAlertPolicies
/// Operation Id: ServerSecurityAlertPolicies_ListByServer
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="ServerSecurityAlertPolicy" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<ServerSecurityAlertPolicy> GetAll(CancellationToken cancellationToken = default)
{
Page<ServerSecurityAlertPolicy> FirstPageFunc(int? pageSizeHint)
{
using var scope = _serverSecurityAlertPolicyClientDiagnostics.CreateScope("ServerSecurityAlertPolicyCollection.GetAll");
scope.Start();
try
{
var response = _serverSecurityAlertPolicyRestClient.ListByServer(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new ServerSecurityAlertPolicy(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<ServerSecurityAlertPolicy> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _serverSecurityAlertPolicyClientDiagnostics.CreateScope("ServerSecurityAlertPolicyCollection.GetAll");
scope.Start();
try
{
var response = _serverSecurityAlertPolicyRestClient.ListByServerNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new ServerSecurityAlertPolicy(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Checks to see if the resource exists in azure.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}
/// Operation Id: ServerSecurityAlertPolicies_Get
/// </summary>
/// <param name="securityAlertPolicyName"> The name of the security alert policy. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<bool>> ExistsAsync(SecurityAlertPolicyName securityAlertPolicyName, CancellationToken cancellationToken = default)
{
using var scope = _serverSecurityAlertPolicyClientDiagnostics.CreateScope("ServerSecurityAlertPolicyCollection.Exists");
scope.Start();
try
{
var response = await GetIfExistsAsync(securityAlertPolicyName, cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Checks to see if the resource exists in azure.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}
/// Operation Id: ServerSecurityAlertPolicies_Get
/// </summary>
/// <param name="securityAlertPolicyName"> The name of the security alert policy. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<bool> Exists(SecurityAlertPolicyName securityAlertPolicyName, CancellationToken cancellationToken = default)
{
using var scope = _serverSecurityAlertPolicyClientDiagnostics.CreateScope("ServerSecurityAlertPolicyCollection.Exists");
scope.Start();
try
{
var response = GetIfExists(securityAlertPolicyName, cancellationToken: cancellationToken);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Tries to get details for this resource from the service.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}
/// Operation Id: ServerSecurityAlertPolicies_Get
/// </summary>
/// <param name="securityAlertPolicyName"> The name of the security alert policy. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<ServerSecurityAlertPolicy>> GetIfExistsAsync(SecurityAlertPolicyName securityAlertPolicyName, CancellationToken cancellationToken = default)
{
using var scope = _serverSecurityAlertPolicyClientDiagnostics.CreateScope("ServerSecurityAlertPolicyCollection.GetIfExists");
scope.Start();
try
{
var response = await _serverSecurityAlertPolicyRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, securityAlertPolicyName, cancellationToken: cancellationToken).ConfigureAwait(false);
if (response.Value == null)
return Response.FromValue<ServerSecurityAlertPolicy>(null, response.GetRawResponse());
return Response.FromValue(new ServerSecurityAlertPolicy(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Tries to get details for this resource from the service.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}
/// Operation Id: ServerSecurityAlertPolicies_Get
/// </summary>
/// <param name="securityAlertPolicyName"> The name of the security alert policy. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<ServerSecurityAlertPolicy> GetIfExists(SecurityAlertPolicyName securityAlertPolicyName, CancellationToken cancellationToken = default)
{
using var scope = _serverSecurityAlertPolicyClientDiagnostics.CreateScope("ServerSecurityAlertPolicyCollection.GetIfExists");
scope.Start();
try
{
var response = _serverSecurityAlertPolicyRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, securityAlertPolicyName, cancellationToken: cancellationToken);
if (response.Value == null)
return Response.FromValue<ServerSecurityAlertPolicy>(null, response.GetRawResponse());
return Response.FromValue(new ServerSecurityAlertPolicy(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
IEnumerator<ServerSecurityAlertPolicy> IEnumerable<ServerSecurityAlertPolicy>.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IAsyncEnumerator<ServerSecurityAlertPolicy> IAsyncEnumerable<ServerSecurityAlertPolicy>.GetAsyncEnumerator(CancellationToken cancellationToken)
{
return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken);
}
}
}
| 60.549724 | 480 | 0.680141 | [
"MIT"
] | KurnakovMaksim/azure-sdk-for-net | sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/ServerSecurityAlertPolicyCollection.cs | 21,919 | C# |
//-----------------------------------------------------------------------
// <copyright file="DistributedPubSubMediatorRouterSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2018 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2018 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using Akka.Actor;
using Akka.Cluster.Tools.PublishSubscribe;
using Akka.Configuration;
using Akka.Event;
using Akka.Routing;
using Akka.TestKit;
using Xunit;
namespace Akka.Cluster.Tools.Tests.PublishSubscribe
{
public class WrappedMessage : RouterEnvelope
{
public WrappedMessage(string message) : base(message)
{
}
}
public class UnwrappedMessage
{
public string Message { get; }
public UnwrappedMessage(string message)
{
Message = message;
}
}
public abstract class DistributedPubSubMediatorRouterSpec : AkkaSpec
{
private IActorRef mediator;
private string path;
public DistributedPubSubMediatorRouterSpec(Config config) : base(config)
{
mediator = DistributedPubSub.Get(Sys).Mediator;
path = TestActor.Path.ToStringWithoutAddress();
}
protected void NonUnwrappingPubSub(object msg)
{
Keep_the_RouterEnvelope_when_sending_to_local_logical_path(msg);
Keep_the_RouterEnvelope_when_sending_to_logical_path(msg);
Keep_the_RouterEnvelope_when_sending_to_all_actors_on_logical_path(msg);
Keep_the_RouterEnvelope_when_sending_to_topic(msg);
Keep_the_RouterEnvelope_when_sending_to_topic_for_group(msg);
Send_message_to_dead_letters_if_no_recipients_available(msg);
}
private void Keep_the_RouterEnvelope_when_sending_to_local_logical_path(object msg)
{
mediator.Tell(new Put(TestActor));
mediator.Tell(new Send(path, msg, localAffinity: true));
ExpectMsg(msg);
mediator.Tell(new Remove(path));
}
private void Keep_the_RouterEnvelope_when_sending_to_logical_path(object msg)
{
mediator.Tell(new Put(TestActor));
mediator.Tell(new Send(path, msg, localAffinity: false));
ExpectMsg(msg);
mediator.Tell(new Remove(path));
}
private void Keep_the_RouterEnvelope_when_sending_to_all_actors_on_logical_path(object msg)
{
mediator.Tell(new Put(TestActor));
mediator.Tell(new SendToAll(path, msg));
ExpectMsg(msg); // SendToAll does not use provided RoutingLogic
mediator.Tell(new Remove(path));
}
private void Keep_the_RouterEnvelope_when_sending_to_topic(object msg)
{
mediator.Tell(new Subscribe("topic", TestActor));
ExpectMsg<SubscribeAck>();
mediator.Tell(new Publish("topic", msg));
ExpectMsg(msg);
mediator.Tell(new Unsubscribe("topic", TestActor));
ExpectMsg<UnsubscribeAck>();
}
private void Keep_the_RouterEnvelope_when_sending_to_topic_for_group(object msg)
{
mediator.Tell(new Subscribe("topic", TestActor, "group"));
ExpectMsg<SubscribeAck>();
mediator.Tell(new Publish("topic", msg, sendOneMessageToEachGroup: true));
ExpectMsg(msg);
mediator.Tell(new Unsubscribe("topic", TestActor));
ExpectMsg<UnsubscribeAck>();
}
private void Send_message_to_dead_letters_if_no_recipients_available(object msg)
{
var probe = CreateTestProbe();
Sys.EventStream.Subscribe(probe.Ref, typeof(DeadLetter));
mediator.Tell(new Publish("nowhere", msg, sendOneMessageToEachGroup: true));
probe.ExpectMsg<DeadLetter>();
Sys.EventStream.Unsubscribe(probe.Ref, typeof(DeadLetter));
}
}
public class DistributedPubSubMediatorWithRandomRouterSpec : DistributedPubSubMediatorRouterSpec
{
public DistributedPubSubMediatorWithRandomRouterSpec() : base(DistributedPubSubMediatorRouterConfig.GetConfig("random"))
{
}
[Fact]
public void DistributedPubSubMediator_when_sending_wrapped_message()
{
var msg = new WrappedMessage("hello");
NonUnwrappingPubSub(msg);
}
[Fact]
public void DistributedPubSubMediator_when_sending_unwrapped_message()
{
var msg = new UnwrappedMessage("hello");
NonUnwrappingPubSub(msg);
}
}
public class DistributedPubSubMediatorWithRoundRobinRouterSpec : DistributedPubSubMediatorRouterSpec
{
public DistributedPubSubMediatorWithRoundRobinRouterSpec() : base(DistributedPubSubMediatorRouterConfig.GetConfig("round-robin"))
{
}
[Fact]
public void DistributedPubSubMediator_when_sending_wrapped_message()
{
var msg = new WrappedMessage("hello");
NonUnwrappingPubSub(msg);
}
[Fact]
public void DistributedPubSubMediator_when_sending_unwrapped_message()
{
var msg = new UnwrappedMessage("hello");
NonUnwrappingPubSub(msg);
}
}
public class DistributedPubSubMediatorWithBroadcastRouterSpec : DistributedPubSubMediatorRouterSpec
{
public DistributedPubSubMediatorWithBroadcastRouterSpec() : base(DistributedPubSubMediatorRouterConfig.GetConfig("broadcast"))
{
}
[Fact]
public void DistributedPubSubMediator_when_sending_wrapped_message()
{
var msg = new WrappedMessage("hello");
NonUnwrappingPubSub(msg);
}
[Fact]
public void DistributedPubSubMediator_when_sending_unwrapped_message()
{
var msg = new UnwrappedMessage("hello");
NonUnwrappingPubSub(msg);
}
}
public class DistributedPubSubMediatorWithHashRouterSpec : AkkaSpec
{
public DistributedPubSubMediatorWithHashRouterSpec() : base(DistributedPubSubMediatorRouterConfig.GetConfig("consistent-hashing"))
{
}
[Fact]
public void DistributedPubSubMediator_with_Consistent_Hash_router_not_be_allowed_constructed_by_extension()
{
Intercept<ArgumentException>(() =>
{
var mediator = DistributedPubSub.Get(Sys).Mediator;
});
}
[Fact]
public void DistributedPubSubMediator_with_Consistent_Hash_router_not_be_allowed_constructed_by_settings()
{
Intercept<ArgumentException>(() =>
{
var config =
DistributedPubSubMediatorRouterConfig.GetConfig("random")
.WithFallback(Sys.Settings.Config)
.GetConfig("akka.cluster.pub-sub");
DistributedPubSubSettings.Create(config).WithRoutingLogic(new ConsistentHashingRoutingLogic(Sys));
});
}
}
public static class DistributedPubSubMediatorRouterConfig
{
public static Config GetConfig(string routingLogic)
{
return ConfigurationFactory.ParseString($@"
akka.loglevel = INFO
akka.actor.provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster""
akka.remote.netty.tcp.port = 0
akka.remote.log-remote-lifecycle-events = off
akka.cluster.pub-sub.routing-logic = {routingLogic}
");
}
}
}
| 34.896396 | 138 | 0.632116 | [
"Apache-2.0"
] | EajksEajks/Akka.NET | src/contrib/cluster/Akka.Cluster.Tools.Tests/PublishSubscribe/DistributedPubSubMediatorRouterSpec.cs | 7,749 | C# |
// *******************************************************************************
// <copyright file="ServiceUnavailableException.cs" company="Intuit">
// Copyright (c) 2019 Intuit
//
// 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.
//
// </copyright>
// *******************************************************************************
namespace Intuit.TSheets.Model.Exceptions
{
using System;
using System.Runtime.Serialization;
/// <summary>
/// Server exception thrown when the server is currently unable to handle the request
/// due to a temporary overloading or maintenance of the server.
/// </summary>
[Serializable]
public sealed class ServiceUnavailableException : ApiServerException
{
/// <summary>
/// The HTTP code for service unavailable.
/// </summary>
internal const int Code = 503;
/// <summary>
/// Initializes a new instance of the <see cref="ServiceUnavailableException"/> class.
/// </summary>
/// <param name="message">
/// The error message that explains the reason for the exception.
/// </param>
public ServiceUnavailableException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ServiceUnavailableException"/> class.
/// </summary>
/// <param name="errorText">
/// Short error text returned from the API call.
/// </param>
/// <param name="message">
/// The error message that explains the reason for the exception.
/// </param>
/// <param name="innerException">
/// The exception that is the cause of the current exception.
/// </param>
public ServiceUnavailableException(string errorText, string message, Exception innerException)
: base(Code, errorText, message, innerException)
{
}
private ServiceUnavailableException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
| 36.774648 | 102 | 0.600153 | [
"Apache-2.0"
] | LaudateCorpus1/TSheets-V1-DotNET-SDK | Intuit.TSheets/Model/Exceptions/ServiceUnavailableException.cs | 2,613 | C# |
using System.Linq;
using System.Threading.Tasks;
using EstoqueProduto.Domain.Contracts.Service;
using EstoqueProduto.Domain.Validations;
using EstoqueProduto.Infra.Notifications;
using EstoqueProduto.ViewModels;
using Microsoft.AspNetCore.Identity;
namespace EstoqueProduto.Domain.Services
{
public class AutenticacaoUsuarioService : IAutenticacaoUsuarioService
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly IRequestNotificator _notifications;
public AutenticacaoUsuarioService(UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager,
IRequestNotificator notifications)
{
_userManager = userManager;
_signInManager = signInManager;
_notifications = notifications;
}
public async Task Registrar(IdentityUser novoUsuario, string senha)
{
var validationNovoUsuarioResult = new LoginValidation().Validate(novoUsuario);
var validationSenhaUsuarioResult = new SenhaUsuarioValidation().Validate(senha);
if (!validationNovoUsuarioResult.IsValid)
{
_notifications.Add(validationNovoUsuarioResult);
return;
}
if (!validationSenhaUsuarioResult.IsValid)
{
_notifications.Add(validationSenhaUsuarioResult);
return;
}
var result = await _userManager.CreateAsync(novoUsuario, senha);
if (result.Succeeded)
{
await _signInManager.SignInAsync(novoUsuario, false);
}
else
{
_notifications.Add(result.Errors.Select(x => x.Description));
return;
}
}
public async Task Login(IdentityUser usuario, string senha)
{
var validationLoginResult = new LoginValidation().Validate(usuario);
var validationSenhaUsuarioResult = new SenhaUsuarioValidation().Validate(senha);
if (!validationLoginResult.IsValid)
{
_notifications.Add(validationLoginResult);
return;
}
if (!validationSenhaUsuarioResult.IsValid)
{
_notifications.Add(validationSenhaUsuarioResult);
return;
}
var result = await _signInManager.PasswordSignInAsync(usuario.Email, senha, false, false);
if (!result.Succeeded)
{
_notifications.Add("E-mail ou senha incorretos.");
return;
}
}
}
} | 36.658228 | 102 | 0.585981 | [
"MIT"
] | juniorcesarrocha/dotnet-learn | src/03 - Identity/EstoqueProduto/Domain/Services/AutenticacaoUsuarioService.cs | 2,896 | C# |
//-----------------------------------------------------------------------
// <copyright file="ApiTrackingState.cs" company="Google LLC">
//
// Copyright 2017 Google LLC
//
// 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.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCoreInternal
{
internal enum ApiTrackingState
{
Tracking = 0,
Paused = 1,
Stopped = 2,
}
}
| 32.066667 | 75 | 0.597713 | [
"Apache-2.0"
] | ANKITVIRGO23/ARVRTest | Assets/GoogleARCore/SDK/Scripts/Api/Types/ApiTrackingState.cs | 962 | C# |
namespace MahJongSolitaireBlazor.Views;
internal struct TileGame
{
public int Deck { get; set; }
public int GameNumber { get; set; }
}
public partial class GameBoardBlazor
{
[Parameter]
public BasicList<BoardInfo> BoardList { get; set; } = new();
//private static TileGame GetTileKey(MahjongSolitaireTileInfo tile)
//{
// return new TileGame()
// {
// Deck = tile.Deck,
// GameNumber = MahJongSolitaireMainViewModel.GameDrawing
// };
//}
private static string GetGameKey => $"MahjongGame{MahJongSolitaireMainViewModel.GameDrawing}";
} | 30.45 | 98 | 0.663383 | [
"MIT"
] | musictopia2/GamingPackXV3 | Blazor/Games/MahJongSolitaireBlazor/Views/GameBoardBlazor.razor.cs | 609 | C# |
using System;
using System.Collections;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
namespace DTDebugMenu.Internal {
public class DebugMenuViewTab : MonoBehaviour {
// PRAGMA MARK - Public Interface
public void Init(DebugMenuItem menuItem, Action<DebugMenuItem> callback) {
menuItem_ = menuItem;
callback_ = callback;
titleText_.text = menuItem.DisplayTitle;
}
public void HandleNewActiveItem(DebugMenuItem activeItem) {
bool isActive = activeItem == menuItem_;
if (isActive) {
canvasGroup_.alpha = 1.0f;
} else {
bool isEven = this.transform.GetSiblingIndex() % 2 == 0;
canvasGroup_.alpha = isEven ? 0.66f : 0.6f;
}
}
// PRAGMA MARK - Internal
[Header("Outlets")]
[SerializeField]
private Text titleText_;
[SerializeField]
private Button button_;
[SerializeField]
private CanvasGroup canvasGroup_;
private DebugMenuItem menuItem_;
private Action<DebugMenuItem> callback_;
private void OnEnable() {
button_.onClick.AddListener(HandleSelected);
}
private void OnDisable() {
button_.onClick.RemoveListener(HandleSelected);
}
private void HandleSelected() {
callback_.Invoke(menuItem_);
}
}
} | 23.076923 | 76 | 0.724167 | [
"MIT"
] | DarrenTsung/DTDebugMenu | View/DebugMenuViewTab.cs | 1,200 | C# |
using System;
using System.Reflection;
using UnityEngine;
namespace KSPNET4
{
// Note(TMSP): Borrowed from BDDMP
public static class Detourer
{
/**
This is a basic first implementation of the IL method 'hooks' (detours) made possible by RawCode's work;
https://ludeon.com/forums/index.php?topic=17143.0
Performs detours, spits out basic logs and warns if a method is detoured multiple times.
**/
public static unsafe Boolean TryDetourFromTo(MethodInfo source, MethodInfo destination)
{
// error out on null arguments
if (source == null)
{
Debug.Log("[Detours] Source MethodInfo is null");
return false;
}
if (destination == null)
{
Debug.Log("[Detours] Destination MethodInfo is null");
return false;
}
if (IntPtr.Size == sizeof(Int64))
{
// 64-bit systems use 64-bit absolute address and jumps
// 12 byte destructive
// Get function pointers
Int64 sourceBase = source.MethodHandle.GetFunctionPointer().ToInt64();
Int64 destinationBase = destination.MethodHandle.GetFunctionPointer().ToInt64();
// Native source address
Byte* pointerRawSource = (Byte*)sourceBase;
// Pointer to insert jump address into native code
Int64* pointerRawAddress = (Int64*)(pointerRawSource + 0x02);
// Insert 64-bit absolute jump into native code (address in rax)
// mov rax, immediate64
// jmp [rax]
*(pointerRawSource + 0x00) = 0x48;
*(pointerRawSource + 0x01) = 0xB8;
*pointerRawAddress = destinationBase; // ( Pointer_Raw_Source + 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 )
*(pointerRawSource + 0x0A) = 0xFF;
*(pointerRawSource + 0x0B) = 0xE0;
}
else
{
// 32-bit systems use 32-bit relative offset and jump
// 5 byte destructive
// Get function pointers
Int32 sourceBase = source.MethodHandle.GetFunctionPointer().ToInt32();
Int32 destinationBase = destination.MethodHandle.GetFunctionPointer().ToInt32();
// Native source address
Byte* pointerRawSource = (Byte*)sourceBase;
// Pointer to insert jump address into native code
Int32* pointerRawAddress = (Int32*)(pointerRawSource + 1);
// Jump offset (less instruction size)
Int32 offset = (destinationBase - sourceBase) - 5;
// Insert 32-bit relative jump into native code
*pointerRawSource = 0xE9;
*pointerRawAddress = offset;
}
// done!
return true;
}
}
} | 36.662651 | 128 | 0.544857 | [
"MIT"
] | blowfishpro/KSP-NET4 | src/Detourer.cs | 3,045 | C# |
using CinemaWebApi.DataAccessLayer.Entities.Common;
using System;
namespace CinemaWebApi.DataAccessLayer.Entities
{
public class Movie : BaseEntity
{
public Guid GenreId { get; set; }
public string Title { get; set; }
public string OriginalTitle { get; set; }
public string Language { get; set; }
public string OriginalLanguage { get; set; }
public DateTime ReleaseDate { get; set; }
public virtual Genre Genre { get; set; }
}
} | 22.909091 | 52 | 0.642857 | [
"MIT"
] | N1K0232/CinemaWebApi | src/CinemaWebApi.DataAccessLayer/Entities/Movie.cs | 506 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection.Context.Custom;
namespace System.Reflection.Context.Virtual
{
internal partial class VirtualPropertyInfo
{
private class PropertySetter : PropertySetterBase
{
private readonly Action<object, object> _setter;
private readonly ParameterInfo _valueParameter;
private readonly IEnumerable<Attribute> _attributes;
public PropertySetter(VirtualPropertyBase property, Action<object, object> setter, IEnumerable<Attribute> setterAttributes)
: base(property)
{
Debug.Assert(null != setter);
_setter = setter;
_valueParameter = new VirtualParameter(this, property.PropertyType, "value", 0);
_attributes = setterAttributes ?? CollectionServices.Empty<Attribute>();
}
public override ParameterInfo[] GetParameters()
{
return new ParameterInfo[] { _valueParameter };
}
public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
{
// invokeAttr, binder, and culture are ignored, similar to what runtime reflection does with the default binder.
if (parameters == null || parameters.Length != 1)
throw new TargetParameterCountException();
object value = parameters[0];
if (obj == null)
throw new TargetException(SR.Target_InstanceMethodRequiresTarget);
if (!ReflectedType.IsInstanceOfType(obj))
throw new TargetException(SR.Target_ObjectTargetMismatch);
if (ReturnType.IsInstanceOfType(value))
throw new ArgumentException(SR.Format(SR.Argument_ObjectArgumentMismatch, value.GetType(), ReturnType));
_setter(obj, value);
return null;
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return CollectionServices.IEnumerableToArray(AttributeUtils.FilterCustomAttributes(_attributes, attributeType), attributeType);
}
public override object[] GetCustomAttributes(bool inherit)
{
return CollectionServices.IEnumerableToArray(_attributes, typeof(Attribute));
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CollectionServices.Empty<CustomAttributeData>();
}
public override bool IsDefined(Type attributeType, bool inherit)
{
return GetCustomAttributes(attributeType, inherit).Length > 0;
}
}
}
}
| 38.746835 | 143 | 0.627246 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyInfo.PropertySetter.cs | 3,061 | C# |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2013 FUJIWARA, Yusuke
//
// 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.
//
#endregion -- License Terms --
using System;
namespace MsgPack.Serialization.DefaultSerializers
{
internal sealed class MsgPack_MessagePackExtendedTypeObjectMessagePackSerializer : MessagePackSerializer<MessagePackExtendedTypeObject>
{
public MsgPack_MessagePackExtendedTypeObjectMessagePackSerializer( PackerCompatibilityOptions packerCompatibilityOptions )
: base( packerCompatibilityOptions ) { }
protected internal sealed override void PackToCore( Packer packer, MessagePackExtendedTypeObject value )
{
packer.PackExtendedTypeValue( value );
}
protected internal sealed override MessagePackExtendedTypeObject UnpackFromCore( Unpacker unpacker )
{
return unpacker.LastReadData.AsMessagePackExtendedTypeObject();
}
}
}
| 35.146341 | 136 | 0.766829 | [
"MIT"
] | Stormancer/Stormancer | src/libs/Unity/MsgPack/Serialization/DefaultSerializers/MsgPack_MessagePackExtendedTypeObjectMessagePackSerializer.cs | 1,443 | C# |
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace Panuon.UI.Silver.Converters
{
#region Minus 2
internal class Minus2Converter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (double)value - 2;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
#endregion
#region Minus 4
internal class Minus4Converter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (double)value - 4;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
#endregion
#region Add 3
internal class Add3Converter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (double)value + 3;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
#endregion
#region Add 5
internal class Add5Converter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (double)value + 5;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
#endregion
#region Add 10
internal class Add10Converter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (double)value + 10;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
#endregion
#region Minus 10
internal class Minus10Converter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var result = (double)value - 10;
return result < 0 ? 0 : result;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
#endregion
#region CornerRadiusAdd1
internal class CornerRadiusAdd1Converter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var thick = (CornerRadius)value;
return new CornerRadius(thick.TopLeft + 1, thick.TopRight + 1, thick.BottomRight + 1, thick.BottomLeft + 1);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
#endregion
}
| 27.842975 | 120 | 0.638468 | [
"MIT"
] | 1017369306/PanuonUI.Silver | SharedResources/Panuon.UI.Silver/Converters/DirtyConverter.cs | 3,371 | C# |
/*
MIT License
Copyright (c) 2017 NICE Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using CyberTech.RecorderApi;
using RecorderAPI2COM.Interfaces;
using System.Runtime.InteropServices;
namespace RecorderAPI2COM.Model
{
/// <summary>
/// Decorator class that add a COM interface to the Recorder API ServerCapabilties model.
/// </summary>
[Guid("636590A0-959D-4EF5-81D8-6E2D0A4EDF8E"),
ClassInterface(ClassInterfaceType.None),
ComDefaultInterface(typeof(CChannelInterface))]
public class CChannel : CChannelInterface
{
private Channel mChannel;
public CChannel()
{
mChannel = new Channel();
}
public CChannel(Channel chan)
{
mChannel = chan;
}
public byte RecID
{
get { return mChannel.RecID; }
set { mChannel.RecID = value; }
}
public ushort ChannelId
{
get { return mChannel.ChannelId; }
set { mChannel.ChannelId = value; }
}
public ushort ParrotId
{
get { return mChannel.ParrotId; }
set { mChannel.ParrotId = value; }
}
public string Name
{
get { return mChannel.Name; }
set { mChannel.Name = value; }
}
//TODO
//public ChannelSeating Seating
//{
// get { return mChannel.Seating; }
// set { mChannel.Seating = value; }
//}
public string Phone
{
get { return mChannel.Phone; }
set { mChannel.Phone = value; }
}
public string IPAddr
{
get { return mChannel.IPAddr; }
set { mChannel.IPAddr = value; }
}
//TODO
//public int[] Mark
//{
// get { return mChannel.Mark; }
// set { mChannel.Mark = value; }
//}
//TODO
//public ParrotChannel Parrotchannel
//{
// get { return mChannel.Parrotchannel; }
// set { mChannel.Parrotchannel = value; }
//}
}
}
| 28.350877 | 94 | 0.591275 | [
"MIT"
] | stewilko/JRecorderAPI | RecorderAPI2COM/RecorderAPI2COM/Model/CChannel.cs | 3,234 | 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.MachineLearningServices.V20200601.Outputs
{
[OutputType]
public sealed class AmlComputeResponse
{
/// <summary>
/// Location for the underlying compute
/// </summary>
public readonly string? ComputeLocation;
/// <summary>
/// The type of compute
/// Expected value is 'AmlCompute'.
/// </summary>
public readonly string ComputeType;
/// <summary>
/// The date and time when the compute was created.
/// </summary>
public readonly string CreatedOn;
/// <summary>
/// The description of the Machine Learning compute.
/// </summary>
public readonly string? Description;
/// <summary>
/// Indicating whether the compute was provisioned by user and brought from outside if true, or machine learning service provisioned it if false.
/// </summary>
public readonly bool IsAttachedCompute;
/// <summary>
/// The date and time when the compute was last modified.
/// </summary>
public readonly string ModifiedOn;
/// <summary>
/// AML Compute properties
/// </summary>
public readonly Outputs.AmlComputeResponseProperties? Properties;
/// <summary>
/// Errors during provisioning
/// </summary>
public readonly ImmutableArray<Outputs.MachineLearningServiceErrorResponse> ProvisioningErrors;
/// <summary>
/// The provision state of the cluster. Valid values are Unknown, Updating, Provisioning, Succeeded, and Failed.
/// </summary>
public readonly string ProvisioningState;
/// <summary>
/// ARM resource id of the underlying compute
/// </summary>
public readonly string? ResourceId;
[OutputConstructor]
private AmlComputeResponse(
string? computeLocation,
string computeType,
string createdOn,
string? description,
bool isAttachedCompute,
string modifiedOn,
Outputs.AmlComputeResponseProperties? properties,
ImmutableArray<Outputs.MachineLearningServiceErrorResponse> provisioningErrors,
string provisioningState,
string? resourceId)
{
ComputeLocation = computeLocation;
ComputeType = computeType;
CreatedOn = createdOn;
Description = description;
IsAttachedCompute = isAttachedCompute;
ModifiedOn = modifiedOn;
Properties = properties;
ProvisioningErrors = provisioningErrors;
ProvisioningState = provisioningState;
ResourceId = resourceId;
}
}
}
| 33.311828 | 153 | 0.620723 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/MachineLearningServices/V20200601/Outputs/AmlComputeResponse.cs | 3,098 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
namespace Komodo.MetadataManager
{
/// <summary>
/// Property for a metadata document.
/// </summary>
public class MetadataDocumentProperty
{
#region Public-Members
/// <summary>
/// The action to take to define the value for this property.
/// </summary>
[JsonProperty(Order = 1)]
public PropertyValueAction ValueAction { get; set; } = PropertyValueAction.Static;
/// <summary>
/// The property from the parse result of the source document.
/// </summary>
[JsonProperty(Order = 2)]
public string SourceProperty
{
get
{
return _SourceProperty;
}
set
{
if (String.IsNullOrEmpty(value)) throw new ArgumentNullException(nameof(value));
else _SourceProperty = value;
}
}
/// <summary>
/// The key to use in the metadata document.
/// </summary>
[JsonProperty(Order = 3)]
public string Key
{
get
{
return _Key;
}
set
{
if (String.IsNullOrEmpty(value)) throw new ArgumentNullException(nameof(value));
else _Key = value;
}
}
/// <summary>
/// For static value actions, the value to use.
/// </summary>
[JsonProperty(Order = 4)]
public string Value { get; set; } = null;
#endregion
#region Private-Members
private string _SourceProperty = null;
private string _Key = null;
#endregion
#region Constructors-and-Factories
/// <summary>
/// Instantiate the object.
/// </summary>
public MetadataDocumentProperty()
{
}
#endregion
#region Public-Methods
#endregion
#region Private-Methods
#endregion
}
}
| 23.054945 | 96 | 0.517636 | [
"MIT"
] | jchristn/komodo | Komodo.Core/MetadataManager/MetadataDocumentProperty.cs | 2,100 | C# |
//
// Encog(tm) Core v3.1 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2012 Heaton Research, Inc.
//
// 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
namespace Encog.Neural.Pattern
{
/// <summary>
/// This class is thrown when an error occurs while using one of the neural
/// network pattern classes.
/// </summary>
///
[Serializable]
public class PatternError : NeuralNetworkError
{
/// <summary>
/// Construct a message exception.
/// </summary>
///
/// <param name="msg">The exception message.</param>
public PatternError(String msg) : base(msg)
{
}
/// <summary>
/// Construct an exception that holds another exception.
/// </summary>
///
/// <param name="t">The other exception.</param>
public PatternError(Exception t) : base(t)
{
}
}
}
| 29.62963 | 79 | 0.64 | [
"BSD-3-Clause"
] | mpcoombes/MaterialPredictor | encog-core-cs/Neural/Pattern/PatternError.cs | 1,600 | C# |
using System;
namespace dotnow
{
public enum CLRFieldAccessMode
{
Read,
Write,
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class CLRFieldDirectAccessBindingAttribute : Attribute
{
// Private
private Type declaringType;
private string fieldName;
private CLRFieldAccessMode fieldAccessMode;
// Properties
public Type DeclaringType
{
get { return declaringType; }
}
public string FieldName
{
get { return fieldName; }
}
public CLRFieldAccessMode FieldAccessMode
{
get { return fieldAccessMode; }
}
// Constructor
public CLRFieldDirectAccessBindingAttribute(Type declaringType, string fieldName, CLRFieldAccessMode fieldAccessMode)
{
this.declaringType = declaringType;
this.fieldName = fieldName;
this.fieldAccessMode = fieldAccessMode;
}
}
}
| 24 | 125 | 0.607008 | [
"MIT"
] | SkutteOleg/dotnow-interpreter | Assets/dotnow/Scripts/Core/_Attributes/CLRFieldDirectAccessBinding.cs | 1,058 | C# |
// Write methods to calculate minimum, maximum, average, sum and product of given set of integer numbers.
// Use variable number of arguments.
// * Modify your last program and try to make it work for any number type, not just integer (e.g. decimal, float, byte, etc.).
// Use generic method (read in Internet about generic methods in C#).
using System;
using System.Collections.Generic;
class CalcMinMaxAvSumProductOfAllTypes
{
static void Main()
{
// find the wanted values
dynamic min = MinValue(1, 2, 3, 4, 5, 6);
dynamic max = MaxValue(1, 2, 3, 4, 5, 6);
dynamic avarage = Avarage(1, 2, 3, 4, 5, 6);
dynamic sum = SumAll(1, 2, 3, 4, 5, 6);
dynamic product = ProductOfAll(1, 2, 3, 4, 5, 6);
// print the results
Console.WriteLine("The minimal value is {0}", min);
Console.WriteLine("The maximal value is {0}", max);
Console.WriteLine("The avarage value is {0}", avarage);
Console.WriteLine("The sum of all elements is {0}", sum);
Console.WriteLine("The product of all elements is {0}", product);
}
/// <summary>
/// This method finds the minimal value from a list and returs it.
/// </summary>
/// <param name="listOfElements">List of elements</param>
/// <returns>Returns the element with minimal value</returns>
public static T MinValue<T>(params T[] elements)
{
dynamic min = elements[0];
foreach (T element in elements)
{
if (min > element)
{
min = element;
}
}
return min;
}
/// <summary>
/// This method finds the maximal value from a list and returs it.
/// </summary>
/// <param name="listOfElements">List of elements</param>
/// <returns>Returns the element with maximal value</returns>
public static T MaxValue<T>(params T[] elements)
{
dynamic max = int.MinValue;
foreach (var element in elements)
{
if (max < element)
{
max = element;
}
}
return max;
}
/// <summary>
/// Method that finds the sum of the elements of a list of elements
/// </summary>
/// <param name="listOfElements">List of elements</param>
/// <returns>Returns the sum (int)</returns>
public static T SumAll<T>(params T[] elements)
{
dynamic sum = 0;
foreach (var element in elements)
{
sum += element;
}
return sum;
}
/// <summary>
/// Find the avarage in a list of integers.
/// </summary>
/// <param name="listOfElements">The list of integers</param>
/// <returns></returns>
public static T Avarage<T>(params T[] elements)
{
dynamic sum = 0;
int counter = 0;
// find the sum and the number of the elements
sum = SumAll(elements);
counter = elements.Length;
// find and return the avarage
return sum / counter;
}
/// <summary>
/// Method that finds the product of the elements of a list of elements
/// </summary>
/// <param name="listOfElements">List of elements</param>
/// <returns>Returns the product (long)</returns>
public static T ProductOfAll<T>(params T[] elements)
{
dynamic product = 1;
foreach (var element in elements)
{
product *= element;
}
return product;
}
}
| 29.846154 | 127 | 0.57417 | [
"MIT"
] | Steffkn/TelerikAcademy | Programming/02. CSharp Part 2/03.Methods/15.CalcMinMaxAvSumProductOfAllTypes/CalcMinMaxAvSumProductOfAllTypes.cs | 3,494 | C# |
/******************************************/
/* */
/* Copyright (c) 2018 monitor1394 */
/* https://github.com/monitor1394 */
/* */
/******************************************/
using System.Collections.Generic;
using UnityEngine;
namespace XCharts
{
internal static class ListPool<T>
{
private static readonly ObjectPool<List<T>> s_ListPool = new ObjectPool<List<T>>(OnGet, OnClear);
static void OnGet(List<T> l)
{
if (l.Capacity < 50)
{
l.Capacity = 50;
}
}
static void OnClear(List<T> l)
{
l.Clear();
}
public static List<T> Get()
{
return s_ListPool.Get();
}
public static void Release(List<T> toRelease)
{
s_ListPool.Release(toRelease);
}
public static void ClearAll()
{
s_ListPool.ClearAll();
}
}
}
| 23.681818 | 105 | 0.415547 | [
"MIT"
] | 764424567/unity-ugui-XCharts | Assets/XCharts/Runtime/Internal/Pools/ListPool.cs | 1,042 | 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 cognito-identity-2014-06-30.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.CognitoIdentity.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.CognitoIdentity.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for IdentityDescription Object
/// </summary>
public class IdentityDescriptionUnmarshaller : IUnmarshaller<IdentityDescription, XmlUnmarshallerContext>, IUnmarshaller<IdentityDescription, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
IdentityDescription IUnmarshaller<IdentityDescription, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public IdentityDescription Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
IdentityDescription unmarshalledObject = new IdentityDescription();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("CreationDate", targetDepth))
{
var unmarshaller = DateTimeUnmarshaller.Instance;
unmarshalledObject.CreationDate = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("IdentityId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.IdentityId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("LastModifiedDate", targetDepth))
{
var unmarshaller = DateTimeUnmarshaller.Instance;
unmarshalledObject.LastModifiedDate = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Logins", targetDepth))
{
var unmarshaller = new ListUnmarshaller<string, StringUnmarshaller>(StringUnmarshaller.Instance);
unmarshalledObject.Logins = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static IdentityDescriptionUnmarshaller _instance = new IdentityDescriptionUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static IdentityDescriptionUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.209091 | 170 | 0.624237 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/CognitoIdentity/Generated/Model/Internal/MarshallTransformations/IdentityDescriptionUnmarshaller.cs | 4,093 | 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.
//
//
//
// Description: Synchronized Input pattern adaptor
//
using System;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Provider;
using MS.Internal;
using SR = MS.Internal.PresentationCore.SR;
using SRID = MS.Internal.PresentationCore.SRID;
namespace MS.Internal.Automation
{
/// <summary>
/// Represents a synchronized input provider that supports the synchronized input pattern across
/// UIElements, ContentElements and UIElement3D.
/// </summary>
internal class SynchronizedInputAdaptor : ISynchronizedInputProvider
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="owner">UIElement or ContentElement or UIElement3D this adaptor is associated with.</param>
internal SynchronizedInputAdaptor(DependencyObject owner)
{
Invariant.Assert(owner != null);
_owner = owner;
}
/// <summary>
/// This method is called by automation framework to trigger synchronized input processing.
/// </summary>
/// <param name="inputType"> Synchronized input type</param>
void ISynchronizedInputProvider.StartListening(SynchronizedInputType inputType)
{
if (inputType != SynchronizedInputType.KeyDown &&
inputType != SynchronizedInputType.KeyUp &&
inputType != SynchronizedInputType.MouseLeftButtonDown &&
inputType != SynchronizedInputType.MouseLeftButtonUp &&
inputType != SynchronizedInputType.MouseRightButtonDown &&
inputType != SynchronizedInputType.MouseRightButtonUp)
{
throw new ArgumentException(SR.Get(SRID.Automation_InvalidSynchronizedInputType, inputType));
}
UIElement e = _owner as UIElement;
if (e != null)
{
if (!e.StartListeningSynchronizedInput(inputType))
{
throw new InvalidOperationException(SR.Get(SRID.Automation_RecursivePublicCall));
}
}
else
{
ContentElement ce = _owner as ContentElement;
if (ce != null)
{
if (!ce.StartListeningSynchronizedInput(inputType))
{
throw new InvalidOperationException(SR.Get(SRID.Automation_RecursivePublicCall));
}
}
else
{
UIElement3D e3D = (UIElement3D)_owner;
if (!e3D.StartListeningSynchronizedInput(inputType))
{
throw new InvalidOperationException(SR.Get(SRID.Automation_RecursivePublicCall));
}
}
}
}
////<summary>
/// Cancel synchronized input processing.
///</summary>
void ISynchronizedInputProvider.Cancel()
{
UIElement e = _owner as UIElement;
if (e != null)
{
e.CancelSynchronizedInput();
}
else
{
ContentElement ce = _owner as ContentElement;
if (ce != null)
{
ce.CancelSynchronizedInput();
}
else
{
UIElement3D e3D = (UIElement3D)_owner;
e3D.CancelSynchronizedInput();
}
}
}
private readonly DependencyObject _owner;
}
}
| 34.681818 | 115 | 0.561206 | [
"MIT"
] | 00mjk/wpf | src/Microsoft.DotNet.Wpf/src/PresentationCore/MS/internal/Automation/SynchronizedInputAdaptor.cs | 3,815 | C# |
using System;
using System.Threading.Tasks;
namespace Shiny.Locations
{
public interface IGpsManager
{
AccessState Status { get; }
Task<AccessState> RequestAccess(bool backgroundMode);
IObservable<IGpsReading> GetLastReading();
IObservable<IGpsReading> WhenReading();
bool IsListening { get; }
Task StartListener(GpsRequest request);
Task StopListener();
}
}
| 22.684211 | 61 | 0.668213 | [
"MIT"
] | DanielCauser/shiny | src/Shiny.Locations/IGpsManager.cs | 433 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Gooios.GoodsService.Applications.DTOs;
using Gooios.GoodsService.Applications.Services;
namespace Gooios.GoodsService.Controllers
{
[Produces("application/json")]
[Route("api/comment/v1")]
public class CommentController : BaseApiController
{
readonly ICommentAppService _commentAppService;
readonly IGoodsTagStatisticsAppService _goodsTagStatisticsAppService;
public CommentController(ICommentAppService commentAppService,IGoodsTagStatisticsAppService goodsTagStatisticsAppService)
{
_commentAppService = commentAppService;
_goodsTagStatisticsAppService = goodsTagStatisticsAppService;
}
[HttpPost]
public void Post([FromBody]CommentDTO model)
{
_commentAppService.AddComment(model, UserId);
}
[HttpGet]
public async Task<IEnumerable<CommentDTO>> Get(string goodsId, int pageIndex, int pageSize)
{
return await _commentAppService.Get(goodsId, pageIndex, pageSize);
}
[HttpGet]
[Route("goodscommentsstatistics")]
public async Task<GoodsTagStatisticsDTO> GetGoodsTagStatistics(string goodsId)
{
return _goodsTagStatisticsAppService.Get(goodsId);
}
}
} | 32.355556 | 129 | 0.706731 | [
"Apache-2.0"
] | hccoo/gooios | netcoremicroservices/Gooios.GoodsService/Controllers/CommentController.cs | 1,458 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FOS.Repositories.Infrastructure
{
//public interface IRepositoryBaseFactory<T> where T : class
//{
// void setTable();
//}
//class RepositoryBaseFactory<T> : IRepositoryBaseFactory<T> where T : class
//{
// public void setTable(T)
//}
}
| 22.388889 | 80 | 0.679901 | [
"MIT"
] | lnmthuc/fos | fos-api/FOS/FOS.Repositories/Infrastructure/RepositoryBaseFactory.cs | 405 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace WPFWaiterExample
{
internal class Async:Waiter
{
public Async(Control spin, ProgressBar progressBar, TextBox elapseTimeTextBox, Button start, Button cancel) : base(spin, progressBar, elapseTimeTextBox, start, cancel)
{
}
internal override async void Start()
{
startWaiting();
try
{
for (int i = 1; i <= Job.JobNumber; i++)
{
await Task.Factory.StartNew(Job.TimeConsumingJob, m_CancellationTokenSource.Token);
m_FinishedJob++;
m_Progressbar.Value = m_FinishedJob;
}
}
catch (OperationCanceledException)
{
m_CancellationTokenSource = new CancellationTokenSource();
}
stopWaiting();
}
}
} | 28.314286 | 175 | 0.550959 | [
"MIT"
] | fresky/WPFWaiterExample | WPFWaiterExample/Async.cs | 993 | C# |
/*
* Copyright 2012 The Netty Project
*
* The Netty Project 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.
*
* Copyright (c) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*
* Copyright (c) 2020 The Dotnetty-Span-Fork Project (cuteant@outlook.com)
*
* https://github.com/cuteant/dotnetty-span-fork
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
namespace DotNetty.Buffers
{
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using DotNetty.Common;
using DotNetty.Common.Utilities;
sealed partial class PooledDuplicatedByteBuffer : AbstractPooledDerivedByteBuffer
{
static readonly ThreadLocalPool<PooledDuplicatedByteBuffer> Recycler = new ThreadLocalPool<PooledDuplicatedByteBuffer>(handle => new PooledDuplicatedByteBuffer(handle));
internal static PooledDuplicatedByteBuffer NewInstance(AbstractByteBuffer unwrapped, IByteBuffer wrapped, int readerIndex, int writerIndex)
{
PooledDuplicatedByteBuffer duplicate = Recycler.Take();
_ = duplicate.Init<PooledDuplicatedByteBuffer>(unwrapped, wrapped, readerIndex, writerIndex, unwrapped.MaxCapacity);
_ = duplicate.MarkReaderIndex();
_ = duplicate.MarkWriterIndex();
return duplicate;
}
public PooledDuplicatedByteBuffer(ThreadLocalPool.Handle recyclerHandle)
: base(recyclerHandle)
{
}
public sealed override int Capacity => Unwrap().Capacity;
public sealed override IByteBuffer AdjustCapacity(int newCapacity)
{
_ = Unwrap().AdjustCapacity(newCapacity);
return this;
}
public sealed override int ArrayOffset => Unwrap().ArrayOffset;
public sealed override ref byte GetPinnableMemoryAddress() => ref Unwrap().GetPinnableMemoryAddress();
public sealed override IntPtr AddressOfPinnedMemory() => Unwrap().AddressOfPinnedMemory();
public sealed override ArraySegment<byte> GetIoBuffer(int index, int length) => Unwrap().GetIoBuffer(index, length);
public sealed override ArraySegment<byte>[] GetIoBuffers(int index, int length) => Unwrap().GetIoBuffers(index, length);
public sealed override IByteBuffer Copy(int index, int length) => Unwrap().Copy(index, length);
public sealed override IByteBuffer RetainedSlice(int index, int length) => PooledSlicedByteBuffer.NewInstance(UnwrapCore(), this, index, length);
public sealed override IByteBuffer Duplicate() => Duplicate0().SetIndex(ReaderIndex, WriterIndex);
public sealed override IByteBuffer RetainedDuplicate() => NewInstance(UnwrapCore(), this, ReaderIndex, WriterIndex);
protected internal sealed override byte _GetByte(int index) => UnwrapCore()._GetByte(index);
protected internal sealed override short _GetShort(int index) => UnwrapCore()._GetShort(index);
protected internal sealed override short _GetShortLE(int index) => UnwrapCore()._GetShortLE(index);
protected internal sealed override int _GetUnsignedMedium(int index) => UnwrapCore()._GetUnsignedMedium(index);
protected internal sealed override int _GetUnsignedMediumLE(int index) => UnwrapCore()._GetUnsignedMediumLE(index);
protected internal sealed override int _GetInt(int index) => UnwrapCore()._GetInt(index);
protected internal sealed override int _GetIntLE(int index) => UnwrapCore()._GetIntLE(index);
protected internal sealed override long _GetLong(int index) => UnwrapCore()._GetLong(index);
protected internal sealed override long _GetLongLE(int index) => UnwrapCore()._GetLongLE(index);
public sealed override IByteBuffer GetBytes(int index, IByteBuffer destination, int dstIndex, int length) { _ = Unwrap().GetBytes(index, destination, dstIndex, length); return this; }
public sealed override IByteBuffer GetBytes(int index, byte[] destination, int dstIndex, int length) { _ = Unwrap().GetBytes(index, destination, dstIndex, length); return this; }
public sealed override IByteBuffer GetBytes(int index, Stream destination, int length) { _ = Unwrap().GetBytes(index, destination, length); return this; }
protected internal sealed override void _SetByte(int index, int value) => UnwrapCore()._SetByte(index, value);
protected internal sealed override void _SetShort(int index, int value) => UnwrapCore()._SetShort(index, value);
protected internal sealed override void _SetShortLE(int index, int value) => UnwrapCore()._SetShortLE(index, value);
protected internal sealed override void _SetMedium(int index, int value) => UnwrapCore()._SetMedium(index, value);
protected internal sealed override void _SetMediumLE(int index, int value) => UnwrapCore()._SetMediumLE(index, value);
public sealed override IByteBuffer SetBytes(int index, IByteBuffer src, int srcIndex, int length) { _ = Unwrap().SetBytes(index, src, srcIndex, length); return this; }
public sealed override Task<int> SetBytesAsync(int index, Stream src, int length, CancellationToken cancellationToken) => Unwrap().SetBytesAsync(index, src, length, cancellationToken);
public sealed override IByteBuffer SetBytes(int index, byte[] src, int srcIndex, int length) { _ = Unwrap().SetBytes(index, src, srcIndex, length); return this; }
protected internal sealed override void _SetInt(int index, int value) => UnwrapCore()._SetInt(index, value);
protected internal sealed override void _SetIntLE(int index, int value) => UnwrapCore()._SetIntLE(index, value);
protected internal sealed override void _SetLong(int index, long value) => UnwrapCore()._SetLong(index, value);
protected internal sealed override void _SetLongLE(int index, long value) => UnwrapCore()._SetLongLE(index, value);
public sealed override int ForEachByte(int index, int length, IByteProcessor processor) => Unwrap().ForEachByte(index, length, processor);
public sealed override int ForEachByteDesc(int index, int length, IByteProcessor processor) => Unwrap().ForEachByteDesc(index, length, processor);
}
} | 52.05303 | 192 | 0.729588 | [
"MIT"
] | cuteant/SpanNetty | src/DotNetty.Buffers/PooledDuplicatedByteBuffer.cs | 6,873 | C# |
//-----------------------------------------------------------------------------
// Copyright 2000-2021 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com)
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: Apache-2.0
//-----------------------------------------------------------------------------
using System;
namespace Arcane.Curves
{
public class DrbarError : NoArgsErrorStrategy
{
public override ErrorInfo Compute(ICurve ref_curve, ICurve target_curve,string name,ErrorStrategyArguments args)
{
RealArray pgr = null;
ICurve pcrb1 = null;
ICurve pcrb2 = null;
Utils.ComputeProjection(ref_curve,target_curve,args.MinX,args.MaxX, out pcrb1,out pcrb2,out pgr);
int nbp = pgr.Length;
RealArray curve3x = pgr;
RealArray curve3y = new RealArray(nbp);
RealConstArrayView pcrb1y = pcrb1.Y;
RealConstArrayView pcrb2y = pcrb2.Y;
double max_ref = pcrb1y[0];
double max_target = pcrb2y[0];
for (int i = 0; i < nbp; ++i){
max_ref = Math.Max(max_ref, pcrb1y[i]);
max_target = Math.Max(max_target, pcrb2y[i]);
curve3y[i] = max_target - max_ref;
}
ICurve curve3 = new BasicCurve(name,curve3x,curve3y);
int nb_p = curve3.NbPoint;
double error_value = 0.0;
if (nb_p > 1)
error_value = Math.Abs(curve3y[nb_p - 1]); // valeur absolue du dernier element
return new ErrorInfo(curve3,error_value);
}
}
}
| 34.465116 | 116 | 0.589744 | [
"Apache-2.0"
] | DavidDureau/framework | arcane/tools/Arcane.Curves/DrbarError.cs | 1,482 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SchoolWFApp
{
static class Program
{
public static CookieContainer cookie = new CookieContainer();
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
}
}
}
| 24 | 69 | 0.631667 | [
"Apache-2.0"
] | davidbull931997/asp.net | WebAPI_Buoi2/SchoolWFApp/Program.cs | 602 | 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.
#nullable disable
using System.Diagnostics;
namespace System.ComponentModel
{
// Shared between dlls
internal static class CoreSwitches
{
private static BooleanSwitch perfTrack;
public static BooleanSwitch PerfTrack
{
get
{
if (perfTrack is null)
{
perfTrack = new BooleanSwitch("PERFTRACK", "Debug performance critical sections.");
}
return perfTrack;
}
}
}
}
| 24.6 | 103 | 0.596206 | [
"MIT"
] | Amy-Li03/winforms | src/System.Windows.Forms/src/misc/CoreSwitches.cs | 740 | C# |
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using Kaizen.Domain.Entities;
using Kaizen.Domain.Repositories;
using Kaizen.Models.Notification;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Kaizen.Controllers
{
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class NotificationsController : ControllerBase
{
private readonly INotificationsRepository _notificationsRepository;
private readonly IMapper _mapper;
private readonly IUnitWork _unitWork;
public NotificationsController(INotificationsRepository notificationsRepository, IUnitWork unitWork,
IMapper mapper)
{
_notificationsRepository = notificationsRepository;
_unitWork = unitWork;
_mapper = mapper;
}
[HttpGet("{userId}")]
public async Task<ActionResult<IEnumerable<NotificationViewModel>>> GetNotifications(string userId)
{
var notifications = await _notificationsRepository
.Where(n => n.UserId == userId && n.State == NotificationState.Pending)
.ToListAsync();
return Ok(_mapper.Map<IEnumerable<NotificationViewModel>>(notifications));
}
[HttpPut("{id}")]
public async Task<ActionResult<NotificationViewModel>> PutNotification(int id,
[FromBody] NotificationEditModel notificationEditModel)
{
var notification = await _notificationsRepository.FindByIdAsync(id);
if (notification is null)
{
return BadRequest($"No existe una notificación con el código {id}.");
}
_mapper.Map(notificationEditModel, notification);
_notificationsRepository.Update(notification);
try
{
await _unitWork.SaveAsync();
}
catch (DbUpdateException)
{
if (!NotificationExists(id))
{
return NotFound($"Actualizacón fallida. No existe ninguna notificación con el código {id}.");
}
throw;
}
return _mapper.Map<NotificationViewModel>(notification);
}
private bool NotificationExists(int id)
{
return _notificationsRepository.GetAll().Any(n => n.Id == id);
}
}
}
| 32.584416 | 113 | 0.626943 | [
"MIT"
] | cantte/Kaizen | Kaizen/Controllers/NotificationsController.cs | 2,516 | C# |
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Script.Serialization;
using System.Web.Security;
using AppConsig.Common.Security;
using AppConsig.Web.Gestor.Mapping;
using AppConsig.Web.Gestor.Modulos;
using Autofac;
using Autofac.Integration.Mvc;
namespace AppConsig.Web.Gestor
{
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
// Autofac Configuration.
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();
builder.RegisterModule(new ServiceModule());
builder.RegisterModule(new EntityModule());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
AutoMapperConfiguration.Configure();
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept");
HttpContext.Current.Response.End();
}
}
protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
{
var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null) return;
var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
var serializer = new JavaScriptSerializer();
if (authTicket == null) return;
var serializeModel = serializer.Deserialize<AppPrincipalSerializedModel>(authTicket.UserData);
var newUser = new AppPrincipal(authTicket.Name)
{
Id = serializeModel.Id,
Name = serializeModel.Name,
Surname = serializeModel.Surname,
Email = serializeModel.Email,
IsAdmin = serializeModel.IsAdmin
};
HttpContext.Current.User = newUser;
}
}
}
| 35.328947 | 126 | 0.653631 | [
"MIT"
] | Tabgyn/appconsig | AppConsig.Web.Gestor/Global.asax.cs | 2,687 | C# |
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.IO.Pem;
using Org.BouncyCastle.X509;
namespace Org.BouncyCastle.OpenSsl
{
/// <remarks>General purpose writer for OpenSSL PEM objects.</remarks>
public class PemWriter
: Utilities.IO.Pem.PemWriter
{
/// <param name="writer">The TextWriter object to write the output to.</param>
public PemWriter(
TextWriter writer)
: base(writer)
{
}
public void WriteObject(
object obj)
{
try
{
base.WriteObject(new MiscPemGenerator(obj));
}
catch (PemGenerationException e)
{
if (e.InnerException is IOException)
throw (IOException)e.InnerException;
throw e;
}
}
public void WriteObject(
object obj,
string algorithm,
char[] password,
SecureRandom random)
{
base.WriteObject(new MiscPemGenerator(obj, algorithm, password, random));
}
}
}
| 22.903226 | 80 | 0.745775 | [
"MIT"
] | SchmooseSA/Schmoose-BouncyCastle | Crypto/openssl/PEMWriter.cs | 1,420 | C# |
using J2N.Collections.Generic.Extensions;
using System;
using System.Collections.Generic;
using System.IO;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Store
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.
*/
/// <summary>
/// Expert: A <see cref="Directory"/> instance that switches files between
/// two other <see cref="Directory"/> instances.
///
/// <para/>Files with the specified extensions are placed in the
/// primary directory; others are placed in the secondary
/// directory. The provided <see cref="T:ISet{string}"/> must not change once passed
/// to this class, and must allow multiple threads to call
/// contains at once.
/// <para/>
/// @lucene.experimental
/// </summary>
public class FileSwitchDirectory : BaseDirectory
{
private readonly Directory secondaryDir;
private readonly Directory primaryDir;
private readonly ISet<string> primaryExtensions;
private bool doClose;
public FileSwitchDirectory(ISet<string> primaryExtensions, Directory primaryDir, Directory secondaryDir, bool doClose)
{
this.primaryExtensions = primaryExtensions;
this.primaryDir = primaryDir;
this.secondaryDir = secondaryDir;
this.doClose = doClose;
this.m_lockFactory = primaryDir.LockFactory;
}
/// <summary>
/// Return the primary directory </summary>
public virtual Directory PrimaryDir => primaryDir;
/// <summary>
/// Return the secondary directory </summary>
public virtual Directory SecondaryDir => secondaryDir;
protected override void Dispose(bool disposing)
{
if (disposing && doClose)
{
try
{
secondaryDir.Dispose();
}
finally
{
primaryDir.Dispose();
}
doClose = false;
}
}
public override string[] ListAll()
{
ISet<string> files = new JCG.HashSet<string>();
// LUCENE-3380: either or both of our dirs could be FSDirs,
// but if one underlying delegate is an FSDir and mkdirs() has not
// yet been called, because so far everything is written to the other,
// in this case, we don't want to throw a NoSuchDirectoryException
DirectoryNotFoundException exc = null;
try
{
foreach (string f in primaryDir.ListAll())
{
files.Add(f);
}
}
catch (DirectoryNotFoundException e)
{
exc = e;
}
try
{
foreach (string f in secondaryDir.ListAll())
{
files.Add(f);
}
}
catch (DirectoryNotFoundException /*e*/)
{
// we got NoSuchDirectoryException from both dirs
// rethrow the first.
if (exc != null)
{
throw exc;
}
// we got NoSuchDirectoryException from the secondary,
// and the primary is empty.
if (files.Count == 0)
{
throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details)
}
}
// we got NoSuchDirectoryException from the primary,
// and the secondary is empty.
if (exc != null && files.Count == 0)
{
throw exc;
}
return files.ToArray();
}
/// <summary>
/// Utility method to return a file's extension. </summary>
public static string GetExtension(string name)
{
int i = name.LastIndexOf('.');
if (i == -1)
{
return "";
}
return name.Substring(i + 1, name.Length - (i + 1));
}
private Directory GetDirectory(string name)
{
string ext = GetExtension(name);
if (primaryExtensions.Contains(ext))
{
return primaryDir;
}
else
{
return secondaryDir;
}
}
[Obsolete("this method will be removed in 5.0")]
public override bool FileExists(string name)
{
return GetDirectory(name).FileExists(name);
}
public override void DeleteFile(string name)
{
GetDirectory(name).DeleteFile(name);
}
public override long FileLength(string name)
{
return GetDirectory(name).FileLength(name);
}
public override IndexOutput CreateOutput(string name, IOContext context)
{
return GetDirectory(name).CreateOutput(name, context);
}
public override void Sync(ICollection<string> names)
{
IList<string> primaryNames = new List<string>();
IList<string> secondaryNames = new List<string>();
foreach (string name in names)
{
if (primaryExtensions.Contains(GetExtension(name)))
{
primaryNames.Add(name);
}
else
{
secondaryNames.Add(name);
}
}
primaryDir.Sync(primaryNames);
secondaryDir.Sync(secondaryNames);
}
public override IndexInput OpenInput(string name, IOContext context)
{
return GetDirectory(name).OpenInput(name, context);
}
public override IndexInputSlicer CreateSlicer(string name, IOContext context)
{
return GetDirectory(name).CreateSlicer(name, context);
}
}
} | 33.516908 | 184 | 0.54497 | [
"Apache-2.0"
] | azhoshkin/lucenenet | src/Lucene.Net/Store/FileSwitchDirectory.cs | 6,938 | C# |
using System;
namespace Guppi.Application.Attributes
{
/// <summary>
/// Sets an alternate display name for a property in the configuration process.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class DisplayAttribute : Attribute
{
public string Description { get; set; }
public DisplayAttribute(string description)
{
Description = description;
}
}
}
| 25.578947 | 88 | 0.654321 | [
"MIT"
] | rprouse/guppi | Guppi.Application/Attributes/DisplayAttribute.cs | 486 | C# |
#pragma warning disable 0472
using System;
using System.Text;
using System.IO;
using System.Collections;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Xml.Serialization;
using BLToolkit.Aspects;
using BLToolkit.DataAccess;
using BLToolkit.EditableObjects;
using BLToolkit.Data;
using BLToolkit.Data.DataProvider;
using BLToolkit.Mapping;
using BLToolkit.Reflection;
using bv.common.Configuration;
using bv.common.Enums;
using bv.common.Core;
using bv.model.BLToolkit;
using bv.model.Model;
using bv.model.Helpers;
using bv.model.Model.Extenders;
using bv.model.Model.Core;
using bv.model.Model.Handlers;
using bv.model.Model.Validators;
using eidss.model.Core;
using eidss.model.Enums;
namespace eidss.model.Schema
{
[XmlType(AnonymousType = true)]
public abstract partial class LabSample :
EditableObject<LabSample>
, IObject
, IDisposable
, ILookupUsage
{
[MapField(_str_idfMaterial), NonUpdatable, PrimaryKey]
public abstract Int64 idfMaterial { get; set; }
[LocalizedDisplayName(_str_idfsSampleStatus)]
[MapField(_str_idfsSampleStatus)]
public abstract Int64? idfsSampleStatus { get; set; }
protected Int64? idfsSampleStatus_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsSampleStatus).OriginalValue; } }
protected Int64? idfsSampleStatus_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsSampleStatus).PreviousValue; } }
[LocalizedDisplayName(_str_datAccession)]
[MapField(_str_datAccession)]
public abstract DateTime? datAccession { get; set; }
protected DateTime? datAccession_Original { get { return ((EditableValue<DateTime?>)((dynamic)this)._datAccession).OriginalValue; } }
protected DateTime? datAccession_Previous { get { return ((EditableValue<DateTime?>)((dynamic)this)._datAccession).PreviousValue; } }
[LocalizedDisplayName("strLabBarcode")]
[MapField(_str_strBarcode)]
public abstract String strBarcode { get; set; }
protected String strBarcode_Original { get { return ((EditableValue<String>)((dynamic)this)._strBarcode).OriginalValue; } }
protected String strBarcode_Previous { get { return ((EditableValue<String>)((dynamic)this)._strBarcode).PreviousValue; } }
[LocalizedDisplayName(_str_idfCase)]
[MapField(_str_idfCase)]
public abstract Int64? idfCase { get; set; }
protected Int64? idfCase_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfCase).OriginalValue; } }
protected Int64? idfCase_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfCase).PreviousValue; } }
[LocalizedDisplayName(_str_idfMonitoringSession)]
[MapField(_str_idfMonitoringSession)]
public abstract Int64? idfMonitoringSession { get; set; }
protected Int64? idfMonitoringSession_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfMonitoringSession).OriginalValue; } }
protected Int64? idfMonitoringSession_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfMonitoringSession).PreviousValue; } }
[LocalizedDisplayName(_str_strCaseID)]
[MapField(_str_strCaseID)]
public abstract String strCaseID { get; set; }
protected String strCaseID_Original { get { return ((EditableValue<String>)((dynamic)this)._strCaseID).OriginalValue; } }
protected String strCaseID_Previous { get { return ((EditableValue<String>)((dynamic)this)._strCaseID).PreviousValue; } }
[LocalizedDisplayName(_str_strMonitoringSessionID)]
[MapField(_str_strMonitoringSessionID)]
public abstract String strMonitoringSessionID { get; set; }
protected String strMonitoringSessionID_Original { get { return ((EditableValue<String>)((dynamic)this)._strMonitoringSessionID).OriginalValue; } }
protected String strMonitoringSessionID_Previous { get { return ((EditableValue<String>)((dynamic)this)._strMonitoringSessionID).PreviousValue; } }
[LocalizedDisplayName(_str_idfVectorSurveillanceSession)]
[MapField(_str_idfVectorSurveillanceSession)]
public abstract Int64? idfVectorSurveillanceSession { get; set; }
protected Int64? idfVectorSurveillanceSession_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfVectorSurveillanceSession).OriginalValue; } }
protected Int64? idfVectorSurveillanceSession_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfVectorSurveillanceSession).PreviousValue; } }
[LocalizedDisplayName(_str_idfsCaseType)]
[MapField(_str_idfsCaseType)]
public abstract Int64? idfsCaseType { get; set; }
protected Int64? idfsCaseType_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsCaseType).OriginalValue; } }
protected Int64? idfsCaseType_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsCaseType).PreviousValue; } }
[LocalizedDisplayName(_str_strSampleName)]
[MapField(_str_strSampleName)]
public abstract String strSampleName { get; set; }
protected String strSampleName_Original { get { return ((EditableValue<String>)((dynamic)this)._strSampleName).OriginalValue; } }
protected String strSampleName_Previous { get { return ((EditableValue<String>)((dynamic)this)._strSampleName).PreviousValue; } }
[LocalizedDisplayName(_str_SpeciesName)]
[MapField(_str_SpeciesName)]
public abstract String SpeciesName { get; set; }
protected String SpeciesName_Original { get { return ((EditableValue<String>)((dynamic)this)._speciesName).OriginalValue; } }
protected String SpeciesName_Previous { get { return ((EditableValue<String>)((dynamic)this)._speciesName).PreviousValue; } }
[LocalizedDisplayName(_str_strAnimalCode)]
[MapField(_str_strAnimalCode)]
public abstract String strAnimalCode { get; set; }
protected String strAnimalCode_Original { get { return ((EditableValue<String>)((dynamic)this)._strAnimalCode).OriginalValue; } }
protected String strAnimalCode_Previous { get { return ((EditableValue<String>)((dynamic)this)._strAnimalCode).PreviousValue; } }
[LocalizedDisplayName("strPatientInfo")]
[MapField(_str_HumanName)]
public abstract String HumanName { get; set; }
protected String HumanName_Original { get { return ((EditableValue<String>)((dynamic)this)._humanName).OriginalValue; } }
protected String HumanName_Previous { get { return ((EditableValue<String>)((dynamic)this)._humanName).PreviousValue; } }
[LocalizedDisplayName(_str_DiagnosisName)]
[MapField(_str_DiagnosisName)]
public abstract String DiagnosisName { get; set; }
protected String DiagnosisName_Original { get { return ((EditableValue<String>)((dynamic)this)._diagnosisName).OriginalValue; } }
protected String DiagnosisName_Previous { get { return ((EditableValue<String>)((dynamic)this)._diagnosisName).PreviousValue; } }
[LocalizedDisplayName(_str_SessionDiagnosisName)]
[MapField(_str_SessionDiagnosisName)]
public abstract String SessionDiagnosisName { get; set; }
protected String SessionDiagnosisName_Original { get { return ((EditableValue<String>)((dynamic)this)._sessionDiagnosisName).OriginalValue; } }
protected String SessionDiagnosisName_Previous { get { return ((EditableValue<String>)((dynamic)this)._sessionDiagnosisName).PreviousValue; } }
[LocalizedDisplayName(_str_idfsShowDiagnosis)]
[MapField(_str_idfsShowDiagnosis)]
public abstract Int64? idfsShowDiagnosis { get; set; }
protected Int64? idfsShowDiagnosis_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsShowDiagnosis).OriginalValue; } }
protected Int64? idfsShowDiagnosis_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsShowDiagnosis).PreviousValue; } }
[LocalizedDisplayName("DepartmentName")]
[MapField(_str_idfInDepartment)]
public abstract Int64? idfInDepartment { get; set; }
protected Int64? idfInDepartment_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfInDepartment).OriginalValue; } }
protected Int64? idfInDepartment_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfInDepartment).PreviousValue; } }
[LocalizedDisplayName(_str_idfSubdivision)]
[MapField(_str_idfSubdivision)]
public abstract Int64? idfSubdivision { get; set; }
protected Int64? idfSubdivision_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfSubdivision).OriginalValue; } }
protected Int64? idfSubdivision_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfSubdivision).PreviousValue; } }
[LocalizedDisplayName(_str_idfFieldCollectedByOffice)]
[MapField(_str_idfFieldCollectedByOffice)]
public abstract Int64? idfFieldCollectedByOffice { get; set; }
protected Int64? idfFieldCollectedByOffice_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfFieldCollectedByOffice).OriginalValue; } }
protected Int64? idfFieldCollectedByOffice_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfFieldCollectedByOffice).PreviousValue; } }
[LocalizedDisplayName(_str_strFieldCollectedByOffice)]
[MapField(_str_strFieldCollectedByOffice)]
public abstract String strFieldCollectedByOffice { get; set; }
protected String strFieldCollectedByOffice_Original { get { return ((EditableValue<String>)((dynamic)this)._strFieldCollectedByOffice).OriginalValue; } }
protected String strFieldCollectedByOffice_Previous { get { return ((EditableValue<String>)((dynamic)this)._strFieldCollectedByOffice).PreviousValue; } }
[LocalizedDisplayName(_str_idfFieldCollectedByPerson)]
[MapField(_str_idfFieldCollectedByPerson)]
public abstract Int64? idfFieldCollectedByPerson { get; set; }
protected Int64? idfFieldCollectedByPerson_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfFieldCollectedByPerson).OriginalValue; } }
protected Int64? idfFieldCollectedByPerson_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfFieldCollectedByPerson).PreviousValue; } }
[LocalizedDisplayName(_str_strFieldCollectedByPerson)]
[MapField(_str_strFieldCollectedByPerson)]
public abstract String strFieldCollectedByPerson { get; set; }
protected String strFieldCollectedByPerson_Original { get { return ((EditableValue<String>)((dynamic)this)._strFieldCollectedByPerson).OriginalValue; } }
protected String strFieldCollectedByPerson_Previous { get { return ((EditableValue<String>)((dynamic)this)._strFieldCollectedByPerson).PreviousValue; } }
[LocalizedDisplayName("strNotes")]
[MapField(_str_strNote)]
public abstract String strNote { get; set; }
protected String strNote_Original { get { return ((EditableValue<String>)((dynamic)this)._strNote).OriginalValue; } }
protected String strNote_Previous { get { return ((EditableValue<String>)((dynamic)this)._strNote).PreviousValue; } }
[LocalizedDisplayName(_str_idfParentMaterial)]
[MapField(_str_idfParentMaterial)]
public abstract Int64? idfParentMaterial { get; set; }
protected Int64? idfParentMaterial_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfParentMaterial).OriginalValue; } }
protected Int64? idfParentMaterial_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfParentMaterial).PreviousValue; } }
[LocalizedDisplayName(_str_strParentBarcode)]
[MapField(_str_strParentBarcode)]
public abstract String strParentBarcode { get; set; }
protected String strParentBarcode_Original { get { return ((EditableValue<String>)((dynamic)this)._strParentBarcode).OriginalValue; } }
protected String strParentBarcode_Previous { get { return ((EditableValue<String>)((dynamic)this)._strParentBarcode).PreviousValue; } }
[LocalizedDisplayName("strCaseType")]
[MapField(_str_CaseType)]
public abstract String CaseType { get; set; }
protected String CaseType_Original { get { return ((EditableValue<String>)((dynamic)this)._caseType).OriginalValue; } }
protected String CaseType_Previous { get { return ((EditableValue<String>)((dynamic)this)._caseType).PreviousValue; } }
[LocalizedDisplayName(_str_datFieldCollectionDate)]
[MapField(_str_datFieldCollectionDate)]
public abstract DateTime? datFieldCollectionDate { get; set; }
protected DateTime? datFieldCollectionDate_Original { get { return ((EditableValue<DateTime?>)((dynamic)this)._datFieldCollectionDate).OriginalValue; } }
protected DateTime? datFieldCollectionDate_Previous { get { return ((EditableValue<DateTime?>)((dynamic)this)._datFieldCollectionDate).PreviousValue; } }
[LocalizedDisplayName(_str_idfsBirdStatus)]
[MapField(_str_idfsBirdStatus)]
public abstract Int64? idfsBirdStatus { get; set; }
protected Int64? idfsBirdStatus_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsBirdStatus).OriginalValue; } }
protected Int64? idfsBirdStatus_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsBirdStatus).PreviousValue; } }
[LocalizedDisplayName(_str_intHACode)]
[MapField(_str_intHACode)]
public abstract Int32 intHACode { get; set; }
protected Int32 intHACode_Original { get { return ((EditableValue<Int32>)((dynamic)this)._intHACode).OriginalValue; } }
protected Int32 intHACode_Previous { get { return ((EditableValue<Int32>)((dynamic)this)._intHACode).PreviousValue; } }
[LocalizedDisplayName(_str_idfsDestructionMethod)]
[MapField(_str_idfsDestructionMethod)]
public abstract Int64? idfsDestructionMethod { get; set; }
protected Int64? idfsDestructionMethod_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsDestructionMethod).OriginalValue; } }
protected Int64? idfsDestructionMethod_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsDestructionMethod).PreviousValue; } }
[LocalizedDisplayName(_str_idfsSite)]
[MapField(_str_idfsSite)]
public abstract Int64 idfsSite { get; set; }
protected Int64 idfsSite_Original { get { return ((EditableValue<Int64>)((dynamic)this)._idfsSite).OriginalValue; } }
protected Int64 idfsSite_Previous { get { return ((EditableValue<Int64>)((dynamic)this)._idfsSite).PreviousValue; } }
[LocalizedDisplayName(_str_idfsCurrentSite)]
[MapField(_str_idfsCurrentSite)]
public abstract Int64? idfsCurrentSite { get; set; }
protected Int64? idfsCurrentSite_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsCurrentSite).OriginalValue; } }
protected Int64? idfsCurrentSite_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsCurrentSite).PreviousValue; } }
[LocalizedDisplayName(_str_blnSampleTransferred)]
[MapField(_str_blnSampleTransferred)]
public abstract Boolean? blnSampleTransferred { get; set; }
protected Boolean? blnSampleTransferred_Original { get { return ((EditableValue<Boolean?>)((dynamic)this)._blnSampleTransferred).OriginalValue; } }
protected Boolean? blnSampleTransferred_Previous { get { return ((EditableValue<Boolean?>)((dynamic)this)._blnSampleTransferred).PreviousValue; } }
#region Set/Get values
#region filed_info definifion
protected class field_info
{
internal string _name;
internal string _formname;
internal string _type;
internal Func<LabSample, object> _get_func;
internal Action<LabSample, string> _set_func;
internal Action<LabSample, LabSample, CompareModel> _compare_func;
}
internal const string _str_Parent = "Parent";
internal const string _str_IsNew = "IsNew";
internal const string _str_idfMaterial = "idfMaterial";
internal const string _str_idfsSampleStatus = "idfsSampleStatus";
internal const string _str_datAccession = "datAccession";
internal const string _str_strBarcode = "strBarcode";
internal const string _str_idfCase = "idfCase";
internal const string _str_idfMonitoringSession = "idfMonitoringSession";
internal const string _str_strCaseID = "strCaseID";
internal const string _str_strMonitoringSessionID = "strMonitoringSessionID";
internal const string _str_idfVectorSurveillanceSession = "idfVectorSurveillanceSession";
internal const string _str_idfsCaseType = "idfsCaseType";
internal const string _str_strSampleName = "strSampleName";
internal const string _str_SpeciesName = "SpeciesName";
internal const string _str_strAnimalCode = "strAnimalCode";
internal const string _str_HumanName = "HumanName";
internal const string _str_DiagnosisName = "DiagnosisName";
internal const string _str_SessionDiagnosisName = "SessionDiagnosisName";
internal const string _str_idfsShowDiagnosis = "idfsShowDiagnosis";
internal const string _str_idfInDepartment = "idfInDepartment";
internal const string _str_idfSubdivision = "idfSubdivision";
internal const string _str_idfFieldCollectedByOffice = "idfFieldCollectedByOffice";
internal const string _str_strFieldCollectedByOffice = "strFieldCollectedByOffice";
internal const string _str_idfFieldCollectedByPerson = "idfFieldCollectedByPerson";
internal const string _str_strFieldCollectedByPerson = "strFieldCollectedByPerson";
internal const string _str_strNote = "strNote";
internal const string _str_idfParentMaterial = "idfParentMaterial";
internal const string _str_strParentBarcode = "strParentBarcode";
internal const string _str_CaseType = "CaseType";
internal const string _str_datFieldCollectionDate = "datFieldCollectionDate";
internal const string _str_idfsBirdStatus = "idfsBirdStatus";
internal const string _str_intHACode = "intHACode";
internal const string _str_idfsDestructionMethod = "idfsDestructionMethod";
internal const string _str_idfsSite = "idfsSite";
internal const string _str_idfsCurrentSite = "idfsCurrentSite";
internal const string _str_blnSampleTransferred = "blnSampleTransferred";
internal const string _str_strFreezer = "strFreezer";
internal const string _str_strCaseInfo = "strCaseInfo";
internal const string _str_strMonitoringSessionInfo = "strMonitoringSessionInfo";
internal const string _str_Department = "Department";
internal const string _str_Freezer = "Freezer";
private static readonly field_info[] _field_infos =
{
new field_info {
_name = _str_idfMaterial, _formname = _str_idfMaterial, _type = "Int64",
_get_func = o => o.idfMaterial,
_set_func = (o, val) => { var newval = ParsingHelper.ParseInt64(val); if (o.idfMaterial != newval) o.idfMaterial = newval; },
_compare_func = (o, c, m) => {
if (o.idfMaterial != c.idfMaterial || o.IsRIRPropChanged(_str_idfMaterial, c))
m.Add(_str_idfMaterial, o.ObjectIdent + _str_idfMaterial, o.ObjectIdent2 + _str_idfMaterial, o.ObjectIdent3 + _str_idfMaterial, "Int64",
o.idfMaterial == null ? "" : o.idfMaterial.ToString(),
o.IsReadOnly(_str_idfMaterial), o.IsInvisible(_str_idfMaterial), o.IsRequired(_str_idfMaterial));
}
},
new field_info {
_name = _str_idfsSampleStatus, _formname = _str_idfsSampleStatus, _type = "Int64?",
_get_func = o => o.idfsSampleStatus,
_set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsSampleStatus != newval) o.idfsSampleStatus = newval; },
_compare_func = (o, c, m) => {
if (o.idfsSampleStatus != c.idfsSampleStatus || o.IsRIRPropChanged(_str_idfsSampleStatus, c))
m.Add(_str_idfsSampleStatus, o.ObjectIdent + _str_idfsSampleStatus, o.ObjectIdent2 + _str_idfsSampleStatus, o.ObjectIdent3 + _str_idfsSampleStatus, "Int64?",
o.idfsSampleStatus == null ? "" : o.idfsSampleStatus.ToString(),
o.IsReadOnly(_str_idfsSampleStatus), o.IsInvisible(_str_idfsSampleStatus), o.IsRequired(_str_idfsSampleStatus));
}
},
new field_info {
_name = _str_datAccession, _formname = _str_datAccession, _type = "DateTime?",
_get_func = o => o.datAccession,
_set_func = (o, val) => { var newval = ParsingHelper.ParseDateTimeNullable(val); if (o.datAccession != newval) o.datAccession = newval; },
_compare_func = (o, c, m) => {
if (o.datAccession != c.datAccession || o.IsRIRPropChanged(_str_datAccession, c))
m.Add(_str_datAccession, o.ObjectIdent + _str_datAccession, o.ObjectIdent2 + _str_datAccession, o.ObjectIdent3 + _str_datAccession, "DateTime?",
o.datAccession == null ? "" : o.datAccession.ToString(),
o.IsReadOnly(_str_datAccession), o.IsInvisible(_str_datAccession), o.IsRequired(_str_datAccession));
}
},
new field_info {
_name = _str_strBarcode, _formname = _str_strBarcode, _type = "String",
_get_func = o => o.strBarcode,
_set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strBarcode != newval) o.strBarcode = newval; },
_compare_func = (o, c, m) => {
if (o.strBarcode != c.strBarcode || o.IsRIRPropChanged(_str_strBarcode, c))
m.Add(_str_strBarcode, o.ObjectIdent + _str_strBarcode, o.ObjectIdent2 + _str_strBarcode, o.ObjectIdent3 + _str_strBarcode, "String",
o.strBarcode == null ? "" : o.strBarcode.ToString(),
o.IsReadOnly(_str_strBarcode), o.IsInvisible(_str_strBarcode), o.IsRequired(_str_strBarcode));
}
},
new field_info {
_name = _str_idfCase, _formname = _str_idfCase, _type = "Int64?",
_get_func = o => o.idfCase,
_set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfCase != newval) o.idfCase = newval; },
_compare_func = (o, c, m) => {
if (o.idfCase != c.idfCase || o.IsRIRPropChanged(_str_idfCase, c))
m.Add(_str_idfCase, o.ObjectIdent + _str_idfCase, o.ObjectIdent2 + _str_idfCase, o.ObjectIdent3 + _str_idfCase, "Int64?",
o.idfCase == null ? "" : o.idfCase.ToString(),
o.IsReadOnly(_str_idfCase), o.IsInvisible(_str_idfCase), o.IsRequired(_str_idfCase));
}
},
new field_info {
_name = _str_idfMonitoringSession, _formname = _str_idfMonitoringSession, _type = "Int64?",
_get_func = o => o.idfMonitoringSession,
_set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfMonitoringSession != newval) o.idfMonitoringSession = newval; },
_compare_func = (o, c, m) => {
if (o.idfMonitoringSession != c.idfMonitoringSession || o.IsRIRPropChanged(_str_idfMonitoringSession, c))
m.Add(_str_idfMonitoringSession, o.ObjectIdent + _str_idfMonitoringSession, o.ObjectIdent2 + _str_idfMonitoringSession, o.ObjectIdent3 + _str_idfMonitoringSession, "Int64?",
o.idfMonitoringSession == null ? "" : o.idfMonitoringSession.ToString(),
o.IsReadOnly(_str_idfMonitoringSession), o.IsInvisible(_str_idfMonitoringSession), o.IsRequired(_str_idfMonitoringSession));
}
},
new field_info {
_name = _str_strCaseID, _formname = _str_strCaseID, _type = "String",
_get_func = o => o.strCaseID,
_set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strCaseID != newval) o.strCaseID = newval; },
_compare_func = (o, c, m) => {
if (o.strCaseID != c.strCaseID || o.IsRIRPropChanged(_str_strCaseID, c))
m.Add(_str_strCaseID, o.ObjectIdent + _str_strCaseID, o.ObjectIdent2 + _str_strCaseID, o.ObjectIdent3 + _str_strCaseID, "String",
o.strCaseID == null ? "" : o.strCaseID.ToString(),
o.IsReadOnly(_str_strCaseID), o.IsInvisible(_str_strCaseID), o.IsRequired(_str_strCaseID));
}
},
new field_info {
_name = _str_strMonitoringSessionID, _formname = _str_strMonitoringSessionID, _type = "String",
_get_func = o => o.strMonitoringSessionID,
_set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strMonitoringSessionID != newval) o.strMonitoringSessionID = newval; },
_compare_func = (o, c, m) => {
if (o.strMonitoringSessionID != c.strMonitoringSessionID || o.IsRIRPropChanged(_str_strMonitoringSessionID, c))
m.Add(_str_strMonitoringSessionID, o.ObjectIdent + _str_strMonitoringSessionID, o.ObjectIdent2 + _str_strMonitoringSessionID, o.ObjectIdent3 + _str_strMonitoringSessionID, "String",
o.strMonitoringSessionID == null ? "" : o.strMonitoringSessionID.ToString(),
o.IsReadOnly(_str_strMonitoringSessionID), o.IsInvisible(_str_strMonitoringSessionID), o.IsRequired(_str_strMonitoringSessionID));
}
},
new field_info {
_name = _str_idfVectorSurveillanceSession, _formname = _str_idfVectorSurveillanceSession, _type = "Int64?",
_get_func = o => o.idfVectorSurveillanceSession,
_set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfVectorSurveillanceSession != newval) o.idfVectorSurveillanceSession = newval; },
_compare_func = (o, c, m) => {
if (o.idfVectorSurveillanceSession != c.idfVectorSurveillanceSession || o.IsRIRPropChanged(_str_idfVectorSurveillanceSession, c))
m.Add(_str_idfVectorSurveillanceSession, o.ObjectIdent + _str_idfVectorSurveillanceSession, o.ObjectIdent2 + _str_idfVectorSurveillanceSession, o.ObjectIdent3 + _str_idfVectorSurveillanceSession, "Int64?",
o.idfVectorSurveillanceSession == null ? "" : o.idfVectorSurveillanceSession.ToString(),
o.IsReadOnly(_str_idfVectorSurveillanceSession), o.IsInvisible(_str_idfVectorSurveillanceSession), o.IsRequired(_str_idfVectorSurveillanceSession));
}
},
new field_info {
_name = _str_idfsCaseType, _formname = _str_idfsCaseType, _type = "Int64?",
_get_func = o => o.idfsCaseType,
_set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsCaseType != newval) o.idfsCaseType = newval; },
_compare_func = (o, c, m) => {
if (o.idfsCaseType != c.idfsCaseType || o.IsRIRPropChanged(_str_idfsCaseType, c))
m.Add(_str_idfsCaseType, o.ObjectIdent + _str_idfsCaseType, o.ObjectIdent2 + _str_idfsCaseType, o.ObjectIdent3 + _str_idfsCaseType, "Int64?",
o.idfsCaseType == null ? "" : o.idfsCaseType.ToString(),
o.IsReadOnly(_str_idfsCaseType), o.IsInvisible(_str_idfsCaseType), o.IsRequired(_str_idfsCaseType));
}
},
new field_info {
_name = _str_strSampleName, _formname = _str_strSampleName, _type = "String",
_get_func = o => o.strSampleName,
_set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strSampleName != newval) o.strSampleName = newval; },
_compare_func = (o, c, m) => {
if (o.strSampleName != c.strSampleName || o.IsRIRPropChanged(_str_strSampleName, c))
m.Add(_str_strSampleName, o.ObjectIdent + _str_strSampleName, o.ObjectIdent2 + _str_strSampleName, o.ObjectIdent3 + _str_strSampleName, "String",
o.strSampleName == null ? "" : o.strSampleName.ToString(),
o.IsReadOnly(_str_strSampleName), o.IsInvisible(_str_strSampleName), o.IsRequired(_str_strSampleName));
}
},
new field_info {
_name = _str_SpeciesName, _formname = _str_SpeciesName, _type = "String",
_get_func = o => o.SpeciesName,
_set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.SpeciesName != newval) o.SpeciesName = newval; },
_compare_func = (o, c, m) => {
if (o.SpeciesName != c.SpeciesName || o.IsRIRPropChanged(_str_SpeciesName, c))
m.Add(_str_SpeciesName, o.ObjectIdent + _str_SpeciesName, o.ObjectIdent2 + _str_SpeciesName, o.ObjectIdent3 + _str_SpeciesName, "String",
o.SpeciesName == null ? "" : o.SpeciesName.ToString(),
o.IsReadOnly(_str_SpeciesName), o.IsInvisible(_str_SpeciesName), o.IsRequired(_str_SpeciesName));
}
},
new field_info {
_name = _str_strAnimalCode, _formname = _str_strAnimalCode, _type = "String",
_get_func = o => o.strAnimalCode,
_set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strAnimalCode != newval) o.strAnimalCode = newval; },
_compare_func = (o, c, m) => {
if (o.strAnimalCode != c.strAnimalCode || o.IsRIRPropChanged(_str_strAnimalCode, c))
m.Add(_str_strAnimalCode, o.ObjectIdent + _str_strAnimalCode, o.ObjectIdent2 + _str_strAnimalCode, o.ObjectIdent3 + _str_strAnimalCode, "String",
o.strAnimalCode == null ? "" : o.strAnimalCode.ToString(),
o.IsReadOnly(_str_strAnimalCode), o.IsInvisible(_str_strAnimalCode), o.IsRequired(_str_strAnimalCode));
}
},
new field_info {
_name = _str_HumanName, _formname = _str_HumanName, _type = "String",
_get_func = o => o.HumanName,
_set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.HumanName != newval) o.HumanName = newval; },
_compare_func = (o, c, m) => {
if (o.HumanName != c.HumanName || o.IsRIRPropChanged(_str_HumanName, c))
m.Add(_str_HumanName, o.ObjectIdent + _str_HumanName, o.ObjectIdent2 + _str_HumanName, o.ObjectIdent3 + _str_HumanName, "String",
o.HumanName == null ? "" : o.HumanName.ToString(),
o.IsReadOnly(_str_HumanName), o.IsInvisible(_str_HumanName), o.IsRequired(_str_HumanName));
}
},
new field_info {
_name = _str_DiagnosisName, _formname = _str_DiagnosisName, _type = "String",
_get_func = o => o.DiagnosisName,
_set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.DiagnosisName != newval) o.DiagnosisName = newval; },
_compare_func = (o, c, m) => {
if (o.DiagnosisName != c.DiagnosisName || o.IsRIRPropChanged(_str_DiagnosisName, c))
m.Add(_str_DiagnosisName, o.ObjectIdent + _str_DiagnosisName, o.ObjectIdent2 + _str_DiagnosisName, o.ObjectIdent3 + _str_DiagnosisName, "String",
o.DiagnosisName == null ? "" : o.DiagnosisName.ToString(),
o.IsReadOnly(_str_DiagnosisName), o.IsInvisible(_str_DiagnosisName), o.IsRequired(_str_DiagnosisName));
}
},
new field_info {
_name = _str_SessionDiagnosisName, _formname = _str_SessionDiagnosisName, _type = "String",
_get_func = o => o.SessionDiagnosisName,
_set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.SessionDiagnosisName != newval) o.SessionDiagnosisName = newval; },
_compare_func = (o, c, m) => {
if (o.SessionDiagnosisName != c.SessionDiagnosisName || o.IsRIRPropChanged(_str_SessionDiagnosisName, c))
m.Add(_str_SessionDiagnosisName, o.ObjectIdent + _str_SessionDiagnosisName, o.ObjectIdent2 + _str_SessionDiagnosisName, o.ObjectIdent3 + _str_SessionDiagnosisName, "String",
o.SessionDiagnosisName == null ? "" : o.SessionDiagnosisName.ToString(),
o.IsReadOnly(_str_SessionDiagnosisName), o.IsInvisible(_str_SessionDiagnosisName), o.IsRequired(_str_SessionDiagnosisName));
}
},
new field_info {
_name = _str_idfsShowDiagnosis, _formname = _str_idfsShowDiagnosis, _type = "Int64?",
_get_func = o => o.idfsShowDiagnosis,
_set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsShowDiagnosis != newval) o.idfsShowDiagnosis = newval; },
_compare_func = (o, c, m) => {
if (o.idfsShowDiagnosis != c.idfsShowDiagnosis || o.IsRIRPropChanged(_str_idfsShowDiagnosis, c))
m.Add(_str_idfsShowDiagnosis, o.ObjectIdent + _str_idfsShowDiagnosis, o.ObjectIdent2 + _str_idfsShowDiagnosis, o.ObjectIdent3 + _str_idfsShowDiagnosis, "Int64?",
o.idfsShowDiagnosis == null ? "" : o.idfsShowDiagnosis.ToString(),
o.IsReadOnly(_str_idfsShowDiagnosis), o.IsInvisible(_str_idfsShowDiagnosis), o.IsRequired(_str_idfsShowDiagnosis));
}
},
new field_info {
_name = _str_idfInDepartment, _formname = _str_idfInDepartment, _type = "Int64?",
_get_func = o => o.idfInDepartment,
_set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val);
if (o.idfInDepartment != newval)
o.Department = o.DepartmentLookup.FirstOrDefault(c => c.idfDepartment == newval);
if (o.idfInDepartment != newval) o.idfInDepartment = newval; },
_compare_func = (o, c, m) => {
if (o.idfInDepartment != c.idfInDepartment || o.IsRIRPropChanged(_str_idfInDepartment, c))
m.Add(_str_idfInDepartment, o.ObjectIdent + _str_idfInDepartment, o.ObjectIdent2 + _str_idfInDepartment, o.ObjectIdent3 + _str_idfInDepartment, "Int64?",
o.idfInDepartment == null ? "" : o.idfInDepartment.ToString(),
o.IsReadOnly(_str_idfInDepartment), o.IsInvisible(_str_idfInDepartment), o.IsRequired(_str_idfInDepartment));
}
},
new field_info {
_name = _str_idfSubdivision, _formname = _str_idfSubdivision, _type = "Int64?",
_get_func = o => o.idfSubdivision,
_set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val);
if (o.idfSubdivision != newval)
o.Freezer = o.FreezerLookup.FirstOrDefault(c => c.ID == newval);
if (o.idfSubdivision != newval) o.idfSubdivision = newval; },
_compare_func = (o, c, m) => {
if (o.idfSubdivision != c.idfSubdivision || o.IsRIRPropChanged(_str_idfSubdivision, c))
m.Add(_str_idfSubdivision, o.ObjectIdent + _str_idfSubdivision, o.ObjectIdent2 + _str_idfSubdivision, o.ObjectIdent3 + _str_idfSubdivision, "Int64?",
o.idfSubdivision == null ? "" : o.idfSubdivision.ToString(),
o.IsReadOnly(_str_idfSubdivision), o.IsInvisible(_str_idfSubdivision), o.IsRequired(_str_idfSubdivision));
}
},
new field_info {
_name = _str_idfFieldCollectedByOffice, _formname = _str_idfFieldCollectedByOffice, _type = "Int64?",
_get_func = o => o.idfFieldCollectedByOffice,
_set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfFieldCollectedByOffice != newval) o.idfFieldCollectedByOffice = newval; },
_compare_func = (o, c, m) => {
if (o.idfFieldCollectedByOffice != c.idfFieldCollectedByOffice || o.IsRIRPropChanged(_str_idfFieldCollectedByOffice, c))
m.Add(_str_idfFieldCollectedByOffice, o.ObjectIdent + _str_idfFieldCollectedByOffice, o.ObjectIdent2 + _str_idfFieldCollectedByOffice, o.ObjectIdent3 + _str_idfFieldCollectedByOffice, "Int64?",
o.idfFieldCollectedByOffice == null ? "" : o.idfFieldCollectedByOffice.ToString(),
o.IsReadOnly(_str_idfFieldCollectedByOffice), o.IsInvisible(_str_idfFieldCollectedByOffice), o.IsRequired(_str_idfFieldCollectedByOffice));
}
},
new field_info {
_name = _str_strFieldCollectedByOffice, _formname = _str_strFieldCollectedByOffice, _type = "String",
_get_func = o => o.strFieldCollectedByOffice,
_set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strFieldCollectedByOffice != newval) o.strFieldCollectedByOffice = newval; },
_compare_func = (o, c, m) => {
if (o.strFieldCollectedByOffice != c.strFieldCollectedByOffice || o.IsRIRPropChanged(_str_strFieldCollectedByOffice, c))
m.Add(_str_strFieldCollectedByOffice, o.ObjectIdent + _str_strFieldCollectedByOffice, o.ObjectIdent2 + _str_strFieldCollectedByOffice, o.ObjectIdent3 + _str_strFieldCollectedByOffice, "String",
o.strFieldCollectedByOffice == null ? "" : o.strFieldCollectedByOffice.ToString(),
o.IsReadOnly(_str_strFieldCollectedByOffice), o.IsInvisible(_str_strFieldCollectedByOffice), o.IsRequired(_str_strFieldCollectedByOffice));
}
},
new field_info {
_name = _str_idfFieldCollectedByPerson, _formname = _str_idfFieldCollectedByPerson, _type = "Int64?",
_get_func = o => o.idfFieldCollectedByPerson,
_set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfFieldCollectedByPerson != newval) o.idfFieldCollectedByPerson = newval; },
_compare_func = (o, c, m) => {
if (o.idfFieldCollectedByPerson != c.idfFieldCollectedByPerson || o.IsRIRPropChanged(_str_idfFieldCollectedByPerson, c))
m.Add(_str_idfFieldCollectedByPerson, o.ObjectIdent + _str_idfFieldCollectedByPerson, o.ObjectIdent2 + _str_idfFieldCollectedByPerson, o.ObjectIdent3 + _str_idfFieldCollectedByPerson, "Int64?",
o.idfFieldCollectedByPerson == null ? "" : o.idfFieldCollectedByPerson.ToString(),
o.IsReadOnly(_str_idfFieldCollectedByPerson), o.IsInvisible(_str_idfFieldCollectedByPerson), o.IsRequired(_str_idfFieldCollectedByPerson));
}
},
new field_info {
_name = _str_strFieldCollectedByPerson, _formname = _str_strFieldCollectedByPerson, _type = "String",
_get_func = o => o.strFieldCollectedByPerson,
_set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strFieldCollectedByPerson != newval) o.strFieldCollectedByPerson = newval; },
_compare_func = (o, c, m) => {
if (o.strFieldCollectedByPerson != c.strFieldCollectedByPerson || o.IsRIRPropChanged(_str_strFieldCollectedByPerson, c))
m.Add(_str_strFieldCollectedByPerson, o.ObjectIdent + _str_strFieldCollectedByPerson, o.ObjectIdent2 + _str_strFieldCollectedByPerson, o.ObjectIdent3 + _str_strFieldCollectedByPerson, "String",
o.strFieldCollectedByPerson == null ? "" : o.strFieldCollectedByPerson.ToString(),
o.IsReadOnly(_str_strFieldCollectedByPerson), o.IsInvisible(_str_strFieldCollectedByPerson), o.IsRequired(_str_strFieldCollectedByPerson));
}
},
new field_info {
_name = _str_strNote, _formname = _str_strNote, _type = "String",
_get_func = o => o.strNote,
_set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strNote != newval) o.strNote = newval; },
_compare_func = (o, c, m) => {
if (o.strNote != c.strNote || o.IsRIRPropChanged(_str_strNote, c))
m.Add(_str_strNote, o.ObjectIdent + _str_strNote, o.ObjectIdent2 + _str_strNote, o.ObjectIdent3 + _str_strNote, "String",
o.strNote == null ? "" : o.strNote.ToString(),
o.IsReadOnly(_str_strNote), o.IsInvisible(_str_strNote), o.IsRequired(_str_strNote));
}
},
new field_info {
_name = _str_idfParentMaterial, _formname = _str_idfParentMaterial, _type = "Int64?",
_get_func = o => o.idfParentMaterial,
_set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfParentMaterial != newval) o.idfParentMaterial = newval; },
_compare_func = (o, c, m) => {
if (o.idfParentMaterial != c.idfParentMaterial || o.IsRIRPropChanged(_str_idfParentMaterial, c))
m.Add(_str_idfParentMaterial, o.ObjectIdent + _str_idfParentMaterial, o.ObjectIdent2 + _str_idfParentMaterial, o.ObjectIdent3 + _str_idfParentMaterial, "Int64?",
o.idfParentMaterial == null ? "" : o.idfParentMaterial.ToString(),
o.IsReadOnly(_str_idfParentMaterial), o.IsInvisible(_str_idfParentMaterial), o.IsRequired(_str_idfParentMaterial));
}
},
new field_info {
_name = _str_strParentBarcode, _formname = _str_strParentBarcode, _type = "String",
_get_func = o => o.strParentBarcode,
_set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strParentBarcode != newval) o.strParentBarcode = newval; },
_compare_func = (o, c, m) => {
if (o.strParentBarcode != c.strParentBarcode || o.IsRIRPropChanged(_str_strParentBarcode, c))
m.Add(_str_strParentBarcode, o.ObjectIdent + _str_strParentBarcode, o.ObjectIdent2 + _str_strParentBarcode, o.ObjectIdent3 + _str_strParentBarcode, "String",
o.strParentBarcode == null ? "" : o.strParentBarcode.ToString(),
o.IsReadOnly(_str_strParentBarcode), o.IsInvisible(_str_strParentBarcode), o.IsRequired(_str_strParentBarcode));
}
},
new field_info {
_name = _str_CaseType, _formname = _str_CaseType, _type = "String",
_get_func = o => o.CaseType,
_set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.CaseType != newval) o.CaseType = newval; },
_compare_func = (o, c, m) => {
if (o.CaseType != c.CaseType || o.IsRIRPropChanged(_str_CaseType, c))
m.Add(_str_CaseType, o.ObjectIdent + _str_CaseType, o.ObjectIdent2 + _str_CaseType, o.ObjectIdent3 + _str_CaseType, "String",
o.CaseType == null ? "" : o.CaseType.ToString(),
o.IsReadOnly(_str_CaseType), o.IsInvisible(_str_CaseType), o.IsRequired(_str_CaseType));
}
},
new field_info {
_name = _str_datFieldCollectionDate, _formname = _str_datFieldCollectionDate, _type = "DateTime?",
_get_func = o => o.datFieldCollectionDate,
_set_func = (o, val) => { var newval = ParsingHelper.ParseDateTimeNullable(val); if (o.datFieldCollectionDate != newval) o.datFieldCollectionDate = newval; },
_compare_func = (o, c, m) => {
if (o.datFieldCollectionDate != c.datFieldCollectionDate || o.IsRIRPropChanged(_str_datFieldCollectionDate, c))
m.Add(_str_datFieldCollectionDate, o.ObjectIdent + _str_datFieldCollectionDate, o.ObjectIdent2 + _str_datFieldCollectionDate, o.ObjectIdent3 + _str_datFieldCollectionDate, "DateTime?",
o.datFieldCollectionDate == null ? "" : o.datFieldCollectionDate.ToString(),
o.IsReadOnly(_str_datFieldCollectionDate), o.IsInvisible(_str_datFieldCollectionDate), o.IsRequired(_str_datFieldCollectionDate));
}
},
new field_info {
_name = _str_idfsBirdStatus, _formname = _str_idfsBirdStatus, _type = "Int64?",
_get_func = o => o.idfsBirdStatus,
_set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsBirdStatus != newval) o.idfsBirdStatus = newval; },
_compare_func = (o, c, m) => {
if (o.idfsBirdStatus != c.idfsBirdStatus || o.IsRIRPropChanged(_str_idfsBirdStatus, c))
m.Add(_str_idfsBirdStatus, o.ObjectIdent + _str_idfsBirdStatus, o.ObjectIdent2 + _str_idfsBirdStatus, o.ObjectIdent3 + _str_idfsBirdStatus, "Int64?",
o.idfsBirdStatus == null ? "" : o.idfsBirdStatus.ToString(),
o.IsReadOnly(_str_idfsBirdStatus), o.IsInvisible(_str_idfsBirdStatus), o.IsRequired(_str_idfsBirdStatus));
}
},
new field_info {
_name = _str_intHACode, _formname = _str_intHACode, _type = "Int32",
_get_func = o => o.intHACode,
_set_func = (o, val) => { var newval = ParsingHelper.ParseInt32(val); if (o.intHACode != newval) o.intHACode = newval; },
_compare_func = (o, c, m) => {
if (o.intHACode != c.intHACode || o.IsRIRPropChanged(_str_intHACode, c))
m.Add(_str_intHACode, o.ObjectIdent + _str_intHACode, o.ObjectIdent2 + _str_intHACode, o.ObjectIdent3 + _str_intHACode, "Int32",
o.intHACode == null ? "" : o.intHACode.ToString(),
o.IsReadOnly(_str_intHACode), o.IsInvisible(_str_intHACode), o.IsRequired(_str_intHACode));
}
},
new field_info {
_name = _str_idfsDestructionMethod, _formname = _str_idfsDestructionMethod, _type = "Int64?",
_get_func = o => o.idfsDestructionMethod,
_set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsDestructionMethod != newval) o.idfsDestructionMethod = newval; },
_compare_func = (o, c, m) => {
if (o.idfsDestructionMethod != c.idfsDestructionMethod || o.IsRIRPropChanged(_str_idfsDestructionMethod, c))
m.Add(_str_idfsDestructionMethod, o.ObjectIdent + _str_idfsDestructionMethod, o.ObjectIdent2 + _str_idfsDestructionMethod, o.ObjectIdent3 + _str_idfsDestructionMethod, "Int64?",
o.idfsDestructionMethod == null ? "" : o.idfsDestructionMethod.ToString(),
o.IsReadOnly(_str_idfsDestructionMethod), o.IsInvisible(_str_idfsDestructionMethod), o.IsRequired(_str_idfsDestructionMethod));
}
},
new field_info {
_name = _str_idfsSite, _formname = _str_idfsSite, _type = "Int64",
_get_func = o => o.idfsSite,
_set_func = (o, val) => { var newval = ParsingHelper.ParseInt64(val); if (o.idfsSite != newval) o.idfsSite = newval; },
_compare_func = (o, c, m) => {
if (o.idfsSite != c.idfsSite || o.IsRIRPropChanged(_str_idfsSite, c))
m.Add(_str_idfsSite, o.ObjectIdent + _str_idfsSite, o.ObjectIdent2 + _str_idfsSite, o.ObjectIdent3 + _str_idfsSite, "Int64",
o.idfsSite == null ? "" : o.idfsSite.ToString(),
o.IsReadOnly(_str_idfsSite), o.IsInvisible(_str_idfsSite), o.IsRequired(_str_idfsSite));
}
},
new field_info {
_name = _str_idfsCurrentSite, _formname = _str_idfsCurrentSite, _type = "Int64?",
_get_func = o => o.idfsCurrentSite,
_set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsCurrentSite != newval) o.idfsCurrentSite = newval; },
_compare_func = (o, c, m) => {
if (o.idfsCurrentSite != c.idfsCurrentSite || o.IsRIRPropChanged(_str_idfsCurrentSite, c))
m.Add(_str_idfsCurrentSite, o.ObjectIdent + _str_idfsCurrentSite, o.ObjectIdent2 + _str_idfsCurrentSite, o.ObjectIdent3 + _str_idfsCurrentSite, "Int64?",
o.idfsCurrentSite == null ? "" : o.idfsCurrentSite.ToString(),
o.IsReadOnly(_str_idfsCurrentSite), o.IsInvisible(_str_idfsCurrentSite), o.IsRequired(_str_idfsCurrentSite));
}
},
new field_info {
_name = _str_blnSampleTransferred, _formname = _str_blnSampleTransferred, _type = "Boolean?",
_get_func = o => o.blnSampleTransferred,
_set_func = (o, val) => { var newval = ParsingHelper.ParseBooleanNullable(val); if (o.blnSampleTransferred != newval) o.blnSampleTransferred = newval; },
_compare_func = (o, c, m) => {
if (o.blnSampleTransferred != c.blnSampleTransferred || o.IsRIRPropChanged(_str_blnSampleTransferred, c))
m.Add(_str_blnSampleTransferred, o.ObjectIdent + _str_blnSampleTransferred, o.ObjectIdent2 + _str_blnSampleTransferred, o.ObjectIdent3 + _str_blnSampleTransferred, "Boolean?",
o.blnSampleTransferred == null ? "" : o.blnSampleTransferred.ToString(),
o.IsReadOnly(_str_blnSampleTransferred), o.IsInvisible(_str_blnSampleTransferred), o.IsRequired(_str_blnSampleTransferred));
}
},
new field_info {
_name = _str_strFreezer, _formname = _str_strFreezer, _type = "string",
_get_func = o => o.strFreezer,
_set_func = (o, val) => {},
_compare_func = (o, c, m) => {
if (o.strFreezer != c.strFreezer || o.IsRIRPropChanged(_str_strFreezer, c)) {
m.Add(_str_strFreezer, o.ObjectIdent + _str_strFreezer, o.ObjectIdent2 + _str_strFreezer, o.ObjectIdent3 + _str_strFreezer, "string", o.strFreezer == null ? "" : o.strFreezer.ToString(), o.IsReadOnly(_str_strFreezer), o.IsInvisible(_str_strFreezer), o.IsRequired(_str_strFreezer));
}
}
},
new field_info {
_name = _str_strCaseInfo, _formname = _str_strCaseInfo, _type = "string",
_get_func = o => o.strCaseInfo,
_set_func = (o, val) => {},
_compare_func = (o, c, m) => {
if (o.strCaseInfo != c.strCaseInfo || o.IsRIRPropChanged(_str_strCaseInfo, c)) {
m.Add(_str_strCaseInfo, o.ObjectIdent + _str_strCaseInfo, o.ObjectIdent2 + _str_strCaseInfo, o.ObjectIdent3 + _str_strCaseInfo, "string", o.strCaseInfo == null ? "" : o.strCaseInfo.ToString(), o.IsReadOnly(_str_strCaseInfo), o.IsInvisible(_str_strCaseInfo), o.IsRequired(_str_strCaseInfo));
}
}
},
new field_info {
_name = _str_strMonitoringSessionInfo, _formname = _str_strMonitoringSessionInfo, _type = "string",
_get_func = o => o.strMonitoringSessionInfo,
_set_func = (o, val) => {},
_compare_func = (o, c, m) => {
if (o.strMonitoringSessionInfo != c.strMonitoringSessionInfo || o.IsRIRPropChanged(_str_strMonitoringSessionInfo, c)) {
m.Add(_str_strMonitoringSessionInfo, o.ObjectIdent + _str_strMonitoringSessionInfo, o.ObjectIdent2 + _str_strMonitoringSessionInfo, o.ObjectIdent3 + _str_strMonitoringSessionInfo, "string", o.strMonitoringSessionInfo == null ? "" : o.strMonitoringSessionInfo.ToString(), o.IsReadOnly(_str_strMonitoringSessionInfo), o.IsInvisible(_str_strMonitoringSessionInfo), o.IsRequired(_str_strMonitoringSessionInfo));
}
}
},
new field_info {
_name = _str_Department, _formname = _str_Department, _type = "Lookup",
_get_func = o => { if (o.Department == null) return null; return o.Department.idfDepartment; },
_set_func = (o, val) => { o.Department = o.DepartmentLookup.Where(c => c.idfDepartment.ToString() == val).SingleOrDefault(); },
_compare_func = (o, c, m) => {
if (o.idfInDepartment != c.idfInDepartment || o.IsRIRPropChanged(_str_Department, c)) {
m.Add(_str_Department, o.ObjectIdent + _str_Department, o.ObjectIdent2 + _str_Department, o.ObjectIdent3 + _str_Department, "Lookup", o.idfInDepartment == null ? "" : o.idfInDepartment.ToString(), o.IsReadOnly(_str_Department), o.IsInvisible(_str_Department), o.IsRequired(_str_Department));
}
}
},
new field_info {
_name = _str_Department + "Lookup", _formname = _str_Department + "Lookup", _type = "LookupContent",
_get_func = o => o.DepartmentLookup,
_set_func = (o, val) => { },
_compare_func = (o, c, m) => { },
},
new field_info {
_name = _str_Freezer, _formname = _str_Freezer, _type = "Lookup",
_get_func = o => { if (o.Freezer == null) return null; return o.Freezer.ID; },
_set_func = (o, val) => { o.Freezer = o.FreezerLookup.Where(c => c.ID.ToString() == val).SingleOrDefault(); },
_compare_func = (o, c, m) => {
if (o.idfSubdivision != c.idfSubdivision || o.IsRIRPropChanged(_str_Freezer, c)) {
m.Add(_str_Freezer, o.ObjectIdent + _str_Freezer, o.ObjectIdent2 + _str_Freezer, o.ObjectIdent3 + _str_Freezer, "Lookup", o.idfSubdivision == null ? "" : o.idfSubdivision.ToString(), o.IsReadOnly(_str_Freezer), o.IsInvisible(_str_Freezer), o.IsRequired(_str_Freezer));
}
}
},
new field_info {
_name = _str_Freezer + "Lookup", _formname = _str_Freezer + "Lookup", _type = "LookupContent",
_get_func = o => o.FreezerLookup,
_set_func = (o, val) => { },
_compare_func = (o, c, m) => { },
},
new field_info()
};
#endregion
private string _getType(string name)
{
var i = _field_infos.FirstOrDefault(n => n._name == name);
return i == null ? "" : i._type;
}
private object _getValue(string name)
{
var i = _field_infos.FirstOrDefault(n => n._name == name);
return i == null ? null : i._get_func(this);
}
private void _setValue(string name, string val)
{
var i = _field_infos.FirstOrDefault(n => n._name == name);
if (i != null) i._set_func(this, val);
}
internal CompareModel _compare(IObject o, CompareModel ret)
{
if (ret == null) ret = new CompareModel();
if (o == null) return ret;
LabSample obj = (LabSample)o;
foreach (var i in _field_infos)
if (i != null && i._compare_func != null) i._compare_func(this, obj, ret);
return ret;
}
#endregion
[LocalizedDisplayName(_str_Department)]
[Relation(typeof(DepartmentLookup), eidss.model.Schema.DepartmentLookup._str_idfDepartment, _str_idfInDepartment)]
public DepartmentLookup Department
{
get { return _Department == null ? null : ((long)_Department.Key == 0 ? null : _Department); }
set
{
var oldVal = _Department;
_Department = value == null ? null : ((long) value.Key == 0 ? null : value);
if (_Department != oldVal)
{
if (idfInDepartment != (_Department == null
? new Int64?()
: (Int64?)_Department.idfDepartment))
idfInDepartment = _Department == null
? new Int64?()
: (Int64?)_Department.idfDepartment;
OnPropertyChanged(_str_Department);
}
}
}
private DepartmentLookup _Department;
public List<DepartmentLookup> DepartmentLookup
{
get { return _DepartmentLookup; }
}
private List<DepartmentLookup> _DepartmentLookup = new List<DepartmentLookup>();
[LocalizedDisplayName(_str_Freezer)]
[Relation(typeof(FreezerTreeLookup), eidss.model.Schema.FreezerTreeLookup._str_ID, _str_idfSubdivision)]
public FreezerTreeLookup Freezer
{
get { return _Freezer == null ? null : ((long)_Freezer.Key == 0 ? null : _Freezer); }
set
{
var oldVal = _Freezer;
_Freezer = value == null ? null : ((long) value.Key == 0 ? null : value);
if (_Freezer != oldVal)
{
if (idfSubdivision != (_Freezer == null
? new Int64?()
: (Int64?)_Freezer.ID))
idfSubdivision = _Freezer == null
? new Int64?()
: (Int64?)_Freezer.ID;
OnPropertyChanged(_str_Freezer);
}
}
}
private FreezerTreeLookup _Freezer;
public List<FreezerTreeLookup> FreezerLookup
{
get { return _FreezerLookup; }
}
private List<FreezerTreeLookup> _FreezerLookup = new List<FreezerTreeLookup>();
private BvSelectList _getList(string name)
{
switch(name)
{
case _str_Department:
return new BvSelectList(DepartmentLookup, eidss.model.Schema.DepartmentLookup._str_idfDepartment, null, Department, _str_idfInDepartment);
case _str_Freezer:
return new BvSelectList(FreezerLookup, eidss.model.Schema.FreezerTreeLookup._str_ID, null, Freezer, _str_idfSubdivision);
}
return null;
}
[XmlIgnore]
[LocalizedDisplayName(_str_strFreezer)]
public string strFreezer
{
get { return new Func<LabSample, string>(c => c.Freezer == null ? "" : c.Freezer.Path)(this); }
}
[XmlIgnore]
[LocalizedDisplayName(_str_strCaseInfo)]
public string strCaseInfo
{
get { return new Func<LabSample, string>(c => c.strCaseID + ", " + c.DiagnosisName)(this); }
}
[XmlIgnore]
[LocalizedDisplayName(_str_strMonitoringSessionInfo)]
public string strMonitoringSessionInfo
{
get { return new Func<LabSample, string>(c => c.strMonitoringSessionID + ", " + c.SessionDiagnosisName)(this); }
}
protected CacheScope m_CS;
protected Accessor _getAccessor() { return Accessor.Instance(m_CS); }
private IObjectPermissions m_permissions = null;
internal IObjectPermissions _permissions { get { return m_permissions; } set { m_permissions = value; } }
internal string m_ObjectName = "LabSample";
#region Parent and Clone supporting
[XmlIgnore]
public IObject Parent
{
get { return m_Parent; }
set { m_Parent = value; /*OnPropertyChanged(_str_Parent);*/ }
}
private IObject m_Parent;
internal void _setParent()
{
}
partial void Cloned();
partial void ClonedWithSetup();
public override object Clone()
{
var ret = base.Clone() as LabSample;
ret.Cloned();
ret.m_Parent = this.Parent;
ret.m_IsMarkedToDelete = this.m_IsMarkedToDelete;
ret.m_IsForcedToDelete = this.m_IsForcedToDelete;
ret._setParent();
if (this.IsDirty && !ret.IsDirty)
ret.SetChange();
else if (!this.IsDirty && ret.IsDirty)
ret.RejectChanges();
return ret;
}
public IObject CloneWithSetup(DbManagerProxy manager, bool bRestricted = false)
{
var ret = base.Clone() as LabSample;
ret.m_Parent = this.Parent;
ret.m_IsMarkedToDelete = this.m_IsMarkedToDelete;
ret.m_IsForcedToDelete = this.m_IsForcedToDelete;
ret.m_IsNew = this.IsNew;
ret.m_ObjectName = this.m_ObjectName;
Accessor.Instance(null)._SetupLoad(manager, ret, true);
ret.ClonedWithSetup();
ret.DeepAcceptChanges();
ret._setParent();
ret._permissions = _permissions;
return ret;
}
public LabSample CloneWithSetup()
{
using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance))
{
return CloneWithSetup(manager) as LabSample;
}
}
#endregion
#region IObject implementation
public object Key { get { return idfMaterial; } }
public string KeyName { get { return "idfMaterial"; } }
public string ToStringProp { get { return ToString(); } }
private bool m_IsNew;
public bool IsNew { get { return m_IsNew; } }
[XmlIgnore]
[LocalizedDisplayName("HasChanges")]
public bool HasChanges
{
get
{
return IsDirty
;
}
}
public new void RejectChanges()
{
var _prev_idfInDepartment_Department = idfInDepartment;
var _prev_idfSubdivision_Freezer = idfSubdivision;
base.RejectChanges();
if (_prev_idfInDepartment_Department != idfInDepartment)
{
_Department = _DepartmentLookup.FirstOrDefault(c => c.idfDepartment == idfInDepartment);
}
if (_prev_idfSubdivision_Freezer != idfSubdivision)
{
_Freezer = _FreezerLookup.FirstOrDefault(c => c.ID == idfSubdivision);
}
}
public void DeepRejectChanges()
{
RejectChanges();
}
public void DeepAcceptChanges()
{
AcceptChanges();
}
private bool m_bForceDirty;
public override void AcceptChanges()
{
m_bForceDirty = false;
base.AcceptChanges();
}
[XmlIgnore]
[LocalizedDisplayName("IsDirty")]
public override bool IsDirty
{
get { return m_bForceDirty || base.IsDirty; }
}
public void SetChange()
{
m_bForceDirty = true;
}
public void DeepSetChange()
{
SetChange();
}
public bool MarkToDelete() { return _Delete(false); }
public string ObjectName { get { return m_ObjectName; } }
public string ObjectIdent { get { return ObjectName + "_" + Key.ToString() + "_"; } }
public string ObjectIdent2 { get { return ObjectIdent; } }
public string ObjectIdent3 { get { return ObjectIdent; } }
public IObjectAccessor GetAccessor() { return _getAccessor(); }
public IObjectPermissions GetPermissions() { return _permissions; }
private IObjectEnvironment _environment;
public IObjectEnvironment Environment { get { return _environment; } set { _environment = value; } }
public bool ReadOnly { get { return _readOnly; } set { _readOnly = value; } }
public bool IsReadOnly(string name) { return _isReadOnly(name); }
public bool IsInvisible(string name) { return _isInvisible(name); }
public bool IsRequired(string name) { return _isRequired(m_isRequired, name); }
public bool IsHiddenPersonalData(string name) { return _isHiddenPersonalData(name); }
public string GetType(string name) { return _getType(name); }
public object GetValue(string name) { return _getValue(name); }
public void SetValue(string name, string val) { _setValue(name, val); }
public CompareModel Compare(IObject o) { return _compare(o, null); }
public BvSelectList GetList(string name) { return _getList(name); }
public event ValidationEvent Validation;
public event ValidationEvent ValidationEnd;
public event AfterPostEvent AfterPost;
public Dictionary<string, string> GetFieldTags(string name)
{
return null;
}
#endregion
private bool IsRIRPropChanged(string fld, LabSample c)
{
return IsReadOnly(fld) != c.IsReadOnly(fld) || IsInvisible(fld) != c.IsInvisible(fld) || IsRequired(fld) != c._isRequired(m_isRequired, fld);
}
public LabSample()
{
m_permissions = new Permissions(this);
}
partial void Changed(string fieldName);
partial void Created(DbManagerProxy manager);
partial void Loaded(DbManagerProxy manager);
partial void Deleted();
partial void ParsedFormCollection(NameValueCollection form);
private bool m_IsForcedToDelete;
[LocalizedDisplayName("IsForcedToDelete")]
public bool IsForcedToDelete { get { return m_IsForcedToDelete; } }
private bool m_IsMarkedToDelete;
[LocalizedDisplayName("IsMarkedToDelete")]
public bool IsMarkedToDelete { get { return m_IsMarkedToDelete; } }
public void _SetupMainHandler()
{
PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(LabSample_PropertyChanged);
}
public void _RevokeMainHandler()
{
PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(LabSample_PropertyChanged);
}
private void LabSample_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
(sender as LabSample).Changed(e.PropertyName);
if (e.PropertyName == _str_Freezer)
OnPropertyChanged(_str_strFreezer);
if (e.PropertyName == _str_idfSubdivision)
OnPropertyChanged(_str_strFreezer);
if (e.PropertyName == _str_strCaseID)
OnPropertyChanged(_str_strCaseInfo);
if (e.PropertyName == _str_DiagnosisName)
OnPropertyChanged(_str_strCaseInfo);
if (e.PropertyName == _str_strMonitoringSessionID)
OnPropertyChanged(_str_strMonitoringSessionInfo);
if (e.PropertyName == _str_SessionDiagnosisName)
OnPropertyChanged(_str_strMonitoringSessionInfo);
}
public bool ForceToDelete() { return _Delete(true); }
internal bool _Delete(bool isForceDelete)
{
if (!_ValidateOnDelete()) return false;
_DeletingExtenders();
m_IsMarkedToDelete = true;
m_IsForcedToDelete = m_IsForcedToDelete ? m_IsForcedToDelete : isForceDelete;
OnPropertyChanged("IsMarkedToDelete");
_DeletedExtenders();
Deleted();
return true;
}
private bool _ValidateOnDelete(bool bReport = true)
{
return true;
}
private void _DeletingExtenders()
{
LabSample obj = this;
}
private void _DeletedExtenders()
{
LabSample obj = this;
}
public bool OnValidation(ValidationModelException ex)
{
if (Validation != null)
{
var args = new ValidationEventArgs(ex.MessageId, ex.FieldName, ex.PropertyName, ex.Pars, ex.ValidatorType, ex.Obj, ex.ShouldAsk);
Validation(this, args);
return args.Continue;
}
return false;
}
public bool OnValidationEnd(ValidationModelException ex)
{
if (ValidationEnd != null)
{
var args = new ValidationEventArgs(ex.MessageId, ex.FieldName, ex.PropertyName, ex.Pars, ex.ValidatorType, ex.Obj, ex.ShouldAsk);
ValidationEnd(this, args);
return args.Continue;
}
return false;
}
public void OnAfterPost()
{
if (AfterPost != null)
{
AfterPost(this, EventArgs.Empty);
}
}
public FormSize FormSize
{
get { return FormSize.Small; }
}
private bool _isInvisible(string name)
{
return false;
}
private static string[] readonly_names1 = "strNote".Split(new char[] { ',' });
private static string[] readonly_names2 = "Department,idfInDepartment".Split(new char[] { ',' });
private static string[] readonly_names3 = "strFieldCollectedByOffice,strFieldCollectedByPerson".Split(new char[] { ',' });
private static string[] readonly_names4 = "strFreezer,Freezer,idfSubdivision".Split(new char[] { ',' });
private bool _isReadOnly(string name)
{
if (readonly_names1.Where(c => c == name).Count() > 0)
return ReadOnly || new Func<LabSample, bool>(c => false)(this);
if (readonly_names2.Where(c => c == name).Count() > 0)
return ReadOnly || new Func<LabSample, bool>(c => string.IsNullOrEmpty(c.strBarcode))(this);
if (readonly_names3.Where(c => c == name).Count() > 0)
return ReadOnly || new Func<LabSample, bool>(c => true)(this);
if (readonly_names4.Where(c => c == name).Count() > 0)
return ReadOnly || new Func<LabSample, bool>(c => true)(this);
return ReadOnly || new Func<LabSample, bool>(c => true)(this);
}
private bool m_readOnly;
private bool _readOnly
{
get { return m_readOnly; }
set
{
m_readOnly = value;
}
}
internal Dictionary<string, Func<LabSample, bool>> m_isRequired;
private bool _isRequired(Dictionary<string, Func<LabSample, bool>> isRequiredDict, string name)
{
if (isRequiredDict != null && isRequiredDict.ContainsKey(name))
return isRequiredDict[name](this);
return false;
}
public void AddRequired(string name, Func<LabSample, bool> func)
{
if (m_isRequired == null)
m_isRequired = new Dictionary<string, Func<LabSample, bool>>();
if (!m_isRequired.ContainsKey(name))
m_isRequired.Add(name, func);
}
internal Dictionary<string, Func<LabSample, bool>> m_isHiddenPersonalData;
private bool _isHiddenPersonalData(string name)
{
if (m_isHiddenPersonalData != null && m_isHiddenPersonalData.ContainsKey(name))
return m_isHiddenPersonalData[name](this);
return false;
}
public void AddHiddenPersonalData(string name, Func<LabSample, bool> func)
{
if (m_isHiddenPersonalData == null)
m_isHiddenPersonalData = new Dictionary<string, Func<LabSample, bool>>();
if (!m_isHiddenPersonalData.ContainsKey(name))
m_isHiddenPersonalData.Add(name, func);
}
#region IDisposable Members
private bool bIsDisposed;
~LabSample()
{
Dispose();
}
public void Dispose()
{
if (!bIsDisposed)
{
bIsDisposed = true;
LookupManager.RemoveObject("DepartmentLookup", this);
LookupManager.RemoveObject("FreezerTreeLookup", this);
}
}
#endregion
#region ILookupUsage Members
public void ReloadLookupItem(DbManagerProxy manager, string lookup_object)
{
if (lookup_object == "DepartmentLookup")
_getAccessor().LoadLookup_Department(manager, this);
if (lookup_object == "FreezerTreeLookup")
_getAccessor().LoadLookup_Freezer(manager, this);
}
#endregion
public void ParseFormCollection(NameValueCollection form, bool bParseLookups = true, bool bParseRelations = true)
{
if (bParseLookups)
{
_field_infos.Where(i => i._type == "Lookup").ToList().ForEach(a => { if (form[ObjectIdent + a._formname] != null) a._set_func(this, form[ObjectIdent + a._formname]);} );
}
_field_infos.Where(i => i._type != "Lookup" && i._type != "Child" && i._type != "Relation" && i._type != null)
.ToList().ForEach(a => { if (form.AllKeys.Contains(ObjectIdent + a._formname)) a._set_func(this, form[ObjectIdent + a._formname]);} );
if (bParseRelations)
{
}
ParsedFormCollection(form);
}
#region Accessor
public abstract partial class Accessor
: DataAccessor<LabSample>
, IObjectAccessor
, IObjectMeta
, IObjectValidator
, IObjectPermissions
, IObjectCreator
, IObjectCreator<LabSample>
, IObjectSelectDetail
, IObjectSelectDetail<LabSample>
, IObjectPost
, IObjectDelete
{
#region IObjectAccessor
public string KeyName { get { return "idfMaterial"; } }
#endregion
private delegate void on_action(LabSample obj);
private static Accessor g_Instance = CreateInstance<Accessor>();
private CacheScope m_CS;
public static Accessor Instance(CacheScope cs)
{
if (cs == null)
return g_Instance;
lock(cs)
{
object acc = cs.Get(typeof (Accessor));
if (acc != null)
{
return acc as Accessor;
}
Accessor ret = CreateInstance<Accessor>();
ret.m_CS = cs;
cs.Add(typeof(Accessor), ret);
return ret;
}
}
private DepartmentLookup.Accessor DepartmentAccessor { get { return eidss.model.Schema.DepartmentLookup.Accessor.Instance(m_CS); } }
private FreezerTreeLookup.Accessor FreezerAccessor { get { return eidss.model.Schema.FreezerTreeLookup.Accessor.Instance(m_CS); } }
public virtual IObject SelectDetail(DbManagerProxy manager, object ident, int? HACode = null)
{
if (ident == null)
{
return CreateNew(manager, null, HACode);
}
else
{
return _SelectByKey(manager
, (Int64?)ident
, null, null
);
}
}
public virtual LabSample SelectDetailT(DbManagerProxy manager, object ident, int? HACode = null)
{
if (ident == null)
{
return CreateNewT(manager, null, HACode);
}
else
{
return _SelectByKey(manager
, (Int64?)ident
, null, null
);
}
}
public virtual LabSample SelectByKey(DbManagerProxy manager
, Int64? idfMaterial
)
{
return _SelectByKey(manager
, idfMaterial
, null, null
);
}
private LabSample _SelectByKey(DbManagerProxy manager
, Int64? idfMaterial
, on_action loading, on_action loaded
)
{
MapResultSet[] sets = new MapResultSet[1];
List<LabSample> objs = new List<LabSample>();
sets[0] = new MapResultSet(typeof(LabSample), objs);
try
{
manager
.SetSpCommand("spLabSample_SelectDetail"
, manager.Parameter("@idfMaterial", idfMaterial)
, manager.Parameter("@LangID", ModelUserContext.CurrentLanguage)
)
.ExecuteResultSet(sets);
if (objs.Count == 0)
return null;
LabSample obj = objs[0];
obj.m_CS = m_CS;
if (loading != null)
loading(obj);
_SetupLoad(manager, obj);
//obj._setParent();
if (loaded != null)
loaded(obj);
obj.Loaded(manager);
return obj;
}
catch(DataException e)
{
throw DbModelException.Create(e);
}
}
internal void _SetupLoad(DbManagerProxy manager, LabSample obj, bool bCloning = false)
{
if (obj == null) return;
// loading extenters - begin
// loading extenters - end
if (!bCloning)
{
}
_LoadLookups(manager, obj);
obj._setParent();
// loaded extenters - begin
// loaded extenters - end
_SetupHandlers(obj);
_SetupChildHandlers(obj, null);
_SetPermitions(obj._permissions, obj);
_SetupRequired(obj);
_SetupPersonalDataRestrictions(obj);
obj._SetupMainHandler();
obj.AcceptChanges();
}
internal void _SetPermitions(IObjectPermissions permissions, LabSample obj)
{
if (obj != null)
{
obj._permissions = permissions;
if (obj._permissions != null)
{
}
}
}
private LabSample _CreateNew(DbManagerProxy manager, IObject Parent, int? HACode, on_action creating, on_action created, bool isFake = false)
{
try
{
LabSample obj = LabSample.CreateInstance();
obj.m_CS = m_CS;
obj.m_IsNew = true;
obj.Parent = Parent;
if (creating != null)
creating(obj);
// creating extenters - begin
// creating extenters - end
_LoadLookups(manager, obj);
_SetupHandlers(obj);
_SetupChildHandlers(obj, null);
obj._SetupMainHandler();
obj._setParent();
// created extenters - begin
// created extenters - end
if (created != null)
created(obj);
obj.Created(manager);
_SetPermitions(obj._permissions, obj);
_SetupRequired(obj);
_SetupPersonalDataRestrictions(obj);
return obj;
}
catch(DataException e)
{
throw DbModelException.Create(e);
}
}
public LabSample CreateNewT(DbManagerProxy manager, IObject Parent, int? HACode = null)
{
return _CreateNew(manager, Parent, HACode, null, null);
}
public IObject CreateNew(DbManagerProxy manager, IObject Parent, int? HACode = null)
{
return _CreateNew(manager, Parent, HACode, null, null);
}
public LabSample CreateFakeT(DbManagerProxy manager, IObject Parent, int? HACode = null)
{
return _CreateNew(manager, Parent, HACode, null, null, true);
}
public IObject CreateFake(DbManagerProxy manager, IObject Parent, int? HACode = null)
{
return _CreateNew(manager, Parent, HACode, null, null, true);
}
public LabSample CreateWithParamsT(DbManagerProxy manager, IObject Parent, List<object> pars)
{
return _CreateNew(manager, Parent, null, null, null);
}
public IObject CreateWithParams(DbManagerProxy manager, IObject Parent, List<object> pars)
{
return _CreateNew(manager, Parent, null, null, null);
}
private void _SetupChildHandlers(LabSample obj, object newobj)
{
}
private void _SetupHandlers(LabSample obj)
{
}
public void LoadLookup_Department(DbManagerProxy manager, LabSample obj)
{
obj.DepartmentLookup.Clear();
obj.DepartmentLookup.Add(DepartmentAccessor.CreateNewT(manager, null));
obj.DepartmentLookup.AddRange(DepartmentAccessor.SelectLookupList(manager
, new Func<LabSample, long>(c => eidss.model.Core.EidssSiteContext.Instance.OrganizationID)(obj)
, null
)
.Where(c => (c.intRowStatus == 0) || (c.idfDepartment == obj.idfInDepartment))
.ToList());
if (obj.idfInDepartment != null && obj.idfInDepartment != 0)
{
obj.Department = obj.DepartmentLookup
.SingleOrDefault(c => c.idfDepartment == obj.idfInDepartment);
}
LookupManager.AddObject("DepartmentLookup", obj, DepartmentAccessor.GetType(), "SelectLookupList");
}
public void LoadLookup_Freezer(DbManagerProxy manager, LabSample obj)
{
obj.FreezerLookup.Clear();
obj.FreezerLookup.Add(FreezerAccessor.CreateNewT(manager, null));
obj.FreezerLookup.AddRange(FreezerAccessor.SelectLookupList(manager
)
.Where(c => (c.intRowStatus == 0) || (c.ID == obj.idfSubdivision))
.ToList());
if (obj.idfSubdivision != null && obj.idfSubdivision != 0)
{
obj.Freezer = obj.FreezerLookup
.SingleOrDefault(c => c.ID == obj.idfSubdivision);
}
LookupManager.AddObject("FreezerTreeLookup", obj, FreezerAccessor.GetType(), "SelectLookupList");
}
private void _LoadLookups(DbManagerProxy manager, LabSample obj)
{
LoadLookup_Department(manager, obj);
LoadLookup_Freezer(manager, obj);
}
public bool DeleteObject(DbManagerProxy manager, object ident)
{
IObject obj = SelectDetail(manager, ident);
if (!obj.MarkToDelete()) return false;
return Post(manager, obj);
}
[SprocName("spLabSample_Post")]
protected abstract void _post(DbManagerProxy manager,
[Direction.InputOutput()] LabSample obj);
protected void _postPredicate(DbManagerProxy manager,
[Direction.InputOutput()] LabSample obj)
{
_post(manager, obj);
}
public bool Post(DbManagerProxy manager, IObject obj, bool bChildObject = false)
{
bool bTransactionStarted = false;
bool bSuccess;
try
{
LabSample bo = obj as LabSample;
if (!bo.IsNew && bo.IsMarkedToDelete) // delete
{
if (!bo.GetPermissions().CanDelete)
throw new PermissionException("Sample", "Delete");
}
else if (bo.IsNew && !bo.IsMarkedToDelete) // insert
{
if (!bo.GetPermissions().CanInsert)
throw new PermissionException("Sample", "Insert");
}
else if (!bo.IsMarkedToDelete) // update
{
if (!bo.GetPermissions().CanUpdate)
throw new PermissionException("Sample", "Update");
}
long mainObject = bo.idfMaterial;
if (!bo.IsNew && bo.IsMarkedToDelete) // delete
{
}
else if (bo.IsNew && !bo.IsMarkedToDelete) // insert
{
}
else if (!bo.IsMarkedToDelete) // update
{
}
if (!manager.IsTransactionStarted)
{
eidss.model.Enums.AuditEventType auditEventType = eidss.model.Enums.AuditEventType.daeFreeDataUpdate;
if (!bo.IsNew && bo.IsMarkedToDelete) // delete
{
auditEventType = eidss.model.Enums.AuditEventType.daeDelete;
}
else if (bo.IsNew && !bo.IsMarkedToDelete) // insert
{
auditEventType = eidss.model.Enums.AuditEventType.daeCreate;
}
else if (!bo.IsMarkedToDelete) // update
{
auditEventType = eidss.model.Enums.AuditEventType.daeEdit;
}
eidss.model.Enums.EIDSSAuditObject objectType = eidss.model.Enums.EIDSSAuditObject.daoSample;
eidss.model.Enums.AuditTable auditTable = eidss.model.Enums.AuditTable.tlbMaterial;
manager.AuditParams = new object[] { auditEventType, objectType, auditTable, mainObject };
bTransactionStarted = true;
manager.BeginTransaction();
}
bSuccess = _PostNonTransaction(manager, obj as LabSample, bChildObject);
if (bTransactionStarted)
{
if (bSuccess)
{
obj.DeepAcceptChanges();
manager.CommitTransaction();
}
else
{
manager.RollbackTransaction();
}
}
if (bSuccess && bo.IsNew && !bo.IsMarkedToDelete) // insert
{
bo.m_IsNew = false;
}
if (bSuccess && bTransactionStarted)
{
bo.OnAfterPost();
}
}
catch(Exception e)
{
if (bTransactionStarted)
{
manager.RollbackTransaction();
}
if (e is DataException)
{
throw DbModelException.Create(e as DataException);
}
else
throw;
}
return bSuccess;
}
private bool _PostNonTransaction(DbManagerProxy manager, LabSample obj, bool bChildObject)
{
bool bHasChanges = obj.HasChanges;
if (!obj.IsNew && obj.IsMarkedToDelete) // delete
{
if (!ValidateCanDelete(manager, obj)) return false;
}
else if (!obj.IsMarkedToDelete) // insert/update
{
if (!bChildObject)
if (!Validate(manager, obj, true, true, true))
return false;
// posting extenters - begin
// posting extenters - end
if (!obj.IsMarkedToDelete && bHasChanges)
_postPredicate(manager, obj);
// posted extenters - begin
// posted extenters - end
}
//obj.AcceptChanges();
return true;
}
public bool ValidateCanDelete(LabSample obj)
{
using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance))
{
return ValidateCanDelete(manager, obj);
}
}
public bool ValidateCanDelete(DbManagerProxy manager, LabSample obj)
{
return true;
}
protected ValidationModelException ChainsValidate(LabSample obj)
{
return null;
}
protected bool ChainsValidate(LabSample obj, bool bRethrowException)
{
ValidationModelException ex = ChainsValidate(obj);
if (ex != null)
{
if (bRethrowException)
throw ex;
if (!obj.OnValidation(ex))
{
obj.OnValidationEnd(ex);
return false;
}
}
return true;
}
public bool Validate(DbManagerProxy manager, IObject obj, bool bPostValidation, bool bChangeValidation, bool bDeepValidation, bool bRethrowException = false)
{
return Validate(manager, obj as LabSample, bPostValidation, bChangeValidation, bDeepValidation, bRethrowException);
}
public bool Validate(DbManagerProxy manager, LabSample obj, bool bPostValidation, bool bChangeValidation, bool bDeepValidation, bool bRethrowException = false)
{
if (!ChainsValidate(obj, bRethrowException))
return false;
return true;
}
#region IObjectPermissions
public bool CanSelect { get { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo("Sample.Select"); } }
public bool CanUpdate { get { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo("Sample.Update"); } }
public bool CanDelete { get { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo("Sample.Delete"); } }
public bool CanInsert { get { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo("Sample.Insert"); } }
public bool CanExecute(string permission) { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo(permission.Contains(".") ? permission : permission + ".Execute"); }
public bool IsReadOnlyForEdit { get { return !CanUpdate; } }
#endregion
private void _SetupRequired(LabSample obj)
{
}
private void _SetupPersonalDataRestrictions(LabSample obj)
{
if (EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Human_PersonName))
{
obj
.AddHiddenPersonalData("HumanName", c=>true);
}
}
#region IObjectMeta
public int? MaxSize(string name) { return Meta.Sizes.ContainsKey(name) ? (int?)Meta.Sizes[name] : null; }
public bool RequiredByField(string name, IObject obj) { return Meta.RequiredByField.ContainsKey(name) ? Meta.RequiredByField[name](obj as LabSample) : false; }
public bool RequiredByProperty(string name, IObject obj) { return Meta.RequiredByProperty.ContainsKey(name) ? Meta.RequiredByProperty[name](obj as LabSample) : false; }
public List<SearchPanelMetaItem> SearchPanelMeta { get { return Meta.SearchPanelMeta; } }
public List<GridMetaItem> GridMeta { get { return Meta.GridMeta; } }
public List<ActionMetaItem> Actions { get { return Meta.Actions; } }
public string DetailPanel { get { return "LabSampleDetail"; } }
public string HelpIdWin { get { return ""; } }
public string HelpIdWeb { get { return ""; } }
public string HelpIdHh { get { return ""; } }
#endregion
}
#region IObjectPermissions
internal class Permissions : IObjectPermissions
{
private LabSample m_obj;
internal Permissions(LabSample obj)
{
m_obj = obj;
}
public bool CanSelect { get { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo("Sample.Select"); } }
public bool CanUpdate { get { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo("Sample.Update"); } }
public bool CanDelete { get { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo("Sample.Delete"); } }
public bool CanInsert { get { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo("Sample.Insert"); } }
public bool CanExecute(string permission) { return ModelUserContext.Instance == null ? true : ModelUserContext.Instance.CanDo(permission.Contains(".") ? permission : permission + ".Execute"); }
public bool IsReadOnlyForEdit { get { return !(CanUpdate || (CanInsert && m_obj.IsNew)); } }
}
#endregion
#region Meta
public static class Meta
{
public static string spSelect = "spLabSample_SelectDetail";
public static string spCount = "";
public static string spPost = "spLabSample_Post";
public static string spInsert = "";
public static string spUpdate = "";
public static string spDelete = "";
public static string spCanDelete = "";
public static Dictionary<string, int> Sizes = new Dictionary<string, int>();
public static Dictionary<string, Func<LabSample, bool>> RequiredByField = new Dictionary<string, Func<LabSample, bool>>();
public static Dictionary<string, Func<LabSample, bool>> RequiredByProperty = new Dictionary<string, Func<LabSample, bool>>();
public static List<SearchPanelMetaItem> SearchPanelMeta = new List<SearchPanelMetaItem>();
public static List<GridMetaItem> GridMeta = new List<GridMetaItem>();
public static List<ActionMetaItem> Actions = new List<ActionMetaItem>();
private static Dictionary<string, List<Func<bool>>> m_isHiddenPersonalData = new Dictionary<string, List<Func<bool>>>();
internal static bool _isHiddenPersonalData(string name)
{
if (m_isHiddenPersonalData.ContainsKey(name))
return m_isHiddenPersonalData[name].Aggregate(false, (s,c) => s | c());
return false;
}
private static void AddHiddenPersonalData(string name, Func<bool> func)
{
if (!m_isHiddenPersonalData.ContainsKey(name))
m_isHiddenPersonalData.Add(name, new List<Func<bool>>());
m_isHiddenPersonalData[name].Add(func);
}
static Meta()
{
Sizes.Add(_str_strBarcode, 200);
Sizes.Add(_str_strCaseID, 200);
Sizes.Add(_str_strMonitoringSessionID, 50);
Sizes.Add(_str_strSampleName, 2000);
Sizes.Add(_str_SpeciesName, 4000);
Sizes.Add(_str_strAnimalCode, 200);
Sizes.Add(_str_HumanName, 602);
Sizes.Add(_str_DiagnosisName, 2000);
Sizes.Add(_str_SessionDiagnosisName, 500);
Sizes.Add(_str_strFieldCollectedByOffice, 2000);
Sizes.Add(_str_strFieldCollectedByPerson, 602);
Sizes.Add(_str_strNote, 500);
Sizes.Add(_str_strParentBarcode, 200);
Sizes.Add(_str_CaseType, 2000);
Actions.Add(new ActionMetaItem(
"Save",
ActionTypes.Save,
false,
String.Empty,
String.Empty,
(manager, c, pars) => new ActResult(ObjectAccessor.PostInterface<LabSample>().Post(manager, (LabSample)c), c),
null,
new ActionMetaItem.VisualItem(
/*from BvMessages*/"strSave_Id",
"Save",
/*from BvMessages*/"tooltipSave_Id",
/*from BvMessages*/"",
"",
/*from BvMessages*/"tooltipSave_Id",
ActionsAlignment.Right,
ActionsPanelType.Main,
ActionsAppType.All
),
false,
null,
null,
null,
null,
null,
false
));
Actions.Add(new ActionMetaItem(
"Ok",
ActionTypes.Ok,
false,
String.Empty,
String.Empty,
(manager, c, pars) => new ActResult(ObjectAccessor.PostInterface<LabSample>().Post(manager, (LabSample)c), c),
null,
new ActionMetaItem.VisualItem(
/*from BvMessages*/"strOK_Id",
"",
/*from BvMessages*/"tooltipOK_Id",
/*from BvMessages*/"",
"",
/*from BvMessages*/"tooltipOK_Id",
ActionsAlignment.Right,
ActionsPanelType.Main,
ActionsAppType.All
),
false,
null,
null,
null,
null,
null,
false
));
Actions.Add(new ActionMetaItem(
"Cancel",
ActionTypes.Cancel,
false,
String.Empty,
String.Empty,
(manager, c, pars) => new ActResult(true, c),
null,
new ActionMetaItem.VisualItem(
/*from BvMessages*/"strCancel_Id",
"",
/*from BvMessages*/"tooltipCancel_Id",
/*from BvMessages*/"strOK_Id",
"",
/*from BvMessages*/"tooltipCancel_Id",
ActionsAlignment.Right,
ActionsPanelType.Main,
ActionsAppType.All
),
false,
null,
null,
null,
null,
null,
false
));
_SetupPersonalDataRestrictions();
}
private static void _SetupPersonalDataRestrictions()
{
AddHiddenPersonalData("HumanName", () => EidssUserContext.User.ForbiddenPersonalDataGroups.Contains(PersonalDataGroup.Human_PersonName));
}
}
#endregion
#endregion
}
}
| 52.232883 | 426 | 0.555289 | [
"BSD-2-Clause"
] | EIDSS/EIDSS-Legacy | EIDSS v6/eidss.model/Schema/LabSample.model.cs | 108,333 | C# |
using System;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.AspNetCore.Components;
namespace StableCube.Bulzor.Components
{
public class BulNavbarBrand : BulComponentBase
{
[Parameter]
public RenderFragment ChildContent { get; set; }
protected BulmaClassBuilder ClassBuilder { get; set; } = new BulmaClassBuilder("navbar-brand");
protected override void BuildBulma()
{
MergeBuilderClassAttribute(ClassBuilder);
}
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
BuildBulma();
builder.OpenElement(0, "div");
builder.AddMultipleAttributes(1, CombinedAdditionalAttributes);
builder.AddContent(2, ChildContent);
builder.CloseElement();
}
}
} | 30.137931 | 104 | 0.632723 | [
"MIT"
] | StableCube/Bulzor | Components/src/Components/BulNavbarBrand.cs | 876 | C# |
// This file is automatically generated.
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace Steam4NET
{
public enum ESteamNotify : int
{
eSteamNotifyTicketsWillExpire = 0,
eSteamNotifyAccountInfoChanged = 1,
eSteamNotifyContentDescriptionChanged = 2,
eSteamNotifyPleaseShutdown = 3,
eSteamNotifyNewContentServer = 4,
eSteamNotifySubscriptionStatusChanged = 5,
eSteamNotifyContentServerConnectionLost = 6,
eSteamNotifyCacheLoadingCompleted = 7,
eSteamNotifyCacheNeedsDecryption = 8,
eSteamNotifyCacheNeedsRepair = 9,
eSteamNotifyAppDownloading = 10,
eSteamNotifyAppDownloadingPaused = 11,
};
}
| 25.153846 | 46 | 0.802752 | [
"MIT"
] | Benramz/SteamBulkActivator | Steam4NET2/autogen/ESteamNotify.cs | 654 | C# |
namespace Merchello.Providers.Resolvers
{
using System;
using Merchello.Providers.Models;
using Merchello.Providers.Payment.Models;
using Umbraco.Core;
using Umbraco.Core.Logging;
/// <summary>
/// The provider settings resolver.
/// </summary>
internal sealed class ProviderSettingsResolver
{
/// <summary>
/// The current instance of the ProviderSettingsResolver.
/// </summary>
private static ProviderSettingsResolver _instance;
/// <summary>
/// Prevents a default instance of the <see cref="ProviderSettingsResolver"/> class from being created.
/// </summary>
private ProviderSettingsResolver()
{
}
/// <summary>
/// Gets the current instance of the singleton.
/// </summary>
public static ProviderSettingsResolver Current
{
get
{
// ReSharper disable once ConvertIfStatementToNullCoalescingExpression
if (_instance == null)
{
_instance = new ProviderSettingsResolver();
}
return _instance;
}
}
/// <summary>
/// Gets the default settings for a provider.
/// </summary>
/// <param name="provider">
/// The provider.
/// </param>
/// <returns>
/// The <see cref="Attempt"/>.
/// </returns>
public Attempt<IPaymentProviderSettings> ResolveByType(Type provider)
{
var attemptType = ResolveSettingsType(provider);
if (!attemptType.Success) return Attempt<IPaymentProviderSettings>.Fail(); // could not resolve type
// Get the provider settings type result
return this.GetDefaultSettings(attemptType.Result);
}
/// <summary>
/// Gets an instantiated default provider settings.
/// </summary>
/// <param name="settings">
/// The settings.
/// </param>
/// <returns>
/// The <see cref="Attempt{IPaymentProviderSettings}"/>.
/// </returns>
public Attempt<IPaymentProviderSettings> GetDefaultSettings(Type settings)
{
try
{
// attempt to create an instance of the type
var instance = Activator.CreateInstance(settings) as IPaymentProviderSettings;
return instance != null
? Attempt<IPaymentProviderSettings>.Succeed(instance)
: Attempt<IPaymentProviderSettings>.Fail();
}
catch (Exception ex)
{
LogHelper.Error(typeof(ProviderSettingsExtensions), "Could not instantiate settings of type " + settings, ex);
return Attempt<IPaymentProviderSettings>.Fail(ex);
}
}
/// <summary>
/// The resolve settings type.
/// </summary>
/// <param name="provider">
/// The provider.
/// </param>
/// <returns>
/// The <see cref="Attempt"/>.
/// </returns>
private static Attempt<Type> ResolveSettingsType(Type provider)
{
var att = provider.GetCustomAttribute<ProviderSettingsMapperAttribute>(false);
return att != null ?
Attempt<Type>.Succeed(att.SettingsType) :
Attempt<Type>.Fail();
}
}
} | 32.53271 | 126 | 0.549267 | [
"MIT"
] | HiteshMah-Jan/Merchello | src/Merchello.Providers/Resolvers/ProviderSettingsResolver.cs | 3,483 | C# |
namespace Legend.Onenet.Response.Notify
{
public class NotifyResponse
{
public Msg Msg { get; set; }
/// <summary>
/// 消息摘要
/// </summary>
public string Msg_signature { get; set; }
/// <summary>
/// 用于计算消息摘要的随机串
/// </summary>
public string Nonce { get; set; }
/// <summary>
/// 加密密文消息体,对明文JSON串(msg字段)的加密
/// </summary>
public string Enc_msg { get; set; }
}
public class Msg
{
/// <summary>
/// 标识消息类型1:设备上传数据点消息2:设备上下线消息7:缓存命令下发后结果上报(仅支持NB设备)
/// </summary>
public int Type { get; set; }
/// <summary>
/// 设备ID
/// </summary>
public string Dev_id { get; set; }
/// <summary>
/// 数据流名称
/// </summary>
public string Ds_id { get; set; }
/// <summary>
/// 平台时间戳,单位ms
/// </summary>
public long At { get; set; }
/// <summary>
/// 具体数据部分,为设备上传至平台或触发的相关数据
/// </summary>
public dynamic Value { get; set; }
/// <summary>
/// 设备上下线标识0:设备下线1:设备上线
/// </summary>
public int Status { get; set; }
/// <summary>
/// 设备登录协议类型1-EDP, 6-MODBUS, 7-MQTT, 10-NB-IoT
/// </summary>
public string Login_type { get; set; }
/// <summary>
/// 命令响应的类型1:设备收到cmd的ACK响应信息2:设备收到cmd的Confirm响应信息
/// </summary>
public int Cmd_type { get; set; }
/// <summary>
/// 命令ID
/// </summary>
public string Cmd_id { get; set; }
}
}
| 27.271186 | 60 | 0.472343 | [
"MIT"
] | myFirstway/Legend.OneNet | Legend.Onenet/Response/Notify/NotifyResponse.cs | 1,947 | C# |
// Copyright 2008-2009 Louis DeJardin - http://whereslou.com
//
// 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.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using Rhino.Mocks;
using Spark.FileSystem;
using Spark.Parser;
using Spark.Web.Mvc.Descriptors;
namespace Spark.Web.Mvc.Tests
{
[TestFixture]
public class DescriptorBuildingTester
{
private SparkViewFactory _factory;
private InMemoryViewFolder _viewFolder;
private RouteData _routeData;
private ControllerContext _controllerContext;
[SetUp]
public void Init()
{
_factory = new SparkViewFactory();
_viewFolder = new InMemoryViewFolder();
_factory.ViewFolder = _viewFolder;
var httpContext = MockRepository.GenerateStub<HttpContextBase>();
_routeData = new RouteData();
var controller = MockRepository.GenerateStub<ControllerBase>();
_controllerContext = new ControllerContext(httpContext, _routeData, controller);
}
private static void AssertDescriptorTemplates(
SparkViewDescriptor descriptor,
ICollection<string> searchedLocations,
params string[] templates)
{
Assert.AreEqual(templates.Length, descriptor.Templates.Count, "Descriptor template count must match");
for (var index = 0; index != templates.Length; ++index)
Assert.AreEqual(templates[index], descriptor.Templates[index]);
Assert.AreEqual(0, searchedLocations.Count, "searchedLocations must be empty");
}
[Test]
public void NormalViewAndNoDefaultLayout()
{
_routeData.Values.Add("controller", "Home");
_viewFolder.Add(@"Home\Index.spark", "");
var searchedLocations = new List<string>();
var result = _factory.CreateDescriptor(_controllerContext, "Index", null, true, searchedLocations);
AssertDescriptorTemplates(
result, searchedLocations,
@"Home\Index.spark");
}
[Test]
public void NormalViewAndDefaultLayoutPresent()
{
_routeData.Values.Add("controller", "Home");
_viewFolder.Add(@"Home\Index.spark", "");
_viewFolder.Add(@"Layouts\Application.spark", "");
var searchedLocations = new List<string>();
var result = _factory.CreateDescriptor(_controllerContext, "Index", null, true, searchedLocations);
AssertDescriptorTemplates(
result, searchedLocations,
@"Home\Index.spark",
@"Layouts\Application.spark");
}
[Test]
public void NormalViewAndControllerLayoutOverrides()
{
_routeData.Values.Add("controller", "Home");
_viewFolder.Add(@"Home\Index.spark", "");
_viewFolder.Add(@"Layouts\Application.spark", "");
_viewFolder.Add(@"Layouts\Home.spark", "");
var searchedLocations = new List<string>();
var result = _factory.CreateDescriptor(_controllerContext, "Index", null, true, searchedLocations);
AssertDescriptorTemplates(
result, searchedLocations,
@"Home\Index.spark",
@"Layouts\Home.spark");
}
[Test]
public void NormalViewAndNamedMaster()
{
_routeData.Values.Add("controller", "Home");
_viewFolder.Add(@"Home\Index.spark", "");
_viewFolder.Add(@"Layouts\Application.spark", "");
_viewFolder.Add(@"Layouts\Home.spark", "");
_viewFolder.Add(@"Layouts\Site.spark", "");
var searchedLocations = new List<string>();
var result = _factory.CreateDescriptor(_controllerContext, "Index", "Site", true, searchedLocations);
AssertDescriptorTemplates(
result, searchedLocations,
@"Home\Index.spark",
@"Layouts\Site.spark");
}
[Test]
public void PartialViewIgnoresDefaultLayouts()
{
_routeData.Values.Add("controller", "Home");
_viewFolder.Add(@"Home\Index.spark", "");
_viewFolder.Add(@"Layouts\Application.spark", "");
_viewFolder.Add(@"Layouts\Home.spark", "");
_viewFolder.Add(@"Shared\Application.spark", "");
_viewFolder.Add(@"Shared\Home.spark", "");
var searchedLocations = new List<string>();
var result = _factory.CreateDescriptor(_controllerContext, "Index", null, false, searchedLocations);
AssertDescriptorTemplates(
result, searchedLocations,
@"Home\Index.spark");
}
[Test]
public void RouteAreaPresentDefaultsToNormalLocation()
{
_routeData.DataTokens.Add("area", "Admin");
_routeData.Values.Add("controller", "Home");
_viewFolder.Add(@"Home\Index.spark", "");
_viewFolder.Add(@"Layouts\Application.spark", "");
var searchedLocations = new List<string>();
var result = _factory.CreateDescriptor(_controllerContext, "Index", null, true, searchedLocations);
AssertDescriptorTemplates(
result, searchedLocations,
@"Home\Index.spark",
@"Layouts\Application.spark");
}
[Test]
public void AreaFolderMayContainControllerFolder()
{
_routeData.DataTokens.Add("area", "Admin");
_routeData.Values.Add("controller", "Home");
_viewFolder.Add(@"Home\Index.spark", "");
_viewFolder.Add(@"Layouts\Application.spark", "");
_viewFolder.Add(@"Admin\Home\Index.spark", "");
var searchedLocations = new List<string>();
var result = _factory.CreateDescriptor(_controllerContext, "Index", null, true, searchedLocations);
AssertDescriptorTemplates(
result, searchedLocations,
@"Admin\Home\Index.spark",
@"Layouts\Application.spark");
}
[Test]
public void AreaRouteValueAlsoRecognizedForBackCompatWithEarlierAssumptions() {
_routeData.Values.Add("area", "Admin");
_routeData.Values.Add("controller", "Home");
_viewFolder.Add(@"Home\Index.spark", "");
_viewFolder.Add(@"Layouts\Application.spark", "");
_viewFolder.Add(@"Admin\Home\Index.spark", "");
var searchedLocations = new List<string>();
var result = _factory.CreateDescriptor(_controllerContext, "Index", null, true, searchedLocations);
AssertDescriptorTemplates(
result, searchedLocations,
@"Admin\Home\Index.spark",
@"Layouts\Application.spark");
}
[Test]
public void AreaFolderMayContainLayoutsFolder()
{
_routeData.DataTokens.Add("area", "Admin");
_routeData.Values.Add("controller", "Home");
_viewFolder.Add(@"Home\Index.spark", "");
_viewFolder.Add(@"Layouts\Application.spark", "");
_viewFolder.Add(@"Admin\Home\Index.spark", "");
_viewFolder.Add(@"Admin\Layouts\Application.spark", "");
var searchedLocations = new List<string>();
var result = _factory.CreateDescriptor(_controllerContext, "Index", null, true, searchedLocations);
AssertDescriptorTemplates(
result, searchedLocations,
@"Admin\Home\Index.spark",
@"Admin\Layouts\Application.spark");
}
[Test]
public void AreaContainsNamedLayout()
{
_routeData.DataTokens.Add("area", "Admin");
_routeData.Values.Add("controller", "Home");
_viewFolder.Add(@"Home\Index.spark", "");
_viewFolder.Add(@"Layouts\Application.spark", "");
_viewFolder.Add(@"Admin\Home\Index.spark", "");
_viewFolder.Add(@"Admin\Layouts\Application.spark", "");
_viewFolder.Add(@"Admin\Layouts\Site.spark", "");
var searchedLocations = new List<string>();
var result = _factory.CreateDescriptor(_controllerContext, "Index", "Site", true, searchedLocations);
AssertDescriptorTemplates(
result, searchedLocations,
@"Admin\Home\Index.spark",
@"Admin\Layouts\Site.spark");
}
[Test]
public void PartialViewFromAreaIgnoresLayout()
{
_routeData.DataTokens.Add("area", "Admin");
_routeData.Values.Add("controller", "Home");
_viewFolder.Add(@"Home\Index.spark", "");
_viewFolder.Add(@"Admin\Home\Index.spark", "");
_viewFolder.Add(@"Layouts\Home.spark", "");
_viewFolder.Add(@"Layouts\Application.spark", "");
_viewFolder.Add(@"Admin\Layouts\Application.spark", "");
_viewFolder.Add(@"Admin\Layouts\Home.spark", "");
_viewFolder.Add(@"Admin\Layouts\Site.spark", "");
var searchedLocations = new List<string>();
var result = _factory.CreateDescriptor(_controllerContext, "Index", null, false, searchedLocations);
AssertDescriptorTemplates(
result, searchedLocations,
@"Admin\Home\Index.spark");
}
[Test]
public void UseMasterCreatesTemplateChain()
{
_routeData.Values.Add("controller", "Home");
_viewFolder.Add(@"Home\Index.spark", "<use master='Green'/>");
_viewFolder.Add(@"Layouts\Red.spark", "<use master='Blue'/>");
_viewFolder.Add(@"Layouts\Green.spark", "<use master='Red'/>");
_viewFolder.Add(@"Layouts\Blue.spark", "");
_viewFolder.Add(@"Layouts\Application.spark", "");
_viewFolder.Add(@"Layouts\Home.spark", "");
var searchedLocations = new List<string>();
var result = _factory.CreateDescriptor(_controllerContext, "Index", null, true, searchedLocations);
AssertDescriptorTemplates(
result, searchedLocations,
@"Home\Index.spark",
@"Layouts\Green.spark",
@"Layouts\Red.spark",
@"Layouts\Blue.spark");
}
[Test]
public void NamedMasterOverridesViewMaster()
{
_routeData.Values.Add("controller", "Home");
_viewFolder.Add(@"Home\Index.spark", "<use master='Green'/>");
_viewFolder.Add(@"Layouts\Red.spark", "<use master='Blue'/>");
_viewFolder.Add(@"Layouts\Green.spark", "<use master='Red'/>");
_viewFolder.Add(@"Layouts\Blue.spark", "");
_viewFolder.Add(@"Layouts\Application.spark", "");
_viewFolder.Add(@"Layouts\Home.spark", "");
var searchedLocations = new List<string>();
var result = _factory.CreateDescriptor(_controllerContext, "Index", "Red", true, searchedLocations);
AssertDescriptorTemplates(
result, searchedLocations,
@"Home\Index.spark",
@"Layouts\Red.spark",
@"Layouts\Blue.spark");
}
[Test]
public void PartialViewIgnoresUseMasterAndDefault()
{
_routeData.Values.Add("controller", "Home");
_viewFolder.Add(@"Home\Index.spark", "<use master='Green'/>");
_viewFolder.Add(@"Layouts\Red.spark", "<use master='Blue'/>");
_viewFolder.Add(@"Layouts\Green.spark", "<use master='Red'/>");
_viewFolder.Add(@"Layouts\Blue.spark", "");
_viewFolder.Add(@"Layouts\Application.spark", "");
_viewFolder.Add(@"Layouts\Home.spark", "");
var searchedLocations = new List<string>();
var result = _factory.CreateDescriptor(_controllerContext, "Index", null, false, searchedLocations);
AssertDescriptorTemplates(
result, searchedLocations,
@"Home\Index.spark");
}
[Test]
public void BuildDescriptorParamsActsAsKey()
{
var param1 = new BuildDescriptorParams("a", "c", "d", "e", false, null);
var param2 = new BuildDescriptorParams("a", "c", "d", "e", false, null);
var param3 = new BuildDescriptorParams("a", "c", "d", "e", true, null);
var param4 = new BuildDescriptorParams("a", "c2", "d", "e", false, null);
Assert.That(param1, Is.EqualTo(param2));
Assert.That(param1, Is.Not.EqualTo(param3));
Assert.That(param1, Is.Not.EqualTo(param4));
}
[Test]
public void ParamsExtraNullActsAsEmpty()
{
var param1 = new BuildDescriptorParams("a", "c", "d", "e", false, null);
var param2 = new BuildDescriptorParams("a", "c", "d", "e", false, new Dictionary<string, object>());
Assert.That(param1, Is.EqualTo(param2));
}
[Test]
public void ParamsExtraEqualityMustBeIdentical()
{
var param1 = new BuildDescriptorParams("a", "c", "d", "e", false, Dict(new[] { "alpha", "beta" }));
var param2 = new BuildDescriptorParams("a", "c", "d", "e", false, Dict(new[] { "alpha" }));
var param3 = new BuildDescriptorParams("a", "c", "d", "e", false, Dict(new[] { "beta" }));
var param4 = new BuildDescriptorParams("a", "c", "d", "e", false, Dict(new[] { "beta", "alpha" }));
var param5 = new BuildDescriptorParams("a", "c", "d", "e", false, Dict(null));
var param6 = new BuildDescriptorParams("a", "c", "d", "e", false, Dict(new string[0]));
var param7 = new BuildDescriptorParams("a", "c", "d", "e", false, Dict(new[] { "alpha", "beta" }));
Assert.That(param1, Is.Not.EqualTo(param2));
Assert.That(param1, Is.Not.EqualTo(param3));
Assert.That(param1, Is.Not.EqualTo(param4));
Assert.That(param1, Is.Not.EqualTo(param5));
Assert.That(param1, Is.Not.EqualTo(param6));
Assert.That(param1, Is.EqualTo(param7));
}
private static IDictionary<string, object> Dict(IEnumerable<string> values)
{
return values == null
? null
: values
.Select((v, k) => new {k, v})
.ToDictionary(kv => kv.k.ToString(), kv => (object) kv.v);
}
[Test]
public void CustomParameterAddedToViewSearchPath()
{
_factory.DescriptorBuilder = new ExtendingDescriptorBuilderWithInheritance(_factory.Engine);
_routeData.Values.Add("controller", "Home");
_routeData.Values.Add("language", "en-us");
_viewFolder.Add(@"Home\Index.en-us.spark", "");
_viewFolder.Add(@"Home\Index.en.spark", "");
_viewFolder.Add(@"Home\Index.spark", "");
_viewFolder.Add(@"Layouts\Application.en.spark", "");
_viewFolder.Add(@"Layouts\Application.ru.spark", "");
_viewFolder.Add(@"Layouts\Application.spark", "");
var searchedLocations = new List<string>();
var result = _factory.CreateDescriptor(_controllerContext, "Index", null, true, searchedLocations);
AssertDescriptorTemplates(
result, searchedLocations,
@"Home\Index.en-us.spark",
@"Layouts\Application.en.spark");
}
public class ExtendingDescriptorBuilderWithInheritance : DefaultDescriptorBuilder
{
public ExtendingDescriptorBuilderWithInheritance()
{
}
public ExtendingDescriptorBuilderWithInheritance(ISparkViewEngine engine)
: base(engine)
{
}
public override IDictionary<string, object> GetExtraParameters(ControllerContext controllerContext)
{
return new Dictionary<string, object>
{
{"language", Convert.ToString(controllerContext.RouteData.Values["language"])}
};
}
protected override IEnumerable<string> PotentialViewLocations(string controllerName, string viewName, IDictionary<string, object> extra)
{
return Merge(base.PotentialViewLocations(controllerName, viewName, extra), extra["language"].ToString());
}
protected override IEnumerable<string> PotentialMasterLocations(string masterName, IDictionary<string, object> extra)
{
return Merge(base.PotentialMasterLocations(masterName, extra), extra["language"].ToString());
}
protected override IEnumerable<string> PotentialDefaultMasterLocations(string controllerName, IDictionary<string, object> extra)
{
return Merge(base.PotentialDefaultMasterLocations(controllerName, extra), extra["language"].ToString());
}
static IEnumerable<string> Merge(IEnumerable<string> locations, string region)
{
var slashPos = (region ?? "").IndexOf('-');
var language = slashPos == -1 ? null : region.Substring(0, slashPos);
foreach (var location in locations)
{
if (!string.IsNullOrEmpty(region))
{
yield return Path.ChangeExtension(location, region + ".spark");
if (slashPos != -1)
yield return Path.ChangeExtension(location, language + ".spark");
}
yield return location;
}
}
}
[Test, ExpectedException(typeof(InvalidCastException))]
public void CustomDescriptorBuildersCantUseDescriptorFilters()
{
_factory.DescriptorBuilder = MockRepository.GenerateStub<IDescriptorBuilder>();
_factory.AddFilter(MockRepository.GenerateStub<IDescriptorFilter>());
}
[Test]
public void SimplifiedUseMasterGrammarDetectsElementCorrectly()
{
var builder = new DefaultDescriptorBuilder();
var a = builder.ParseUseMaster(new Position(new SourceContext("<use master='a'/>")));
var b = builder.ParseUseMaster(new Position(new SourceContext("<use\r\nmaster \r\n =\r\n'b' />")));
var c = builder.ParseUseMaster(new Position(new SourceContext("<use master=\"c\"/>")));
var def = builder.ParseUseMaster(new Position(new SourceContext(" x <use etc=''/> <use master=\"def\"/> y ")));
var none = builder.ParseUseMaster(new Position(new SourceContext(" x <use etc=''/> <using master=\"def\"/> y ")));
var g = builder.ParseUseMaster(new Position(new SourceContext("-<use master=\"g\"/>-<use master=\"h\"/>-")));
Assert.That(a.Value, Is.EqualTo("a"));
Assert.That(b.Value, Is.EqualTo("b"));
Assert.That(c.Value, Is.EqualTo("c"));
Assert.That(def.Value, Is.EqualTo("def"));
Assert.That(none, Is.Null);
Assert.That(g.Value, Is.EqualTo("g"));
}
}
}
| 44.771739 | 149 | 0.568779 | [
"Apache-2.0"
] | adzerk/spark | src/Spark.Web.Mvc.Tests/DescriptorBuildingTester.cs | 20,595 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Diagnostics.ContractsLight;
using BuildXL.FrontEnd.Script.Evaluator;
using BuildXL.Utilities;
using LineInfo = TypeScript.Net.Utilities.LineInfo;
namespace BuildXL.FrontEnd.Script.Values
{
/// <summary>
/// An array literal associated with a custom merge function defined in DScript.
/// </summary>
public sealed class ArrayLiteralWithCustomMerge : EvaluatedArrayLiteral
{
private readonly EvaluationResult m_customMergeFunction;
/// <summary>
/// Creates array literal from an existing array, adding a custom merge function
/// </summary>
public static ArrayLiteralWithCustomMerge Create(ArrayLiteral arrayLiteral, Closure customMergeClosure, LineInfo location, AbsolutePath path)
{
Contract.Assert(arrayLiteral != null);
Contract.Assert(customMergeClosure != null);
Contract.Assert(path.IsValid);
var data = new EvaluationResult[arrayLiteral.Length];
arrayLiteral.Copy(0, data, 0, arrayLiteral.Length);
return new ArrayLiteralWithCustomMerge(data, customMergeClosure, location, path);
}
/// <nodoc />
internal ArrayLiteralWithCustomMerge(EvaluationResult[] data, Closure customMergeClosure, LineInfo location, AbsolutePath path)
: base(data, location, path)
{
Contract.Requires(customMergeClosure != null);
m_customMergeFunction = EvaluationResult.Create(customMergeClosure);
}
/// <inheritdoc/>
protected override MergeFunction GetDefaultMergeFunction(Context context, EvaluationStackFrame captures)
{
return GetCustomMergeFunctionFromClosure(context, captures, m_customMergeFunction);
}
/// <inheritdoc/>
protected override MergeFunction TryGetCustomMergeFunction(Context context, EvaluationStackFrame captures)
{
return GetCustomMergeFunctionFromClosure(context, captures, m_customMergeFunction);
}
}
}
| 39.4 | 150 | 0.677896 | [
"MIT"
] | BearerPipelineTest/BuildXL | Public/Src/FrontEnd/Script/Ast/Values/ObjectLiterals/ArrayLiteralWithCustomMerge.cs | 2,167 | C# |
using Medidata.MAuth.Core.Exceptions;
using Medidata.MAuth.Core.Models;
namespace Medidata.MAuth.Core
{
internal class MAuthCoreFactory
{
public static IMAuthCore Instantiate(MAuthVersion version = MAuthVersion.MWS)
{
if (version == MAuthVersion.MWSV2)
return new MAuthCoreV2();
else if (version == MAuthVersion.MWS)
return new MAuthCore();
throw new InvalidVersionException($"Version is not recognized:{version}");
}
}
}
| 27.842105 | 86 | 0.63138 | [
"MIT"
] | eraffel-MDSol/mauth-client-dotnet | src/Medidata.MAuth.Core/MAuthCoreFactory.cs | 531 | C# |
//-----------------------------------------------------------------------
// <copyright file="TypeExtensionsTests.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.Linq;
using Akka.TestKit;
using Akka.Util.Internal;
using FluentAssertions;
using Xunit;
namespace Akka.Tests.Util.Internal
{
public class ExtensionsTests
{
[Fact]
public void TestBetweenDoubleQuotes()
{
"akka.net".BetweenDoubleQuotes().ShouldBe("\"akka.net\"");
"\"".BetweenDoubleQuotes().ShouldBe("\"\"\"");
"".BetweenDoubleQuotes().ShouldBe("\"\"");
((string)null).BetweenDoubleQuotes().ShouldBe("\"\"");
}
[Fact]
public void TestAlternateSelectMany()
{
var input = new[] { 0, 0, 1, 1, 2, 2, 1 };
var actual = input.AlternateSelectMany(count => Enumerable.Repeat("even", count),
count => Enumerable.Repeat("odd", count)).ToArray();
var expectation = new[] {"even", "odd", "even", "even", "odd", "odd", "even"};
actual.ShouldAllBeEquivalentTo(expectation);
}
[Fact]
public void TestSplitDottedPathHonouringQuotesHandlesLongPathWithOneQuotedPartWithDot()
{
var path = @"akka.actor.deployment.""/a/dotted.path/*"".dispatcher";
var actual = path.SplitDottedPathHonouringQuotes().ToArray();
var expectation = new[] {"akka", "actor", "deployment", "/a/dotted.path/*", "dispatcher"};
actual.ShouldAllBeEquivalentTo(expectation);
}
[Fact]
public void TestSplitDottedPathHonouringQuotesHandlesSingleItem()
{
var path = @"akka";
var actual = path.SplitDottedPathHonouringQuotes().ToArray();
var expectation = new[] { "akka" };
actual.ShouldAllBeEquivalentTo(expectation);
}
[Fact]
public void TestSplitDottedPathHonouringQuotesHandlesClassicPath()
{
var path = @"akka.dot.net.rules";
var actual = path.SplitDottedPathHonouringQuotes().ToArray();
var expectation = new[] { "akka", "dot", "net", "rules" };
actual.ShouldAllBeEquivalentTo(expectation);
}
[Fact]
public void TestSplitDottedPathHonouringQuotesHandlesSingleQuotedItem()
{
var path = @"""akka""";
var actual = path.SplitDottedPathHonouringQuotes().ToArray();
var expectation = new[] { "akka" };
actual.ShouldAllBeEquivalentTo(expectation);
}
[Fact]
public void TestSplitDottedPathHonouringQuotesHandlesSingleQuotedItemWithDot()
{
var path = @"""ak.ka""";
var actual = path.SplitDottedPathHonouringQuotes().ToArray();
var expectation = new[] { "ak.ka" };
actual.ShouldAllBeEquivalentTo(expectation);
}
[Fact]
public void TestSplitDottedPathHonouringQuotesHandlesLongPathWithTwoQuotedParts()
{
var path = @"akka.actor.deployment.""/a/dotted.path/*"".""dispatcher""";
var actual = path.SplitDottedPathHonouringQuotes().ToArray();
var expectation = new[] { "akka", "actor", "deployment", "/a/dotted.path/*", "dispatcher" };
actual.ShouldAllBeEquivalentTo(expectation);
}
}
}
| 38.860215 | 104 | 0.571666 | [
"Apache-2.0"
] | uQr/akka.net | src/core/Akka.Tests/Util/Internal/ExtensionsTests.cs | 3,616 | 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("Programming-Language-Feature")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Programming-Language-Feature")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[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("cf2b1923-de30-4eef-a875-97fd2c4f47c6")]
// 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.486486 | 84 | 0.750702 | [
"MIT"
] | aamirWasi/Programming-Language-Feature | Programming-Language-Feature/Programming-Language-Feature/Properties/AssemblyInfo.cs | 1,427 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Backports;
using NUnit.Framework;
namespace Tests
{
public class FloatingPointDataProvider
{
public static IEnumerable<string> DataFilesPaths
{
get
{
var root = Environment.GetEnvironmentVariable(@"PARSE_NUMBER_FXX_TEST_DATA_ROOT");
if (root is null)
{
throw new Exception("`PARSE_NUMBER_FXX_TEST_DATA_ROOT` environment variable is not set.");
}
if (!Directory.Exists(root))
{
throw new Exception("Test data root folder not found.");
}
var data = Path.GetFullPath(Path.Combine(root, "data"));
return Directory.EnumerateFiles(data, "*txt");
}
}
public static IEnumerable<FPDataSetProvider> DataSetProviders =>
DataFilesPaths
.Select(x => new FPDataSetProvider(x));
}
[TestFixture]
// ReSharper disable once InconsistentNaming
public class FPDataTests
{
[Test]
[Parallelizable(ParallelScope.All)]
[TestCaseSource(typeof(FloatingPointDataProvider), nameof(FloatingPointDataProvider.DataSetProviders))]
public async Task Test_FloatingPointParsing(FPDataSetProvider provider)
{
await foreach (var item in provider.ReadTestDataAsync())
{
#if !NET40_OR_GREATER
// Disabled for .NET Core-based runtimes
if(string.Equals(
item.StrRep,
"6250000000000000000000000000000000e-12",
StringComparison.Ordinal
)
)
{
// Avoid rare parsing issue
// https://github.com/dotnet/runtime/issues/48648
// https://github.com/pgovind/runtime/commit/9897a27aaace156628735acdcb06938e3a24ce15
continue;
}
#endif
Assert.IsTrue(
item.StrRep.AsSpan().TryParse(
NumberStyles.Any, NumberFormatInfo.InvariantInfo, out float single
),
$"Cant parse single from `{item.StrRep}`"
);
Assert.IsTrue(
item.StrRep.AsSpan().TryParse(
NumberStyles.Any, NumberFormatInfo.InvariantInfo, out double @double
),
$"Cant parse double from `{item.StrRep}`"
);
var doubleBytes = BitConverter.GetBytes(@double);
var singleBytes = BitConverter.GetBytes(single);
CollectionAssert.AreEqual(
item.DoubleBytes,
doubleBytes,
$"Failed double comparison for `{item.StrRep}`"
);
CollectionAssert.AreEqual(
item.SingleBytes,
singleBytes,
$"Failed single comparison for `{item.StrRep}`"
);
}
}
}
}
| 34.87234 | 111 | 0.526846 | [
"MIT"
] | Ilia-Kosenkov/Backports | Tests/FPDataTests.cs | 3,280 | C# |
using System;
using Elasticsearch.Net;
using FluentAssertions;
using Nest;
using Tests.Framework;
using Tests.Framework.Integration;
using Tests.Framework.MockData;
using Xunit;
namespace Tests.Search.Percolator.UnregisterPercolator
{
[Collection(IntegrationContext.Indexing)]
public class UnregisterPercolatorApiTests : ApiIntegrationTestBase<IUnregisterPercolateResponse, IUnregisterPercolatorRequest, UnregisterPercolatorDescriptor<Project>, UnregisterPercolatorRequest>
{
public UnregisterPercolatorApiTests(IndexingCluster cluster, EndpointUsage usage) : base(cluster, usage)
{
}
protected override void OnBeforeCall(IElasticClient client)
{
var createIndex = this.Client.CreateIndex(this.CallIsolatedValue + "-index");
if (!createIndex.IsValid)
throw new Exception($"Setup: failed to first register percolator {this.CallIsolatedValue}");
var register = this.Client.RegisterPercolator<Project>(this.CallIsolatedValue, r => r.Query(q => q.MatchAll()).Index(this.CallIsolatedValue + "-index"));
if (!register.IsValid)
throw new Exception($"Setup: failed to first register percolator {this.CallIsolatedValue}");
}
protected override LazyResponses ClientUsage() => Calls(
fluent: (c, f) => c.UnregisterPercolator<Project>(this.CallIsolatedValue, f),
fluentAsync: (c, f) => c.UnregisterPercolatorAsync<Project>(this.CallIsolatedValue, f),
request: (c, r) => c.UnregisterPercolator(r),
requestAsync: (c, r) => c.UnregisterPercolatorAsync(r)
);
protected override int ExpectStatusCode => 200;
protected override bool ExpectIsValid => true;
protected override HttpMethod HttpMethod => HttpMethod.DELETE;
protected override string UrlPath => $"/{this.CallIsolatedValue}-index/.percolator/{this.CallIsolatedValue}";
protected override void ExpectResponse(IUnregisterPercolateResponse response)
{
response.Found.Should().BeTrue();
response.Index.Should().NotBeNullOrEmpty();
response.Type.Should().NotBeNullOrEmpty();
response.Version.Should().BeGreaterThan(0);
response.Id.Should().NotBeNullOrEmpty();
}
protected override UnregisterPercolatorDescriptor<Project> NewDescriptor() => new UnregisterPercolatorDescriptor<Project>(this.CallIsolatedValue);
protected override Func<UnregisterPercolatorDescriptor<Project>, IUnregisterPercolatorRequest> Fluent => d=> d.Index(this.CallIsolatedValue + "-index");
protected override UnregisterPercolatorRequest Initializer => new UnregisterPercolatorRequest(this.CallIsolatedValue + "-index", this.CallIsolatedValue);
}
}
| 44.12069 | 197 | 0.780383 | [
"Apache-2.0"
] | lukapor/NEST | src/Tests/Search/Percolator/UnregisterPercolator/UnregisterPercolatorApiTests.cs | 2,561 | C# |
namespace lib.Tests
{
using System.Diagnostics.CodeAnalysis;
[ExcludeFromCodeCoverage]
public class ClassTwo
{
public int Id { get; set; }
}
} | 17.2 | 42 | 0.639535 | [
"MIT"
] | zaiboot/OpenCover-Automapper | test/ClassTwo.cs | 174 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using MyJobSite.Data.Models;
namespace MyJobSite.Web.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class ExternalLoginModel : PageModel
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly UserManager<ApplicationUser> _userManager;
private readonly IEmailSender _emailSender;
private readonly ILogger<ExternalLoginModel> _logger;
public ExternalLoginModel(
SignInManager<ApplicationUser> signInManager,
UserManager<ApplicationUser> userManager,
ILogger<ExternalLoginModel> logger,
IEmailSender emailSender)
{
_signInManager = signInManager;
_userManager = userManager;
_logger = logger;
_emailSender = emailSender;
}
[BindProperty]
public InputModel Input { get; set; }
public string ProviderDisplayName { get; set; }
public string ReturnUrl { get; set; }
[TempData]
public string ErrorMessage { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
}
public IActionResult OnGetAsync()
{
return RedirectToPage("./Login");
}
public IActionResult OnPost(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Page("./ExternalLogin", pageHandler: "Callback", values: new { returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return new ChallengeResult(provider, properties);
}
public async Task<IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (remoteError != null)
{
ErrorMessage = $"Error from external provider: {remoteError}";
return RedirectToPage("./Login", new {ReturnUrl = returnUrl });
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
ErrorMessage = "Error loading external login information.";
return RedirectToPage("./Login", new { ReturnUrl = returnUrl });
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor : true);
if (result.Succeeded)
{
_logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider);
return LocalRedirect(returnUrl);
}
if (result.IsLockedOut)
{
return RedirectToPage("./Lockout");
}
else
{
// If the user does not have an account, then ask the user to create an account.
ReturnUrl = returnUrl;
ProviderDisplayName = info.ProviderDisplayName;
if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email))
{
Input = new InputModel
{
Email = info.Principal.FindFirstValue(ClaimTypes.Email)
};
}
return Page();
}
}
public async Task<IActionResult> OnPostConfirmationAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
ErrorMessage = "Error loading external login information during confirmation.";
return RedirectToPage("./Login", new { ReturnUrl = returnUrl });
}
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
_logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
var userId = await _userManager.GetUserIdAsync(user);
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = userId, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
// If account confirmation is required, we need to show the link if we don't have a real email sender
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
return RedirectToPage("./RegisterConfirmation", new { Email = Input.Email });
}
await _signInManager.SignInAsync(user, isPersistent: false, info.LoginProvider);
return LocalRedirect(returnUrl);
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
ProviderDisplayName = info.ProviderDisplayName;
ReturnUrl = returnUrl;
return Page();
}
}
}
| 40.717647 | 154 | 0.576856 | [
"MIT"
] | AndreaDenikova/csharp-jobsite-repository | Web/MyJobSite.Web/Areas/Identity/Pages/Account/ExternalLogin.cshtml.cs | 6,924 | C# |
using KnowledgeApi.Models;
using KnowledgeApi.Services;
using Microsoft.AspNetCore.Mvc;
namespace KnowledgeApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ArtTypeController : BaseMongoController<ArtType>
{
public ArtTypeController(ArtTypeRepository artTypeRepository): base(artTypeRepository)
{
}
}
}
| 22.823529 | 95 | 0.695876 | [
"Apache-2.0"
] | onselaydin/KnowledgeApi | Controllers/ArtTypeController.cs | 390 | C# |
using Hotel.Core.Interfaces;
using Hotel.Core.Models;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Collections.Generic;
namespace Hotel.Web.Pages;
public class RoomReservationsModel : PageModel
{
private readonly IRoomReservationRepository _roomReservationRepository;
public RoomReservationsModel(IRoomReservationRepository roomReservationRepository)
{
_roomReservationRepository = roomReservationRepository;
}
public IEnumerable<RoomReservationDto> RoomReservations { get; set; }
public void OnGet()
{
RoomReservations = _roomReservationRepository.GetAll();
}
}
| 26.166667 | 86 | 0.778662 | [
"MIT"
] | mohammad-niazmand/TDD-Course-HotelReservation | Hotel.Web/Pages/RoomReservations.cshtml.cs | 630 | C# |
/**
* Autogenerated by Thrift Compiler (0.11.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Thrift;
using Thrift.Collections;
using System.Runtime.Serialization;
using Thrift.Protocol;
using Thrift.Transport;
namespace STB_Modeling_Techniques.DEISProject.ODEDataModel.ThriftContract
{
#if !SILVERLIGHT
[Serializable]
#endif
public partial class TDDIOutputEvent : TBase
{
private long _Id;
private string _Name;
private string _Description;
private bool _IsCitation;
private bool _IsAbstract;
private List<TDDIKeyValueMapRef> _KeyValueMaps;
private TDDIAbstractBaseElement _CitedElement;
private TDDIOutputFailure _OutputFailure;
public long Id
{
get
{
return _Id;
}
set
{
__isset.Id = true;
this._Id = value;
}
}
public string Name
{
get
{
return _Name;
}
set
{
__isset.Name = true;
this._Name = value;
}
}
public string Description
{
get
{
return _Description;
}
set
{
__isset.Description = true;
this._Description = value;
}
}
public bool IsCitation
{
get
{
return _IsCitation;
}
set
{
__isset.IsCitation = true;
this._IsCitation = value;
}
}
public bool IsAbstract
{
get
{
return _IsAbstract;
}
set
{
__isset.IsAbstract = true;
this._IsAbstract = value;
}
}
public List<TDDIKeyValueMapRef> KeyValueMaps
{
get
{
return _KeyValueMaps;
}
set
{
__isset.KeyValueMaps = true;
this._KeyValueMaps = value;
}
}
public TDDIAbstractBaseElement CitedElement
{
get
{
return _CitedElement;
}
set
{
__isset.CitedElement = true;
this._CitedElement = value;
}
}
public TDDIOutputFailure OutputFailure
{
get
{
return _OutputFailure;
}
set
{
__isset.OutputFailure = true;
this._OutputFailure = value;
}
}
public Isset __isset;
#if !SILVERLIGHT
[Serializable]
#endif
public struct Isset {
public bool Id;
public bool Name;
public bool Description;
public bool IsCitation;
public bool IsAbstract;
public bool KeyValueMaps;
public bool CitedElement;
public bool OutputFailure;
}
public TDDIOutputEvent() {
this._Name = "";
this.__isset.Name = true;
this._Description = "";
this.__isset.Description = true;
this._IsCitation = false;
this.__isset.IsCitation = true;
this._IsAbstract = false;
this.__isset.IsAbstract = true;
this._KeyValueMaps = new List<TDDIKeyValueMapRef>();
this.__isset.KeyValueMaps = true;
}
public void Read (TProtocol iprot)
{
iprot.IncrementRecursionDepth();
try
{
TField field;
iprot.ReadStructBegin();
while (true)
{
field = iprot.ReadFieldBegin();
if (field.Type == TType.Stop) {
break;
}
switch (field.ID)
{
case 1:
if (field.Type == TType.I64) {
Id = iprot.ReadI64();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 2:
if (field.Type == TType.String) {
Name = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 3:
if (field.Type == TType.String) {
Description = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 4:
if (field.Type == TType.Bool) {
IsCitation = iprot.ReadBool();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 5:
if (field.Type == TType.Bool) {
IsAbstract = iprot.ReadBool();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 6:
if (field.Type == TType.List) {
{
KeyValueMaps = new List<TDDIKeyValueMapRef>();
TList _list584 = iprot.ReadListBegin();
for( int _i585 = 0; _i585 < _list584.Count; ++_i585)
{
TDDIKeyValueMapRef _elem586;
_elem586 = new TDDIKeyValueMapRef();
_elem586.Read(iprot);
KeyValueMaps.Add(_elem586);
}
iprot.ReadListEnd();
}
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 7:
if (field.Type == TType.Struct) {
CitedElement = new TDDIAbstractBaseElement();
CitedElement.Read(iprot);
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 8:
if (field.Type == TType.Struct) {
OutputFailure = new TDDIOutputFailure();
OutputFailure.Read(iprot);
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
default:
TProtocolUtil.Skip(iprot, field.Type);
break;
}
iprot.ReadFieldEnd();
}
iprot.ReadStructEnd();
}
finally
{
iprot.DecrementRecursionDepth();
}
}
public void Write(TProtocol oprot) {
oprot.IncrementRecursionDepth();
try
{
TStruct struc = new TStruct("TDDIOutputEvent");
oprot.WriteStructBegin(struc);
TField field = new TField();
if (__isset.Id) {
field.Name = "Id";
field.Type = TType.I64;
field.ID = 1;
oprot.WriteFieldBegin(field);
oprot.WriteI64(Id);
oprot.WriteFieldEnd();
}
if (Name != null && __isset.Name) {
field.Name = "Name";
field.Type = TType.String;
field.ID = 2;
oprot.WriteFieldBegin(field);
oprot.WriteString(Name);
oprot.WriteFieldEnd();
}
if (Description != null && __isset.Description) {
field.Name = "Description";
field.Type = TType.String;
field.ID = 3;
oprot.WriteFieldBegin(field);
oprot.WriteString(Description);
oprot.WriteFieldEnd();
}
if (__isset.IsCitation) {
field.Name = "IsCitation";
field.Type = TType.Bool;
field.ID = 4;
oprot.WriteFieldBegin(field);
oprot.WriteBool(IsCitation);
oprot.WriteFieldEnd();
}
if (__isset.IsAbstract) {
field.Name = "IsAbstract";
field.Type = TType.Bool;
field.ID = 5;
oprot.WriteFieldBegin(field);
oprot.WriteBool(IsAbstract);
oprot.WriteFieldEnd();
}
if (KeyValueMaps != null && __isset.KeyValueMaps) {
field.Name = "KeyValueMaps";
field.Type = TType.List;
field.ID = 6;
oprot.WriteFieldBegin(field);
{
oprot.WriteListBegin(new TList(TType.Struct, KeyValueMaps.Count));
foreach (TDDIKeyValueMapRef _iter587 in KeyValueMaps)
{
_iter587.Write(oprot);
}
oprot.WriteListEnd();
}
oprot.WriteFieldEnd();
}
if (CitedElement != null && __isset.CitedElement) {
field.Name = "CitedElement";
field.Type = TType.Struct;
field.ID = 7;
oprot.WriteFieldBegin(field);
CitedElement.Write(oprot);
oprot.WriteFieldEnd();
}
if (OutputFailure != null && __isset.OutputFailure) {
field.Name = "OutputFailure";
field.Type = TType.Struct;
field.ID = 8;
oprot.WriteFieldBegin(field);
OutputFailure.Write(oprot);
oprot.WriteFieldEnd();
}
oprot.WriteFieldStop();
oprot.WriteStructEnd();
}
finally
{
oprot.DecrementRecursionDepth();
}
}
public override string ToString() {
StringBuilder __sb = new StringBuilder("TDDIOutputEvent(");
bool __first = true;
if (__isset.Id) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Id: ");
__sb.Append(Id);
}
if (Name != null && __isset.Name) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Name: ");
__sb.Append(Name);
}
if (Description != null && __isset.Description) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Description: ");
__sb.Append(Description);
}
if (__isset.IsCitation) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("IsCitation: ");
__sb.Append(IsCitation);
}
if (__isset.IsAbstract) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("IsAbstract: ");
__sb.Append(IsAbstract);
}
if (KeyValueMaps != null && __isset.KeyValueMaps) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("KeyValueMaps: ");
__sb.Append(KeyValueMaps);
}
if (CitedElement != null && __isset.CitedElement) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("CitedElement: ");
__sb.Append(CitedElement== null ? "<null>" : CitedElement.ToString());
}
if (OutputFailure != null && __isset.OutputFailure) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("OutputFailure: ");
__sb.Append(OutputFailure== null ? "<null>" : OutputFailure.ToString());
}
__sb.Append(")");
return __sb.ToString();
}
}
}
| 25.961071 | 80 | 0.509185 | [
"MIT"
] | DEIS-Project-EU/DDI-Scripting-Tools | ODE_Tooladapter/ThriftContract/ODEThriftContract/gen_Thrift_ODE/csharp/STB_Modeling_Techniques/DEISProject/ODEDataModel/ThriftContract/TDDIOutputEvent.cs | 10,670 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: EnumType.cs.tt
namespace Microsoft.Graph
{
using System.Text.Json.Serialization;
/// <summary>
/// The enum RequiredPasswordType.
/// </summary>
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum RequiredPasswordType
{
/// <summary>
/// Device Default
/// </summary>
DeviceDefault = 0,
/// <summary>
/// Alphanumeric
/// </summary>
Alphanumeric = 1,
/// <summary>
/// Numeric
/// </summary>
Numeric = 2,
}
}
| 25.74359 | 153 | 0.49502 | [
"MIT"
] | Aliases/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/model/RequiredPasswordType.cs | 1,004 | C# |
using NHibernate;
using NHibernate.Transform;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Gako.Data.EntityBinder.NHibernateUtilities
{
/// <summary>
/// </summary>
public static partial class NhibernateUtility
{
/// <summary>
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="query"></param>
/// <returns></returns>
public static IList<TEntity> EntityList<TEntity>(this IQuery query) where TEntity : new()
{
query.SetResultTransformer(new EntityTransformer<TEntity>());
var result = query.List<TEntity>();
return result;
}
/// <summary>
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="query"></param>
/// <returns></returns>
public static IList<TEntity> EntityList<TEntity>(this IQuery query, Func<TEntity> entityCreateor)
{
query.SetResultTransformer(new EntityTransformer<TEntity>(entityCreateor));
var result = query.List<TEntity>();
return result;
}
/// <summary>
///
/// </summary>
/// <param name="query"></param>
/// <param name="name"></param>
/// <param name="val"></param>
/// <returns></returns>
public static IQuery SetNullableBoolean(this IQuery query, string name, bool? val) => query.SetParameter(name, val);
/// <summary>
///
/// </summary>
/// <param name="query"></param>
/// <param name="name"></param>
/// <param name="val"></param>
/// <returns></returns>
public static IQuery SetNullableDateTime(this IQuery query, string name, DateTime? val) => query.SetParameter(name, val);
/// <summary>
///
/// </summary>
/// <param name="query"></param>
/// <param name="name"></param>
/// <param name="val"></param>
/// <returns></returns>
public static IQuery SetNullableDecimal(this IQuery query, string name, decimal? val) => query.SetParameter(name, val);
/// <summary>
///
/// </summary>
/// <param name="query"></param>
/// <param name="name"></param>
/// <param name="val"></param>
/// <returns></returns>
public static IQuery SetNullableDouble(this IQuery query, string name, double? val) => query.SetParameter(name, val);
/// <summary>
///
/// </summary>
/// <param name="query"></param>
/// <param name="name"></param>
/// <param name="val"></param>
/// <returns></returns>
public static IQuery SetNullableEnum<T>(this IQuery query, string name, T? val) where T : struct, Enum => query.SetParameter(name, val);
/// <summary>
///
/// </summary>
/// <param name="query"></param>
/// <param name="name"></param>
/// <param name="val"></param>
/// <returns></returns>
public static IQuery SetNullableInt16(this IQuery query, string name, short? val) => query.SetParameter(name, val);
/// <summary>
///
/// </summary>
/// <param name="query"></param>
/// <param name="name"></param>
/// <param name="val"></param>
/// <returns></returns>
public static IQuery SetNullableInt32(this IQuery query, string name, int? val) => query.SetParameter(name, val);
/// <summary>
///
/// </summary>
/// <param name="query"></param>
/// <param name="name"></param>
/// <param name="val"></param>
/// <returns></returns>
public static IQuery SetNullableInt64(this IQuery query, string name, long? val) => query.SetParameter(name, val);
/// <summary>
///
/// </summary>
/// <param name="query"></param>
/// <param name="name"></param>
/// <param name="val"></param>
/// <returns></returns>
public static IQuery SetNullableSingle(this IQuery query, string name, float? val) => query.SetParameter(name, val);
}
}
| 34.34375 | 145 | 0.52616 | [
"MIT"
] | gako4u/EnitityBinder | src/Gako.Data.EntityBinder.NHibernateUtilities/NhibernateUtility.cs | 4,398 | C# |
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.SystemConsole.Themes;
namespace Krola.Authorization.IdentityServer
{
public class Program
{
public static void Main(string[] args)
{
//var seed = args.Any(x => x == "/seed");
//if (seed) args = args.Except(new[] { "/seed" }).ToArray();
var host = CreateWebHostBuilder(args).Build();
//if (seed)
//{
using (var scope = host.Services.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
SeedData.EnsureSeedData(scope.ServiceProvider);
//return;
}
//}
host
.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls("http://0.0.0.0:5000")
.UseSerilog((context, configuration) =>
{
configuration
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("System", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.File(@"identityserver4_log.txt")
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Literate);
});
}
}
}
| 37.607843 | 195 | 0.532847 | [
"MIT"
] | krola/krola | src/Services/Authorization.IdentityServer/Program.cs | 1,920 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class countRealNumbers
{
static void Main(string[] args)
{
var numbers = Console.ReadLine()
.Split(' ')
.Select(double.Parse);
var result = new SortedDictionary<double, int>();
foreach (var num in numbers)
{
if (!result.ContainsKey(num))
{
result[num] = 0;
}
result[num]++;
}
foreach (var item in result)
{
Console.WriteLine($"{item.Key} -> {item.Value}");
}
}
}
| 17.736842 | 61 | 0.505935 | [
"MIT"
] | mlkumanova/Programming-Fundamentals | 5. DICTIONARIES, LAMBDA AND LINQ/01. Count Real Numbers/countRealNumbers.cs | 676 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v8/enums/google_ads_field_category.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Ads.GoogleAds.V8.Enums {
/// <summary>Holder for reflection information generated from google/ads/googleads/v8/enums/google_ads_field_category.proto</summary>
public static partial class GoogleAdsFieldCategoryReflection {
#region Descriptor
/// <summary>File descriptor for google/ads/googleads/v8/enums/google_ads_field_category.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static GoogleAdsFieldCategoryReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cj1nb29nbGUvYWRzL2dvb2dsZWFkcy92OC9lbnVtcy9nb29nbGVfYWRzX2Zp",
"ZWxkX2NhdGVnb3J5LnByb3RvEh1nb29nbGUuYWRzLmdvb2dsZWFkcy52OC5l",
"bnVtcxocZ29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90byKKAQoaR29vZ2xl",
"QWRzRmllbGRDYXRlZ29yeUVudW0ibAoWR29vZ2xlQWRzRmllbGRDYXRlZ29y",
"eRIPCgtVTlNQRUNJRklFRBAAEgsKB1VOS05PV04QARIMCghSRVNPVVJDRRAC",
"Eg0KCUFUVFJJQlVURRADEgsKB1NFR01FTlQQBRIKCgZNRVRSSUMQBkLwAQoh",
"Y29tLmdvb2dsZS5hZHMuZ29vZ2xlYWRzLnY4LmVudW1zQhtHb29nbGVBZHNG",
"aWVsZENhdGVnb3J5UHJvdG9QAVpCZ29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJv",
"dG8vZ29vZ2xlYXBpcy9hZHMvZ29vZ2xlYWRzL3Y4L2VudW1zO2VudW1zogID",
"R0FBqgIdR29vZ2xlLkFkcy5Hb29nbGVBZHMuVjguRW51bXPKAh1Hb29nbGVc",
"QWRzXEdvb2dsZUFkc1xWOFxFbnVtc+oCIUdvb2dsZTo6QWRzOjpHb29nbGVB",
"ZHM6OlY4OjpFbnVtc2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V8.Enums.GoogleAdsFieldCategoryEnum), global::Google.Ads.GoogleAds.V8.Enums.GoogleAdsFieldCategoryEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V8.Enums.GoogleAdsFieldCategoryEnum.Types.GoogleAdsFieldCategory) }, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Container for enum that determines if the described artifact is a resource
/// or a field, and if it is a field, when it segments search queries.
/// </summary>
public sealed partial class GoogleAdsFieldCategoryEnum : pb::IMessage<GoogleAdsFieldCategoryEnum>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<GoogleAdsFieldCategoryEnum> _parser = new pb::MessageParser<GoogleAdsFieldCategoryEnum>(() => new GoogleAdsFieldCategoryEnum());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<GoogleAdsFieldCategoryEnum> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Ads.GoogleAds.V8.Enums.GoogleAdsFieldCategoryReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public GoogleAdsFieldCategoryEnum() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public GoogleAdsFieldCategoryEnum(GoogleAdsFieldCategoryEnum other) : this() {
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public GoogleAdsFieldCategoryEnum Clone() {
return new GoogleAdsFieldCategoryEnum(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as GoogleAdsFieldCategoryEnum);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(GoogleAdsFieldCategoryEnum other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(GoogleAdsFieldCategoryEnum other) {
if (other == null) {
return;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
}
#endif
#region Nested types
/// <summary>Container for nested types declared in the GoogleAdsFieldCategoryEnum message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static partial class Types {
/// <summary>
/// The category of the artifact.
/// </summary>
public enum GoogleAdsFieldCategory {
/// <summary>
/// Unspecified
/// </summary>
[pbr::OriginalName("UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// Unknown
/// </summary>
[pbr::OriginalName("UNKNOWN")] Unknown = 1,
/// <summary>
/// The described artifact is a resource.
/// </summary>
[pbr::OriginalName("RESOURCE")] Resource = 2,
/// <summary>
/// The described artifact is a field and is an attribute of a resource.
/// Including a resource attribute field in a query may segment the query if
/// the resource to which it is attributed segments the resource found in
/// the FROM clause.
/// </summary>
[pbr::OriginalName("ATTRIBUTE")] Attribute = 3,
/// <summary>
/// The described artifact is a field and always segments search queries.
/// </summary>
[pbr::OriginalName("SEGMENT")] Segment = 5,
/// <summary>
/// The described artifact is a field and is a metric. It never segments
/// search queries.
/// </summary>
[pbr::OriginalName("METRIC")] Metric = 6,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| 39.849206 | 324 | 0.699761 | [
"Apache-2.0"
] | friedenberg/google-ads-dotnet | src/V8/Types/GoogleAdsFieldCategory.g.cs | 10,042 | C# |
namespace LoadTests
{
using System;
using System.Threading.Tasks;
using SqlStreamStore;
using SqlStreamStore.TestUtils.Postgres;
using Xunit.Abstractions;
public class PostgresStreamStoreDb : IDisposable
{
public string ConnectionString => _databaseManager.ConnectionString;
private readonly string _schema;
private readonly PostgresDatabaseManager _databaseManager;
public PostgresStreamStoreDb(string schema)
: this(schema, new ConsoleTestoutputHelper())
{ }
public PostgresStreamStoreDb(string schema, ITestOutputHelper testOutputHelper)
{
_schema = schema;
_databaseManager = new PostgresDockerDatabaseManager(
testOutputHelper,
$"test_{Guid.NewGuid():n}");
}
public PostgresStreamStoreDb(string schema, string connectionString)
{
_schema = schema;
_databaseManager = new PostgresDockerDatabaseManager(
new ConsoleTestoutputHelper(),
$"test_{Guid.NewGuid():n}");
}
public async Task<PostgresStreamStore> GetPostgresStreamStore(bool scavengeAsynchronously = false)
{
var store = await GetUninitializedPostgresStreamStore(scavengeAsynchronously);
await store.CreateSchemaIfNotExists();
return store;
}
public async Task<PostgresStreamStore> GetUninitializedPostgresStreamStore(bool scavengeAsynchronously = false)
{
await CreateDatabase();
var settings = new PostgresStreamStoreSettings(ConnectionString)
{
Schema = _schema,
ScavengeAsynchronously = scavengeAsynchronously
};
return new PostgresStreamStore(settings);
}
public void Dispose()
{
_databaseManager?.Dispose();
}
public Task CreateDatabase() => _databaseManager.CreateDatabase();
private class ConsoleTestoutputHelper : ITestOutputHelper
{
public void WriteLine(string message) => Console.Write(message);
public void WriteLine(string format, params object[] args) => Console.WriteLine(format, args);
}
}
} | 31.493151 | 119 | 0.635929 | [
"MIT"
] | BillHally/SQLStreamStore | tests/LoadTests/PostgresStreamStoreDb.cs | 2,301 | C# |
using Microsoft.EntityFrameworkCore.Storage;
using Mix.Cms.Lib.Constants;
using Mix.Cms.Lib.Enums;
using Mix.Cms.Lib.Helpers;
using Mix.Cms.Lib.Interfaces;
using Mix.Cms.Lib.Models.Cms;
using Mix.Cms.Lib.Services;
using Mix.Heart.Infrastructure.ViewModels;
using Mix.Heart.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Mix.Cms.Lib.ViewModels.MixPosts
{
public class ReadMvcViewModel
: ViewModelBase<MixCmsContext, MixPost, ReadMvcViewModel>, IMvcViewModel
{
#region Properties
#region Models
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("specificulture")]
public string Specificulture { get; set; }
[JsonProperty("cultures")]
public List<SupportedCulture> Cultures { get; set; }
[JsonProperty("template")]
public string Template { get; set; }
[JsonProperty("thumbnail")]
public string Thumbnail { get; set; }
[JsonProperty("image")]
public string Image { get; set; }
[JsonIgnore]
[JsonProperty("extraFields")]
public string ExtraFields { get; set; } = "[]";
[JsonIgnore]
[JsonProperty("extraProperties")]
public string ExtraProperties { get; set; } = "[]";
[JsonProperty("icon")]
public string Icon { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("excerpt")]
public string Excerpt { get; set; }
[JsonProperty("content")]
public string Content { get; set; }
[JsonProperty("seoName")]
public string SeoName { get; set; }
[JsonProperty("seoTitle")]
public string SeoTitle { get; set; }
[JsonProperty("seoDescription")]
public string SeoDescription { get; set; }
[JsonProperty("seoKeywords")]
public string SeoKeywords { get; set; }
[JsonProperty("source")]
public string Source { get; set; }
[JsonProperty("views")]
public int? Views { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("publishedDateTime")]
public DateTime? PublishedDateTime { get; set; }
[JsonProperty("tags")]
public string Tags { get; set; } = "[]";
public string CreatedBy { get; set; }
[JsonProperty("createdDateTime")]
public DateTime CreatedDateTime { get; set; }
[JsonProperty("modifiedBy")]
public string ModifiedBy { get; set; }
[JsonProperty("lastModified")]
public DateTime? LastModified { get; set; }
[JsonProperty("priority")]
public int Priority { get; set; }
[JsonProperty("status")]
public MixContentStatus Status { get; set; }
#endregion Models
#region Views
[JsonProperty("detailsUrl")]
public string DetailsUrl { get; set; }
[JsonProperty("view")]
public MixTemplates.ReadListItemViewModel View { get; set; }
[JsonProperty("modules")]
public List<ViewModels.MixModules.ReadMvcViewModel> Modules { get; set; }
[JsonProperty("domain")]
public string Domain { get { return MixService.GetAppSetting<string>(MixAppSettingKeywords.Domain); } }
[JsonProperty("imageUrl")]
public string ImageUrl
{
get
{
if (!string.IsNullOrEmpty(Image) && (Image.IndexOf("http") == -1))
{
return $"{Domain.TrimEnd('/')}/{Image.TrimStart('/')}";
}
else
{
return Image;
}
}
}
[JsonProperty("thumbnailUrl")]
public string ThumbnailUrl
{
get
{
if (Thumbnail != null && Thumbnail.IndexOf("http") == -1)
{
return $"{Domain.TrimEnd('/')}/{Thumbnail.TrimStart('/')}";
}
else
{
return string.IsNullOrEmpty(Thumbnail) ? ImageUrl : Thumbnail;
}
}
}
[JsonProperty("templatePath")]
public string TemplatePath
{
get
{
return $"/{ MixFolders.TemplatesFolder}/{MixService.GetConfig<string>(MixAppSettingKeywords.ThemeFolder, Specificulture) ?? "Default"}/{Template}";
}
}
[JsonProperty("mediaNavs")]
public List<MixPostMedias.ReadViewModel> MediaNavs { get; set; }
[JsonProperty("moduleNavs")]
public List<MixPostModules.ReadViewModel> ModuleNavs { get; set; }
[JsonProperty("postNavs")]
public List<MixPostPosts.ReadViewModel> PostNavs { get; set; }
[JsonProperty("Databases")]
public List<MixDatabases.ReadViewModel> Databases { get; set; } = new List<MixDatabases.ReadViewModel>();
[JsonProperty("attributeData")]
public MixDatabaseDataAssociations.ReadMvcViewModel AttributeData { get; set; }
[JsonProperty("sysTags")]
public List<MixDatabaseDataAssociations.FormViewModel> SysTags { get; set; } = new List<MixDatabaseDataAssociations.FormViewModel>();
[JsonProperty("sysCategories")]
public List<MixDatabaseDataAssociations.FormViewModel> SysCategories { get; set; } = new List<MixDatabaseDataAssociations.FormViewModel>();
[JsonProperty("listTag")]
public List<string> ListTag { get => SysTags.Select(t => t.AttributeData?.Property<string>("title")).Distinct().ToList(); }
[JsonProperty("listCategory")]
public List<string> ListCategory { get => SysCategories.Select(t => t.AttributeData?.Property<string>("title")).Distinct().ToList(); }
[JsonProperty("pages")]
public List<MixPagePosts.ReadViewModel> Pages { get; set; }
[JsonProperty("Layout")]
public string Layout { get; set; }
[JsonProperty("author")]
public JObject Author { get; set; }
[JsonProperty("bodyClass")]
public string BodyClass => Property<string>("body_class");
[JsonProperty("aliases")]
public List<MixUrlAliases.UpdateViewModel> Aliases { get; set; }
#endregion Views
#endregion Properties
#region Contructors
public ReadMvcViewModel() : base()
{
}
public ReadMvcViewModel(MixPost model, MixCmsContext _context = null, IDbContextTransaction _transaction = null) : base(model, _context, _transaction)
{
}
#endregion Contructors
#region Overrides
public override void ExpandView(MixCmsContext _context = null, IDbContextTransaction _transaction = null)
{
LoadAttributes(_context, _transaction);
LoadTags(_context, _transaction);
LoadCategories(_context, _transaction);
//Load Template + Style + Scripts for views
LoadAuthor(_context, _transaction);
this.View = MixTemplates.ReadListItemViewModel.GetTemplateByPath(Template, Specificulture, _context, _transaction).Data;
if (Pages == null)
{
LoadPages(_context, _transaction);
var getPostMedia = MixPostMedias.ReadViewModel.Repository.GetModelListBy(n => n.PostId == Id && n.Specificulture == Specificulture, _context, _transaction);
if (getPostMedia.IsSucceed)
{
MediaNavs = getPostMedia.Data.OrderBy(p => p.Priority).ToList();
MediaNavs.ForEach(n => n.IsActived = true);
}
// Modules
var getPostModule = MixPostModules.ReadViewModel.Repository.GetModelListBy(
n => n.PostId == Id && n.Specificulture == Specificulture, _context, _transaction);
if (getPostModule.IsSucceed)
{
ModuleNavs = getPostModule.Data.OrderBy(p => p.Priority).ToList();
foreach (var item in ModuleNavs)
{
item.IsActived = true;
item.Module.LoadData(postId: Id, _context: _context, _transaction: _transaction);
}
}
// Related Posts
PostNavs = MixPostPosts.ReadViewModel.Repository.GetModelListBy(n => n.SourceId == Id && n.Specificulture == Specificulture, _context, _transaction).Data;
}
LoadAliased(_context, _transaction);
DetailsUrl = Aliases.Count > 0
? MixCmsHelper.GetDetailsUrl(Specificulture, $"/{Aliases[0].Alias}")
: Id > 0
? MixCmsHelper.GetDetailsUrl(Specificulture, $"/{MixService.GetConfig("PostController", Specificulture, "post")}/{Id}/{SeoName}")
: null;
}
private void LoadAliased(MixCmsContext context, IDbContextTransaction transaction)
{
Aliases = MixUrlAliases.UpdateViewModel.Repository.GetModelListBy(
m => m.Type == (int)MixUrlAliasType.Post && m.SourceId == Id.ToString(),
context, transaction).Data;
}
private void LoadAuthor(MixCmsContext context, IDbContextTransaction transaction)
{
if (!string.IsNullOrEmpty(CreatedBy))
{
var getAuthor = MixDatabaseDatas.Helper.LoadAdditionalData(MixDatabaseParentType.User, CreatedBy, MixDatabaseNames.SYSTEM_USER_DATA
, Specificulture, context, transaction);
if (getAuthor.IsSucceed)
{
Author = getAuthor.Data.Obj;
}
}
}
private void LoadTags(MixCmsContext context, IDbContextTransaction transaction)
{
var getTags = MixDatabaseDataAssociations.FormViewModel.Repository.GetModelListBy(
m => m.Specificulture == Specificulture && m.Status == MixContentStatus.Published
&& m.ParentId == Id.ToString() && m.ParentType == MixDatabaseParentType.Post
&& m.MixDatabaseName == MixConstants.MixDatabaseName.SYSTEM_TAG, context, transaction);
if (getTags.IsSucceed)
{
SysTags = getTags.Data;
}
}
private void LoadCategories(MixCmsContext context, IDbContextTransaction transaction)
{
var getData = MixDatabaseDataAssociations.FormViewModel.Repository.GetModelListBy(m => m.Specificulture == Specificulture
&& m.ParentId == Id.ToString() && m.ParentType == MixDatabaseParentType.Post
&& m.MixDatabaseName == MixConstants.MixDatabaseName.SYSTEM_CATEGORY, context, transaction);
if (getData.IsSucceed)
{
SysCategories = getData.Data;
}
}
#endregion Overrides
#region Expands
private void LoadPages(MixCmsContext _context, IDbContextTransaction _transaction)
{
this.Pages = MixPagePosts.Helper.GetActivedNavAsync<MixPagePosts.ReadViewModel>(Id, null, Specificulture, _context, _transaction).Data;
this.Pages.ForEach(p => p.LoadPage(_context, _transaction));
}
/// <summary>Loads the attributes.</summary>
/// <param name="_context">The context.</param>
/// <param name="_transaction">The transaction.</param>
private void LoadAttributes(MixCmsContext _context, IDbContextTransaction _transaction)
{
Type = string.IsNullOrEmpty(Type) ? MixConstants.MixDatabaseName.ADDITIONAL_FIELD_POST : Type;
var getAttrs = MixDatabases.UpdateViewModel.Repository.GetSingleModel(m => m.Name == Type, _context, _transaction);
if (getAttrs.IsSucceed)
{
AttributeData = MixDatabaseDataAssociations.ReadMvcViewModel.Repository.GetFirstModel(
a => a.ParentId == Id.ToString() && a.Specificulture == Specificulture && a.MixDatabaseId == getAttrs.Data.Id
, _context, _transaction).Data ?? new MixDatabaseDataAssociations.ReadMvcViewModel();
}
}
public bool HasValue(string fieldName)
{
return AttributeData != null && AttributeData.Data.Obj.GetValue(fieldName) != null;
}
/// <summary>Get Post's Property by type and name</summary>
/// <typeparam name="T">Type of field</typeparam>
/// <param name="fieldName">Name of the field.</param>
/// <returns>T</returns>
public T Property<T>(string fieldName)
{
return MixCmsHelper.Property<T>(AttributeData?.Data?.Obj, fieldName);
}
/// <summary>Gets the module.</summary>
/// <param name="name">The name.</param>
/// <returns>MixModules.ReadMvcViewModel</returns>
public MixModules.ReadMvcViewModel GetModule(string name)
{
return ModuleNavs.FirstOrDefault(m => m.Module.Name == name)?.Module;
}
/// <summary>Gets the attribute set.</summary>
/// <param name="name">The name.</param>
/// <returns>Databases.ReadMvcViewModel</returns>
public MixDatabases.ReadViewModel GetMixDatabase(string name)
{
return Databases.FirstOrDefault(m => m.Name == name);
}
#endregion Expands
}
} | 36.983651 | 172 | 0.595299 | [
"MIT"
] | Mixcore-IO/mix.core | src/Mix.Cms.Lib/ViewModels/MixPosts/ReadMvcViewModel.cs | 13,575 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT).
// See third-party-notices in the repository root for more information.
// Ported from um/winnt.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
// <auto-generated />
#pragma warning disable CS0649
namespace TerraFX.Interop
{
internal enum VARENUM
{
VT_EMPTY = 0,
VT_NULL = 1,
VT_I2 = 2,
VT_I4 = 3,
VT_R4 = 4,
VT_R8 = 5,
VT_CY = 6,
VT_DATE = 7,
VT_BSTR = 8,
VT_DISPATCH = 9,
VT_ERROR = 10,
VT_BOOL = 11,
VT_VARIANT = 12,
VT_UNKNOWN = 13,
VT_DECIMAL = 14,
VT_I1 = 16,
VT_UI1 = 17,
VT_UI2 = 18,
VT_UI4 = 19,
VT_I8 = 20,
VT_UI8 = 21,
VT_INT = 22,
VT_UINT = 23,
VT_VOID = 24,
VT_HRESULT = 25,
VT_PTR = 26,
VT_SAFEARRAY = 27,
VT_CARRAY = 28,
VT_USERDEFINED = 29,
VT_LPSTR = 30,
VT_LPWSTR = 31,
VT_RECORD = 36,
VT_INT_PTR = 37,
VT_UINT_PTR = 38,
VT_FILETIME = 64,
VT_BLOB = 65,
VT_STREAM = 66,
VT_STORAGE = 67,
VT_STREAMED_OBJECT = 68,
VT_STORED_OBJECT = 69,
VT_BLOB_OBJECT = 70,
VT_CF = 71,
VT_CLSID = 72,
VT_VERSIONED_STREAM = 73,
VT_BSTR_BLOB = 0xfff,
VT_VECTOR = 0x1000,
VT_ARRAY = 0x2000,
VT_BYREF = 0x4000,
VT_RESERVED = 0x8000,
VT_ILLEGAL = 0xffff,
VT_ILLEGALMASKED = 0xfff,
VT_TYPEMASK = 0xfff,
}
}
| 24.720588 | 85 | 0.531826 | [
"MIT"
] | saucecontrol/PhotoSauce | src/MagicScaler/External/Interop/Windows/shared/wtypes/VARENUM.cs | 1,683 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.