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 |
|---|---|---|---|---|---|---|---|---|
//-----------------------------------------------------------------------------
// Copyright : (c) Chris Moore, 2020
// License : MIT
//-----------------------------------------------------------------------------
namespace Z0
{
using System;
using System.Runtime.CompilerServices;
using static Root;
using static Numeric;
using static BitMaskLiterals;
partial class BitMasks
{
/// <summary>
/// Defines a central bitmask over 8-bit segments with a parametric bit density
/// D:[N2 | N4 | N6]
/// </summary>
/// <param name="f">The repetition frequency</param>
/// <param name="t">A mask type representative</param>
/// <typeparam name="D">The bit density type</typeparam>
/// <typeparam name="T">The primal mask type</typeparam>
[MethodImpl(Inline)]
public static T central<D,T>(N8 f, D d = default, T t = default)
where T : unmanaged
where D : unmanaged, ITypeNat
{
if(typeof(D) == typeof(N2))
return central<T>(f,n2);
else if(typeof(D) == typeof(N4))
return central<T>(f,n4);
else if(typeof(D) == typeof(N6))
return central<T>(f,n6);
else
throw no<D>();
}
/// <summary>
/// [00011000]
/// </summary>
/// <param name="f">The repetition frequency</param>
/// <param name="d">The bit density</param>
/// <param name="t">A mask type representative</param>
/// <typeparam name="T">The mask data type</typeparam>
[MethodImpl(Inline), Op, Closures(Closure)]
public static T central<T>(N8 f, N2 d, T t = default)
where T : unmanaged
{
if(typeof(T) == typeof(byte))
return force<byte,T>(Central8x8x2);
else if(typeof(T) == typeof(ushort))
return force<ushort,T>(Central16x8x2);
else if(typeof(T) == typeof(uint))
return force<uint,T>(Central32x8x2);
else if(typeof(T) == typeof(ulong))
return force<ulong,T>(Central64x8x2);
else
throw no<T>();
}
/// <summary>
/// [00111100]
/// </summary>
/// <param name="f">The repetition frequency</param>
/// <param name="d">The bit density</param>
/// <param name="t">A mask type representative</param>
/// <typeparam name="T">The mask data type</typeparam>
[MethodImpl(Inline), Op, Closures(Closure)]
public static T central<T>(N8 f, N4 d, T t = default)
where T : unmanaged
{
if(typeof(T) == typeof(byte))
return force<byte,T>(Central8x8x4);
else if(typeof(T) == typeof(ushort))
return force<ushort,T>(Central16x8x4);
else if(typeof(T) == typeof(uint))
return force<uint,T>(Central32x8x4);
else if(typeof(T) == typeof(ulong))
return force<ulong,T>(Central64x8x4);
else
throw no<T>();
}
/// <summary>
/// [01111110]
/// </summary>
/// <param name="f">The repetition frequency</param>
/// <param name="d">The bit density</param>
/// <param name="t">A mask type representative</param>
/// <typeparam name="T">The mask data type</typeparam>
[MethodImpl(Inline), Op, Closures(Closure)]
public static T central<T>(N8 f, N6 d, T t = default)
where T : unmanaged
{
if(typeof(T) == typeof(byte))
return force<byte,T>(Central8x8x6);
else if(typeof(T) == typeof(ushort))
return force<ushort,T>(Central16x8x6);
else if(typeof(T) == typeof(uint))
return force<uint,T>(Central32x8x6);
else if(typeof(T) == typeof(ulong))
return force<ulong,T>(Central64x8x6);
else
throw no<T>();
}
}
} | 37.981481 | 87 | 0.495124 | [
"BSD-3-Clause"
] | 0xCM/z0 | src/bits/src/bitmasks/ops/central.cs | 4,102 | C# |
using System;
using System.Linq;
namespace PrivateWiki.DataModels.Pages
{
public record Path
{
private readonly string[]? _namespaces;
public string? NamespaceString => _namespaces?.Aggregate((acc, el) => acc + ":" + el);
public string Title { get; }
public string FullPath
{
get
{
if (_namespaces != null)
{
return _namespaces.Aggregate((acc, el) => acc + ":" + el) + ":" + Title;
}
else
{
return Title;
}
}
}
private Path(string[] path, string name)
{
_namespaces = path;
Title = name;
}
private Path(string name)
{
Title = name;
}
/// <summary>
/// Returns true, if the path belongs to the system namespace.
/// </summary>
/// <returns></returns>
public bool IsSystemNamespace()
{
if (_namespaces == null) return false;
var a = _namespaces[0];
return a != null && a.ToUpperInvariant() == "SYSTEM";
}
public override string ToString()
{
return FullPath;
}
public static Path ofLink(string link)
{
var path = link.Split(new[] {':'}, StringSplitOptions.RemoveEmptyEntries);
if (path.Length > 1)
{
var path2 = new string[path.Length - 1];
Array.Copy(path, path2, path.Length - 1);
return new Path(path2, path[path.Length - 1]);
}
return new Path(link);
}
public static Path of(string[] path, string name)
{
return new Path(path, name);
}
}
} | 18.064103 | 88 | 0.606813 | [
"MIT"
] | lampenlampen/PrivateWiki | PrivateWiki/DataModels/Pages/Path.cs | 1,411 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using EntityFrameworkCore3Mock.Tests.Models;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
namespace EntityFrameworkCore3Mock.NSubstitute.Tests
{
[TestFixture]
public class DbSetMockTests
{
[Test]
public void DbSetMock_AsNoTracking_ShouldBeMocked()
{
var dbSetMock = new DbSetMock<Order>(null, (x, _) => x.Id);
var dbSet = dbSetMock.Object;
Assert.That(dbSet.AsNoTracking(), Is.EqualTo(dbSet));
}
[Test]
public void DbSetMock_Include_ShouldBeMocked()
{
var dbSetMock = new DbSetMock<Order>(null, (x, _) => x.Id);
var dbSet = dbSetMock.Object;
Assert.That(dbSet.Include(x => x.User), Is.EqualTo(dbSet));
}
[Test]
public void DbSetMock_GivenEntityIsAdded_ShouldAddAfterCallingSaveChanges()
{
var user = new User { Id = Guid.NewGuid(), FullName = "Fake Drake" };
var dbSetMock = new DbSetMock<User>(null, (x, _) => x.Id);
var dbSet = dbSetMock.Object;
Assert.That(dbSet.Count(), Is.EqualTo(0));
dbSet.Add(user);
Assert.That(dbSet.Count(), Is.EqualTo(0));
((IDbSetMock)dbSetMock).SaveChanges();
Assert.That(dbSet.Count(), Is.EqualTo(1));
Assert.That(dbSet.Any(x => x.Id == user.Id && x.FullName == user.FullName), Is.True);
}
[Test]
public void DbSetMock_GivenEntityRangeIsAdded_ShouldAddAfterCallingSaveChanges()
{
// Arrange
var users = new List<User>()
{
new User() { Id = Guid.NewGuid(), FullName = "Ian Kilmister" },
new User() { Id = Guid.NewGuid(), FullName = "Phil Taylor" },
new User() { Id = Guid.NewGuid(), FullName = "Eddie Clarke" }
};
var dbSetMock = new DbSetMock<User>(null, (x, _) => x.Id);
var dbSet = dbSetMock.Object;
Assert.That(dbSet.Count(), Is.EqualTo(0));
// Act
dbSet.AddRange(users);
((IDbSetMock)dbSetMock).SaveChanges();
// Assert
var firstUser = users.First();
Assert.That(dbSet.Count(), Is.EqualTo(3));
Assert.That(dbSet.Any(x => x.Id == firstUser.Id
&& x.FullName == firstUser.FullName), Is.True);
}
[Test]
public async Task DbSetMock_AsyncProvider()
{
var user = new User { Id = Guid.NewGuid(), FullName = "Fake Drake" };
var dbSetMock = new DbSetMock<User>(null, (x, _) => x.Id);
var dbSet = dbSetMock.Object;
Assert.That(await dbSet.CountAsync(), Is.EqualTo(0));
dbSet.Add(user);
Assert.That(await dbSet.CountAsync(), Is.EqualTo(0));
((IDbSetMock)dbSetMock).SaveChanges();
Assert.That(await dbSet.CountAsync(), Is.EqualTo(1));
Assert.That(await dbSet.AnyAsync(x => x.Id == user.Id && x.FullName == user.FullName), Is.True);
}
[Test]
public void DbSetMock_GivenEntityIsRemoved_ShouldRemoveAfterCallingSaveChanges()
{
var user = new User { Id = Guid.NewGuid(), FullName = "Fake Drake" };
var dbSetMock = new DbSetMock<User>(new[]
{
user,
new User {Id = Guid.NewGuid(), FullName = "Jackira Spicy"}
}, (x, _) => x.Id);
var dbSet = dbSetMock.Object;
Assert.That(dbSet.Count(), Is.EqualTo(2));
dbSet.Remove(new User { Id = user.Id });
Assert.That(dbSet.Count(), Is.EqualTo(2));
Assert.That(dbSet.Any(x => x.Id == user.Id && x.FullName == user.FullName), Is.True);
((IDbSetMock)dbSetMock).SaveChanges();
Assert.That(dbSet.Count(), Is.EqualTo(1));
Assert.That(dbSet.Any(x => x.Id == user.Id && x.FullName == user.FullName), Is.False);
}
[Test]
public void DbSetMock_GivenRangeOfEntitiesIsRemoved_ShouldRemoveAfterCallingSaveChanges()
{
var users = new[]
{
new User {Id = Guid.NewGuid(), FullName = "User 1"},
new User {Id = Guid.NewGuid(), FullName = "User 2"},
new User {Id = Guid.NewGuid(), FullName = "User 3"}
};
var dbSetMock = new DbSetMock<User>(users, (x, _) => x.Id);
var dbSet = dbSetMock.Object;
Assert.That(dbSet.Count(), Is.EqualTo(3));
dbSet.RemoveRange(users.Skip(1));
Assert.That(dbSet.Count(), Is.EqualTo(3));
((IDbSetMock)dbSetMock).SaveChanges();
Assert.That(dbSet.Count(), Is.EqualTo(1));
Assert.That(dbSet.Any(x => x.FullName == "User 1"), Is.True);
Assert.That(dbSet.Any(x => x.FullName == "User 2"), Is.False);
}
[Test]
public void DbSetMock_SaveChanges_GivenEntityPropertyIsChanged_ShouldFireSavedChangesEventWithCorrectUpdatedInfo()
{
var userId = Guid.NewGuid();
var dbSetMock = new DbSetMock<User>(new[]
{
new User {Id = userId, FullName = "Mark Kramer"},
new User {Id = Guid.NewGuid(), FullName = "Freddy Kipcurry"}
}, (x, _) => x.Id);
var dbSet = dbSetMock.Object;
Assert.That(dbSet.Count(), Is.EqualTo(2));
var fetchedUser = dbSet.First(x => x.Id == userId);
fetchedUser.FullName = "Kramer Mark";
SavedChangesEventArgs<User> eventArgs = null;
dbSetMock.SavedChanges += (sender, args) => eventArgs = args;
((IDbSetMock)dbSetMock).SaveChanges();
Assert.That(eventArgs, Is.Not.Null);
Assert.That(eventArgs.UpdatedEntities, Has.Length.EqualTo(1));
var updatedEntity = eventArgs.UpdatedEntities[0];
Assert.That(updatedEntity.UpdatedProperties, Has.Length.EqualTo(1));
var updatedProperty = updatedEntity.UpdatedProperties[0];
Assert.That(updatedProperty.Name, Is.EqualTo("FullName"));
Assert.That(updatedProperty.Original, Is.EqualTo("Mark Kramer"));
Assert.That(updatedProperty.New, Is.EqualTo("Kramer Mark"));
}
[Test]
public void DbSetMock_SaveChanges_GivenEntityPropertyMarkedAsNotMapped_ShouldNotMarkNotMappedPropertyAsModified()
{
var dbSetMock = new DbSetMock<NestedModel>(new[]
{
new NestedModel {Id = Guid.NewGuid(), NestedDocument = new NestedModel.Document()},
new NestedModel {Id = Guid.NewGuid(), NestedDocument = new NestedModel.Document()},
new NestedModel {Id = Guid.NewGuid(), NestedDocument = new NestedModel.Document()}
}, (x, _) => x.Id);
SavedChangesEventArgs<NestedModel> eventArgs = null;
dbSetMock.SavedChanges += (sender, args) => eventArgs = args;
dbSetMock.Object.First().Value = "abc";
((IDbSetMock)dbSetMock).SaveChanges();
Assert.That(eventArgs, Is.Not.Null);
Assert.That(eventArgs.UpdatedEntities, Has.Length.EqualTo(1));
Assert.That(eventArgs.UpdatedEntities.First().UpdatedProperties, Has.Length.EqualTo(1));
var updatedProperty = eventArgs.UpdatedEntities.First().UpdatedProperties.First();
Assert.That(updatedProperty.Name, Is.EqualTo("Value"));
Assert.That(updatedProperty.Original, Is.EqualTo(null));
Assert.That(updatedProperty.New, Is.EqualTo("abc"));
}
[Test]
public void DbSetMock_Empty_AsEnumerable_ShouldReturnEmptyEnumerable()
{
var dbSetMock = new DbSetMock<NestedModel>(new List<NestedModel>(), (x, _) => x.Id);
var nestedModels = dbSetMock.Object.AsEnumerable();
Assert.That(nestedModels, Is.Not.Null);
Assert.That(nestedModels, Is.Empty);
}
[Test]
public void DbSetMock_AsEnumerable_ShouldReturnEnumerableCollection()
{
var dbSetMock = new DbSetMock<NestedModel>(new[]
{
new NestedModel {Id = Guid.NewGuid(), NestedDocument = new NestedModel.Document()},
new NestedModel {Id = Guid.NewGuid(), NestedDocument = new NestedModel.Document()}
}, (x, _) => x.Id);
var nestedModels = dbSetMock.Object.AsEnumerable();
Assert.That(nestedModels, Is.Not.Null);
Assert.That(nestedModels.Count(), Is.EqualTo(2));
}
[Test]
public async Task DbSetMock_AsyncProvider_ShouldReturnRequestedModel()
{
var userId = Guid.NewGuid();
var dbSetMock = new DbSetMock<User>(new[]
{
new User {Id = userId, FullName = "Mark Kramer"},
new User {Id = Guid.NewGuid(), FullName = "Freddy Kipcurry"}
}, (x, _) => x.Id);
var model = await dbSetMock.Object.Where(x => x.Id == userId).FirstOrDefaultAsync();
Assert.That(model, Is.Not.Null);
Assert.That(model.FullName, Is.EqualTo("Mark Kramer"));
}
[Test]
public async Task DbSetMock_AsyncProvider_OrderBy_ShouldReturnRequestedModel()
{
var dbSetMock = new DbSetMock<User>(new[]
{
new User {Id = Guid.NewGuid(), FullName = "Mark Kramer"},
new User {Id = Guid.NewGuid(), FullName = "Freddy Kipcurry"}
}, (x, _) => x.Id);
var result = await dbSetMock.Object.Where(x => x.Id != Guid.Empty).OrderBy(x => x.FullName).ToListAsync();
Assert.That(result, Is.Not.Null);
Assert.That(result, Has.Count.EqualTo(2));
Assert.That(result.First().FullName, Is.EqualTo("Freddy Kipcurry"));
}
[Test]
public void DbSetMock_Find_ShouldReturnRequestedModel()
{
Guid user1 = Guid.NewGuid(), user2 = Guid.NewGuid();
var dbSetMock = new DbSetMock<User>(new[]
{
new User {Id = user1, FullName = "Mark Kramer"},
new User {Id = user2, FullName = "Freddy Kipcurry"}
}, (x, _) => x.Id);
var result = dbSetMock.Object.Find(user2);
Assert.That(result, Is.Not.Null);
Assert.That(result.FullName, Is.EqualTo("Freddy Kipcurry"));
}
[Test]
public void DbSetMock_Find_UnknownId_ShouldReturnNull()
{
var unknownUser = Guid.NewGuid();
var dbSetMock = new DbSetMock<User>(new[]
{
new User {Id = Guid.NewGuid(), FullName = "Mark Kramer"},
new User {Id = Guid.NewGuid(), FullName = "Freddy Kipcurry"}
}, (x, _) => x.Id);
var result = dbSetMock.Object.Find(unknownUser);
Assert.That(result, Is.Null);
}
[Test]
public void DbSetMock_FindOnCompositeTupleKey_ShouldReturnRequestedModel()
{
Guid modelId1 = Guid.NewGuid(), modelId2 = Guid.NewGuid();
var dbSetMock = new DbSetMock<NoKeyModel>(new[]
{
new NoKeyModel {ModelId = modelId1, Value = "Value 1"},
new NoKeyModel {ModelId = modelId2, Value = "Value 2"}
}, (x, _) => new Tuple<Guid, string>(x.ModelId, x.Value));
var result = dbSetMock.Object.Find(modelId2, "Value 2");
Assert.That(result, Is.Not.Null);
Assert.That(result.ModelId, Is.EqualTo(modelId2));
Assert.That(result.Value, Is.EqualTo("Value 2"));
}
[Test]
public void DbSetMock_FindOnCompositeValueTupleKey_ShouldReturnRequestedModel()
{
Guid modelId1 = Guid.NewGuid(), modelId2 = Guid.NewGuid();
var dbSetMock = new DbSetMock<NoKeyModel>(new[]
{
new NoKeyModel {ModelId = modelId1, Value = "Value 1"},
new NoKeyModel {ModelId = modelId2, Value = "Value 2"}
}, (x, _) => (x.ModelId, x.Value));
var result = dbSetMock.Object.Find(modelId2, "Value 2");
Assert.That(result, Is.Not.Null);
Assert.That(result.ModelId, Is.EqualTo(modelId2));
Assert.That(result.Value, Is.EqualTo("Value 2"));
}
public class NestedModel
{
public Guid Id { get; set; }
public string Value { get; set; }
[NotMapped]
public Document NestedDocument
{
get { return new Document { Name = Guid.NewGuid().ToString("N") }; }
// ReSharper disable once ValueParameterNotUsed
set { }
}
public class Document
{
public string Name { get; set; }
}
}
[Test]
public void DbSetMock_SaveChanges_GivenAbstractEntityModel_ShouldNotThrowException()
{
var dbSetMock = new DbSetMock<AbstractModel>(new[]
{
new ConcreteModel {Id = Guid.NewGuid()}
}, (x, _) => x.Id);
((IDbSetMock)dbSetMock).SaveChanges();
}
public abstract class AbstractModel
{
public Guid Id { get; set; }
}
public class ConcreteModel : AbstractModel
{
public string Name { get; set; } = "SomeName";
}
}
} | 40.336283 | 122 | 0.560407 | [
"MIT"
] | AddonContributor/entity-framework-core3-mock | tests/EntityFrameworkCore3Mock.NSubstitute.Tests/DbSetMockTests.cs | 13,676 | C# |
using Models.Infrastructure;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Drawing;
using System.Text;
namespace Models.UserModels
{
/// <summary>
/// 知识库分类
/// </summary>
public class KnowledgeCategory
{
public KnowledgeCategory()
{
SystemId = "000";
Enable = true;
}
/// <summary>
/// 分类名称
/// </summary>
[Required]
public string Name { get; set; }
/// <summary>
/// 系统编号
/// </summary>
[Required]
public string SystemId { get; set; }
public bool Enable { get; set; }
}
} | 19.525 | 51 | 0.572343 | [
"MIT"
] | fanshuyi/.netcore-admin | Models/Knowledge/KnowledgeCategory.cs | 807 | C# |
// Copyright 2021 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
//
// https://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.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Logging.V2.Snippets
{
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Logging.V2;
public sealed partial class GeneratedConfigServiceV2ClientStandaloneSnippets
{
/// <summary>Snippet for CreateExclusion</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void CreateExclusionResourceNames2()
{
// Create client
ConfigServiceV2Client configServiceV2Client = ConfigServiceV2Client.Create();
// Initialize request argument(s)
OrganizationName parent = OrganizationName.FromOrganization("[ORGANIZATION]");
LogExclusion exclusion = new LogExclusion();
// Make the request
LogExclusion response = configServiceV2Client.CreateExclusion(parent, exclusion);
}
}
}
| 39.341463 | 93 | 0.698078 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/logging/v2/google-cloud-logging-v2-csharp/Google.Cloud.Logging.V2.StandaloneSnippets/ConfigServiceV2Client.CreateExclusionResourceNames2Snippet.g.cs | 1,613 | C# |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System.Text;
using Zeds.Engine;
using Zeds.Pawns.HumanLogic;
namespace Zeds.UI.PawnInfoPanel
{
class PawnInfo
{
public static bool IsPawnInfoVisible;
public static Rectangle PawnInfoRec;
public static Rectangle MenuCloseRec;
public static Rectangle PawnOutlineBox;
public static Rectangle PawnHeadBox;
public static Rectangle PawnChestBox;
public static Rectangle PawnHandBox;
public static Rectangle PawnMiscBox;
public static Rectangle ExpandHandBox;
public static Rectangle ExpandHeadBox;
public static Rectangle ExpandsChestBox;
public static Rectangle ExpandMiscBox;
public static Vector2 InfoLocation;
public static string DisplayInfo;
private static readonly StringBuilder pawnInfoSB = new StringBuilder();
public static void DisplayPawnInfo(Human pawn)
{
PawnInfoRec = new Rectangle
{
X = 0,
Y = 0,
Width = 250,
Height = 300
};
MenuCloseRec = new Rectangle
{
X = PawnInfoRec.X + PawnInfoRec.Width - 30,
Y = PawnInfoRec.Y + 10,
Width = 20,
Height = 20
};
InfoLocation = new Vector2
{
X = PawnInfoRec.X + 10,
Y = PawnInfoRec.Y + 10
};
DisplayInfo = CreatePawnInfoString(pawn);
PawnOutlineBox = new Rectangle
{
X = PawnInfoRec.X +10,
Y = PawnInfoRec.Y + 150,
Width = Textures.InfoPawnOutline.Width,
Height = Textures.InfoPawnOutline.Height
};
// Row 1
PawnHeadBox = new Rectangle
{
X = PawnOutlineBox.X + PawnOutlineBox.Width + 20,
Y = PawnOutlineBox.Y,
Width = 40,
Height = 40
};
ExpandHeadBox = new Rectangle
{
X = PawnHeadBox.X + PawnHeadBox.Width - 5,
Y = PawnHeadBox.Y + PawnHeadBox.Height - 5,
Width = 10,
Height = 10
};
PawnChestBox = new Rectangle
{
X = PawnHeadBox.X + PawnHeadBox.Width + 10,
Y = PawnOutlineBox.Y,
Width = 40,
Height = 40
};
ExpandsChestBox = new Rectangle
{
X = PawnChestBox.X + PawnChestBox.Width - 5,
Y = PawnChestBox.Y + PawnChestBox.Height - 5,
Width = 10,
Height = 10
};
//Row 2
PawnHandBox = new Rectangle
{
X = PawnOutlineBox.X + PawnOutlineBox.Width + 20,
Y = PawnHeadBox.Y + PawnHeadBox.Height +20,
Width = 40,
Height = 40
};
ExpandHandBox = new Rectangle
{
X = PawnHandBox.X + PawnHandBox.Width - 5,
Y = PawnHandBox.Y + PawnHandBox.Height - 5,
Width = 10,
Height = 10
};
PawnMiscBox = new Rectangle
{
X = PawnHandBox.X + PawnHandBox.Width + 10,
Y = PawnChestBox.Y + PawnChestBox.Height +20,
Width = 40,
Height = 40
};
ExpandMiscBox = new Rectangle
{
X = PawnMiscBox.X + PawnMiscBox.Width - 5,
Y = PawnMiscBox.Y + PawnMiscBox.Height -5,
Width = 10,
Height = 10
};
}
public static void ClosePawnInfo()
{
if (Cursor.CursorRectangle.Intersects(MenuCloseRec) && Mouse.GetState().LeftButton == ButtonState.Pressed)
IsPawnInfoVisible = false;
}
private static string CreatePawnInfoString(Human pawn)
{
pawnInfoSB.Clear();
pawnInfoSB.Append("Name: " + pawn.Name + "\n");
pawnInfoSB.Append("A " + pawn.Age + " year old " + pawn.Occupation + "\n\n");
pawnInfoSB.Append("Health: " + pawn.CurrentHealth + "/" + pawn.MaxHealth + "\n");
pawnInfoSB.Append("Morale: " + "\n");
pawnInfoSB.Append("Current task: " + "\n");
pawnInfoSB.Append("Power: " + pawn.AttackPower + "\n");
return pawnInfoSB.ToString();
}
public static void UpdatePawnInfo()
{
foreach (var human in EntityLists.HumanList)
if (human.IsSelected)
DisplayInfo = CreatePawnInfoString(human);
}
}
} | 30.385093 | 118 | 0.494481 | [
"MIT"
] | Ratstool/Zeds | UI/PawnInfoPanel/PawnInfo.cs | 4,894 | C# |
using System;
using System.IO;
using System.Text;
public class DataReader {
public static short ReadShort(MemoryStream dataStream) {
byte[] buffer = new byte[2];
dataStream.Read(buffer, 0, 2);
return BitConverter.ToInt16(buffer, 0);;
}
public static int ReadInt(MemoryStream dataStream) {
byte[] buffer = new byte[4];
dataStream.Read(buffer, 0, 4);
return BitConverter.ToInt32(buffer, 0);;
}
public static float ReadFloat(MemoryStream dataStream) {
byte[] buffer = new byte[4];
dataStream.Read(buffer, 0, 4);
return BitConverter.ToSingle(buffer, 0);;
}
public static bool ReadBool(MemoryStream dataStream) {
byte[] buffer = new byte[1];
dataStream.Read(buffer, 0, 1);
return BitConverter.ToBoolean(buffer, 0);;
}
public static string ReadString(MemoryStream dataStream) {
short length = ReadShort(dataStream);
byte[] buffer = new byte[length];
dataStream.Read(buffer, 0, length);
buffer = Encoding.Convert(Encoding.GetEncoding("iso-8859-1"), Encoding.UTF8, buffer);
return Encoding.UTF8.GetString(buffer, 0, length);
}
} | 27.74359 | 87 | 0.714418 | [
"MIT"
] | saundemanu/CSC631-HW4 | WoB_Client_Basic/Assets/Network/DataReader.cs | 1,082 | C# |
using Microsoft.Xna.Framework;
using OpenKh.Common;
using OpenKh.Game.DataContent;
using OpenKh.Game.Debugging;
using OpenKh.Game.Infrastructure;
using OpenKh.Game.States;
using OpenKh.Game.States.Title;
using System;
using System.Collections.Generic;
using System.IO;
namespace OpenKh.Game
{
public class OpenKhGameStartup
{
public string ContentPath { get; internal set; }
public int InitialState { get; internal set; }
public int InitialMap { get; internal set; }
public int? InitialPlace { get; internal set; }
public int? InitialSpawnScriptMap { get; internal set; }
public int? InitialSpawnScriptBtl { get; internal set; }
public int? InitialSpawnScriptEvt { get; internal set; }
}
public class OpenKhGame : Microsoft.Xna.Framework.Game, IStateChange
{
private GraphicsDeviceManager graphics;
private readonly Dictionary<string, string> GlobalSettings;
private readonly IDataContent _dataContent;
private readonly Kernel _kernel;
private readonly ArchiveManager archiveManager;
private readonly InputManager inputManager;
private readonly DebugOverlay _debugOverlay;
private readonly OpenKhGameStartup _startup;
private IState state;
private bool _isResolutionChanged;
public int State
{
set
{
Log.Info("State={0}", value);
switch (value)
{
case 0:
state = new TitleState();
state.Initialize(GetStateInitDesc());
break;
case 1:
state = new MapState();
state.Initialize(GetStateInitDesc());
break;
case 2:
// WARNING: this is quite buggy since no game context will be passed to
// the menu, but it useful for quick menu testing.
var myState = new MenuState(null);
myState.Initialize(GetStateInitDesc());
myState.OpenMenu();
state = myState;
break;
default:
Log.Err("Invalid state {0}", value);
return;
}
if (state is IDebugConsumer debugConsumer)
{
_debugOverlay.OnUpdate = debugConsumer.DebugUpdate;
_debugOverlay.OnDraw = debugConsumer.DebugDraw;
}
}
}
public OpenKhGame(OpenKhGameStartup startup)
{
_startup = startup;
GlobalSettings = new Dictionary<string, string>();
TryAddSetting("WorldId", startup.InitialMap);
TryAddSetting("PlaceId", startup.InitialPlace);
//TryAddSetting("SpawnId", );
TryAddSetting("SpawnScriptMap", startup.InitialSpawnScriptMap);
TryAddSetting("SpawnScriptBtl", startup.InitialSpawnScriptBtl);
TryAddSetting("SpawnScriptEvt", startup.InitialSpawnScriptEvt);
var contentPath = startup.ContentPath ?? Config.DataPath;
_dataContent = CreateDataContent(contentPath, Config.IdxFilePath, Config.ImgFilePath);
_dataContent = new MultipleDataContent(new ModDataContent(), _dataContent);
if (Kernel.IsReMixFileHasHdAssetHeader(_dataContent, "fm"))
{
Log.Info("ReMIX files with HD asset header detected");
_dataContent = new HdAssetContent(_dataContent);
}
_dataContent = new SafeDataContent(_dataContent);
_kernel = new Kernel(_dataContent);
if (startup.InitialState != 0)
_kernel.LoadSaveData(Config.LastSave);
var resolutionWidth = GetResolutionWidth();
var resolutionHeight = GetResolutionHeight();
Log.Info("Internal game resolution set to {0}x{1}", resolutionWidth, resolutionHeight);
graphics = new GraphicsDeviceManager(this)
{
PreferredBackBufferWidth = (int)Math.Round(resolutionWidth * Config.ResolutionBoost),
PreferredBackBufferHeight = (int)Math.Round(resolutionHeight * Config.ResolutionBoost),
IsFullScreen = Config.IsFullScreen,
};
Content.RootDirectory = "Content";
IsMouseVisible = true;
archiveManager = new ArchiveManager(_dataContent);
inputManager = new InputManager();
_debugOverlay = new DebugOverlay(this);
Config.OnConfigurationChange += () =>
{
var resolutionWidth = GetResolutionWidth();
var resolutionHeight = GetResolutionHeight();
var backBufferWidth = (int)Math.Round(resolutionWidth * Config.ResolutionBoost);
var backBufferHeight = (int)Math.Round(resolutionHeight * Config.ResolutionBoost);
if (graphics.PreferredBackBufferWidth != backBufferWidth ||
graphics.PreferredBackBufferHeight != backBufferHeight ||
graphics.IsFullScreen != Config.IsFullScreen)
{
graphics.PreferredBackBufferWidth = backBufferWidth;
graphics.PreferredBackBufferHeight = backBufferHeight;
graphics.IsFullScreen = Config.IsFullScreen;
_isResolutionChanged = true;
Log.Info($"Internal game resolution set to {resolutionWidth}x{resolutionHeight}");
}
};
}
protected override void Initialize()
{
_debugOverlay.Initialize(GetStateInitDesc());
State = _startup.InitialState;
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
// TODO: use this.Content to load your game content here
}
protected override void Update(GameTime gameTime)
{
inputManager.Update(gameTime);
if (inputManager.IsExit)
Exit();
var deltaTimes = GetDeltaTimes(gameTime);
if (Config.DebugMode)
_debugOverlay.Update(deltaTimes);
state?.Update(deltaTimes);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
if (_isResolutionChanged)
{
graphics.ApplyChanges();
_isResolutionChanged = false;
}
graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
var deltaTimes = GetDeltaTimes(gameTime);
state?.Draw(deltaTimes);
if (Config.DebugMode)
_debugOverlay.Draw(deltaTimes);
base.Draw(gameTime);
}
private void TryAddSetting(string key, string value)
{
if (!string.IsNullOrEmpty(value))
GlobalSettings.Add(key, value);
}
private void TryAddSetting(string key, int value)
{
if (value >= 0)
GlobalSettings.Add(key, value.ToString());
}
private void TryAddSetting(string key, int? value)
{
if (value.HasValue)
TryAddSetting(key, value.Value);
}
private StateInitDesc GetStateInitDesc()
{
return new StateInitDesc
{
DataContent = _dataContent,
ArchiveManager = archiveManager,
Kernel = _kernel,
InputManager = inputManager,
ContentManager = Content,
GraphicsDevice = graphics,
StateChange = this,
StateSettings = GlobalSettings,
};
}
private DeltaTimes GetDeltaTimes(GameTime gameTime)
{
return new DeltaTimes
{
DeltaTime = 1.0 / 60.0 * Config.GameSpeed
};
}
private static IDataContent CreateDataContent(string basePath, string idxFileName, string imgFileName)
{
Log.Info("Base directory is {0}", basePath);
var idxFullPath = Path.Combine(basePath, idxFileName);
var imgFullPath = Path.Combine(basePath, imgFileName);
if (File.Exists(idxFullPath) && File.Exists(imgFullPath))
{
Log.Info("{0} and {1} has been found", idxFullPath, imgFullPath);
var imgStream = File.OpenRead(imgFullPath);
var idxDataContent = File.OpenRead(idxFullPath)
.Using(stream => new IdxDataContent(stream, imgStream));
return new MultipleDataContent(
new StandardDataContent(basePath),
idxDataContent,
new IdxMultipleDataContent(idxDataContent, imgStream)
);
}
else
{
Log.Info("No {0} or {1}, loading extracted files", idxFullPath, imgFullPath);
return new StandardDataContent(basePath);
}
}
private static int GetResolutionHeight()
{
var resolutionHeight = Config.ResolutionHeight;
if (resolutionHeight == 0)
resolutionHeight = Global.ResolutionHeight;
return resolutionHeight;
}
private int GetResolutionWidth()
{
var resolutionWidth = Config.ResolutionWidth;
if (resolutionWidth == 0)
resolutionWidth = _kernel.IsReMix ? Global.ResolutionRemixWidth : Global.ResolutionWidth;
return resolutionWidth;
}
}
}
| 36.505495 | 110 | 0.564921 | [
"Apache-2.0"
] | Tasos500/OpenKh | OpenKh.Game/OpenKhGame.cs | 9,966 | C# |
namespace formulate.app.Persistence
{
// Namespaces.
using Forms;
using System;
using System.Collections.Generic;
/// <summary>
/// Interface for persistence of Configured Forms.
/// </summary>
public interface IConfiguredFormPersistence
{
/// <summary>
/// Persist a Configured Form.
/// </summary>
/// <param name="configuredForm">The Configured Form.</param>
void Persist(ConfiguredForm configuredForm);
/// <summary>
/// Delete a Configured Form by ID.
/// </summary>
/// <param name="configuredFormId">The Configured Form ID.</param>
void Delete(Guid configuredFormId);
/// <summary>
/// Delete a Configured Form by alias.
/// </summary>
/// <param name="configuredFormAlias">The Configured Form alias.</param>
void Delete(string configuredFormAlias);
/// <summary>
/// Retrieve a Configured Form by ID.
/// </summary>
/// <param name="configuredFormId">The Configured Form ID.</param>
/// <returns>If found a <see cref="ConfiguredForm"/>.</returns>
ConfiguredForm Retrieve(Guid configuredFormId);
/// <summary>
/// Retrieve a Configured Form by alias.
/// </summary>
/// <param name="configuredFormAlias">The Configured Form alias.</param>
/// <returns>If found a <see cref="ConfiguredForm"/>.</returns>
ConfiguredForm Retrieve(string configuredFormAlias);
/// <summary>
/// Retrieve children by their parent ID.
/// </summary>
/// <param name="parentId">
/// The parent id.
/// </param>
/// <returns>
/// If found a collection of <see cref="ConfiguredForm"/>s.
/// </returns>
IEnumerable<ConfiguredForm> RetrieveChildren(Guid parentId);
}
}
| 32.62069 | 80 | 0.585624 | [
"MIT"
] | rhythmagency/formulate | src/formulate.app/Persistence/IConfiguredFormPersistence.cs | 1,894 | C# |
/*
* WebAPI
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: data
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using SwaggerDateConverter = ARXivarNEXT.Client.Client.SwaggerDateConverter;
namespace ARXivarNEXT.Client.Model
{
/// <summary>
/// ServerPluginDto
/// </summary>
[DataContract]
public partial class ServerPluginDto : IEquatable<ServerPluginDto>
{
/// <summary>
/// Initializes a new instance of the <see cref="ServerPluginDto" /> class.
/// </summary>
/// <param name="name">Name.</param>
/// <param name="version">Version.</param>
/// <param name="baseUrl">Url Address.</param>
/// <param name="code">Code.</param>
public ServerPluginDto(string name = default(string), string version = default(string), string baseUrl = default(string), string code = default(string))
{
this.Name = name;
this.Version = version;
this.BaseUrl = baseUrl;
this.Code = code;
}
/// <summary>
/// Name
/// </summary>
/// <value>Name</value>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Version
/// </summary>
/// <value>Version</value>
[DataMember(Name="version", EmitDefaultValue=false)]
public string Version { get; set; }
/// <summary>
/// Url Address
/// </summary>
/// <value>Url Address</value>
[DataMember(Name="baseUrl", EmitDefaultValue=false)]
public string BaseUrl { get; set; }
/// <summary>
/// Code
/// </summary>
/// <value>Code</value>
[DataMember(Name="code", EmitDefaultValue=false)]
public string Code { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ServerPluginDto {\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Version: ").Append(Version).Append("\n");
sb.Append(" BaseUrl: ").Append(BaseUrl).Append("\n");
sb.Append(" Code: ").Append(Code).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as ServerPluginDto);
}
/// <summary>
/// Returns true if ServerPluginDto instances are equal
/// </summary>
/// <param name="input">Instance of ServerPluginDto to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ServerPluginDto input)
{
if (input == null)
return false;
return
(
this.Name == input.Name ||
(this.Name != null &&
this.Name.Equals(input.Name))
) &&
(
this.Version == input.Version ||
(this.Version != null &&
this.Version.Equals(input.Version))
) &&
(
this.BaseUrl == input.BaseUrl ||
(this.BaseUrl != null &&
this.BaseUrl.Equals(input.BaseUrl))
) &&
(
this.Code == input.Code ||
(this.Code != null &&
this.Code.Equals(input.Code))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Name != null)
hashCode = hashCode * 59 + this.Name.GetHashCode();
if (this.Version != null)
hashCode = hashCode * 59 + this.Version.GetHashCode();
if (this.BaseUrl != null)
hashCode = hashCode * 59 + this.BaseUrl.GetHashCode();
if (this.Code != null)
hashCode = hashCode * 59 + this.Code.GetHashCode();
return hashCode;
}
}
}
}
| 32.854545 | 160 | 0.517617 | [
"BSD-3-Clause"
] | Artusoft/ARXivarNEXT.Client | src/ARXivarNEXT.Client/Model/ServerPluginDto.cs | 5,421 | C# |
using cloudscribe.Pagination.Models;
using LanguageBuilder.Data;
using LanguageBuilder.Data.Models;
using LanguageBuilder.Data.Services;
using LanguageBuilder.Services.Contracts;
using LanguageBuilder.Services.Models;
using LanguageBuilder.Services.Models.WordsSearch;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LanguageBuilder.Services.Implementations
{
public class WordsService : BaseRepository<Word, int>, IWordsService
{
private readonly LanguageBuilderDbContext _db;
public WordsService(LanguageBuilderDbContext context)
: base(context)
{
_db = context;
}
public async Task<Word> FindByIdAsync(int id)
{
return await _db
.Words
.Include(w => w.Language)
.Include(w => w.SourceTranslations)
.Include(w => w.TargetTranslations)
.Where(w => w.Id == id && w.IsDeleted == false)
.FirstOrDefaultAsync();
}
public IEnumerable<Word> GetByUser(User user)
{
return _db
.UserWords
.Where(uw => uw.UserId == user.Id)
.Select(uw => uw.Word)
.ToList();
}
public IEnumerable<Word> GetByUserId(string userId)
{
return _db
.UserWords
.Where(uw => uw.UserId == userId)
.Select(uw => uw.Word)
.ToList();
}
public IEnumerable<Word> GetByUserAndLanguage(User user, Language language)
{
return _db
.UserWords
.Where(uw => uw.UserId == user.Id && uw.Word.Language.Id == language.Id)
.Select(uw => uw.Word)
.ToList();
}
public async Task<IEnumerable<Word>> GetByUserAsync(User user)
{
return await this.GetByUserIdAsync(user.Id);
}
public async Task<IEnumerable<Word>> GetByUserIdAsync(string userId)
{
return await _db
.UserWords
.Where(uw => uw.UserId == userId)
.Select(uw => uw.Word)
.ToListAsync();
}
public async Task<Word> SoftDeleteAsync(int id)
{
var word = await _db
.Words
.Where(w => w.Id == id)
.FirstOrDefaultAsync();
if (word != null)
{
word.IsDeleted = true;
await _db.SaveChangesAsync();
}
return word;
}
public async Task<bool> ExistInUserAsync(int id, string userId)
{
return await _db.UserWords.AnyAsync(uw => uw.WordId == id && uw.UserId == userId);
}
public async Task<UserWord> SoftDeleteInUserAsync(int id, string userId)
{
var wordInUser = await _db
.UserWords
.Where(uw => uw.WordId == id && uw.UserId == userId)
.FirstOrDefaultAsync();
if (wordInUser != null)
{
_db.Remove(wordInUser);
await _db.SaveChangesAsync();
}
return wordInUser;
}
public async Task AddWordsWithTranslationWithUserConnectionAsync(Word source, Word target, string userId)
{
if (!await ExistAsync(source.Content)) { _db.Words.Add(source); }
if (!await ExistAsync(target.Content)) { _db.Words.Add(target); }
_db.SaveChanges();
source = await _db.Words.Where(w => w.Content == source.Content).FirstOrDefaultAsync();
target = await _db.Words.Where(w => w.Content == target.Content).FirstOrDefaultAsync();
await _db
.UserWords
.AddAsync(
new UserWord
{
UserId = userId,
WordId = target.Id,
IsTargeted = true
});
await _db
.Translations
.AddAsync(new Translation
{
SourceWordId = source.Id,
TargetWordId = target.Id
});
_db.SaveChanges();
}
public async Task AddWordsWithTranslationAsync(Word source, Word target)
{
await _db
.Words
.AddRangeAsync(new[] { source, target });
await _db
.Translations
.AddAsync(new Translation
{
SourceWordId = source.Id,
TargetWordId = target.Id
});
_db.SaveChanges();
}
public async Task<IEnumerable<Word>> SearchAsync(string keywords, int languageId, int rows = 10)
{
return await _db
.Words
.Where(w => w.Content.Contains(keywords) && w.LanguageId == languageId)
.Take(rows)
.ToListAsync();
}
//public Task AddInUserAsync(Word word, User user)
//{
// throw new NotImplementedException();
//}
public async Task<Response> Search(Request request, SortOptions sortOptions)
{
request.CancellationToken.ThrowIfCancellationRequested();
int offset = (request.PageSize * request.PageNumber) - request.PageSize;
if (offset < 0) { offset = 0; }
var query = _db.Words.AsQueryable();
switch (sortOptions.SortColumn.ToLower())
{
case "content":
query = sortOptions.SortDirection == SortDirection.Ascending
? query.OrderBy(t => t.Content)
: query.OrderByDescending(t => t.Content);
break;
case "gender":
query = sortOptions.SortDirection == SortDirection.Ascending
? query.OrderBy(t => t.Gender)
: query.OrderByDescending(t => t.Gender);
break;
default:
query = sortOptions.SortDirection == SortDirection.Ascending
? query.OrderBy(t => t.Content)
: query.OrderByDescending(t => t.Content);
break;
}
if (request.Keywords != null)
{
query = query.Where(t => t.Content.Contains(request.Keywords.ToLower()));
}
if (request.Filter != null)
{
query = query.Where(request.Filter);
}
if (request.LanguageIds.Any())
{
query = query.Where(w => request.LanguageIds.Contains(w.LanguageId));
}
var totalItems = await query.CountAsync();
query = query
.Select(p => p)
.Skip(offset)
.Take(request.PageSize);
var pagedResult = new PagedResult<Word>
{
Data = await query.AsNoTracking().ToListAsync(request.CancellationToken),
TotalItems = totalItems,
PageNumber = request.PageNumber,
PageSize = request.PageSize
};
var response = new Response()
{
Records = pagedResult,
TotalRecords = totalItems
};
return response;
}
public async Task<bool> ExistAsync(string content)
{
return await _db.Words.AnyAsync(w => w.Content.ToLower() == content.ToLower());
}
}
}
| 31.266932 | 113 | 0.499618 | [
"MIT"
] | peter-stoyanov/ASP.NET-Core-MVC | LanguageBuilder/LanguageBuilder.Services/Implementations/WordsService.cs | 7,850 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Fl8xy.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("00000000000000_CreateIdentitySchema")]
partial class CreateIdentitySchema
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rc3")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Fl8xy.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("Fl8xy.Models.ApplicationUser")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("Fl8xy.Models.ApplicationUser")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Users")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Fl8xy.Models.ApplicationUser")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| 34.308756 | 117 | 0.495097 | [
"MIT"
] | VGGeorgiev/fl8xy | src/Fl8xy/Data/Migrations/00000000000000_CreateIdentitySchema.Designer.cs | 7,447 | C# |
namespace IncidentService.Migrations
{
using Data;
using Data.Helpers;
using System.Data.Entity.Migrations;
internal sealed class Configuration : DbMigrationsConfiguration<IncidentServiceContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(IncidentServiceContext context)
{
TenantConfiguration.Seed(context);
}
}
public class DbConfiguration : System.Data.Entity.DbConfiguration
{
public DbConfiguration()
{
AddInterceptor(new SoftDeleteInterceptor());
}
}
}
| 23.428571 | 91 | 0.637195 | [
"MIT"
] | QuinntyneBrown/IncidentService | Data/Migrations/Configuration.cs | 656 | C# |
//GENERATED: CS Code
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace UnrealEngine{
public partial class UInterpTrackMoveAxis:UInterpTrackFloatBase
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern new IntPtr StaticClass();
}
}
| 26.75 | 65 | 0.806854 | [
"MIT"
] | RobertAcksel/UnrealCS | Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile/UInterpTrackMoveAxis.cs | 321 | C# |
// UrlRewriter - A .NET URL Rewriter module
// Version 2.0
//
// Copyright 2011 Intelligencia
// Copyright 2011 Seth Yates
//
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using Intelligencia.UrlRewriter.Utilities;
namespace Intelligencia.UrlRewriter
{
/// <summary>
/// Replacement for <asp:form> to handle rewritten form postback.
/// </summary>
/// <remarks>
/// <p>This form should be used for pages that use the URL Rewriter and have
/// forms that are posted back. If you use the normal ASP.NET <see cref="System.Web.UI.HtmlControls.HtmlForm">HtmlForm</see>,
/// then the postback will not be able to correctly resolve the postback data to the form data.
/// </p>
/// <p>This form is a direct replacement for the <asp:form> tag.
/// </p>
/// <p>The following code demonstrates the usage of this control.</p>
/// <code>
/// <%@ Page language="c#" Codebehind="MyPage.aspx.cs" AutoEventWireup="false" Inherits="MyPage" %>
/// <%@ Register TagPrefix="url" Namespace="Intelligencia.UrlRewriter" Assembly="Intelligencia.UrlRewriter" %>
/// <html>
/// ...
/// <body>
/// <url:form id="MyForm" runat="server">
/// ...
/// </url:form>
/// </body>
/// </html>
/// </code>
/// </remarks>
[ComVisible(false)]
[ToolboxData("<{0}:Form runat=\"server\"></{0}:Form>")]
public class Form : HtmlForm
{
/// <summary>
/// Renders children of the form control.
/// </summary>
/// <param name="writer">The output writer.</param>
/// <exclude />
protected override void RenderChildren(HtmlTextWriter writer)
{
writer.RenderBeginTag(HtmlTextWriterTag.Div);
base.RenderChildren(writer);
writer.RenderEndTag();
}
/// <summary>
/// Renders attributes.
/// </summary>
/// <param name="writer">The output writer.</param>
/// <exclude />
protected override void RenderAttributes(HtmlTextWriter writer)
{
writer.WriteAttribute(Constants.AttrName, GetName());
Attributes.Remove(Constants.AttrName);
writer.WriteAttribute(Constants.AttrMethod, GetMethod());
Attributes.Remove(Constants.AttrMethod);
writer.WriteAttribute(Constants.AttrAction, GetAction(), true);
Attributes.Remove(Constants.AttrAction);
Attributes.Render(writer);
if (ID != null)
{
writer.WriteAttribute(Constants.AttrID, GetID());
}
}
private string GetID()
{
return ClientID;
}
private string GetName()
{
return Name;
}
private string GetMethod()
{
return Method;
}
private string GetAction()
{
return RewriterHttpModule.RawUrl;
}
}
}
| 31.39604 | 131 | 0.564175 | [
"MIT"
] | sethyates/urlrewriter | src/Form.cs | 3,171 | C# |
using System;
using System.Reflection; //WE NEED THIS
namespace lab_44_assemblies
{
class Program
{
static void Main(string[] args)
{
//use INT type as an example
var myType = typeof(int);
//lets find DLL where INT LIVES IN WINDOWS
//Ie: Assembly
var myAssembly = Assembly.GetAssembly(myType);
Console.WriteLine($"Assembly is called {myAssembly.GetName()}\n\n");
Console.ReadLine();
//check out all other types in the same assembly
//pritn them out
foreach (var type in myAssembly.GetTypes())
{
Console.WriteLine(type);
}
}
}
}
| 28.038462 | 80 | 0.540466 | [
"MIT"
] | TheEletricboy/2019-09-C-sharp-Labs | Labs/lab_44_assemblies/Program.cs | 731 | C# |
namespace EasyConsulClient
{
public class ServiceNode
{
public string Host { get; set; }
public int Port { get; set; }
}
}
| 16.888889 | 40 | 0.578947 | [
"MIT"
] | water1st/EasyConsulClient | src/EasyConsulClient/ServiceNode.cs | 154 | C# |
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D),typeof(Collider2D))]
public class desactiveitor : MonoBehaviour
{
public void Quita()
{
var rb = GetComponent<Rigidbody2D>();
var col = GetComponent<Collider2D>();
if (!rb || !col) return;
rb.simulated = !rb.simulated;
col.isTrigger = !col.isTrigger;
}
}
| 21.647059 | 58 | 0.630435 | [
"MIT"
] | Evolis3d/Cuevana | Assets/Scripts/desactiveitor.cs | 370 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the macie-2017-12-19.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Macie.Model
{
/// <summary>
/// This is the response object from the ListMemberAccounts operation.
/// </summary>
public partial class ListMemberAccountsResponse : AmazonWebServiceResponse
{
private List<MemberAccount> _memberAccounts = new List<MemberAccount>();
private string _nextToken;
/// <summary>
/// Gets and sets the property MemberAccounts.
/// <para>
/// A list of the Amazon Macie member accounts returned by the action. The current master
/// account is also included in this list.
/// </para>
/// </summary>
public List<MemberAccount> MemberAccounts
{
get { return this._memberAccounts; }
set { this._memberAccounts = value; }
}
// Check to see if MemberAccounts property is set
internal bool IsSetMemberAccounts()
{
return this._memberAccounts != null && this._memberAccounts.Count > 0;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// When a response is generated, if there is more data to be listed, this parameter is
/// present in the response and contains the value to use for the nextToken parameter
/// in a subsequent pagination request. If there is no more data to be listed, this parameter
/// is set to null.
/// </para>
/// </summary>
[AWSProperty(Max=500)]
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
}
} | 33.259259 | 103 | 0.638456 | [
"Apache-2.0"
] | SVemulapalli/aws-sdk-net | sdk/src/Services/Macie/Generated/Model/ListMemberAccountsResponse.cs | 2,694 | C# |
namespace Pure.NetCoreExtensions
{
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
/// <summary>
/// Requires that a HTTP request does not contain a trailing slash. If it does, return a 404 Not Found. This is
/// useful if you are dynamically generating something which acts like it's a file on the web server.
/// E.g. /Robots.txt/ should not have a trailing slash and should be /Robots.txt. Note, that we also don't care if
/// it is upper-case or lower-case in this instance.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public class NoTrailingSlashAttribute : Attribute, IResourceFilter
{
private const char SlashCharacter = '/';
/// <summary>
/// Executes the resource filter. Called after execution of the remainder of the pipeline.
/// </summary>
/// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ResourceExecutedContext" />.</param>
public void OnResourceExecuted(ResourceExecutedContext context)
{
}
/// <summary>
/// Executes the resource filter. Called before execution of the remainder of the pipeline. Determines whether
/// a request contains a trailing slash and, if it does, calls the <see cref="HandleTrailingSlashRequest"/>
/// method.
/// </summary>
/// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ResourceExecutingContext" />.</param>
public void OnResourceExecuting(ResourceExecutingContext context)
{
var path = context.HttpContext.Request.Path;
if (path.HasValue)
{
if (path.Value[path.Value.Length - 1] == SlashCharacter)
{
this.HandleTrailingSlashRequest(context);
}
}
}
/// <summary>
/// Handles HTTP requests that have a trailing slash but are not meant to.
/// </summary>
/// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ResourceExecutingContext" />.</param>
protected virtual void HandleTrailingSlashRequest(ResourceExecutingContext context) =>
context.Result = new NotFoundResult();
}
} | 46.529412 | 121 | 0.645596 | [
"MIT"
] | purestackorg/Pure.NETCoreExtensions | Pure.NetCoreExtensions/Mvc/Filters/NoTrailingSlashAttribute.cs | 2,373 | C# |
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Abp.Configuration;
using Abp.Localization;
using Abp.MultiTenancy;
using Abp.Net.Mail;
namespace ThuHoach.EntityFrameworkCore.Seed.Host
{
public class DefaultSettingsCreator
{
private readonly ThuHoachDbContext _context;
public DefaultSettingsCreator(ThuHoachDbContext context)
{
_context = context;
}
public void Create()
{
int? tenantId = null;
if (ThuHoachConsts.MultiTenancyEnabled == false)
{
tenantId = MultiTenancyConsts.DefaultTenantId;
}
// Emailing
AddSettingIfNotExists(EmailSettingNames.DefaultFromAddress, "admin@mydomain.com", tenantId);
AddSettingIfNotExists(EmailSettingNames.DefaultFromDisplayName, "mydomain.com mailer", tenantId);
// Languages
AddSettingIfNotExists(LocalizationSettingNames.DefaultLanguage, "en", tenantId);
}
private void AddSettingIfNotExists(string name, string value, int? tenantId = null)
{
if (_context.Settings.IgnoreQueryFilters().Any(s => s.Name == name && s.TenantId == tenantId && s.UserId == null))
{
return;
}
_context.Settings.Add(new Setting(tenantId, null, name, value));
_context.SaveChanges();
}
}
}
| 29.770833 | 126 | 0.624213 | [
"MIT"
] | nguyenvanchuong98/thuhoach | aspnet-core/src/ThuHoach.EntityFrameworkCore/EntityFrameworkCore/Seed/Host/DefaultSettingsCreator.cs | 1,431 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.OperationalInsights.Models;
using Microsoft.Azure.Management.OperationalInsights;
using Microsoft.Azure.Management.OperationalInsights.Models;
using Microsoft.Rest;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Net;
using Microsoft.Azure.Commands.OperationalInsights.Properties;
namespace Microsoft.Azure.Commands.OperationalInsights.Client
{
public partial class OperationalInsightsClient
{
public virtual List<PSDataExport> FilterPSDataExports(string resourceGroupName, string workspaceName, string dataExportName = null)
{
List<PSDataExport> dataExports = new List<PSDataExport>();
if (!string.IsNullOrWhiteSpace(dataExportName))
{
if (string.IsNullOrWhiteSpace(resourceGroupName))
{
throw new PSArgumentException(Resources.ResourceGroupNameCannotBeEmpty);
}
dataExports.Add(GetPSDataExport(resourceGroupName, workspaceName, dataExportName));
}
else
{
dataExports.AddRange(ListPSDataExports(resourceGroupName, workspaceName));
}
return dataExports;
}
public virtual PSDataExport GetPSDataExport(string resourceGroupName, string workspaceName, string dataExportName)
{
return new PSDataExport(OperationalInsightsManagementClient.DataExports.Get(resourceGroupName, workspaceName, dataExportName));
}
public virtual List<PSDataExport> ListPSDataExports(string resourceGroupName, string workspaceName)
{
List<PSDataExport> dataExports = new List<PSDataExport>();
var responseDataExports = OperationalInsightsManagementClient.DataExports.ListByWorkspace(resourceGroupName, workspaceName);
if (responseDataExports != null)
{
dataExports.AddRange(from DataExport dataExport in responseDataExports select new PSDataExport(dataExport));
}
return dataExports;
}
public virtual PSDataExport CreateDataExport(string resourceGroupName, CreatePSDataExportParameters parameters)
{
PSDataExport existingDataExport;
try
{
existingDataExport = GetPSDataExport(resourceGroupName, parameters.WorkspaceName, parameters.DataExportName);
}
catch (RestException)
{
existingDataExport = null;
}
if (existingDataExport != null)
{
throw new PSInvalidOperationException(string.Format("DataExport: '{0}' already exists in workspace '{1}'. Please use Update-AzOperationalInsightsDataExport for updating.", parameters.DataExportName, parameters.WorkspaceName));
}
return new PSDataExport(OperationalInsightsManagementClient.DataExports.CreateOrUpdate(
resourceGroupName: resourceGroupName,
workspaceName: parameters.WorkspaceName,
dataExportName: parameters.DataExportName,
parameters: PSDataExport.getDataExport(parameters)));
}
public virtual PSDataExport UpdateDataExport(string resourceGroupName, CreatePSDataExportParameters parameters)
{
PSDataExport existingDataExport;
try
{
existingDataExport = GetPSDataExport(resourceGroupName, parameters.WorkspaceName, parameters.DataExportName);
}
catch (RestException)
{
throw new PSArgumentException($"Data export {parameters.DataExportName} under resourceGroup {resourceGroupName} worspace:{parameters.WorkspaceName} does not exist, please use 'New-AzOperationalInsightsDataExport' instead.");
}
//validate user input parameters were not null - if they were then use existing values so they wont be ran over by null values
parameters.TableNames = parameters.TableNames ?? existingDataExport.TableNames;
parameters.DestinationResourceId = parameters.DestinationResourceId ?? existingDataExport.ResourceId;
parameters.EventHubName = parameters.EventHubName ?? existingDataExport.EventHubName;
parameters.Enable = parameters.Enable ?? existingDataExport.Enable;
return new PSDataExport(OperationalInsightsManagementClient.DataExports.CreateOrUpdate(
resourceGroupName: resourceGroupName,
workspaceName: parameters.WorkspaceName,
dataExportName: parameters.DataExportName,
parameters: PSDataExport.getDataExport(parameters)));
}
public virtual HttpStatusCode DeleteDataExports(string resourceGroupName, string workspaceName, string dataExportName)
{
Rest.Azure.AzureOperationResponse result = OperationalInsightsManagementClient.DataExports.DeleteWithHttpMessagesAsync(resourceGroupName, workspaceName, dataExportName).GetAwaiter().GetResult();
return result.Response.StatusCode;
}
}
}
| 47.748031 | 243 | 0.662434 | [
"MIT"
] | Agazoth/azure-powershell | src/OperationalInsights/OperationalInsights/Client/OperationalInsightsClient.DataExports.cs | 5,940 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Charlotte.Games
{
public static class GameCommon
{
// none
}
}
| 12.769231 | 33 | 0.746988 | [
"MIT"
] | soleil-taruto/Elsa | e20201129_StealGunner/Elsa20200001/Elsa20200001/Games/GameCommon.cs | 168 | C# |
/********************************************************************************
* Module : Lapis.Math.Algebra
* Class : Pattern
* Description : Provides methods for pattern matching for algebraic expressions.
* Created : 2015/4/6
* Note :
*********************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lapis.Math.Algebra.Expressions;
using Lapis.Math.Numbers;
namespace Lapis.Math.Algebra.Arithmetics
{
/// <summary>
/// Provides methods for pattern matching for algebraic expressions.
/// </summary>
public static partial class Pattern
{
/// <summary>
/// Returns a value that indicates whether the algebraic expression is an integer.
/// </summary>
/// <param name="expression">The algebraic expression.</param>
/// <param name="integer">When this method returns, contains the integer that <paramref name="expression"/> represents. This parameter is passed uninitialized; any value originally supplied in <paramref name="integer"/> will be overwritten.</param>
/// <returns><see langword="true"/> if <paramref name="expression"/> represents an integer; otherwise, <see langword="false"/>.</returns>
/// <exception cref="ArgumentNullException">The parameter is <see langword="null"/>.</exception>
public static bool IsInteger(this Expression expression, out Integer integer)
{
if (expression == null)
throw new ArgumentNullException();
if (expression is Number)
{
Real num = (Real)(Number)expression;
if (num is Integer)
{
integer = (Integer)num;
return true;
}
}
integer = null;
return false;
}
/// <summary>
/// Returns a value that indicates whether the algebraic expression is a rational number.
/// </summary>
/// <param name="expression">The algebraic expression.</param>
/// <param name="rational">When this method returns, contains the rational number that <paramref name="expression"/> represents. This parameter is passed uninitialized; any value originally supplied in <paramref name="rational"/> will be overwritten.</param>
/// <returns><see langword="true"/> if <paramref name="expression"/> represents a rational number; otherwise, <see langword="false"/>.</returns>
/// <exception cref="ArgumentNullException">The parameter is <see langword="null"/>.</exception>
public static bool IsRational(this Expression expression, out Rational rational)
{
if (expression == null)
throw new ArgumentNullException();
if (expression is Number)
{
Real num = (Real)(Number)expression;
if (num is Rational)
{
rational = (Rational)num;
return true;
}
}
rational = null;
return false;
}
/// <summary>
/// Returns a value that indicates whether the algebraic expression is a positive integer exponentiation.
/// </summary>
/// <param name="expression">The algebraic expression.</param>
/// <param name="base">When this method returns, contains the base of the exponential expression. This parameter is passed uninitialized; any value originally supplied in <paramref name="base"/> will be overwritten.</param>
/// <param name="exponent">When this method returns, contains the exponent of the exponential expression. This parameter is passed uninitialized; any value originally supplied in <paramref name="exponent"/> will be overwritten.</param>
/// <returns><see langword="true"/> if <paramref name="expression"/> represents a positive integer exponentiation; otherwise, <see langword="false"/>.</returns>
/// <exception cref="ArgumentNullException">The parameter is <see langword="null"/>.</exception>
public static bool IsPositiveIntegerPower(this Expression expression,
out Expression @base, out Integer exponent)
{
if (expression == null)
throw new ArgumentNullException();
if (expression is Power)
{
var power = (Power)expression;
Integer integer;
if (power.Exponent.IsInteger(out integer))
{
if (integer.Sign > 0)
{
@base = power.Base;
exponent = integer;
return true;
}
}
}
@base = null;
exponent = null;
return false;
}
/// <summary>
/// Returns a value that indicates whether the algebraic expression is a negative integer exponentiation.
/// </summary>
/// <param name="expression">The algebraic expression.</param>
/// <param name="base">When this method returns, contains the base of the exponential expression. This parameter is passed uninitialized; any value originally supplied in <paramref name="base"/> will be overwritten.</param>
/// <param name="exponent">When this method returns, contains the exponent of the exponential expression. This parameter is passed uninitialized; any value originally supplied in <paramref name="exponent"/> will be overwritten.</param>
/// <returns><see langword="true"/> if <paramref name="expression"/> represents a negative integer exponentiation; otherwise, <see langword="false"/>.</returns>
/// <exception cref="ArgumentNullException">The parameter is <see langword="null"/>.</exception>
public static bool IsNegativeIntegerPower(this Expression expression,
out Expression @base, out Integer exponent)
{
if (expression == null)
throw new ArgumentNullException();
if (expression is Power)
{
var power = (Power)expression;
Integer integer;
if (power.Exponent.IsInteger(out integer))
{
if (integer.Sign < 0)
{
@base = power.Base;
exponent = integer;
return true;
}
}
}
@base = null;
exponent = null;
return false;
}
/// <summary>
/// Returns a value that indicates whether the algebraic expression is a negative rational exponentiation.
/// </summary>
/// <param name="expression">The algebraic expression.</param>
/// <param name="base">When this method returns, contains the base of the exponential expression. This parameter is passed uninitialized; any value originally supplied in <paramref name="base"/> will be overwritten.</param>
/// <param name="exponent">When this method returns, contains the exponent of the exponential expression. This parameter is passed uninitialized; any value originally supplied in <paramref name="exponent"/> will be overwritten.</param>
/// <returns><see langword="true"/> if <paramref name="expression"/> represents a negative rational exponentiation; otherwise, <see langword="false"/>.</returns>
/// <exception cref="ArgumentNullException">The parameter is <see langword="null"/>.</exception>
public static bool IsNegativeRationalPower(this Expression expression,
out Expression @base, out Rational exponent)
{
if (expression == null)
throw new ArgumentNullException();
if (expression is Power)
{
var power = (Power)expression;
Rational rational;
if (power.Exponent.IsRational(out rational))
{
if (rational.Sign < 0)
{
@base = power.Base;
exponent = rational;
return true;
}
}
}
@base = null;
exponent = null;
return false;
}
}
}
| 50.473373 | 266 | 0.571864 | [
"MIT"
] | LapisDev/LapisMath | src/Lapis.Math.Algebra/Arithmetics/Pattern.cs | 8,536 | C# |
#pragma checksum "D:\SoftUni\TrendTexErpAndClient\TrendTex.Core\TrendTex.Core\Areas\Identity\Pages\Account\ConfirmEmail.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "69fd2432bd09e377aec34c04642364485eee4a7d"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Areas_Identity_Pages_Account_ConfirmEmail), @"mvc.1.0.razor-page", @"/Areas/Identity/Pages/Account/ConfirmEmail.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "D:\SoftUni\TrendTexErpAndClient\TrendTex.Core\TrendTex.Core\Areas\Identity\Pages\_ViewImports.cshtml"
using Microsoft.AspNetCore.Identity;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "D:\SoftUni\TrendTexErpAndClient\TrendTex.Core\TrendTex.Core\Areas\Identity\Pages\_ViewImports.cshtml"
using TrendTex.Web.Areas.Identity;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "D:\SoftUni\TrendTexErpAndClient\TrendTex.Core\TrendTex.Core\Areas\Identity\Pages\_ViewImports.cshtml"
using TrendTex.Web.Areas.Identity.Pages;
#line default
#line hidden
#nullable disable
#nullable restore
#line 1 "D:\SoftUni\TrendTexErpAndClient\TrendTex.Core\TrendTex.Core\Areas\Identity\Pages\Account\_ViewImports.cshtml"
using TrendTex.Web.Areas.Identity.Pages.Account;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"69fd2432bd09e377aec34c04642364485eee4a7d", @"/Areas/Identity/Pages/Account/ConfirmEmail.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"241ed5db073c1d69dd06b3fdf94838e1bd775124", @"/Areas/Identity/Pages/_ViewImports.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"b4a723c86a65352ec47e30a47491545342d0ad8a", @"/Areas/Identity/Pages/Account/_ViewImports.cshtml")]
public class Areas_Identity_Pages_Account_ConfirmEmail : global::Microsoft.AspNetCore.Mvc.RazorPages.Page
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#nullable restore
#line 3 "D:\SoftUni\TrendTexErpAndClient\TrendTex.Core\TrendTex.Core\Areas\Identity\Pages\Account\ConfirmEmail.cshtml"
ViewData["Title"] = "Confirm email";
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n<h1>");
#nullable restore
#line 7 "D:\SoftUni\TrendTexErpAndClient\TrendTex.Core\TrendTex.Core\Areas\Identity\Pages\Account\ConfirmEmail.cshtml"
Write(ViewData["Title"]);
#line default
#line hidden
#nullable disable
WriteLiteral("</h1>");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<ConfirmEmailModel> Html { get; private set; }
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<ConfirmEmailModel> ViewData => (global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<ConfirmEmailModel>)PageContext?.ViewData;
public ConfirmEmailModel Model => ViewData.Model;
}
}
#pragma warning restore 1591
| 49.729412 | 220 | 0.784008 | [
"MIT"
] | kalinailieva/BeeTexERP | TrendTex.Core/TrendTex.Core/obj/Debug/net5.0/Razor/Areas/Identity/Pages/Account/ConfirmEmail.cshtml.g.cs | 4,227 | C# |
// Copyright 2017 the original author or authors.
//
// 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 Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using Xunit;
namespace Steeltoe.Extensions.Configuration.ConfigServer.Test
{
public class ConfigServerDiscoveryServiceTest
{
[Fact]
public void FindGetInstancesMethod_FindsMethod()
{
var values = new Dictionary<string, string>()
{
{ "eureka:client:serviceUrl", "http://localhost:8761/eureka/" }
};
var builder = new ConfigurationBuilder();
builder.AddInMemoryCollection(values);
var config = builder.Build();
var settings = new ConfigServerClientSettings();
var service = new ConfigServerDiscoveryService(config, settings);
Assert.NotNull(service.FindGetInstancesMethod());
}
[Fact]
public void InvokeGetInstances_ReturnsExpected()
{
var values = new Dictionary<string, string>()
{
{ "eureka:client:serviceUrl", "http://localhost:8761/eureka/" }
};
var builder = new ConfigurationBuilder();
builder.AddInMemoryCollection(values);
var config = builder.Build();
var settings = new ConfigServerClientSettings();
var service = new ConfigServerDiscoveryService(config, settings);
var method = service.FindGetInstancesMethod();
var result = service.InvokeGetInstances(method);
Assert.Empty(result);
}
[Fact]
public void InvokeGetInstances_RetryEnabled_ReturnsExpected()
{
var values = new Dictionary<string, string>()
{
{ "eureka:client:serviceUrl", "http://foo.bar:8761/eureka/" }
};
var builder = new ConfigurationBuilder();
builder.AddInMemoryCollection(values);
var config = builder.Build();
var settings = new ConfigServerClientSettings()
{
RetryEnabled = true
};
var service = new ConfigServerDiscoveryService(config, settings);
var method = service.FindGetInstancesMethod();
var result = service.InvokeGetInstances(method);
Assert.Empty(result);
}
[Fact]
public void GetConfigServerInstances_ReturnsExpected()
{
var values = new Dictionary<string, string>()
{
{ "eureka:client:serviceUrl", "http://localhost:8761/eureka/" }
};
var builder = new ConfigurationBuilder();
builder.AddInMemoryCollection(values);
var config = builder.Build();
var settings = new ConfigServerClientSettings();
var service = new ConfigServerDiscoveryService(config, settings);
var result = service.GetConfigServerInstances();
Assert.Empty(result);
}
}
}
| 36.680412 | 79 | 0.615795 | [
"ECL-2.0",
"Apache-2.0"
] | kyegupov/Configuration | test/Steeltoe.Extensions.Configuration.ConfigServerBase.Test/ConfigServerDiscoveryServiceTest.cs | 3,560 | C# |
namespace SuperShopMainV1._00
{
partial class adminReport
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(adminReport));
this.AdminDashboardPanel = new System.Windows.Forms.Panel();
this.Reports = new System.Windows.Forms.Button();
this.logoutbutton = new System.Windows.Forms.Button();
this.RemonveProduct = new System.Windows.Forms.Button();
this.Inventory = new System.Windows.Forms.Button();
this.clubdashboardpicbox = new System.Windows.Forms.PictureBox();
this.ReportAdmin = new System.Windows.Forms.Panel();
this.datelabel = new System.Windows.Forms.Label();
this.SalesReport = new System.Windows.Forms.DateTimePicker();
this.dgvReport = new System.Windows.Forms.DataGridView();
this.REPORT_ID = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.MONTH = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.PROFIT = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Rportinventorybtn = new System.Windows.Forms.Button();
this.superShopMSDBDataSet2 = new SuperShopMainV1._00.SuperShopMSDBDataSet2();
this.superShopMSDBDataSet2BindingSource = new System.Windows.Forms.BindingSource(this.components);
this.AdminDashboardPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.clubdashboardpicbox)).BeginInit();
this.ReportAdmin.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dgvReport)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.superShopMSDBDataSet2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.superShopMSDBDataSet2BindingSource)).BeginInit();
this.SuspendLayout();
//
// AdminDashboardPanel
//
this.AdminDashboardPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(70)))), ((int)(((byte)(51)))), ((int)(((byte)(76)))));
this.AdminDashboardPanel.Controls.Add(this.Reports);
this.AdminDashboardPanel.Controls.Add(this.logoutbutton);
this.AdminDashboardPanel.Controls.Add(this.RemonveProduct);
this.AdminDashboardPanel.Controls.Add(this.Inventory);
this.AdminDashboardPanel.Dock = System.Windows.Forms.DockStyle.Left;
this.AdminDashboardPanel.Location = new System.Drawing.Point(0, 0);
this.AdminDashboardPanel.Name = "AdminDashboardPanel";
this.AdminDashboardPanel.Size = new System.Drawing.Size(177, 749);
this.AdminDashboardPanel.TabIndex = 4;
//
// Reports
//
this.Reports.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
this.Reports.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(36)))), ((int)(((byte)(77)))), ((int)(((byte)(77)))));
this.Reports.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.Reports.Font = new System.Drawing.Font("Microsoft JhengHei UI", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Reports.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
this.Reports.Location = new System.Drawing.Point(12, 147);
this.Reports.Name = "Reports";
this.Reports.Size = new System.Drawing.Size(150, 47);
this.Reports.TabIndex = 3;
this.Reports.Text = "Reports";
this.Reports.UseVisualStyleBackColor = true;
this.Reports.Click += new System.EventHandler(this.Reports_Click);
//
// logoutbutton
//
this.logoutbutton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.logoutbutton.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
this.logoutbutton.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(36)))), ((int)(((byte)(77)))), ((int)(((byte)(77)))));
this.logoutbutton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.logoutbutton.Font = new System.Drawing.Font("Microsoft JhengHei UI", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.logoutbutton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
this.logoutbutton.Location = new System.Drawing.Point(12, 673);
this.logoutbutton.Name = "logoutbutton";
this.logoutbutton.Size = new System.Drawing.Size(150, 40);
this.logoutbutton.TabIndex = 2;
this.logoutbutton.Text = "Logout";
this.logoutbutton.UseVisualStyleBackColor = true;
this.logoutbutton.Click += new System.EventHandler(this.logoutbutton_Click);
//
// RemonveProduct
//
this.RemonveProduct.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
this.RemonveProduct.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(36)))), ((int)(((byte)(77)))), ((int)(((byte)(77)))));
this.RemonveProduct.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.RemonveProduct.Font = new System.Drawing.Font("Microsoft JhengHei UI", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.RemonveProduct.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
this.RemonveProduct.Location = new System.Drawing.Point(12, 83);
this.RemonveProduct.Name = "RemonveProduct";
this.RemonveProduct.Size = new System.Drawing.Size(150, 47);
this.RemonveProduct.TabIndex = 1;
this.RemonveProduct.Text = "Delete Product";
this.RemonveProduct.UseVisualStyleBackColor = true;
this.RemonveProduct.Click += new System.EventHandler(this.RemonveProduct_Click);
//
// Inventory
//
this.Inventory.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
this.Inventory.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(36)))), ((int)(((byte)(77)))), ((int)(((byte)(77)))));
this.Inventory.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.Inventory.Font = new System.Drawing.Font("Microsoft JhengHei UI", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Inventory.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
this.Inventory.Location = new System.Drawing.Point(12, 21);
this.Inventory.Name = "Inventory";
this.Inventory.Size = new System.Drawing.Size(150, 47);
this.Inventory.TabIndex = 0;
this.Inventory.Text = "Add Products";
this.Inventory.UseVisualStyleBackColor = true;
this.Inventory.Click += new System.EventHandler(this.Inventory_Click);
//
// clubdashboardpicbox
//
this.clubdashboardpicbox.BackColor = System.Drawing.Color.Transparent;
this.clubdashboardpicbox.Dock = System.Windows.Forms.DockStyle.Top;
this.clubdashboardpicbox.Image = global::SuperShopMainV1._00.Properties.Resources.shoplogo1;
this.clubdashboardpicbox.Location = new System.Drawing.Point(177, 0);
this.clubdashboardpicbox.Name = "clubdashboardpicbox";
this.clubdashboardpicbox.Size = new System.Drawing.Size(817, 105);
this.clubdashboardpicbox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
this.clubdashboardpicbox.TabIndex = 5;
this.clubdashboardpicbox.TabStop = false;
this.clubdashboardpicbox.UseWaitCursor = true;
//
// ReportAdmin
//
this.ReportAdmin.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ReportAdmin.BackColor = System.Drawing.SystemColors.ActiveCaption;
this.ReportAdmin.Controls.Add(this.datelabel);
this.ReportAdmin.Controls.Add(this.SalesReport);
this.ReportAdmin.Location = new System.Drawing.Point(203, 122);
this.ReportAdmin.Name = "ReportAdmin";
this.ReportAdmin.Size = new System.Drawing.Size(779, 58);
this.ReportAdmin.TabIndex = 21;
//
// datelabel
//
this.datelabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.datelabel.AutoSize = true;
this.datelabel.Font = new System.Drawing.Font("Microsoft JhengHei UI", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.datelabel.Location = new System.Drawing.Point(548, 24);
this.datelabel.Name = "datelabel";
this.datelabel.Size = new System.Drawing.Size(101, 17);
this.datelabel.TabIndex = 7;
this.datelabel.Text = "Report Month :";
//
// SalesReport
//
this.SalesReport.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.SalesReport.CustomFormat = "MMMM";
this.SalesReport.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
this.SalesReport.Location = new System.Drawing.Point(649, 21);
this.SalesReport.Name = "SalesReport";
this.SalesReport.ShowUpDown = true;
this.SalesReport.Size = new System.Drawing.Size(121, 21);
this.SalesReport.TabIndex = 1;
//
// dgvReport
//
this.dgvReport.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dgvReport.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
this.dgvReport.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells;
this.dgvReport.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvReport.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.REPORT_ID,
this.MONTH,
this.PROFIT});
this.dgvReport.Location = new System.Drawing.Point(203, 284);
this.dgvReport.Name = "dgvReport";
this.dgvReport.Size = new System.Drawing.Size(779, 313);
this.dgvReport.TabIndex = 22;
//
// REPORT_ID
//
this.REPORT_ID.DataPropertyName = "REPORT_ID";
this.REPORT_ID.HeaderText = "REPORT_ID";
this.REPORT_ID.Name = "REPORT_ID";
//
// MONTH
//
this.MONTH.DataPropertyName = "MONTH";
this.MONTH.HeaderText = "MONTH";
this.MONTH.Name = "MONTH";
//
// PROFIT
//
this.PROFIT.DataPropertyName = "PROFIT";
this.PROFIT.HeaderText = "PROFIT";
this.PROFIT.Name = "PROFIT";
//
// Rportinventorybtn
//
this.Rportinventorybtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.Rportinventorybtn.BackColor = System.Drawing.Color.PaleTurquoise;
this.Rportinventorybtn.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.Rportinventorybtn.Font = new System.Drawing.Font("Microsoft JhengHei UI", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Rportinventorybtn.ForeColor = System.Drawing.Color.Black;
this.Rportinventorybtn.Location = new System.Drawing.Point(817, 220);
this.Rportinventorybtn.Name = "Rportinventorybtn";
this.Rportinventorybtn.Size = new System.Drawing.Size(165, 38);
this.Rportinventorybtn.TabIndex = 23;
this.Rportinventorybtn.Text = "Show Report\r\n";
this.Rportinventorybtn.UseVisualStyleBackColor = false;
this.Rportinventorybtn.Click += new System.EventHandler(this.Rportinventorybtn_Click_1);
//
// superShopMSDBDataSet2
//
this.superShopMSDBDataSet2.DataSetName = "SuperShopMSDBDataSet2";
this.superShopMSDBDataSet2.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// superShopMSDBDataSet2BindingSource
//
this.superShopMSDBDataSet2BindingSource.DataSource = this.superShopMSDBDataSet2;
this.superShopMSDBDataSet2BindingSource.Position = 0;
//
// adminReport
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 14F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackgroundImage = global::SuperShopMainV1._00.Properties.Resources.background1;
this.ClientSize = new System.Drawing.Size(994, 749);
this.Controls.Add(this.Rportinventorybtn);
this.Controls.Add(this.dgvReport);
this.Controls.Add(this.ReportAdmin);
this.Controls.Add(this.clubdashboardpicbox);
this.Controls.Add(this.AdminDashboardPanel);
this.Font = new System.Drawing.Font("Microsoft JhengHei UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MinimumSize = new System.Drawing.Size(1010, 736);
this.Name = "adminReport";
this.Text = "Report";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.AdminDashboardPanel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.clubdashboardpicbox)).EndInit();
this.ReportAdmin.ResumeLayout(false);
this.ReportAdmin.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dgvReport)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.superShopMSDBDataSet2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.superShopMSDBDataSet2BindingSource)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel AdminDashboardPanel;
private System.Windows.Forms.Button Reports;
private System.Windows.Forms.Button logoutbutton;
private System.Windows.Forms.Button RemonveProduct;
private System.Windows.Forms.Button Inventory;
private System.Windows.Forms.PictureBox clubdashboardpicbox;
private System.Windows.Forms.Panel ReportAdmin;
private System.Windows.Forms.Label datelabel;
private System.Windows.Forms.DateTimePicker SalesReport;
private System.Windows.Forms.DataGridView dgvReport;
private System.Windows.Forms.Button Rportinventorybtn;
private System.Windows.Forms.BindingSource superShopMSDBDataSet2BindingSource;
private SuperShopMSDBDataSet2 superShopMSDBDataSet2;
private System.Windows.Forms.DataGridViewTextBoxColumn REPORT_ID;
private System.Windows.Forms.DataGridViewTextBoxColumn MONTH;
private System.Windows.Forms.DataGridViewTextBoxColumn PROFIT;
}
} | 62.014085 | 177 | 0.639337 | [
"MIT"
] | NAI-Inc/SuperShopV1.00-BETA | SuperShopMainV1.00_BETA/SuperShopMainV1.00/ui_ux Desingn/adminReport.Designer.cs | 17,614 | C# |
//
// Touches_ClassicViewController.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2011 Xamarin <http://xamarin.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;
using System.Drawing;
using System.Linq;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
namespace Touches_Classic
{
public partial class Touches_ClassicViewController : UIViewController
{
UIWindow window;
public Touches_ClassicViewController (UIWindow window, string nibName, NSBundle bundle) : base (nibName, bundle)
{
this.window = window;
}
protected override void Dispose (bool disposing)
{
base.Dispose (disposing);
// Release images
firstImage.Dispose ();
secondImage.Dispose ();
thirdImage.Dispose ();
// Release labels
touchInfoLabel.Dispose ();
touchPhaseLabel.Dispose ();
touchInstructionLabel.Dispose ();
touchTrackingLabel.Dispose ();
}
#region Touch handling
bool piecesOnTop;
public override void TouchesBegan (NSSet touchesSet, UIEvent evt)
{
var touches = touchesSet.ToArray<UITouch> ();
touchPhaseLabel.Text = "Phase:Touches began";
touchInfoLabel.Text = "";
var numTaps = touches.Sum (t => t.TapCount);
if (numTaps >= 2){
touchInfoLabel.Text = string.Format ("{0} taps", numTaps);
if (numTaps == 2 && piecesOnTop) {
// recieved double tap -> align the three pieces diagonal.
if (firstImage.Center.X == secondImage.Center.X)
secondImage.Center = new PointF (firstImage.Center.X - 50, firstImage.Center.Y - 50);
if (firstImage.Center.X == thirdImage.Center.X)
thirdImage.Center = new PointF (firstImage.Center.X + 50, firstImage.Center.Y + 50);
if (secondImage.Center.X == thirdImage.Center.X)
thirdImage.Center = new PointF (secondImage.Center.X + 50, secondImage.Center.Y + 50);
touchInstructionLabel.Text = "";
}
} else {
touchTrackingLabel.Text = "";
}
foreach (var touch in touches) {
// Send to the dispatch method, which will make sure the appropriate subview is acted upon
DispatchTouchAtPoint (touch.LocationInView (window));
}
}
// Checks which image the point is in & performs the opening animation (which makes the image a bit larger)
void DispatchTouchAtPoint (PointF touchPoint)
{
if (firstImage.Frame.Contains (touchPoint))
AnimateTouchDownAtPoint (firstImage, touchPoint);
if (secondImage.Frame.Contains (touchPoint))
AnimateTouchDownAtPoint (secondImage, touchPoint);
if (thirdImage.Frame.Contains (touchPoint))
AnimateTouchDownAtPoint (thirdImage, touchPoint);
}
// Handles the continuation of a touch
public override void TouchesMoved (NSSet touchesSet, UIEvent evt)
{
var touches = touchesSet.ToArray<UITouch> ();
touchPhaseLabel.Text = "Phase: Touches moved";
foreach (var touch in touches) {
// Send to the dispatch touch method, which ensures that the image is moved
DispatchTouchEvent (touch.View, touch.LocationInView (window));
}
// When multiple touches, report the number of touches.
if (touches.Length > 1) {
touchTrackingLabel.Text = string.Format ("Tracking {0} touches", touches.Length);
} else {
touchTrackingLabel.Text = "Tracking 1 touch";
}
}
// Checks to see which view is touch point is in and sets the center of the moved view to the new position.
void DispatchTouchEvent (UIView theView, PointF touchPoint)
{
if (firstImage.Frame.Contains (touchPoint))
firstImage.Center = touchPoint;
if (secondImage.Frame.Contains (touchPoint))
secondImage.Center = touchPoint;
if (thirdImage.Frame.Contains (touchPoint))
thirdImage.Center = touchPoint;
}
public override void TouchesEnded (NSSet touchesSet, UIEvent evt)
{
touchPhaseLabel.Text = "Phase: Touches ended";
foreach (var touch in touchesSet.ToArray<UITouch> ()) {
DispatchTouchEndEvent (touch.View, touch.LocationInView (window));
}
}
// Puts back the images to their original size
void DispatchTouchEndEvent (UIView theView, PointF touchPoint)
{
if (firstImage.Frame.Contains (touchPoint))
AnimateTouchUpAtPoint (firstImage, touchPoint);
if (secondImage.Frame.Contains (touchPoint))
AnimateTouchUpAtPoint (secondImage, touchPoint);
if (thirdImage.Frame.Contains (touchPoint))
AnimateTouchUpAtPoint (thirdImage, touchPoint);
// If one piece obscures another, display a message so the user can move the pieces apart
piecesOnTop = firstImage.Center == secondImage.Center ||
firstImage.Center == thirdImage.Center ||
secondImage.Center == thirdImage.Center;
if (piecesOnTop)
touchInstructionLabel.Text = @"Double tap the background to move the pieces apart.";
}
public override void TouchesCancelled (NSSet touchesSet, UIEvent evt)
{
touchPhaseLabel.Text = "Phase: Touches cancelled";
foreach (var touch in touchesSet.ToArray<UITouch> ()) {
DispatchTouchEndEvent (touch.View, touch.LocationInView (window));
}
}
#endregion
#region Animating subviews
const double GROW_ANIMATION_DURATION_SECONDS = 0.15;
const double SHRINK_ANIMATION_DURATION_SECONDS = 0.15;
// Scales up a image slightly
void AnimateTouchDownAtPoint (UIImageView theView, PointF touchPoint)
{
theView.AnimationDuration = GROW_ANIMATION_DURATION_SECONDS;
theView.Transform = MonoTouch.CoreGraphics.CGAffineTransform.MakeScale (1.2f, 1.2f);
}
// Scales down a image slightly
void AnimateTouchUpAtPoint (UIImageView theView, PointF touchPoint)
{
// Set the center to the touch position
theView.Center = touchPoint;
// Resets the transformation
theView.AnimationDuration = SHRINK_ANIMATION_DURATION_SECONDS;
theView.Transform = MonoTouch.CoreGraphics.CGAffineTransform.MakeIdentity ();
}
#endregion
public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
{
// Return true for supported orientations
return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown);
}
}
}
| 35.879397 | 114 | 0.726891 | [
"Apache-2.0"
] | anujb/monotouch-samples | Touches_Classic/Classes/Touches_ClassicViewController.cs | 7,141 | C# |
using System;
using ToStringSourceGenerator.Attributes;
namespace ToStringSourceGeneratorTypes
{
[AutoToString]
public partial class DemoType
{
public DemoType()
{
}
public int Id { get; set; }
public string? Text { get; set; }
[SkipToString]
public string? Password { get; set; }
[FormatToString("HH:mm")]
public DateTime Time { get; set; }
private string? PrivateValue { get; set; }
}
}
| 20.416667 | 50 | 0.587755 | [
"MIT"
] | acolom/ToStringSourceGenerator | src/ToStringSourceGeneratorTypes/DemoType.cs | 492 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Suls.Data
{
public class Problem
{
public Problem()
{
this.Id = Guid.NewGuid().ToString();
this.Submissions = new HashSet<Submission>();
}
public string Id { get; set; }
[Required]
[MaxLength(20)]
public string Name { get; set; }
public ushort Points { get; set; }
public virtual ICollection<Submission> Submissions { get; set; }
}
}
| 22.96 | 73 | 0.56446 | [
"MIT"
] | dinikolaeva/WebBasics-CSharp | Server2020/10.ExamPreparation/Exam-Suls(16.06.2019)/Solution/Suls/Data/Problem.cs | 576 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StarshipSeven.GameInterfaces
{
public interface IPlanet : IGameEntity
{
string Name { set; get; }
Position? Position { get; }
int GetDistanceTo(IPlanet planet);
int ProductionRate { get; }
int Ships { get; }
double KillPercentage { get; }
IPlayer Owner { get; }
}
}
| 18.48 | 43 | 0.588745 | [
"MIT"
] | smolyakoff/starshipseven | StarshipSeven.GameInterfaces/IPlanet.cs | 464 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Domain
{
/// <summary>
/// KbCodeInfoVO Data Structure.
/// </summary>
public class KbCodeInfoVO : AlipayObject
{
/// <summary>
/// 创建口碑码的批次号
/// </summary>
[JsonPropertyName("batch_id")]
public long BatchId { get; set; }
/// <summary>
/// 口碑码图片(不带背景图)
/// </summary>
[JsonPropertyName("code_url")]
public string CodeUrl { get; set; }
/// <summary>
/// 口碑码创建时间
/// </summary>
[JsonPropertyName("create_time")]
public string CreateTime { get; set; }
/// <summary>
/// 口碑码ID
/// </summary>
[JsonPropertyName("qr_code")]
public string QrCode { get; set; }
/// <summary>
/// 口碑码物料图(带背景)
/// </summary>
[JsonPropertyName("resource_url")]
public string ResourceUrl { get; set; }
/// <summary>
/// 口碑店铺ID
/// </summary>
[JsonPropertyName("shop_id")]
public string ShopId { get; set; }
/// <summary>
/// 口碑门店名称
/// </summary>
[JsonPropertyName("shop_name")]
public string ShopName { get; set; }
/// <summary>
/// 物料模板
/// </summary>
[JsonPropertyName("stuff_template")]
public string StuffTemplate { get; set; }
/// <summary>
/// 物料模板描述
/// </summary>
[JsonPropertyName("stuff_template_desc")]
public string StuffTemplateDesc { get; set; }
/// <summary>
/// 口碑码类型描述
/// </summary>
[JsonPropertyName("stuff_type_desc")]
public string StuffTypeDesc { get; set; }
/// <summary>
/// 桌号
/// </summary>
[JsonPropertyName("table_no")]
public string TableNo { get; set; }
}
}
| 24.792208 | 53 | 0.504453 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Domain/KbCodeInfoVO.cs | 2,049 | 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.Aws.WafV2.Inputs
{
public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatchAllQueryArgumentsArgs : Pulumi.ResourceArgs
{
public WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatchAllQueryArgumentsArgs()
{
}
}
}
| 37.25 | 193 | 0.806711 | [
"ECL-2.0",
"Apache-2.0"
] | Otanikotani/pulumi-aws | sdk/dotnet/WafV2/Inputs/WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatchAllQueryArgumentsArgs.cs | 745 | C# |
using System;
namespace Kimchi.Webjobs.NewShowsChecker
{
public class Class1
{
}
}
| 10.777778 | 40 | 0.670103 | [
"MIT"
] | emimontesdeoca/Kimchi | Kimchi.Webjobs.NewShowsChecker/Class1.cs | 99 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Azure.Analytics.Synapse.Tests;
using Azure.Core;
using Azure.Core.TestFramework;
using NUnit.Framework;
namespace Azure.Analytics.Synapse.AccessControl.Tests
{
/// <summary>
/// The suite of tests for the <see cref="AccessControlClient"/> class.
/// </summary>
/// <remarks>
/// These tests have a dependency on live Azure services and may incur costs for the associated
/// Azure subscription.
/// </remarks>
[LiveOnly] // Assignment IDs can not be reused for at least 30 days.
public class AccessControlClientLiveTests : RecordedTestBase<SynapseTestEnvironment>
{
internal class DisposableClientRole : IAsyncDisposable
{
private readonly RoleAssignmentsClient _client;
// properties of RoleAssignmentDetails used in this class, and are public because we make them visible to tests.
public string RoleAssignmentId { get; private set; }
public string RoleAssignmentRoleDefinitionId { get; private set; }
public string RoleAssignmentPrincipalId { get; private set; }
private DisposableClientRole(RoleAssignmentsClient assignmentsClient, RoleDefinitionsClient definitionsClient, Response createResponse)
{
_client = assignmentsClient;
var content = createResponse.Content;
using var roleAssignmentDetailsJson = JsonDocument.Parse(content.ToMemory());
RoleAssignmentId = roleAssignmentDetailsJson.RootElement.GetProperty("id").GetString();
RoleAssignmentRoleDefinitionId = roleAssignmentDetailsJson.RootElement.GetProperty("roleDefinitionId").GetString();
RoleAssignmentPrincipalId = roleAssignmentDetailsJson.RootElement.GetProperty("principalId").GetString();
}
public static async ValueTask<DisposableClientRole> Create(RoleAssignmentsClient assignmentsClient, RoleDefinitionsClient definitionsClient, SynapseTestEnvironment testEnvironment)
{
var clientRole = new DisposableClientRole(assignmentsClient, definitionsClient, await CreateResource(assignmentsClient, definitionsClient, testEnvironment));
return clientRole;
}
public static async ValueTask<Response> CreateResource(RoleAssignmentsClient assignmentsClient, RoleDefinitionsClient definitionsClient, SynapseTestEnvironment testEnvironment)
{
Response listReponse = await definitionsClient.GetRoleDefinitionsAsync(new());
var listContent = listReponse.Content;
using var roleDefinitionsJson = JsonDocument.Parse(listContent.ToMemory());
var count = roleDefinitionsJson.RootElement.GetArrayLength();
var roleId = roleDefinitionsJson.RootElement.EnumerateArray().First(roleDefinitionJson => roleDefinitionJson.GetProperty("name").ToString() == "Synapse Administrator").GetProperty("id").ToString();
string roleAssignmentId = Guid.NewGuid().ToString();
var roleAssignmentDetails = new
{
roleId = roleId,
principalId = Guid.NewGuid(),
scope = "workspaces/" + testEnvironment.WorkspaceName
};
return await assignmentsClient.CreateRoleAssignmentAsync(roleAssignmentId, RequestContent.Create(roleAssignmentDetails));
}
public async ValueTask DisposeAsync()
{
await _client.DeleteRoleAssignmentByIdAsync(RoleAssignmentId);
}
}
public AccessControlClientLiveTests(bool isAsync) : base(isAsync)
{
}
private RoleAssignmentsClient CreateAssignmentClient()
{
return InstrumentClient(new RoleAssignmentsClient(
new Uri(TestEnvironment.EndpointUrl),
TestEnvironment.Credential,
InstrumentClientOptions(new AccessControlClientOptions())
));
}
private RoleDefinitionsClient CreateDefinitionsClient()
{
return InstrumentClient(new RoleDefinitionsClient(
new Uri(TestEnvironment.EndpointUrl),
TestEnvironment.Credential,
InstrumentClientOptions(new AccessControlClientOptions())
));
}
[Test]
public async Task CanCreateRoleAssignment()
{
RoleAssignmentsClient assignmentsClient = CreateAssignmentClient();
RoleDefinitionsClient definitionsClient = CreateDefinitionsClient();
await using DisposableClientRole role = await DisposableClientRole.Create(assignmentsClient, definitionsClient, TestEnvironment);
Assert.NotNull(role.RoleAssignmentId);
Assert.NotNull(role.RoleAssignmentRoleDefinitionId);
Assert.NotNull(role.RoleAssignmentPrincipalId);
}
[Test]
public async Task CanGetRoleAssignment()
{
RoleAssignmentsClient assignmentsClient = CreateAssignmentClient();
RoleDefinitionsClient definitionsClient = CreateDefinitionsClient();
await using DisposableClientRole role = await DisposableClientRole.Create(assignmentsClient, definitionsClient, TestEnvironment);
var response = await assignmentsClient.GetRoleAssignmentByIdAsync(role.RoleAssignmentId, new());
var content = response.Content;
using var roleAssignmentJson = JsonDocument.Parse(content.ToMemory());
Assert.AreEqual(role.RoleAssignmentRoleDefinitionId, roleAssignmentJson.RootElement.GetProperty("roleDefinitionId").GetString());
Assert.AreEqual(role.RoleAssignmentPrincipalId, roleAssignmentJson.RootElement.GetProperty("principalId").GetString());
}
[Test]
public async Task CanGetRoleAssignmentViaGrowUpHelper()
{
RoleAssignmentsClient assignmentsClient = CreateAssignmentClient();
RoleDefinitionsClient definitionsClient = CreateDefinitionsClient();
await using DisposableClientRole role = await DisposableClientRole.Create(assignmentsClient, definitionsClient, TestEnvironment);
Response<RoleAssignmentDetails> response = await assignmentsClient.GetRoleAssignmentByIdAsync(role.RoleAssignmentId);
Assert.AreEqual(role.RoleAssignmentRoleDefinitionId, response.Value.RoleDefinitionId.ToString());
Assert.AreEqual(role.RoleAssignmentPrincipalId, response.Value.PrincipalId.ToString());
}
[Test]
public async Task CanListRoleDefinitions()
{
RoleAssignmentsClient assignmentsClient = CreateAssignmentClient();
RoleDefinitionsClient definitionsClient = CreateDefinitionsClient();
await using DisposableClientRole role = await DisposableClientRole.Create(assignmentsClient, definitionsClient, TestEnvironment);
// TODO: This will change to pageable with next LLC Generator update
Response listReponse = await definitionsClient.GetRoleDefinitionsAsync(new());
var listContent = listReponse.Content;
using var roleDefinitionsJson = JsonDocument.Parse(listContent.ToMemory());
foreach (var expectedRoleDefinitionJson in roleDefinitionsJson.RootElement.EnumerateArray())
{
string id = expectedRoleDefinitionJson.GetProperty("id").ToString();
var roleDefinitionResponse = await definitionsClient.GetRoleDefinitionByIdAsync(id, new());
var roleDefinitionContent = roleDefinitionResponse.Content;
using var actualRoleDefinitionJson = JsonDocument.Parse(roleDefinitionContent.ToMemory());
Assert.AreEqual(expectedRoleDefinitionJson.GetProperty("id").ToString(), actualRoleDefinitionJson.RootElement.GetProperty("id").ToString());
Assert.AreEqual(expectedRoleDefinitionJson.GetProperty("name").ToString(), actualRoleDefinitionJson.RootElement.GetProperty("name").ToString());
}
Assert.GreaterOrEqual(roleDefinitionsJson.RootElement.GetArrayLength(), 1);
}
[Test]
public async Task CanListRoleAssignments()
{
RoleAssignmentsClient assignmentsClient = CreateAssignmentClient();
RoleDefinitionsClient definitionsClient = CreateDefinitionsClient();
await using DisposableClientRole role = await DisposableClientRole.Create(assignmentsClient, definitionsClient, TestEnvironment);
// TODO: This will change to pageable with https://github.com/azure/azure-sdk-for-net/issues/24680
Response listReponse = await assignmentsClient.GetRoleAssignmentsAsync(new());
var listContent = listReponse.Content;
using var outerJson = JsonDocument.Parse(listContent.ToMemory());
var roleAssignmentsJson = outerJson.RootElement.GetProperty("value");
foreach (var expectedRoleAssignmentJson in roleAssignmentsJson.EnumerateArray())
{
string id = expectedRoleAssignmentJson.GetProperty("id").ToString();
var roleAssignmentResponse = await assignmentsClient.GetRoleAssignmentByIdAsync(id, new());
var roleAssignmentContent = roleAssignmentResponse.Content;
using var actualRoleDefinitionJson = JsonDocument.Parse(roleAssignmentContent.ToMemory());
Assert.AreEqual(expectedRoleAssignmentJson.GetProperty("id").ToString(), actualRoleDefinitionJson.RootElement.GetProperty("id").ToString());
Assert.AreEqual(expectedRoleAssignmentJson.GetProperty("roleDefinitionId").ToString(), actualRoleDefinitionJson.RootElement.GetProperty("roleDefinitionId").ToString());
Assert.AreEqual(expectedRoleAssignmentJson.GetProperty("principalId").ToString(), actualRoleDefinitionJson.RootElement.GetProperty("principalId").ToString());
Assert.AreEqual(expectedRoleAssignmentJson.GetProperty("scope").ToString(), actualRoleDefinitionJson.RootElement.GetProperty("scope").ToString());
}
Assert.GreaterOrEqual(roleAssignmentsJson.GetArrayLength(), 1);
}
[Test]
public async Task CanDeleteRoleAssignments()
{
RoleAssignmentsClient assignmentsClient = CreateAssignmentClient();
RoleDefinitionsClient definitionsClient = CreateDefinitionsClient();
var createResponse = await DisposableClientRole.CreateResource(assignmentsClient, definitionsClient, TestEnvironment);
var content = createResponse.Content;
using var roleAssignmentDetailsJson = JsonDocument.Parse(content.ToMemory());
Response deleteResponse = await assignmentsClient.DeleteRoleAssignmentByIdAsync(roleAssignmentDetailsJson.RootElement.GetProperty("id").GetString());
deleteResponse.AssertSuccess();
}
[Test]
public async Task CanCheckPrincipalAccess()
{
// Arrange
RoleAssignmentsClient assignmentsClient = CreateAssignmentClient();
RoleDefinitionsClient definitionsClient = CreateDefinitionsClient();
string scope = "workspaces/" + TestEnvironment.WorkspaceName;
string actionId = "Microsoft.Synapse/workspaces/read";
await using DisposableClientRole role = await DisposableClientRole.Create(assignmentsClient, definitionsClient, TestEnvironment);
// Act
var accessRequest = new
{
subject = new
{
principalId = role.RoleAssignmentPrincipalId,
groupIds = new string[] { },
},
scope = scope,
actions = new[]
{
new
{
id = actionId,
isDataAction = true
}
}
};
var response = await assignmentsClient.CheckPrincipalAccessAsync(RequestContent.Create(accessRequest));
// Assert
var content = response.Content;
using var accessDecisionsJson = JsonDocument.Parse(content.ToMemory());
var accessDecisionsEnumerator = accessDecisionsJson.RootElement.GetProperty("AccessDecisions").EnumerateArray();
Assert.AreEqual(1, accessDecisionsEnumerator.Count());
var accessDecisionJson = accessDecisionsEnumerator.First();
Assert.AreEqual("Allowed", accessDecisionJson.GetProperty("accessDecision").ToString());
Assert.AreEqual(actionId, accessDecisionJson.GetProperty("actionId").ToString());
var roleAssignmentJson = accessDecisionJson.GetProperty("roleAssignment");
Assert.AreEqual(role.RoleAssignmentId, roleAssignmentJson.GetProperty("id").ToString());
Assert.AreEqual(role.RoleAssignmentRoleDefinitionId, roleAssignmentJson.GetProperty("roleDefinitionId").ToString());
Assert.AreEqual(role.RoleAssignmentPrincipalId, roleAssignmentJson.GetProperty("principalId").ToString());
Assert.AreEqual(scope, roleAssignmentJson.GetProperty("scope").ToString());
}
[Test]
public async Task CanCheckPrincipalAccessViaGrowUpHelper()
{
// Arrange
RoleAssignmentsClient assignmentsClient = CreateAssignmentClient();
RoleDefinitionsClient definitionsClient = CreateDefinitionsClient();
string scope = "workspaces/" + TestEnvironment.WorkspaceName;
string actionId = "Microsoft.Synapse/workspaces/read";
await using DisposableClientRole role = await DisposableClientRole.Create(assignmentsClient, definitionsClient, TestEnvironment);
// Act
CheckPrincipalAccessRequest checkAccessRequest = new CheckPrincipalAccessRequest(
new SubjectInfo(new Guid(role.RoleAssignmentPrincipalId)),
new List<RequiredAction>() { new RequiredAction(actionId, isDataAction: true) },
scope);
Response<CheckPrincipalAccessResponse> response = await assignmentsClient.CheckPrincipalAccessAsync(checkAccessRequest);
// Assert
var decisions = response.Value.AccessDecisions;
Assert.AreEqual(1, decisions.Count);
var decision = decisions[0];
Assert.AreEqual("Allowed", decision.AccessDecision);
Assert.AreEqual(actionId, decision.ActionId);
Assert.AreEqual(role.RoleAssignmentPrincipalId, decision.RoleAssignment.PrincipalId.ToString());
Assert.AreEqual(role.RoleAssignmentRoleDefinitionId, decision.RoleAssignment.RoleDefinitionId.ToString());
Assert.AreEqual(scope, decision.RoleAssignment.Scope);
Assert.AreEqual(role.RoleAssignmentId, decision.RoleAssignment.Id);
}
}
}
| 50.217105 | 213 | 0.68348 | [
"MIT"
] | Ohad-Fein/azure-sdk-for-net | sdk/synapse/Azure.Analytics.Synapse.AccessControl/tests/AccessControlClientLiveTests.cs | 15,266 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Audio;
using osu.Framework.Graphics.Containers;
using osu.Game.Audio;
namespace osu.Game.Skinning
{
/// <summary>
/// A sample corresponding to an <see cref="ISampleInfo"/> that supports being pooled and responding to skin changes.
/// </summary>
public class PoolableSkinnableSample : SkinReloadableDrawable, IAdjustableAudioComponent
{
/// <summary>
/// The currently-loaded <see cref="DrawableSample"/>.
/// </summary>
[CanBeNull]
public DrawableSample Sample { get; private set; }
private readonly AudioContainer<DrawableSample> sampleContainer;
private ISampleInfo sampleInfo;
private SampleChannel activeChannel;
/// <summary>
/// Creates a new <see cref="PoolableSkinnableSample"/> with no applied <see cref="ISampleInfo"/>.
/// An <see cref="ISampleInfo"/> can be applied later via <see cref="Apply"/>.
/// </summary>
public PoolableSkinnableSample()
{
InternalChild = sampleContainer = new AudioContainer<DrawableSample> { RelativeSizeAxes = Axes.Both };
}
/// <summary>
/// Creates a new <see cref="PoolableSkinnableSample"/> with an applied <see cref="ISampleInfo"/>.
/// </summary>
/// <param name="sampleInfo">The <see cref="ISampleInfo"/> to attach.</param>
public PoolableSkinnableSample(ISampleInfo sampleInfo)
: this()
{
Apply(sampleInfo);
}
/// <summary>
/// Applies an <see cref="ISampleInfo"/> that describes the sample to retrieve.
/// Only one <see cref="ISampleInfo"/> can ever be applied to a <see cref="PoolableSkinnableSample"/>.
/// </summary>
/// <param name="sampleInfo">The <see cref="ISampleInfo"/> to apply.</param>
/// <exception cref="InvalidOperationException">If an <see cref="ISampleInfo"/> has already been applied to this <see cref="PoolableSkinnableSample"/>.</exception>
public void Apply(ISampleInfo sampleInfo)
{
if (this.sampleInfo != null)
throw new InvalidOperationException($"A {nameof(PoolableSkinnableSample)} cannot be applied multiple {nameof(ISampleInfo)}s.");
this.sampleInfo = sampleInfo;
Volume.Value = sampleInfo.Volume / 100.0;
if (LoadState >= LoadState.Ready)
updateSample();
}
protected override void LoadComplete()
{
base.LoadComplete();
CurrentSkin.SourceChanged += skinChangedImmediate;
}
private void skinChangedImmediate()
{
// Clean up the previous sample immediately on a source change.
// This avoids a potential call to Play() of an already disposed sample (samples are disposed along with the skin, but SkinChanged is scheduled).
clearPreviousSamples();
}
protected override void SkinChanged(ISkinSource skin)
{
base.SkinChanged(skin);
updateSample();
}
/// <summary>
/// Whether this sample was playing before a skin source change.
/// </summary>
private bool wasPlaying;
private void clearPreviousSamples()
{
// only run if the samples aren't already cleared.
// this ensures the "wasPlaying" state is stored correctly even if multiple clear calls are executed.
if (!sampleContainer.Any()) return;
wasPlaying = Playing;
sampleContainer.Clear();
Sample = null;
}
private void updateSample()
{
if (sampleInfo == null)
return;
var sample = CurrentSkin.GetSample(sampleInfo);
if (sample == null)
return;
sampleContainer.Add(Sample = new DrawableSample(sample));
// Start playback internally for the new sample if the previous one was playing beforehand.
if (wasPlaying && Looping)
Play();
}
/// <summary>
/// Plays the sample.
/// </summary>
public void Play()
{
if (Sample == null)
return;
activeChannel = Sample.GetChannel();
activeChannel.Looping = Looping;
activeChannel.Play();
Played = true;
}
/// <summary>
/// Stops the sample.
/// </summary>
public void Stop()
{
activeChannel?.Stop();
activeChannel = null;
}
/// <summary>
/// Whether the sample is currently playing.
/// </summary>
public bool Playing => activeChannel?.Playing ?? false;
public bool Played { get; private set; }
private bool looping;
/// <summary>
/// Whether the sample should loop on completion.
/// </summary>
public bool Looping
{
get => looping;
set
{
looping = value;
if (activeChannel != null)
activeChannel.Looping = value;
}
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (CurrentSkin != null)
CurrentSkin.SourceChanged -= skinChangedImmediate;
}
#region Re-expose AudioContainer
public BindableNumber<double> Volume => sampleContainer.Volume;
public BindableNumber<double> Balance => sampleContainer.Balance;
public BindableNumber<double> Frequency => sampleContainer.Frequency;
public BindableNumber<double> Tempo => sampleContainer.Tempo;
public void BindAdjustments(IAggregateAudioAdjustment component) => sampleContainer.BindAdjustments(component);
public void UnbindAdjustments(IAggregateAudioAdjustment component) => sampleContainer.UnbindAdjustments(component);
public void AddAdjustment(AdjustableProperty type, IBindable<double> adjustBindable) => sampleContainer.AddAdjustment(type, adjustBindable);
public void RemoveAdjustment(AdjustableProperty type, IBindable<double> adjustBindable) => sampleContainer.RemoveAdjustment(type, adjustBindable);
public void RemoveAllAdjustments(AdjustableProperty type) => sampleContainer.RemoveAllAdjustments(type);
public IBindable<double> AggregateVolume => sampleContainer.AggregateVolume;
public IBindable<double> AggregateBalance => sampleContainer.AggregateBalance;
public IBindable<double> AggregateFrequency => sampleContainer.AggregateFrequency;
public IBindable<double> AggregateTempo => sampleContainer.AggregateTempo;
#endregion
}
}
| 34.821596 | 172 | 0.599569 | [
"MIT"
] | peppy/osu-new | osu.Game/Skinning/PoolableSkinnableSample.cs | 7,205 | C# |
using Microsoft.VisualStudio.Shell;
using OpenInVS2015;
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace OpenInApp
{
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[InstalledProductRegistration("#110", "#112", Vsix.Version, IconResourceID = 400)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[ProvideOptionPage(typeof(Options), Vsix.Name, Vsix.Name, 0, 0, true)]
[Guid(PackageGuids.guidOpenInAppPackageString)]
public sealed class VSPackage : AsyncPackage
{
protected override async System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
await JoinableTaskFactory.SwitchToMainThreadAsync();
var options = (Options)GetDialogPage(typeof(Options));
Logger.Initialize(this, Vsix.Name);
OpenInAppCommand.Initialize(this, options);
}
}
}
| 36.333333 | 154 | 0.727829 | [
"MIT"
] | GregTrevellick/OpenInApp | src/VS2015/OpenInApp/VSPackage.cs | 983 | C# |
using NHapi.Base.Parser;
using NHapi.Base;
using NHapi.Base.Log;
using System;
using System.Collections.Generic;
using NHapi.Model.V25.Segment;
using NHapi.Model.V25.Datatype;
using NHapi.Base.Model;
namespace NHapi.Model.V25.Group
{
///<summary>
///Represents the OML_O35_PATIENT_VISIT_PRIOR Group. A Group is an ordered collection of message
/// segments that can repeat together or be optionally in/excluded together.
/// This Group contains the following elements:
///<ol>
///<li>0: PV1 (Patient Visit) </li>
///<li>1: PV2 (Patient Visit - Additional Information) optional </li>
///</ol>
///</summary>
[Serializable]
public class OML_O35_PATIENT_VISIT_PRIOR : AbstractGroup {
///<summary>
/// Creates a new OML_O35_PATIENT_VISIT_PRIOR Group.
///</summary>
public OML_O35_PATIENT_VISIT_PRIOR(IGroup parent, IModelClassFactory factory) : base(parent, factory){
try {
this.add(typeof(PV1), true, false);
this.add(typeof(PV2), false, false);
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating OML_O35_PATIENT_VISIT_PRIOR - this is probably a bug in the source code generator.", e);
}
}
///<summary>
/// Returns PV1 (Patient Visit) - creates it if necessary
///</summary>
public PV1 PV1 {
get{
PV1 ret = null;
try {
ret = (PV1)this.GetStructure("PV1");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns PV2 (Patient Visit - Additional Information) - creates it if necessary
///</summary>
public PV2 PV2 {
get{
PV2 ret = null;
try {
ret = (PV2)this.GetStructure("PV2");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
}
}
| 31.242857 | 166 | 0.669867 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | afaonline/nHapi | src/NHapi.Model.V25/Group/OML_O35_PATIENT_VISIT_PRIOR.cs | 2,187 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Proxies;
namespace Packt.Shared
{
// this manages the connection to the database
public class Northwind : DbContext
{
// these properties map to tables in the database
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
protected override void OnConfiguring(
DbContextOptionsBuilder optionsBuilder)
{
string path = System.IO.Path.Combine(
System.Environment.CurrentDirectory, "Northwind.db");
optionsBuilder.UseLazyLoadingProxies()
.UseSqlite($"Filename={path}");
}
protected override void OnModelCreating(
ModelBuilder modelBuilder)
{
// example of using Fluent API instead of attributes
// to limit the length of a category name to under 15
modelBuilder.Entity<Category>()
.Property(category => category.CategoryName)
.IsRequired() // NOT NULL
.HasMaxLength(15);
// added to "fix" the lack of decimal support in SQLite
modelBuilder.Entity<Product>()
.Property(product => product.Cost)
.HasConversion<double>();
// global filter to remove discontinued products
modelBuilder.Entity<Product>()
.HasQueryFilter(p => !p.Discontinued);
}
}
} | 31.162791 | 61 | 0.674627 | [
"MIT"
] | zherar7ordoya/AP3 | (CSharp)/1) Mark Price/Code/Chapter11/WorkingWithEFCore/Northwind.cs | 1,340 | C# |
using Facebook.CSSLayout;
namespace ReactNative.UIManager
{
static class CSSNodeExtensions
{
public static float GetLeftBorderWidth(this CSSNode node)
{
var width = node.GetBorder(CSSSpacingType.Left);
if (!CSSConstants.IsUndefined(width))
{
return width;
}
width = node.GetBorder(CSSSpacingType.Horizontal);
if (!CSSConstants.IsUndefined(width))
{
return width;
}
width = node.GetBorder(CSSSpacingType.All);
if (!CSSConstants.IsUndefined(width))
{
return width;
}
return 0.0f;
}
public static float GetPaddingSpace(this CSSNode node, CSSSpacingType spacingType)
{
var padding = node.GetPadding(spacingType);
if (!CSSConstants.IsUndefined(padding))
{
return padding;
}
if (spacingType == CSSSpacingType.Left || spacingType == CSSSpacingType.Right)
{
padding = node.GetPadding(CSSSpacingType.Horizontal);
}
if (!CSSConstants.IsUndefined(padding))
{
return padding;
}
if (spacingType == CSSSpacingType.Top || spacingType == CSSSpacingType.Bottom)
{
padding = node.GetPadding(CSSSpacingType.Vertical);
}
if (!CSSConstants.IsUndefined(padding))
{
return padding;
}
padding = node.GetPadding(CSSSpacingType.All);
if (!CSSConstants.IsUndefined(padding))
{
return padding;
}
return 0.0f;
}
public static float GetTopBorderWidth(this CSSNode node)
{
var width = node.GetBorder(CSSSpacingType.Top);
if (!CSSConstants.IsUndefined(width))
{
return width;
}
width = node.GetBorder(CSSSpacingType.Vertical);
if (!CSSConstants.IsUndefined(width))
{
return width;
}
width = node.GetBorder(CSSSpacingType.All);
if (!CSSConstants.IsUndefined(width))
{
return width;
}
return 0.0f;
}
}
}
| 26.659341 | 90 | 0.500824 | [
"MIT"
] | ankasani/react-native-windows | ReactWindows/ReactNative/UIManager/CSSNodeExtensions.cs | 2,428 | C# |
using System.Threading.Tasks;
namespace PFCom.Selfhosted.DataAccess
{
public interface IUnitOfWork
{
public ITransaction BeginTransaction();
public Task<ITransaction> BeginTransactionAsync();
public void Complete();
public Task CompleteAsync();
public void SaveChanges();
public Task SaveChangesAsync();
}
}
| 20.105263 | 58 | 0.65445 | [
"MIT"
] | PFCom/SelfhostedServer | src/DataAccess/PFCom.Selfhosted.DataAccess/IUnitOfWork.cs | 384 | C# |
using System.Windows;
namespace GraphicsBook
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Content = new PhotoDisplay("none");
Title = "Photo Sorter";
Show();
}
}
}
| 18.95 | 47 | 0.530343 | [
"MIT"
] | NewLuminous/computer-graphics | GraphicsBook/PSApp/MainWindow.xaml.cs | 381 | C# |
/////////////////////////////////////////////////////////////////////////////////
//
// vp_KillZone.cs
// © Opsive. All Rights Reserved.
// https://twitter.com/Opsive
// http://www.opsive.com
//
// description: a trigger to kill an object on contact. this script will only
// work on targets with a vp_DamageHandler-derived component and
// a collider on them. it has logic to address cases where
// 'OnTriggerEnter' behaves erratically
//
// IMPORTANT: make sure to add a collider to the killzone
// gameobject and enable the 'IsTrigger' checkbox!
//
// TIP: killzones can be used most creatively with other scripts for
// singleplayer traps and puzzles. use with rigidbodies for rolling
// boulders. put on the floor for a pool of lava. create a spinning,
// moving giant circular saw blade with vp_Spin and vp_Bob. or use
// with vp_Timer and vp_AngleBob to activate / deactivate a devious
// rotating death-ray! you can even use it with vp_Shooter to fire an
// insta-kill rigidbody ...
//
/////////////////////////////////////////////////////////////////////////////////
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class vp_KillZone : MonoBehaviour
{
vp_DamageHandler m_TargetDamageHandler = null;
vp_Respawner m_TargetRespawner = null;
/// <summary>
///
/// </summary>
void Start()
{
gameObject.layer = vp_Layer.Trigger;
}
/// <summary>
///
/// </summary>
void OnTriggerEnter(Collider col)
{
// return if this is not a relevant object. TIP: this check can be expanded
if (col.gameObject.layer == vp_Layer.Debris
|| col.gameObject.layer == vp_Layer.Pickup)
return;
// try to find a damagehandler on the target and abort on fail
m_TargetDamageHandler = vp_DamageHandler.GetDamageHandlerOfCollider(col);
if (m_TargetDamageHandler == null)
return;
// abort if target is already dead
// NOTE: this deals with cases of multiple 'OnTriggerEnter' calls on contact
if (m_TargetDamageHandler.CurrentHealth <= 0)
return;
// try to find a respawner on the target to see if it's currently OK to kill it
m_TargetRespawner = vp_Respawner.GetByCollider(col);
if (m_TargetRespawner != null)
{
// abort if target has respawned within one second before this call.
// NOTE: this addresses a case where 'OnTriggerEnter' is called when
// teleporting (respawning) away from the trigger, resulting in the
// object getting insta-killed on respawn. it will only work if the
// target gameobject has a vp_Respawner-derived component
if (Time.time < m_TargetRespawner.LastRespawnTime + 1.0f)
return;
}
m_TargetDamageHandler.Damage(new vp_DamageInfo(m_TargetDamageHandler.CurrentHealth, m_TargetDamageHandler.Transform, vp_DamageInfo.DamageType.KillZone));
}
} | 33.364706 | 155 | 0.681946 | [
"MIT"
] | PotentialGames/Cal-tEspa-l | BRGAME/Assets/UFPS/Base/Scripts/Gameplay/Level/vp_KillZone.cs | 2,839 | C# |
using MonitoredUndo;
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using VideoScriptEditor.Collections;
using VideoScriptEditor.Geometry;
using VideoScriptEditor.Models;
using VideoScriptEditor.Services;
using VideoScriptEditor.Services.ScriptVideo;
using VideoScriptEditor.ViewModels.Timeline;
using Debug = System.Diagnostics.Debug;
namespace VideoScriptEditor.ViewModels.Masking.Shapes
{
/// <summary>
/// Base masking shape segment view model class for coordinating interaction between a view and a <see cref="SegmentModelBase">masking shape segment model</see>.
/// </summary>
public abstract class MaskShapeViewModelBase : SegmentViewModelBase, IEquatable<MaskShapeViewModelBase>
{
protected string ShapeResizedChangeSetDescription => $"'{Name}' masking shape resized";
protected string ShapeKeyFrameAddedChangeSetDescription => $"'{Name}' masking shape key frame added";
protected string ShapeKeyFrameCopiedChangeSetDescription => $"'{Name}' masking shape key frame copied";
/// <summary>
/// The geometric type of masking shape this view model represents.
/// </summary>
public abstract MaskShapeType ShapeType { get; }
/// <summary>
/// Gets or sets a <see cref="Rect"/> that represents the bounding box of this masking shape.
/// </summary>
public abstract Rect Bounds { get; set; }
/// <summary>
/// Base constructor for masking shape segment view models derived from the <see cref="MaskShapeViewModelBase"/> class.
/// </summary>
/// <inheritdoc cref="SegmentViewModelBase(SegmentModelBase, IScriptVideoContext, object, IUndoService, IChangeFactory, IClipboardService, KeyFrameViewModelCollection)"/>
protected MaskShapeViewModelBase(SegmentModelBase model, IScriptVideoContext scriptVideoContext, object rootUndoObject, IUndoService undoService, IChangeFactory undoChangeFactory, IClipboardService clipboardService, KeyFrameViewModelCollection keyFrameViewModels = null) : base(model, scriptVideoContext, rootUndoObject, undoService, undoChangeFactory, clipboardService, keyFrameViewModels)
{
}
/// <summary>
/// Determines whether this masking shape supports the
/// specified <see cref="MaskShapeResizeMode">resize mode</see>
/// </summary>
/// <param name="resizeMode">A <see cref="MaskShapeResizeMode"/> enum value representing the resize mode to check.</param>
/// <returns><see langword="true"/> if this masking shape supports the specified resize mode; otherwise, <see langword="false"/>.</returns>
public abstract bool SupportsResizeMode(MaskShapeResizeMode resizeMode);
/// <summary>
/// Resizes the bounding box of the masking shape from the specified origin point.
/// </summary>
/// <param name="newBounds">A <see cref="Rect"/> specifying the new bounding size and location for this masking shape.</param>
/// <param name="resizeOrigin">A <see cref="RectanglePoint"/> enum value representing the resize origin point. Can be <see langword="null"/>.</param>
public abstract void ResizeBounds(Rect newBounds, RectanglePoint? resizeOrigin = null);
/// <summary>
/// Begins an undoable action making <see cref="UndoRoot.BeginChangeSetBatch(string, bool)">batch changes</see>
/// to the location of the masking shape.
/// </summary>
public virtual void BeginShapeMoveAction()
{
_undoRoot.BeginChangeSetBatch($"{Name} mask shape moved", true);
}
/// <summary>
/// Begins an undoable action making <see cref="UndoRoot.BeginChangeSetBatch(string, bool)">batch changes</see>
/// to the size of the masking shape.
/// </summary>
public virtual void BeginShapeResizeAction()
{
_undoRoot.BeginChangeSetBatch($"{Name} mask shape resized", true);
}
/// <summary>
/// Moves the bounding box of the masking shape by the specified <see cref="Vector"/>.
/// </summary>
/// <param name="offsetVector">
/// A <see cref="Vector"/> that specifies the horizontal and vertical amounts to move the bounding box.
/// </param>
public abstract void OffsetBounds(Vector offsetVector);
/// <summary>
/// Moves the bounding box of the masking shape by the specified <see cref="Vector"/>
/// within the <see cref="IScriptVideoContext.VideoFrameSize">video frame bounds</see>.
/// </summary>
/// <param name="offsetVector">
/// A <see cref="Vector"/> that specifies the horizontal and vertical amounts to move the bounding box.
/// </param>
public void OffsetWithinVideoFrameBounds(Vector offsetVector)
{
if (!CanBeEdited)
{
return;
}
Rect videoFrameBounds = new Rect(ScriptVideoContext.VideoFrameSize.ToWpfSize());
Rect currentBounds = Bounds;
Rect offsetBounds = currentBounds.OffsetFromCenterWithinBounds(offsetVector, videoFrameBounds);
OffsetBounds(offsetBounds.Location - currentBounds.Location);
}
/// <summary>
/// Resizes the bounding box of the masking shape by offsetting a bounding point,
/// optionally using a scaled resize method.
/// </summary>
/// <param name="boundingBoxPoint">A <see cref="RectanglePoint"/> enum value representing the bounding point to offset.</param>
/// <param name="boundingPointOffset">The pixel offset to apply to the bounding point.</param>
/// <param name="scaledResize">Whether to use a scaled resize method. Defaults to <see langword="false"/>.</param>
public void ResizeFromBoundingPointOffset(RectanglePoint boundingBoxPoint, Vector boundingPointOffset, bool scaledResize = false)
{
if (!CanBeEdited)
{
return;
}
Rect videoBounds = new Rect(ScriptVideoContext.VideoFrameSize.ToWpfSize());
Rect shapeBounds = Bounds;
Point centerPoint = shapeBounds.CenterPoint();
double left = shapeBounds.Left, top = shapeBounds.Top, right = shapeBounds.Right, bottom = shapeBounds.Bottom;
double width = shapeBounds.Width, height = shapeBounds.Height, scaleWidth = 1d, scaleHeight = 1d;
Point originalPoint, projectedPoint;
Line projectionLine;
double xOffset, xOffsetMax, yOffset, yOffsetMax;
switch (boundingBoxPoint)
{
case RectanglePoint.TopLeft:
originalPoint = shapeBounds.TopLeft;
projectedPoint = videoBounds.ConstrainPoint(originalPoint + boundingPointOffset);
if (scaledResize)
{
if (projectedPoint == originalPoint || projectedPoint.X > centerPoint.X || projectedPoint.Y > centerPoint.Y)
{
break;
}
projectionLine = centerPoint.LineTo(originalPoint);
projectedPoint = projectionLine.Project(projectedPoint);
if (!videoBounds.Contains(projectedPoint))
{
break;
}
}
left = projectedPoint.X;
top = projectedPoint.Y;
break;
case RectanglePoint.TopCenter:
originalPoint = shapeBounds.TopCenter();
projectedPoint = videoBounds.ConstrainPoint(new Point(originalPoint.X, originalPoint.Y + boundingPointOffset.Y));
if (scaledResize)
{
if (projectedPoint == originalPoint || projectedPoint.Y > centerPoint.Y)
{
break;
}
height = shapeBounds.Bottom - projectedPoint.Y;
scaleHeight = height / shapeBounds.Height;
width = shapeBounds.Width * scaleHeight;
xOffset = (width - shapeBounds.Width) / 2d;
if (height > shapeBounds.Height)
{
// Upscaling
if (shapeBounds.Left == videoBounds.Left || shapeBounds.Right == videoBounds.Right)
{
// Can't expand width any further
break;
}
xOffsetMax = Math.Min(shapeBounds.Left, videoBounds.Right - shapeBounds.Right);
if (xOffset > xOffsetMax)
{
// Scale by width
width = shapeBounds.Width + (xOffsetMax * 2d);
scaleWidth = width / shapeBounds.Width;
height = shapeBounds.Height * scaleWidth;
projectedPoint.Y = shapeBounds.Bottom - height;
xOffset = xOffsetMax;
}
}
left = shapeBounds.Left - xOffset;
right = shapeBounds.Right + xOffset;
}
top = projectedPoint.Y;
break;
case RectanglePoint.TopRight:
originalPoint = shapeBounds.TopRight;
projectedPoint = videoBounds.ConstrainPoint(originalPoint + boundingPointOffset);
if (scaledResize)
{
if (projectedPoint == originalPoint || projectedPoint.X < centerPoint.X || projectedPoint.Y > centerPoint.Y)
{
break;
}
projectionLine = centerPoint.LineTo(originalPoint);
projectedPoint = projectionLine.Project(projectedPoint);
if (!videoBounds.Contains(projectedPoint))
{
break;
}
}
right = projectedPoint.X;
top = projectedPoint.Y;
break;
case RectanglePoint.CenterLeft:
originalPoint = shapeBounds.CenterLeft();
projectedPoint = videoBounds.ConstrainPoint(new Point(originalPoint.X + boundingPointOffset.X, originalPoint.Y));
if (scaledResize)
{
if (projectedPoint == originalPoint || projectedPoint.X > centerPoint.X)
{
break;
}
width = shapeBounds.Right - projectedPoint.X;
scaleWidth = width / shapeBounds.Width;
height = shapeBounds.Height * scaleWidth;
yOffset = (height - shapeBounds.Height) / 2d;
if (width > shapeBounds.Width)
{
// Upscaling
if (shapeBounds.Top == videoBounds.Top || shapeBounds.Bottom == videoBounds.Bottom)
{
// Can't expand height any further
break;
}
yOffsetMax = Math.Min(shapeBounds.Top, videoBounds.Bottom - shapeBounds.Bottom);
if (yOffset > yOffsetMax)
{
// Scale by height
height = shapeBounds.Height + (yOffsetMax * 2d);
scaleHeight = height / shapeBounds.Height;
width = shapeBounds.Width * scaleHeight;
projectedPoint.X = shapeBounds.Right - width;
yOffset = yOffsetMax;
}
}
top = shapeBounds.Top - yOffset;
bottom = shapeBounds.Bottom + yOffset;
}
left = projectedPoint.X;
break;
case RectanglePoint.CenterRight:
originalPoint = shapeBounds.CenterRight();
projectedPoint = videoBounds.ConstrainPoint(new Point(originalPoint.X + boundingPointOffset.X, originalPoint.Y));
if (scaledResize)
{
if (projectedPoint == originalPoint || projectedPoint.X < centerPoint.X)
{
break;
}
width = projectedPoint.X - shapeBounds.Left;
scaleWidth = width / shapeBounds.Width;
height = shapeBounds.Height * scaleWidth;
yOffset = (height - shapeBounds.Height) / 2d;
if (width > shapeBounds.Width)
{
// Upscaling
if (shapeBounds.Top == videoBounds.Top || shapeBounds.Bottom == videoBounds.Bottom)
{
// Can't expand height any further
break;
}
yOffsetMax = Math.Min(shapeBounds.Top, videoBounds.Bottom - shapeBounds.Bottom);
if (yOffset > yOffsetMax)
{
// Scale by height
height = shapeBounds.Height + (yOffsetMax * 2d);
scaleHeight = height / shapeBounds.Height;
width = shapeBounds.Width * scaleHeight;
projectedPoint.X = shapeBounds.Left + width;
yOffset = yOffsetMax;
}
}
top = shapeBounds.Top - yOffset;
bottom = shapeBounds.Bottom + yOffset;
}
right = projectedPoint.X;
break;
case RectanglePoint.BottomLeft:
originalPoint = shapeBounds.BottomLeft;
projectedPoint = videoBounds.ConstrainPoint(originalPoint + boundingPointOffset);
if (scaledResize)
{
if (projectedPoint == originalPoint || projectedPoint.X > centerPoint.X || projectedPoint.Y < centerPoint.Y)
{
break;
}
projectionLine = centerPoint.LineTo(originalPoint);
projectedPoint = projectionLine.Project(projectedPoint);
if (!videoBounds.Contains(projectedPoint))
{
break;
}
}
left = projectedPoint.X;
bottom = projectedPoint.Y;
break;
case RectanglePoint.BottomCenter:
originalPoint = shapeBounds.BottomCenter();
projectedPoint = videoBounds.ConstrainPoint(new Point(originalPoint.X, originalPoint.Y + boundingPointOffset.Y));
if (scaledResize)
{
if (projectedPoint == originalPoint || projectedPoint.Y < centerPoint.Y)
{
break;
}
height = projectedPoint.Y - shapeBounds.Top;
scaleHeight = height / shapeBounds.Height;
width = shapeBounds.Width * scaleHeight;
xOffset = (width - shapeBounds.Width) / 2d;
if (height > shapeBounds.Height)
{
// Upscaling
if (shapeBounds.Left == videoBounds.Left || shapeBounds.Right == videoBounds.Right)
{
// Can't expand width any further
break;
}
xOffsetMax = Math.Min(shapeBounds.Left, videoBounds.Right - shapeBounds.Right);
if (xOffset > xOffsetMax)
{
// Scale by width
width = shapeBounds.Width + (xOffsetMax * 2d);
scaleWidth = width / shapeBounds.Width;
height = shapeBounds.Height * scaleWidth;
projectedPoint.Y = shapeBounds.Top + height;
xOffset = xOffsetMax;
}
}
left = shapeBounds.Left - xOffset;
right = shapeBounds.Right + xOffset;
}
bottom = projectedPoint.Y;
break;
case RectanglePoint.BottomRight:
originalPoint = shapeBounds.BottomRight;
projectedPoint = videoBounds.ConstrainPoint(originalPoint + boundingPointOffset);
if (scaledResize)
{
if (projectedPoint == originalPoint || projectedPoint.X < centerPoint.X || projectedPoint.Y < centerPoint.Y)
{
break;
}
projectionLine = centerPoint.LineTo(originalPoint);
projectedPoint = projectionLine.Project(projectedPoint);
if (!videoBounds.Contains(projectedPoint))
{
break;
}
}
right = projectedPoint.X;
bottom = projectedPoint.Y;
break;
default:
throw new InvalidEnumArgumentException(nameof(boundingBoxPoint));
}
shapeBounds = new Rect(new Point(left, top),
new Point(right, bottom));
#if DEBUG
if (scaledResize)
{
Debug.Assert((float)(shapeBounds.Width / Bounds.Width) == (float)(shapeBounds.Height / Bounds.Height));
}
#endif
ResizeBounds(shapeBounds, boundingBoxPoint);
}
/// <summary>
/// Flips the masking shape along the specified axis.
/// </summary>
/// <param name="axis">The axis to flip the masking shape along.</param>
public abstract void Flip(Axis axis);
/// <inheritdoc/>
protected override void OnActiveKeyFrameChanged()
{
base.OnActiveKeyFrameChanged();
OnDataPropertyValuesChanged();
}
/// <summary>
/// Invoked when all data property values have changed.
/// Raises <see cref="INotifyPropertyChanged.PropertyChanged"/> for each property.
/// </summary>
protected abstract void OnDataPropertyValuesChanged();
/// <summary>
/// Raises the <see cref="INotifyPropertyChanged.PropertyChanged"/> event for the <see cref="Bounds"/> property.
/// </summary>
protected void RaiseBoundsPropertyChanged() => RaisePropertyChanged(nameof(Bounds));
/// <inheritdoc/>
public override bool Equals(object obj)
{
return Equals(obj as MaskShapeViewModelBase);
}
/// <inheritdoc cref="IEquatable{T}.Equals(T)"/>
/// <remarks>
/// Based on sample code from https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-define-value-equality-for-a-type#class-example
/// </remarks>
public bool Equals([AllowNull] MaskShapeViewModelBase other)
{
// If parameter is null, return false.
if (other is null)
{
return false;
}
// Optimization for a common success case.
if (ReferenceEquals(this, other))
{
return true;
}
// Check properties that this class declares
// and let base class check its own fields and do the run-time type comparison.
return ShapeType == other.ShapeType && base.Equals(other);
}
/// <inheritdoc/>
public override int GetHashCode()
{
return HashCode.Combine(base.GetHashCode(), ShapeType);
}
}
}
| 46.006479 | 398 | 0.513732 | [
"MIT"
] | danjoconnell/VideoScriptEditor | VideoScriptEditor/VideoScriptEditor/ViewModels/Masking/Shapes/MaskShapeViewModelBase.cs | 21,303 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using ZeroLevel.Services.Pools;
namespace ZeroLevel.Network
{
internal sealed class RequestBuffer
{
private ConcurrentDictionary<long, RequestInfo> _requests = new ConcurrentDictionary<long, RequestInfo>();
private static Pool<RequestInfo> _ri_pool = new Pool<RequestInfo>(128, (p) => new RequestInfo());
public void RegisterForFrame(int identity, Action<byte[]> callback, Action<string> fail = null)
{
var ri = _ri_pool.Acquire();
ri.Reset(callback, fail);
_requests[identity] = ri;
}
public void Fail(long frameId, string message)
{
RequestInfo ri;
if (_requests.TryRemove(frameId, out ri))
{
ri.Fail(message);
_ri_pool.Release(ri);
}
}
public void Success(long frameId, byte[] data)
{
RequestInfo ri;
if (_requests.TryRemove(frameId, out ri))
{
ri.Success(data);
_ri_pool.Release(ri);
}
}
public void StartSend(long frameId)
{
RequestInfo ri;
if (_requests.TryGetValue(frameId, out ri))
{
ri.StartSend();
}
}
public void Timeout(List<long> frameIds)
{
RequestInfo ri;
for (int i = 0; i < frameIds.Count; i++)
{
if (_requests.TryRemove(frameIds[i], out ri))
{
_ri_pool.Release(ri);
}
}
}
public void TestForTimeouts()
{
var now_ticks = DateTime.UtcNow.Ticks;
var to_remove = new List<long>();
foreach (var pair in _requests)
{
if (pair.Value.Sended == false) continue;
var diff = now_ticks - pair.Value.Timestamp;
if (diff > BaseSocket.MAX_REQUEST_TIME_TICKS)
{
to_remove.Add(pair.Key);
}
}
Timeout(to_remove);
}
}
}
| 28.615385 | 114 | 0.503136 | [
"MIT"
] | ogoun/Zero | ZeroLevel/Services/Network/Utils/RequestBuffer.cs | 2,234 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class Binder
{
internal readonly struct NamespaceOrTypeOrAliasSymbolWithAnnotations
{
private readonly TypeSymbolWithAnnotations _type;
private readonly Symbol _symbol;
private readonly bool _isNullableEnabled;
private NamespaceOrTypeOrAliasSymbolWithAnnotations(TypeSymbolWithAnnotations type)
{
Debug.Assert(type.HasType);
_type = type;
_symbol = null;
_isNullableEnabled = false; // Not meaningful for a TypeSymbolWithAnnotations, it already baked the fact into its content.
}
private NamespaceOrTypeOrAliasSymbolWithAnnotations(Symbol symbol, bool isNullableEnabled)
{
Debug.Assert(!(symbol is TypeSymbol));
_type = default;
_symbol = symbol;
_isNullableEnabled = isNullableEnabled;
}
internal TypeSymbolWithAnnotations Type => _type;
internal Symbol Symbol => _symbol ?? Type.TypeSymbol;
internal bool IsType => !_type.IsDefault;
internal bool IsAlias => _symbol?.Kind == SymbolKind.Alias;
internal NamespaceOrTypeSymbol NamespaceOrTypeSymbol => Symbol as NamespaceOrTypeSymbol;
internal bool IsDefault => !_type.HasType && _symbol is null;
internal bool IsNullableEnabled
{
get
{
Debug.Assert(_symbol?.Kind == SymbolKind.Alias); // Not meaningful to use this property otherwise
return _isNullableEnabled;
}
}
internal static NamespaceOrTypeOrAliasSymbolWithAnnotations CreateUnannotated(bool isNullableEnabled, Symbol symbol)
{
if (symbol is null)
{
return default;
}
var type = symbol as TypeSymbol;
return type is null ?
new NamespaceOrTypeOrAliasSymbolWithAnnotations(symbol, isNullableEnabled) :
new NamespaceOrTypeOrAliasSymbolWithAnnotations(TypeSymbolWithAnnotations.Create(isNullableEnabled, type));
}
public static implicit operator NamespaceOrTypeOrAliasSymbolWithAnnotations(TypeSymbolWithAnnotations type)
{
return new NamespaceOrTypeOrAliasSymbolWithAnnotations(type);
}
}
}
}
| 41.671642 | 161 | 0.619628 | [
"Apache-2.0"
] | acesiddhu/roslyn | src/Compilers/CSharp/Portable/Binder/Binder.NamespaceOrTypeOrAliasSymbolWithAnnotations.cs | 2,794 | C# |
using Adnc.Infra.Core;
using Adnc.Infra.Helper;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Text.Json;
using System.Threading.Tasks;
namespace Adnc.WebApi.Shared.Middleware
{
public class CustomExceptionHandlerMiddleware
{
private readonly ILogger<CustomExceptionHandlerMiddleware> _logger;
private readonly IWebHostEnvironment _env;
private readonly RequestDelegate _next;
public CustomExceptionHandlerMiddleware(RequestDelegate next
, IWebHostEnvironment env
, ILogger<CustomExceptionHandlerMiddleware> logger)
{
_next = next;
_env = env;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
#region old code
//var statusCode = context.Response.StatusCode;
//string msg = string.Empty;
//if (statusCode == 401)
//{
// msg = "未授权";
//}
//else if (statusCode == 403)
//{
// msg = "未授权,没有权限";
//}
//else if (statusCode == 404)
//{
// msg = "未找到服务";
//}
//if (!string.IsNullOrWhiteSpace(msg))
//{
// await HandleExceptionAsync(context, statusCode, msg);
//}
#endregion old code
}
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var eventId = new EventId(exception.HResult);
_logger.LogError(eventId, exception, exception.Message);
var status = 500;
var type = string.Concat("https://httpstatuses.com/", status);
var title = _env.IsDevelopment() ? exception.Message : $"系统异常";
var detial = _env.IsDevelopment() ? exception.GetExceptionDetail() : $"系统异常,请联系管理员({eventId})";
var problemDetails = new ProblemDetails
{
Title = title
,
Detail = detial
,
Type = type
,
Status = status
};
context.Response.StatusCode = status;
context.Response.ContentType = "application/problem+json";
var errorText = JsonSerializer.Serialize(problemDetails, SystemTextJson.GetAdncDefaultOptions());
await context.Response.WriteAsync(errorText);
}
}
public static class CustomExceptionHandlerMiddlewareExtensions
{
public static IApplicationBuilder UseCustomExceptionHandler(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CustomExceptionHandlerMiddleware>();
}
}
} | 31.168317 | 109 | 0.56925 | [
"MIT"
] | AjuPrince/Adnc | src/ServerApi/Services/Shared/Adnc.WebApi.Shared/Middleware/CustomExceptionHandlerMiddleware.cs | 3,210 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using discovery.Library.Core;
using discovery.Library.identity;
using discovery.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
namespace discovery.Controllers
{
public class patternsController : BaseController
{
public patternsController(IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor)
{
}
// GET: patterns
public ActionResult Index()
{
this.setPageTitle("Index");
var res = this.ormProxy.patterns.Include(a => a.category)
.Where(sc => sc.category.ownerID == User.GetUserId())
.Select(item =>
new patternsviewmodel()
{
categoryId = item.categoryId,
categoryTitle = item.category.category,
ID = item.ID,
title = item.title
}
);
return View(res);
}
// GET: patterns/Create
public ActionResult Create()
{
this.setPageTitle("Create");
//Load category models from a hook method
ViewBag.category = new SelectList(this.ormProxy.categories.Where(sc => sc.ownerID == User.GetUserId()), "ID", "category");
return View();
}
// POST: patterns/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(patterns collection)
{
try
{
this.ormProxy.patterns.Add(collection);
this.ormProxy.SaveChanges();
this._session.SetString(Keys._MSG, ExceptionType.Info + "Pattern Successfully Created");
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
// GET: patterns/Edit/5
public ActionResult Edit(int id)
{
this.setPageTitle("Edit");
var item = this.ormProxy.patterns.First(a => a.ID == id);
//Load category models from a hook method
ViewBag.category = new SelectList(this.ormProxy.categories.Where(sc => sc.ownerID == User.GetUserId()), "ID", "category");
return View(item);
}
// POST: patterns/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, patterns collection)
{
try
{
this.ormProxy.patterns.Update(collection);
this.ormProxy.SaveChanges();
this._session.SetString(Keys._MSG, ExceptionType.Info + "Pattern Successfully Updated");
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
public ActionResult Delete(int id)
{
this.setPageTitle("Delete");
try
{
var item = this.ormProxy.patterns.FirstOrDefault(a => a.ID == id);
this.ormProxy.patterns.Remove(item);
this.ormProxy.SaveChanges();
this._session.SetString(Keys._MSG, ExceptionType.Info + "Pattern Successfully Deleted");
return RedirectToAction(nameof(Index));
}
catch
{
this._session.SetString(Keys._MSG, ExceptionType.Eror + "Delete pattern Failed");
return View(nameof(Index));
}
}
//Hook method for scenrio cheking
public override bool needScenario()
{
return false;
}
//template method for setting the title of each page
public override void setPageTitle(string actionRequester)
{
string _pageTitle = "";
switch (actionRequester)
{
case "Index":
_pageTitle = "Pattern Management";
break;
case "Create":
_pageTitle = "Create Pattern";
break;
case "Delete":
_pageTitle = "Delete Pattern";
break;
case "Edit":
_pageTitle = "Edit Pattern";
break;
default:
_pageTitle = "Pattern Management";
break;
}
ViewBag.Title = _pageTitle;
}
}
} | 31.346667 | 134 | 0.521268 | [
"MIT"
] | javadbayzavi/PatternDiscovery | discovery/Controllers/patternsController.cs | 4,704 | C# |
namespace HomeSchoolDayBook
{
partial class frpReportViewer
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
Microsoft.Reporting.WinForms.ReportDataSource reportDataSource2 = new Microsoft.Reporting.WinForms.ReportDataSource();
this.DT22VariousBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.hsdReportDS = new HomeSchoolDayBook.hsdReportDS();
this.reportViewer1 = new Microsoft.Reporting.WinForms.ReportViewer();
((System.ComponentModel.ISupportInitialize)(this.DT22VariousBindingSource)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.hsdReportDS)).BeginInit();
this.SuspendLayout();
//
// DT22VariousBindingSource
//
this.DT22VariousBindingSource.DataMember = "DT22Various";
this.DT22VariousBindingSource.DataSource = this.hsdReportDS;
//
// hsdReportDS
//
this.hsdReportDS.DataSetName = "hsdReportDS";
this.hsdReportDS.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// reportViewer1
//
this.reportViewer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.reportViewer1.DocumentMapCollapsed = true;
this.reportViewer1.DocumentMapWidth = 25;
reportDataSource2.Name = "hsdReportDS_DT22Various";
reportDataSource2.Value = this.DT22VariousBindingSource;
this.reportViewer1.LocalReport.DataSources.Add(reportDataSource2);
this.reportViewer1.LocalReport.ReportEmbeddedResource = "HomeSchoolDayBook.Report1.rdlc";
this.reportViewer1.Location = new System.Drawing.Point(0, 0);
this.reportViewer1.Name = "reportViewer1";
this.reportViewer1.ShowBackButton = false;
this.reportViewer1.ShowDocumentMapButton = false;
this.reportViewer1.ShowFindControls = false;
this.reportViewer1.ShowZoomControl = false;
this.reportViewer1.Size = new System.Drawing.Size(682, 641);
this.reportViewer1.TabIndex = 0;
//
// frpReportViewer
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(682, 641);
this.Controls.Add(this.reportViewer1);
this.Name = "frpReportViewer";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Printable Reports:";
this.Load += new System.EventHandler(this.frmPopReportViewer_Load);
((System.ComponentModel.ISupportInitialize)(this.DT22VariousBindingSource)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.hsdReportDS)).EndInit();
this.ResumeLayout(false);
}
#endregion
private Microsoft.Reporting.WinForms.ReportViewer reportViewer1;
private System.Windows.Forms.BindingSource DT22VariousBindingSource;
private hsdReportDS hsdReportDS;
}
} | 46.788889 | 131 | 0.621468 | [
"MIT"
] | MattConrad/HomeschoolDayBook | HomeSchoolDayBook/frpReportViewer.Designer.cs | 4,211 | C# |
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Awake.Core.Models;
using Microsoft.Win32;
using NLog;
namespace Awake.Core
{
public delegate bool ConsoleEventHandler(ControlType ctrlType);
/// <summary>
/// Helper class that allows talking to Win32 APIs without having to rely on PInvoke in other parts
/// of the codebase.
/// </summary>
public class APIHelper
{
private const string BuildRegistryLocation = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion";
private const int StdOutputHandle = -11;
private const uint GenericWrite = 0x40000000;
private const uint GenericRead = 0x80000000;
private static readonly Logger _log;
private static CancellationTokenSource _tokenSource;
private static CancellationToken _threadToken;
private static Task? _runnerThread;
private static System.Timers.Timer _timedLoopTimer;
static APIHelper()
{
_timedLoopTimer = new System.Timers.Timer();
_log = LogManager.GetCurrentClassLogger();
_tokenSource = new CancellationTokenSource();
}
public static void SetConsoleControlHandler(ConsoleEventHandler handler, bool addHandler)
{
NativeMethods.SetConsoleCtrlHandler(handler, addHandler);
}
public static void AllocateConsole()
{
_log.Debug("Bootstrapping the console allocation routine.");
NativeMethods.AllocConsole();
_log.Debug($"Console allocation result: {Marshal.GetLastWin32Error()}");
var outputFilePointer = NativeMethods.CreateFile("CONOUT$", GenericRead | GenericWrite, FileShare.Write, IntPtr.Zero, FileMode.OpenOrCreate, 0, IntPtr.Zero);
_log.Debug($"CONOUT creation result: {Marshal.GetLastWin32Error()}");
NativeMethods.SetStdHandle(StdOutputHandle, outputFilePointer);
_log.Debug($"SetStdHandle result: {Marshal.GetLastWin32Error()}");
Console.SetOut(new StreamWriter(Console.OpenStandardOutput(), Console.OutputEncoding) { AutoFlush = true });
}
/// <summary>
/// Sets the computer awake state using the native Win32 SetThreadExecutionState API. This
/// function is just a nice-to-have wrapper that helps avoid tracking the success or failure of
/// the call.
/// </summary>
/// <param name="state">Single or multiple EXECUTION_STATE entries.</param>
/// <returns>true if successful, false if failed</returns>
private static bool SetAwakeState(ExecutionState state)
{
try
{
var stateResult = NativeMethods.SetThreadExecutionState(state);
return stateResult != 0;
}
catch
{
return false;
}
}
public static void SetIndefiniteKeepAwake(Action<bool> callback, Action failureCallback, bool keepDisplayOn = false)
{
_tokenSource.Cancel();
try
{
if (_runnerThread != null && !_runnerThread.IsCanceled)
{
_runnerThread.Wait(_threadToken);
}
}
catch (OperationCanceledException)
{
_log.Info("Confirmed background thread cancellation when setting indefinite keep awake.");
}
_tokenSource = new CancellationTokenSource();
_threadToken = _tokenSource.Token;
_runnerThread = Task.Run(() => RunIndefiniteLoop(keepDisplayOn), _threadToken)
.ContinueWith((result) => callback(result.Result), TaskContinuationOptions.OnlyOnRanToCompletion)
.ContinueWith((result) => failureCallback, TaskContinuationOptions.NotOnRanToCompletion);
}
public static void SetNoKeepAwake()
{
_tokenSource.Cancel();
try
{
if (_runnerThread != null && !_runnerThread.IsCanceled)
{
_runnerThread.Wait(_threadToken);
}
}
catch (OperationCanceledException)
{
_log.Info("Confirmed background thread cancellation when disabling explicit keep awake.");
}
}
public static void SetTimedKeepAwake(uint seconds, Action<bool> callback, Action failureCallback, bool keepDisplayOn = true)
{
_tokenSource.Cancel();
try
{
if (_runnerThread != null && !_runnerThread.IsCanceled)
{
_runnerThread.Wait(_threadToken);
}
}
catch (OperationCanceledException)
{
_log.Info("Confirmed background thread cancellation when setting timed keep awake.");
}
_tokenSource = new CancellationTokenSource();
_threadToken = _tokenSource.Token;
_runnerThread = Task.Run(() => RunTimedLoop(seconds, keepDisplayOn), _threadToken)
.ContinueWith((result) => callback(result.Result), TaskContinuationOptions.OnlyOnRanToCompletion)
.ContinueWith((result) => failureCallback, TaskContinuationOptions.NotOnRanToCompletion);
}
private static bool RunIndefiniteLoop(bool keepDisplayOn = false)
{
bool success;
if (keepDisplayOn)
{
success = SetAwakeState(ExecutionState.ES_SYSTEM_REQUIRED | ExecutionState.ES_DISPLAY_REQUIRED | ExecutionState.ES_CONTINUOUS);
}
else
{
success = SetAwakeState(ExecutionState.ES_SYSTEM_REQUIRED | ExecutionState.ES_CONTINUOUS);
}
try
{
if (success)
{
_log.Info($"Initiated indefinite keep awake in background thread: {NativeMethods.GetCurrentThreadId()}. Screen on: {keepDisplayOn}");
WaitHandle.WaitAny(new[] { _threadToken.WaitHandle });
return success;
}
else
{
_log.Info("Could not successfully set up indefinite keep awake.");
return success;
}
}
catch (OperationCanceledException ex)
{
// Task was clearly cancelled.
_log.Info($"Background thread termination: {NativeMethods.GetCurrentThreadId()}. Message: {ex.Message}");
return success;
}
}
private static bool RunTimedLoop(uint seconds, bool keepDisplayOn = true)
{
bool success = false;
// In case cancellation was already requested.
_threadToken.ThrowIfCancellationRequested();
try
{
if (keepDisplayOn)
{
success = SetAwakeState(ExecutionState.ES_SYSTEM_REQUIRED | ExecutionState.ES_DISPLAY_REQUIRED | ExecutionState.ES_CONTINUOUS);
}
else
{
success = SetAwakeState(ExecutionState.ES_SYSTEM_REQUIRED | ExecutionState.ES_CONTINUOUS);
}
if (success)
{
_log.Info($"Initiated temporary keep awake in background thread: {NativeMethods.GetCurrentThreadId()}. Screen on: {keepDisplayOn}");
_timedLoopTimer = new System.Timers.Timer(seconds * 1000);
_timedLoopTimer.Elapsed += (s, e) =>
{
_tokenSource.Cancel();
_timedLoopTimer.Stop();
};
_timedLoopTimer.Disposed += (s, e) =>
{
_log.Info("Old timer disposed.");
};
_timedLoopTimer.Start();
WaitHandle.WaitAny(new[] { _threadToken.WaitHandle });
_timedLoopTimer.Stop();
_timedLoopTimer.Dispose();
return success;
}
else
{
_log.Info("Could not set up timed keep-awake with display on.");
return success;
}
}
catch (OperationCanceledException ex)
{
// Task was clearly cancelled.
_log.Info($"Background thread termination: {NativeMethods.GetCurrentThreadId()}. Message: {ex.Message}");
return success;
}
}
public static string GetOperatingSystemBuild()
{
try
{
#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type.
RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(BuildRegistryLocation);
#pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type.
if (registryKey != null)
{
var versionString = $"{registryKey.GetValue("ProductName")} {registryKey.GetValue("DisplayVersion")} {registryKey.GetValue("BuildLabEx")}";
return versionString;
}
else
{
_log.Info("Registry key acquisition for OS failed.");
return string.Empty;
}
}
catch (Exception ex)
{
_log.Info($"Could not get registry key for the build number. Error: {ex.Message}");
return string.Empty;
}
}
}
}
| 38.651685 | 170 | 0.551938 | [
"MIT"
] | Acidburn0zzz/PowerToys | src/modules/awake/Awake/Core/APIHelper.cs | 10,056 | C# |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceModel;
namespace Workday.AcademicFoundation
{
[GeneratedCode("System.ServiceModel", "4.0.0.0"), EditorBrowsable(EditorBrowsableState.Advanced), DebuggerStepThrough, MessageContract(IsWrapped = false)]
public class Put_Student_Tag_CategoryInput
{
[MessageHeader(Namespace = "urn:com.workday/bsvc")]
public Workday_Common_HeaderType Workday_Common_Header;
[MessageBodyMember(Namespace = "urn:com.workday/bsvc", Order = 0)]
public Put_Student_Tag_Category_RequestType Put_Student_Tag_Category_Request;
public Put_Student_Tag_CategoryInput()
{
}
public Put_Student_Tag_CategoryInput(Workday_Common_HeaderType Workday_Common_Header, Put_Student_Tag_Category_RequestType Put_Student_Tag_Category_Request)
{
this.Workday_Common_Header = Workday_Common_Header;
this.Put_Student_Tag_Category_Request = Put_Student_Tag_Category_Request;
}
}
}
| 34.034483 | 158 | 0.829787 | [
"MIT"
] | matteofabbri/Workday.WebServices | Workday.AcademicFoundation/Put_Student_Tag_CategoryInput.cs | 987 | C# |
using Bam.Net.Schema.Org.DataTypes;
namespace Bam.Net.Schema.Org.Things
{
///<summary>A property, used to indicate attributes and relationships of some Thing; equivalent to rdf:Property.</summary>
public class Property: Intangible
{
///<summary>Relates a property to a class that is (one of) the type(s) the property is expected to be used on.</summary>
public Class DomainIncludes {get; set;}
///<summary>Relates a property to a property that is its inverse. Inverse properties relate the same pairs of items to each other, but in reversed direction. For example, the 'alumni' and 'alumniOf' properties are inverseOf each other. Some properties don't have explicit inverses; in these situations RDFa and JSON-LD syntax for reverse properties can be used.</summary>
public Property InverseOf {get; set;}
///<summary>Relates a property to a class that constitutes (one of) the expected type(s) for values of the property.</summary>
public Class RangeIncludes {get; set;}
///<summary>Relates a term (i.e. a property, class or enumeration) to one that supersedes it.</summary>
public OneOfThese<Class,Enumeration,Property> SupersededBy {get; set;}
}
}
| 65 | 373 | 0.759829 | [
"MIT"
] | BryanApellanes/bamsdo | bam.net.schema.org/Schema.Org/Things/Property.cs | 1,170 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.EntityFrameworkCore.Metadata.Internal
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static class ScaffoldingAnnotationNames
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public const string Prefix = "Scaffolding:";
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public const string ColumnOrdinal = Prefix + "ColumnOrdinal";
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public const string EntityTypeErrors = Prefix + "EntityTypeErrors";
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public const string DbSetName = Prefix + "DbSetName";
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public const string DatabaseName = Prefix + "DatabaseName";
}
}
| 48.511628 | 111 | 0.652924 | [
"Apache-2.0"
] | EasonDongH/EntityFrameworkCore | src/EFCore.Design/Metadata/Internal/ScaffoldingAnnotationNames.cs | 2,086 | C# |
namespace Shapes.Models
{
public class Triangle : Shape
{
public Triangle()
{
}
public Triangle(double width, double height)
: base(width, height)
{
}
public override double CalculateSurface()
{
var surface = (this.Height * this.Width) / 2;
return surface;
}
}
} | 19.3 | 57 | 0.492228 | [
"MIT"
] | Horwits/Telerik-Academy-2016-2017 | C#/C#-OOP/05.OOPPrinciplesPartTwo/Shapes/Models/Triangle.cs | 388 | 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: Templates\CSharp\Model\ComplexType.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
/// <summary>
/// The type TargetPolicyEndpoints.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
[JsonConverter(typeof(DerivedTypeConverter))]
public partial class TargetPolicyEndpoints
{
/// <summary>
/// Initializes a new instance of the <see cref="TargetPolicyEndpoints"/> class.
/// </summary>
public TargetPolicyEndpoints()
{
this.ODataType = "microsoft.graph.targetPolicyEndpoints";
}
/// <summary>
/// Gets or sets platformTypes.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "platformTypes", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<string> PlatformTypes { get; set; }
/// <summary>
/// Gets or sets additional data.
/// </summary>
[JsonExtensionData(ReadData = true)]
public IDictionary<string, object> AdditionalData { get; set; }
/// <summary>
/// Gets or sets @odata.type.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "@odata.type", Required = Newtonsoft.Json.Required.Default)]
public string ODataType { get; set; }
}
}
| 36.962264 | 153 | 0.597754 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Models/Generated/TargetPolicyEndpoints.cs | 1,959 | C# |
//
// This file has been generated automatically by MonoDevelop to store outlets and
// actions made in the Xcode designer. If it is removed, they will be lost.
// Manual changes to this file may not be handled correctly.
//
using Foundation;
namespace DwxSpeaker.Ios
{
[Register("ViewController")]
partial class ViewController
{
void ReleaseDesignerOutlets()
{
}
}
}
| 22.777778 | 81 | 0.685366 | [
"MIT"
] | reghrafa/XamarinExpertDay_2019 | ExpertDay.FormsIntegrationSample/DwxSpeaker.Ios/ViewController.designer.cs | 412 | C# |
/*
The contents of this file are subject to the Mozilla Public License Version 1.1
(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.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the
specific language governing rights and limitations under the License.
The Original Code is "PipeParser.java". Description:
"An implementation of Parser that supports traditionally encoded (i.e"
The Initial Developer of the Original Code is University Health Network. Copyright (C)
2001. All Rights Reserved.
Contributor(s): Kenneth Beaton.
Alternatively, the contents of this file may be used under the terms of the
GNU General Public License (the "GPL"), in which case the provisions of the GPL are
applicable instead of those above. If you wish to allow use of your version of this
file only under the terms of the GPL and not to allow others to use your version
of this file under the MPL, indicate your decision by deleting the provisions above
and replace them with the notice and other provisions required by the GPL License.
If you do not delete the provisions above, a recipient may use your version of
this file under either the MPL or the GPL.
*/
namespace NHapi.Base.Parser
{
using System;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using NHapi.Base.Log;
using NHapi.Base.Model;
using NHapi.Base.Util;
/// <summary>
/// This is a legacy implementation of the PipeParser and should not be used
/// for new projects.
/// <para>
/// In versions of NHapi prior to version 3, a behaviour was corrected where unexpected segments
/// would be placed at the tail end of the first segment group encountered.
/// </para>
/// Any legacy code which still depends on previous behaviour can use this
/// implementation.
/// </summary>
[Obsolete("Use PipeParser instead.")]
public class LegacyPipeParser : ParserBase
{
private const string SegDelim = "\r"; // see section 2.8 of spec
private static readonly IHapiLog Log;
static LegacyPipeParser()
{
Log = HapiLogFactory.GetHapiLog(typeof(LegacyPipeParser));
}
/// <summary>Creates a new LegacyPipeParser. </summary>
public LegacyPipeParser()
{
}
/// <summary>Creates a new LegacyPipeParser. </summary>
public LegacyPipeParser(IModelClassFactory factory)
: base(factory)
{
}
/// <summary>
/// Gets the preferred encoding of this Parser.
/// </summary>
public override string DefaultEncoding => "VB";
/// <summary>
/// Splits the given composite string into an array of components using
/// the given delimiter.
/// </summary>
public static string[] Split(string composite, string delim)
{
var components = new ArrayList();
// defend against evil nulls
if (composite == null)
{
composite = string.Empty;
}
if (delim == null)
{
delim = string.Empty;
}
var tok = new SupportClass.Tokenizer(composite, delim, true);
var previousTokenWasDelim = true;
while (tok.HasMoreTokens())
{
var thisTok = tok.NextToken();
if (thisTok.Equals(delim))
{
if (previousTokenWasDelim)
{
components.Add(null);
}
previousTokenWasDelim = true;
}
else
{
components.Add(thisTok);
previousTokenWasDelim = false;
}
}
var ret = new string[components.Count];
for (var i = 0; i < components.Count; i++)
{
ret[i] = (string)components[i];
}
return ret;
}
/// <summary>
/// Encodes the given Type, using the given encoding characters.
/// It is assumed that the Type represents a complete field rather than a component.
/// </summary>
public static string Encode(IType source, EncodingCharacters encodingChars)
{
var field = new StringBuilder();
for (var i = 1; i <= Terser.NumComponents(source); i++)
{
var comp = new StringBuilder();
for (var j = 1; j <= Terser.NumSubComponents(source, i); j++)
{
var p = Terser.GetPrimitive(source, i, j);
comp.Append(EncodePrimitive(p, encodingChars));
comp.Append(encodingChars.SubcomponentSeparator);
}
field.Append(StripExtraDelimiters(comp.ToString(), encodingChars.SubcomponentSeparator));
field.Append(encodingChars.ComponentSeparator);
}
return StripExtraDelimiters(field.ToString(), encodingChars.ComponentSeparator);
}
/// <summary>
/// Returns given group serialized as a pipe-encoded string - this method is called
/// by encode(Message source, String encoding).
/// </summary>
public static string Encode(IGroup source, EncodingCharacters encodingChars)
{
var result = new StringBuilder();
var names = source.Names;
for (var i = 0; i < names.Length; i++)
{
var reps = source.GetAll(names[i]);
for (var rep = 0; rep < reps.Length; rep++)
{
if (reps[rep] is IGroup)
{
result.Append(Encode((IGroup)reps[rep], encodingChars));
}
else
{
var segString = Encode((ISegment)reps[rep], encodingChars);
if (segString.Length >= 4)
{
result.Append(segString);
result.Append('\r');
}
}
}
}
return result.ToString();
}
public static string Encode(ISegment source, EncodingCharacters encodingChars)
{
var result = new StringBuilder();
result.Append(source.GetStructureName());
result.Append(encodingChars.FieldSeparator);
// start at field 2 for MSH segment because field 1 is the field delimiter
var startAt = 1;
if (IsDelimDefSegment(source.GetStructureName()))
{
startAt = 2;
}
// loop through fields; for every field delimit any repetitions and add field delimiter after ...
var numFields = source.NumFields();
for (var i = startAt; i <= numFields; i++)
{
try
{
var reps = source.GetField(i);
for (var j = 0; j < reps.Length; j++)
{
var fieldText = Encode(reps[j], encodingChars);
// if this is MSH-2, then it shouldn't be escaped, so un-escape it again
if (IsDelimDefSegment(source.GetStructureName()) && i == 2)
{
fieldText = Escape.UnescapeText(fieldText, encodingChars);
}
result.Append(fieldText);
if (j < reps.Length - 1)
{
result.Append(encodingChars.RepetitionSeparator);
}
}
}
catch (HL7Exception e)
{
Log.Error("Error while encoding segment: ", e);
}
result.Append(encodingChars.FieldSeparator);
}
// strip trailing delimiters ...
return StripExtraDelimiters(result.ToString(), encodingChars.FieldSeparator);
}
/// <summary>
/// Removes leading whitespace from the given string. This method was created to deal with frequent
/// problems parsing messages that have been hand-written in windows. The intuitive way to delimit
/// segments is to hit ENTER at the end of each segment, but this creates both a carriage return
/// and a line feed, so to the parser, the first character of the next segment is the line feed.
/// </summary>
public static string StripLeadingWhitespace(string in_Renamed)
{
var out_Renamed = new StringBuilder();
var chars = in_Renamed.ToCharArray();
var c = 0;
while (c < chars.Length)
{
if (!char.IsWhiteSpace(chars[c]))
{
break;
}
c++;
}
for (var i = c; i < chars.Length; i++)
{
out_Renamed.Append(chars[i]);
}
return out_Renamed.ToString();
}
public override void Parse(IMessage message, string @string)
{
var messageIter = new Util.MessageIterator(message, "MSH", true);
FilterIterator.IPredicate segmentsOnly = new AnonymousClassPredicate(this);
var segmentIter = new FilterIterator(messageIter, segmentsOnly);
var segments = Split(@string, SegDelim);
var encodingChars = GetEncodingChars(@string);
var delimiter = '|';
for (var i = 0; i < segments.Length; i++)
{
// get rid of any leading whitespace characters ...
if (segments[i] != null && segments[i].Length > 0 && char.IsWhiteSpace(segments[i][0]))
{
segments[i] = StripLeadingWhitespace(segments[i]);
}
// sometimes people put extra segment delimiters at end of msg ...
if (segments[i] != null && segments[i].Length >= 3)
{
var name = segments[i].Substring(0, 3 - 0);
if (i == 0)
{
name = segments[i].Substring(0, 3);
delimiter = segments[i][3];
}
else
{
name = segments[i].IndexOf(delimiter) >= 0
? segments[i].Substring(0, segments[i].IndexOf(delimiter))
: segments[i];
}
Log.Debug("Parsing segment " + name);
messageIter.Direction = name;
FilterIterator.IPredicate byDirection = new AnonymousClassPredicate1(name, this);
var dirIter = new FilterIterator(segmentIter, byDirection);
if (dirIter.MoveNext())
{
Parse((ISegment)dirIter.Current, segments[i], encodingChars);
}
}
}
}
/// <summary> Returns a String representing the encoding of the given message, if
/// the encoding is recognized. For example if the given message appears
/// to be encoded using HL7 2.x XML rules then "XML" would be returned.
/// If the encoding is not recognized then null is returned. That this
/// method returns a specific encoding does not guarantee that the
/// message is correctly encoded (e.g. well formed XML) - just that
/// it is not encoded using any other encoding than the one returned.
/// </summary>
public override string GetEncoding(string message)
{
string encoding = null;
// quit if the string is too short
if (message.Length < 4)
{
return null;
}
// see if it looks like this message is | encoded ...
var ok = true;
// string should start with "MSH"
if (!message.StartsWith("MSH", StringComparison.Ordinal))
{
return null;
}
// 4th character of each segment should be field delimiter
var fourthChar = message[3];
var st = new SupportClass.Tokenizer(message, Convert.ToString(SegDelim), false);
while (st.HasMoreTokens())
{
var x = st.NextToken();
if (x.Length > 0)
{
if (char.IsWhiteSpace(x[0]))
{
x = StripLeadingWhitespace(x);
}
if (x.Length >= 4 && x[3] != fourthChar)
{
return null;
}
}
}
// should be at least 11 field delimiters (because MSH-12 is required)
var nextFieldDelimLoc = 0;
for (var i = 0; i < 11; i++)
{
nextFieldDelimLoc = message.IndexOf((char)fourthChar, nextFieldDelimLoc + 1);
if (nextFieldDelimLoc < 0)
{
return null;
}
}
if (ok)
{
encoding = "VB";
}
return encoding;
}
/// <deprecated> this method should not be public.
/// </deprecated>
/// <param name="message">
/// </param>
/// <returns>
/// </returns>
/// <throws> HL7Exception. </throws>
/// <throws> EncodingNotSupportedException. </throws>
public virtual string GetMessageStructure(string message)
{
return GetStructure(message).Structure;
}
/// <summary> Parses a segment string and populates the given Segment object. Unexpected fields are
/// added as Varies' at the end of the segment.
///
/// </summary>
/// <throws> HL7Exception if the given string does not contain the. </throws>
/// <summary> given segment or if the string is not encoded properly.
/// </summary>
public virtual void Parse(ISegment destination, string segment, EncodingCharacters encodingChars)
{
var fieldOffset = 0;
if (IsDelimDefSegment(destination.GetStructureName()))
{
fieldOffset = 1;
// set field 1 to fourth character of string
Terser.Set(destination, 1, 0, 1, 1, Convert.ToString(encodingChars.FieldSeparator));
}
var fields = Split(segment, Convert.ToString(encodingChars.FieldSeparator));
for (var i = 1; i < fields.Length; i++)
{
var reps = Split(fields[i], Convert.ToString(encodingChars.RepetitionSeparator));
if (Log.DebugEnabled)
{
Log.Debug(reps.Length + "reps delimited by: " + encodingChars.RepetitionSeparator);
}
// MSH-2 will get split incorrectly so we have to fudge it ...
var isMSH2 = IsDelimDefSegment(destination.GetStructureName()) && i + fieldOffset == 2;
if (isMSH2)
{
reps = new string[1];
reps[0] = fields[i];
}
for (var j = 0; j < reps.Length; j++)
{
try
{
var statusMessage = $"Parsing field {i + fieldOffset} repetition {j}";
Log.Debug(statusMessage);
var field = destination.GetField(i + fieldOffset, j);
if (isMSH2)
{
Terser.GetPrimitive(field, 1, 1).Value = reps[j];
}
else
{
Parse(field, reps[j], encodingChars);
}
}
catch (HL7Exception e)
{
// set the field location and throw again ...
e.FieldPosition = i + fieldOffset;
e.SegmentRepetition = Util.MessageIterator.GetIndex(destination.ParentStructure, destination).Rep;
e.SegmentName = destination.GetStructureName();
throw;
}
}
}
// set data type of OBX-5
if (destination.GetType().FullName.IndexOf("OBX") >= 0)
{
Varies.FixOBX5(destination, Factory);
}
}
/// <summary> <p>Returns a minimal amount of data from a message string, including only the
/// data needed to send a response to the remote system. This includes the
/// following fields:
/// <ul><li>field separator</li>
/// <li>encoding characters</li>
/// <li>processing ID</li>
/// <li>message control ID</li></ul>
/// This method is intended for use when there is an error parsing a message,
/// (so the Message object is unavailable) but an error message must be sent
/// back to the remote system including some of the information in the inbound
/// message. This method parses only that required information, hopefully
/// avoiding the condition that caused the original error. The other
/// fields in the returned MSH segment are empty.</p>
/// </summary>
public override ISegment GetCriticalResponseData(string message)
{
// try to get MSH segment
var locStartMSH = message.IndexOf("MSH");
if (locStartMSH < 0)
{
throw new HL7Exception("Couldn't find MSH segment in message: " + message, ErrorCode.SEGMENT_SEQUENCE_ERROR);
}
var locEndMSH = message.IndexOf('\r', locStartMSH + 1);
if (locEndMSH < 0)
{
locEndMSH = message.Length;
}
var mshString = message.Substring(locStartMSH, locEndMSH - locStartMSH);
// find out what the field separator is
var fieldSep = mshString[3];
// get field array
var fields = Split(mshString, Convert.ToString(fieldSep));
ISegment msh;
try
{
// parse required fields
var encChars = fields[1];
var compSep = encChars[0];
var messControlID = fields[9];
var procIDComps = Split(fields[10], Convert.ToString(compSep));
// fill MSH segment
var version = "2.4"; // default
try
{
version = GetVersion(message);
}
catch (Exception)
{
/* use the default */
}
msh = MakeControlMSH(version, Factory);
Terser.Set(msh, 1, 0, 1, 1, Convert.ToString(fieldSep));
Terser.Set(msh, 2, 0, 1, 1, encChars);
Terser.Set(msh, 10, 0, 1, 1, messControlID);
Terser.Set(msh, 11, 0, 1, 1, procIDComps[0]);
}
catch (Exception e)
{
SupportClass.WriteStackTrace(e, Console.Error);
throw new HL7Exception(
"Can't parse critical fields from MSH segment (" + e.GetType().FullName + ": " + e.Message + "): " + mshString,
ErrorCode.REQUIRED_FIELD_MISSING);
}
return msh;
}
/// <summary> For response messages, returns the value of MSA-2 (the message ID of the message
/// sent by the sending system). This value may be needed prior to main message parsing,
/// so that (particularly in a multi-threaded scenario) the message can be routed to
/// the thread that sent the request. We need this information first so that any
/// parse exceptions are thrown to the correct thread.
/// Returns null if MSA-2 can not be found (e.g. if the message is not a
/// response message).
/// </summary>
public override string GetAckID(string message)
{
string ackID = null;
var startMSA = message.IndexOf("\rMSA");
if (startMSA >= 0)
{
var startFieldOne = startMSA + 5;
var fieldDelim = message[startFieldOne - 1];
var start = message.IndexOf((char)fieldDelim, startFieldOne) + 1;
var end = message.IndexOf((char)fieldDelim, start);
var segEnd = message.IndexOf(Convert.ToString(SegDelim), start);
if (segEnd > start && segEnd < end)
{
end = segEnd;
}
// if there is no field delimiter after MSH-2, need to go to end of message, but not including end segment delimiter if it exists
if (end < 0)
{
if (message[message.Length - 1] == '\r')
{
end = message.Length - 1;
}
else
{
end = message.Length;
}
}
if (start > 0 && end > start)
{
ackID = message.Substring(start, end - start);
}
}
Log.Debug("ACK ID: " + ackID);
return ackID;
}
/// <summary> Returns the version ID (MSH-12) from the given message, without fully parsing the message.
/// The version is needed prior to parsing in order to determine the message class
/// into which the text of the message should be parsed.
/// </summary>
/// <throws> HL7Exception if the version field can not be found. </throws>
public override string GetVersion(string message)
{
var startMSH = message.IndexOf("MSH");
if (startMSH < 0)
{
throw new HL7Exception("No MSH header segment found.", ErrorCode.REQUIRED_FIELD_MISSING);
}
var endMSH = message.IndexOf(SegDelim, startMSH);
if (endMSH < 0)
{
endMSH = message.Length;
}
var msh = message.Substring(startMSH, endMSH - startMSH);
string fieldSep;
if (msh.Length > 3)
{
fieldSep = Convert.ToString(msh[3]);
}
else
{
throw new HL7Exception("Can't find field separator in MSH: " + msh, ErrorCode.UNSUPPORTED_VERSION_ID);
}
var fields = Split(msh, fieldSep);
string compSep;
if (fields.Length >= 2 && fields[0] == "MSH" && fields[1] != null && fields[1].Length > 0)
{
compSep = Convert.ToString(fields[1][0]); // get component separator as 1st encoding char
}
else
{
throw new HL7Exception(
"Can't find encoding characters - MSH has only " + fields.Length + " fields",
ErrorCode.REQUIRED_FIELD_MISSING);
}
if (fields.Length < 12)
{
throw new HL7Exception(
$"Can't find version ID - MSH has only {fields.Length} fields.",
ErrorCode.REQUIRED_FIELD_MISSING);
}
if (fields[11] == null)
{
throw new HL7Exception("MSH Version field is null.", ErrorCode.REQUIRED_FIELD_MISSING);
}
var version = Split(fields[11], compSep)[0];
if (version == null)
{
throw new HL7Exception("MSH Version field is invalid.", ErrorCode.REQUIRED_FIELD_MISSING);
}
return version.Trim();
}
/// <summary> Formats a Message object into an HL7 message string using the given
/// encoding.
/// </summary>
/// <throws> HL7Exception if the data fields in the message do not permit encoding. </throws>
/// <summary> (e.g. required fields are null).
/// </summary>
/// <throws> EncodingNotSupportedException if the requested encoding is not. </throws>
/// <summary> supported by this parser.
/// </summary>
protected internal override string DoEncode(IMessage source, string encoding)
{
if (!SupportsEncoding(encoding))
{
throw new EncodingNotSupportedException("This parser does not support the " + encoding + " encoding");
}
return Encode(source);
}
/// <summary> Formats a Message object into an HL7 message string using this parser's
/// default encoding ("VB").
/// </summary>
/// <throws> HL7Exception if the data fields in the message do not permit encoding. </throws>
/// <summary> (e.g. required fields are null).
/// </summary>
protected internal override string DoEncode(IMessage source)
{
// get encoding characters ...
var msh = (ISegment)source.GetStructure("MSH");
var fieldSepString = Terser.Get(msh, 1, 0, 1, 1);
if (fieldSepString == null)
{
// cdc: This was breaking when trying to construct a blank message, and there is no way to set the fieldSeperator, so fill in a default
// throw new HL7Exception("Can't encode message: MSH-1 (field separator) is missing");
fieldSepString = "|";
Terser.Set(msh, 1, 0, 1, 1, fieldSepString);
}
var fieldSep = '|';
if (fieldSepString != null && fieldSepString.Length > 0)
{
fieldSep = fieldSepString[0];
}
var encCharString = Terser.Get(msh, 2, 0, 1, 1);
if (encCharString == null)
{
// cdc: This was breaking when trying to construct a blank message, and there is no way to set the EncChars, so fill in a default
// throw new HL7Exception("Can't encode message: MSH-2 (encoding characters) is missing");
encCharString = @"^~\&";
Terser.Set(msh, 2, 0, 1, 1, encCharString);
}
var version = Terser.Get(msh, 12, 0, 1, 1);
if (version == null)
{
// Put in the message version
Terser.Set(msh, 12, 0, 1, 1, source.Version);
}
var msgStructure = Terser.Get(msh, 9, 0, 1, 1);
if (msgStructure == null)
{
// Create the MsgType and Trigger Event if not there
var messageTypeFullname = source.GetStructureName();
var i = messageTypeFullname.IndexOf("_");
if (i > 0)
{
var type = messageTypeFullname.Substring(0, i);
var triggerEvent = messageTypeFullname.Substring(i + 1);
Terser.Set(msh, 9, 0, 1, 1, type);
Terser.Set(msh, 9, 0, 2, 1, triggerEvent);
}
else
{
Terser.Set(msh, 9, 0, 1, 1, messageTypeFullname);
}
}
if (encCharString.Length != 4)
{
throw new HL7Exception(
"Encoding characters '" + encCharString + "' invalid -- must be 4 characters",
ErrorCode.DATA_TYPE_ERROR);
}
var en = new EncodingCharacters(fieldSep, encCharString);
// pass down to group encoding method which will operate recursively on children ...
return Encode((IGroup)source, en);
}
/// <summary> Parses a message string and returns the corresponding Message
/// object. Unexpected segments added at the end of their group.
///
/// </summary>
/// <throws> HL7Exception if the message is not correctly formatted. </throws>
/// <throws> EncodingNotSupportedException if the message encoded. </throws>
/// <summary> is not supported by this parser.
/// </summary>
protected internal override IMessage DoParse(string message, string version)
{
// try to instantiate a message object of the right class
var structure = GetStructure(message);
var m = InstantiateMessage(structure.Structure, version, structure.ExplicitlyDefined);
Parse(m, message);
return m;
}
/// <summary> Returns object that contains the field separator and encoding characters
/// for this message.
/// </summary>
private static EncodingCharacters GetEncodingChars(string message)
{
return new EncodingCharacters(message[3], message.Substring(4, 8 - 4));
}
private static string EncodePrimitive(IPrimitive p, EncodingCharacters encodingChars)
{
var val = ((IPrimitive)p).Value;
if (val == null)
{
val = string.Empty;
}
else
{
val = Escape.EscapeText(val, encodingChars);
}
return val;
}
/// <summary>
/// Removes unnecessary delimiters from the end of a field or segment.
/// This seems to be more convenient than checking to see if they are needed
/// while we are building the encoded string.
/// </summary>
private static string StripExtraDelimiters(string in_Renamed, char delim)
{
var chars = in_Renamed.ToCharArray();
// search from back end for first occurrence of non-delimiter ...
var c = chars.Length - 1;
var found = false;
while (c >= 0 && !found)
{
if (chars[c--] != delim)
{
found = true;
}
}
var ret = string.Empty;
if (found)
{
ret = new string(chars, 0, c + 2);
}
return ret;
}
/// <returns> true if the segment is MSH, FHS, or BHS. These need special treatment
/// because they define delimiters.
/// </returns>
/// <param name="theSegmentName">
/// </param>
private static bool IsDelimDefSegment(string theSegmentName)
{
var is_Renamed = false;
if (theSegmentName.Equals("MSH") || theSegmentName.Equals("FHS") || theSegmentName.Equals("BHS"))
{
is_Renamed = true;
}
return is_Renamed;
}
/// <summary> Fills a field with values from an unparsed string representing the field. </summary>
/// <param name="destinationField">the field Type.
/// </param>
/// <param name="data">the field string (including all components and subcomponents; not including field delimiters).
/// </param>
/// <param name="encodingCharacters">the encoding characters used in the message.
/// </param>
private static void Parse(IType destinationField, string data, EncodingCharacters encodingCharacters)
{
var components = Split(data, Convert.ToString(encodingCharacters.ComponentSeparator));
for (var i = 0; i < components.Length; i++)
{
var subcomponents = Split(components[i], Convert.ToString(encodingCharacters.SubcomponentSeparator));
for (var j = 0; j < subcomponents.Length; j++)
{
var val = subcomponents[j];
if (val != null)
{
val = Escape.UnescapeText(val, encodingCharacters);
}
Terser.GetPrimitive(destinationField, i + 1, j + 1).Value = val;
}
}
}
/// <returns>s the message structure from MSH-9-3.
/// </returns>
private MessageStructure GetStructure(string message)
{
var ec = GetEncodingChars(message);
var explicityDefined = true;
string wholeFieldNine;
string messageStructure;
try
{
var fields = Split(
message.Substring(0, Math.Max(message.IndexOf(SegDelim), message.Length) - 0),
Convert.ToString(ec.FieldSeparator));
wholeFieldNine = fields[8];
// message structure is component 3 but we'll accept a composite of 1 and 2 if there is no component 3 ...
// if component 1 is ACK, then the structure is ACK regardless of component 2
var comps = Split(wholeFieldNine, Convert.ToString(ec.ComponentSeparator));
if (comps.Length >= 3)
{
messageStructure = comps[2];
}
else if (comps.Length > 0 && comps[0] != null && comps[0].Equals("ACK"))
{
messageStructure = "ACK";
}
else if (comps.Length == 2)
{
explicityDefined = false;
messageStructure = comps[0] + "_" + comps[1];
}
else
{
var buf = new StringBuilder("Can't determine message structure from MSH-9: ");
buf.Append(wholeFieldNine);
if (comps.Length < 3)
{
buf.Append(" HINT: there are only ");
buf.Append(comps.Length);
buf.Append(" of 3 components present");
}
throw new HL7Exception(buf.ToString(), ErrorCode.UNSUPPORTED_MESSAGE_TYPE);
}
}
catch (IndexOutOfRangeException e)
{
throw new HL7Exception("Can't find message structure (MSH-9-3): " + e.Message, ErrorCode.UNSUPPORTED_MESSAGE_TYPE);
}
return new MessageStructure(messageStructure, explicityDefined);
}
/// <summary>
/// A struct for holding a message class string and a boolean indicating whether it
/// was defined explicitly.
/// </summary>
private class MessageStructure
{
public MessageStructure(string theMessageStructure, bool isExplicitlyDefined)
{
Structure = theMessageStructure;
ExplicitlyDefined = isExplicitlyDefined;
}
public string Structure { get; }
public bool ExplicitlyDefined { get; }
}
private class AnonymousClassPredicate : FilterIterator.IPredicate
{
public AnonymousClassPredicate(LegacyPipeParser enclosingInstance)
{
Enclosing_Instance = enclosingInstance;
}
public LegacyPipeParser Enclosing_Instance { get; }
public virtual bool evaluate(object obj)
{
return Evaluate(obj);
}
public virtual bool Evaluate(object obj)
{
return typeof(ISegment).IsAssignableFrom(obj.GetType());
}
}
private class AnonymousClassPredicate1 : FilterIterator.IPredicate
{
public AnonymousClassPredicate1(string name, LegacyPipeParser enclosingInstance)
{
Name = name;
Enclosing_Instance = enclosingInstance;
}
public LegacyPipeParser Enclosing_Instance { get; }
private string Name { get; }
/// <inheritdoc />
public virtual bool evaluate(object obj)
{
return Evaluate(obj);
}
/// <inheritdoc />
public virtual bool Evaluate(object obj)
{
var structureName = ((IStructure)obj).GetStructureName();
Log.Debug($"LegacyPipeParser iterating message in direction {Name} at {structureName}");
return Regex.IsMatch(structureName, Regex.Escape(Name) + $"\\d*");
}
}
}
} | 38.422085 | 151 | 0.514598 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | AMCN41R/nHapi | src/NHapi.Base/Parser/LegacyPipeParser.cs | 37,233 | C# |
namespace SKIT.FlurlHttpClient.ByteDance.TikTokShop.Models
{
/// <summary>
/// <para>表示 [POST] /afterSale/applyLogisticsIntercept 接口的响应。</para>
/// </summary>
public class AftersaleApplyLogisticsInterceptResponse : TikTokShopResponse<AftersaleApplyLogisticsInterceptResponse.Types.Data>
{
public static class Types
{
public class Data
{
public static class Types
{
public class InterceptResult
{
public static class Types
{
public class Product
{
/// <summary>
/// 获取或设置商品单号。
/// </summary>
[Newtonsoft.Json.JsonProperty("order_id")]
[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.NumericalStringConverter))]
[System.Text.Json.Serialization.JsonPropertyName("order_id")]
[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Converters.NumericalStringConverter))]
public string ProductOrderId { get; set; } = default!;
/// <summary>
/// 获取或设置商品图片 URL。
/// </summary>
[Newtonsoft.Json.JsonProperty("product_image")]
[System.Text.Json.Serialization.JsonPropertyName("product_image")]
public string ProductImageUrl { get; set; } = default!;
/// <summary>
/// 获取或设置商品名称。
/// </summary>
[Newtonsoft.Json.JsonProperty("product_name")]
[System.Text.Json.Serialization.JsonPropertyName("product_name")]
public string ProductName { get; set; } = default!;
/// <summary>
/// 获取或设置商品规格。
/// </summary>
[Newtonsoft.Json.JsonProperty("product_spec")]
[System.Text.Json.Serialization.JsonPropertyName("product_spec")]
public string ProductSpecification { get; set; } = default!;
/// <summary>
/// 获取或设置商品标签列表。
/// </summary>
[Newtonsoft.Json.JsonProperty("tags")]
[System.Text.Json.Serialization.JsonPropertyName("tags")]
public string[]? TagList { get; set; }
/// <summary>
/// 获取或设置单价(单位:分)。
/// </summary>
[Newtonsoft.Json.JsonProperty("price")]
[System.Text.Json.Serialization.JsonPropertyName("price")]
public int Price { get; set; }
/// <summary>
/// 获取或设置数量。
/// </summary>
[Newtonsoft.Json.JsonProperty("amount")]
[System.Text.Json.Serialization.JsonPropertyName("amount")]
public int Count { get; set; }
}
}
/// <summary>
/// 获取或设置物流公司编码。
/// </summary>
[Newtonsoft.Json.JsonProperty("company_code")]
[System.Text.Json.Serialization.JsonPropertyName("company_code")]
public string CompanyCode { get; set; } = default!;
/// <summary>
/// 获取或设置物流公司名称。
/// </summary>
[Newtonsoft.Json.JsonProperty("company_name")]
[System.Text.Json.Serialization.JsonPropertyName("company_name")]
public string CompanyName { get; set; } = default!;
/// <summary>
/// 获取或设置物流单号。
/// </summary>
[Newtonsoft.Json.JsonProperty("tracking_no")]
[System.Text.Json.Serialization.JsonPropertyName("tracking_no")]
public string LogisticsNumber { get; set; } = default!;
/// <summary>
/// 获取或设置包裹价值(单位:分)。
/// </summary>
[Newtonsoft.Json.JsonProperty("value_amount")]
[System.Text.Json.Serialization.JsonPropertyName("value_amount")]
public int ValueAmount { get; set; }
/// <summary>
/// 获取或设置是否可拦截。
/// </summary>
[Newtonsoft.Json.JsonProperty("can_intercept")]
[System.Text.Json.Serialization.JsonPropertyName("can_intercept")]
public bool? CanIntercept { get; set; }
/// <summary>
/// 获取或设置是否拦截成功。
/// </summary>
[Newtonsoft.Json.JsonProperty("is_success")]
[System.Text.Json.Serialization.JsonPropertyName("is_success")]
public bool? IsSuccessful { get; set; }
/// <summary>
/// 获取或设置不可拦截编码。
/// </summary>
[Newtonsoft.Json.JsonProperty("unavailable_reason_code")]
[System.Text.Json.Serialization.JsonPropertyName("unavailable_reason_code")]
public int UnavailableReasonCode { get; set; }
/// <summary>
/// 获取或设置不可拦截编码。
/// </summary>
[Newtonsoft.Json.JsonProperty("unavailable_reason")]
[System.Text.Json.Serialization.JsonPropertyName("unavailable_reason")]
public string? UnavailableReason { get; set; }
/// <summary>
/// 获取或设置拦截费用(单位:分)。
/// </summary>
[Newtonsoft.Json.JsonProperty("intercept_cost")]
[System.Text.Json.Serialization.JsonPropertyName("intercept_cost")]
public int? InterceptCost { get; set; }
/// <summary>
/// 获取或设置当前售后商品信息。
/// </summary>
[Newtonsoft.Json.JsonProperty("cur_product")]
[System.Text.Json.Serialization.JsonPropertyName("cur_product")]
public Types.Product CurrentProduct { get; set; } = default!;
/// <summary>
/// 获取或设置其它商品列表。
/// </summary>
[Newtonsoft.Json.JsonProperty("other_products")]
[System.Text.Json.Serialization.JsonPropertyName("other_products")]
public Types.Product[]? OtherProduct { get; set; }
/// <summary>
/// 获取或设置其他商品件数。
/// </summary>
[Newtonsoft.Json.JsonProperty("other_product_amount")]
[System.Text.Json.Serialization.JsonPropertyName("other_product_amount")]
public int OtherProductCount { get; set; }
}
}
/// <summary>
/// 获取或设置物流拦截结果列表。
/// </summary>
[Newtonsoft.Json.JsonProperty("intercept_results")]
[System.Text.Json.Serialization.JsonPropertyName("intercept_results")]
public Types.InterceptResult[] InterceptResultList { get; set; } = default!;
/// <summary>
/// 获取或设置拦截成功次数。
/// </summary>
[Newtonsoft.Json.JsonProperty("success_count")]
[System.Text.Json.Serialization.JsonPropertyName("success_count")]
public int SuccessCount { get; set; }
/// <summary>
/// 获取或设置拦截失败次数。
/// </summary>
[Newtonsoft.Json.JsonProperty("failed_count")]
[System.Text.Json.Serialization.JsonPropertyName("failed_count")]
public int FailCount { get; set; }
/// <summary>
/// 获取或设置不可拦截编码。
/// </summary>
[Newtonsoft.Json.JsonProperty("unavailable_reason_code")]
[System.Text.Json.Serialization.JsonPropertyName("unavailable_reason_code")]
public int UnavailableReasonCode { get; set; }
/// <summary>
/// 获取或设置不可拦截编码。
/// </summary>
[Newtonsoft.Json.JsonProperty("unavailable_reason")]
[System.Text.Json.Serialization.JsonPropertyName("unavailable_reason")]
public string? UnavailableReason { get; set; }
/// <summary>
/// 获取或设置售后单退款总金额(单位:分)。
/// </summary>
[Newtonsoft.Json.JsonProperty("refund_amount")]
[System.Text.Json.Serialization.JsonPropertyName("refund_amount")]
public int RefundAmount { get; set; }
}
}
}
}
| 48.833333 | 140 | 0.439068 | [
"MIT"
] | JohnZhaoXiaoHu/DotNetCore.SKIT.FlurlHttpClient.ByteDance | src/SKIT.FlurlHttpClient.ByteDance.TikTokShop/Models/Aftersale/AftersaleApplyLogisticsInterceptResponse.cs | 10,594 | 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;
namespace Hager_Ind_CRM.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class ExternalLoginModel : PageModel
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly UserManager<IdentityUser> _userManager;
private readonly IEmailSender _emailSender;
private readonly ILogger<ExternalLoginModel> _logger;
public ExternalLoginModel(
SignInManager<IdentityUser> signInManager,
UserManager<IdentityUser> 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 IdentityUser { 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.698225 | 154 | 0.575022 | [
"Unlicense",
"MIT"
] | raytellier/Hager_Ind_CRM | Areas/Identity/Pages/Account/ExternalLogin.cshtml.cs | 6,880 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NestorRojas_Blog.Models;
using Microsoft.Extensions.Configuration;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
namespace NestorRojas_Blog.Controllers
{
public class BlogController : Controller
{
IConfiguration _iconfiguration;
public BlogController(IConfiguration iconfiguration)
{
_iconfiguration = iconfiguration;
}
// GET: Blog
public async Task<IActionResult> Index()
{
List<BlogViewModel> blog = await GetBlogs();
return View(blog);
}
// GET: Blog/Details/5
public async Task<IActionResult> ReadBlog(int Id)
{
BlogViewModel blog = await ReadBlog_API(Id);
return View(blog);
}
// GET: Blog/Create
public ActionResult CreateBlog()
{
return View();
}
// POST: Blog/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateBlog(BlogViewModel model)
{
try
{
var result = await CreateBlog_API(model);
if (result)
{
return RedirectToAction(nameof(Index));
}
else
{
ViewBag.Result = "Blog was not created, please review";
return RedirectToAction(nameof(CreateBlog));
}
}
catch(Exception ex)
{
ViewBag.Result = ex.Message;
return RedirectToAction(nameof(Index));
}
}
// GET: Blog/Edit/5
public async Task<IActionResult> EditBlog(int id)
{
BlogViewModel blog = await ReadBlog_API(id);
return View(blog);
}
// POST: Blog/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditBlog(BlogViewModel model)
{
try
{
var result = await UpdateBlog_API(model);
if (result)
{
return RedirectToAction(nameof(Index));
}
else
{
ViewBag.Result = "Blog was not updated, please review";
return RedirectToAction(nameof(CreateBlog));
}
}
catch (Exception ex)
{
ViewBag.Result = ex.Message;
return RedirectToAction(nameof(Index));
}
}
// GET: Blog/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: Blog/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, IFormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
#region API Calls
private async Task<List<BlogViewModel>> GetBlogs()
{
List<BlogViewModel> blog = new List<BlogViewModel>();
var apiServerURL = _iconfiguration["ApiServer"];
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(apiServerURL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("api/Blog/GetBlogs");
if (response.IsSuccessStatusCode)
{
var responseData = await response.Content.ReadAsStringAsync();
blog = JsonConvert.DeserializeObject<List<BlogViewModel>>(responseData);
response.Dispose();
}
}
return blog;
}
private async Task<BlogViewModel> ReadBlog_API(int Id)
{
BlogViewModel blog = new BlogViewModel();
var apiServerURL = _iconfiguration["ApiServer"];
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(apiServerURL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string param = "?Id=" + Id;
HttpResponseMessage response = await client.GetAsync("api/Blog/ReadBlog" + param);
if (response.IsSuccessStatusCode)
{
var responseData = await response.Content.ReadAsStringAsync();
blog = JsonConvert.DeserializeObject<BlogViewModel>(responseData);
response.Dispose();
}
}
return blog;
}
private async Task<bool> CreateBlog_API(BlogViewModel model)
{
bool result = false;
var stringData = JsonConvert.SerializeObject(model);
var contentData = new StringContent(stringData, System.Text.Encoding.UTF8, "application/json");
var apiServerURL = _iconfiguration["ApiServer"];
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(apiServerURL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsync("api/Blog/CreateBlog", contentData);
if (response.IsSuccessStatusCode)
{
var responseData = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<bool>(responseData);
response.Dispose();
}
}
return result;
}
private async Task<bool> UpdateBlog_API(BlogViewModel model)
{
bool result = false;
var stringData = JsonConvert.SerializeObject(model);
var contentData = new StringContent(stringData, System.Text.Encoding.UTF8, "application/json");
var apiServerURL = _iconfiguration["ApiServer"];
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(apiServerURL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsync("api/Blog/UpdateBlog", contentData);
if (response.IsSuccessStatusCode)
{
var responseData = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<bool>(responseData);
response.Dispose();
}
}
return result;
}
#endregion
}
} | 33.711712 | 113 | 0.544094 | [
"MIT"
] | nestorojas/ASP.NET-Web-API | NestorRojas-Blog/Controllers/BlogController.cs | 7,486 | C# |
using Ooze.Configuration.Options;
using System.Linq;
namespace Ooze.Validation
{
internal class OozeOptionsValidator
{
public bool Validate(OozeOptions options)
{
return ValidateOperations(options.Operations);
}
private bool ValidateOperations(OozeOperations operations)
{
var fields = operations.GetType()
.GetFields()
.ToList();
var fieldCount = fields.Count;
var fieldValues = fields.Select(field => field.GetValue(operations).ToString())
.Distinct()
.ToList();
if (fieldCount != fieldValues.Count)
return false;
var anyPropHasLettersOrDigits = fieldValues.Any(value => value.Where(@char => !char.IsLetterOrDigit(@char)).Count() != value.Count());
if (anyPropHasLettersOrDigits)
return false;
return true;
}
}
}
| 27.828571 | 146 | 0.571869 | [
"MIT"
] | DenisPav/Ooze | src/Ooze/Validation/OozeOptionsValidator.cs | 976 | C# |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// 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.Globalization;
using System.Text;
using DiscUtils.Streams;
namespace DiscUtils.Registry
{
/// <summary>
/// A registry value.
/// </summary>
internal sealed class RegistryValue
{
private readonly ValueCell _cell;
private readonly RegistryHive _hive;
internal RegistryValue(RegistryHive hive, ValueCell cell)
{
_hive = hive;
_cell = cell;
}
/// <summary>
/// Gets the type of the value.
/// </summary>
public RegistryValueType DataType
{
get { return _cell.DataType; }
}
/// <summary>
/// Gets the name of the value, or empty string if unnamed.
/// </summary>
public string Name
{
get { return _cell.Name ?? string.Empty; }
}
/// <summary>
/// Gets the value data mapped to a .net object.
/// </summary>
/// <remarks>The mapping from registry type of .NET type is as follows:
/// <list type="table">
/// <listheader>
/// <term>Value Type</term>
/// <term>.NET type</term>
/// </listheader>
/// <item>
/// <description>String</description>
/// <description>string</description>
/// </item>
/// <item>
/// <description>ExpandString</description>
/// <description>string</description>
/// </item>
/// <item>
/// <description>Link</description>
/// <description>string</description>
/// </item>
/// <item>
/// <description>DWord</description>
/// <description>uint</description>
/// </item>
/// <item>
/// <description>DWordBigEndian</description>
/// <description>uint</description>
/// </item>
/// <item>
/// <description>MultiString</description>
/// <description>string[]</description>
/// </item>
/// <item>
/// <description>QWord</description>
/// <description>ulong</description>
/// </item>
/// </list>
/// </remarks>
public object Value
{
get { return ConvertToObject(GetData(), DataType); }
}
/// <summary>
/// The raw value data as a byte array.
/// </summary>
/// <returns>The value as a raw byte array.</returns>
public byte[] GetData()
{
if (_cell.DataLength < 0)
{
int len = _cell.DataLength & 0x7FFFFFFF;
byte[] buffer = new byte[4];
EndianUtilities.WriteBytesLittleEndian(_cell.DataIndex, buffer, 0);
byte[] result = new byte[len];
Array.Copy(buffer, result, len);
return result;
}
return _hive.RawCellData(_cell.DataIndex, _cell.DataLength);
}
/// <summary>
/// Sets the value as raw bytes, with no validation that enough data is specified for the given value type.
/// </summary>
/// <param name="data">The data to store.</param>
/// <param name="offset">The offset within <c>data</c> of the first byte to store.</param>
/// <param name="count">The number of bytes to store.</param>
/// <param name="valueType">The type of the data.</param>
public void SetData(byte[] data, int offset, int count, RegistryValueType valueType)
{
// If we can place the data in the DataIndex field, do that to save space / allocation
if ((valueType == RegistryValueType.Dword || valueType == RegistryValueType.DwordBigEndian) && count <= 4)
{
if (_cell.DataLength >= 0)
{
_hive.FreeCell(_cell.DataIndex);
}
_cell.DataLength = (int)((uint)count | 0x80000000);
_cell.DataIndex = EndianUtilities.ToInt32LittleEndian(data, offset);
_cell.DataType = valueType;
}
else
{
if (_cell.DataIndex == -1 || _cell.DataLength < 0)
{
_cell.DataIndex = _hive.AllocateRawCell(count);
}
if (!_hive.WriteRawCellData(_cell.DataIndex, data, offset, count))
{
int newDataIndex = _hive.AllocateRawCell(count);
_hive.WriteRawCellData(newDataIndex, data, offset, count);
_hive.FreeCell(_cell.DataIndex);
_cell.DataIndex = newDataIndex;
}
_cell.DataLength = count;
_cell.DataType = valueType;
}
_hive.UpdateCell(_cell, false);
}
/// <summary>
/// Sets the value stored.
/// </summary>
/// <param name="value">The value to store.</param>
/// <param name="valueType">The registry type of the data.</param>
public void SetValue(object value, RegistryValueType valueType)
{
if (valueType == RegistryValueType.None)
{
if (value is int)
{
valueType = RegistryValueType.Dword;
}
else if (value is byte[])
{
valueType = RegistryValueType.Binary;
}
else if (value is string[])
{
valueType = RegistryValueType.MultiString;
}
else
{
valueType = RegistryValueType.String;
}
}
byte[] data = ConvertToData(value, valueType);
SetData(data, 0, data.Length, valueType);
}
/// <summary>
/// Gets a string representation of the registry value.
/// </summary>
/// <returns>The registry value as a string.</returns>
public override string ToString()
{
return Name + ":" + DataType + ":" + DataAsString();
}
private static object ConvertToObject(byte[] data, RegistryValueType type)
{
switch (type)
{
case RegistryValueType.String:
case RegistryValueType.ExpandString:
case RegistryValueType.Link:
return Encoding.Unicode.GetString(data).Trim('\0');
case RegistryValueType.Dword:
return EndianUtilities.ToInt32LittleEndian(data, 0);
case RegistryValueType.DwordBigEndian:
return EndianUtilities.ToInt32BigEndian(data, 0);
case RegistryValueType.MultiString:
string multiString = Encoding.Unicode.GetString(data).Trim('\0');
return multiString.Split('\0');
case RegistryValueType.QWord:
return string.Empty + EndianUtilities.ToUInt64LittleEndian(data, 0);
default:
return data;
}
}
private static byte[] ConvertToData(object value, RegistryValueType valueType)
{
if (valueType == RegistryValueType.None)
{
throw new ArgumentException("Specific registry value type must be specified", nameof(valueType));
}
byte[] data;
switch (valueType)
{
case RegistryValueType.String:
case RegistryValueType.ExpandString:
string strValue = value.ToString();
data = new byte[strValue.Length * 2 + 2];
Encoding.Unicode.GetBytes(strValue, 0, strValue.Length, data, 0);
break;
case RegistryValueType.Dword:
data = new byte[4];
EndianUtilities.WriteBytesLittleEndian((int)value, data, 0);
break;
case RegistryValueType.DwordBigEndian:
data = new byte[4];
EndianUtilities.WriteBytesBigEndian((int)value, data, 0);
break;
case RegistryValueType.MultiString:
string multiStrValue = string.Join("\0", (string[])value) + "\0";
data = new byte[multiStrValue.Length * 2 + 2];
Encoding.Unicode.GetBytes(multiStrValue, 0, multiStrValue.Length, data, 0);
break;
default:
data = (byte[])value;
break;
}
return data;
}
private string DataAsString()
{
switch (DataType)
{
case RegistryValueType.String:
case RegistryValueType.ExpandString:
case RegistryValueType.Link:
case RegistryValueType.Dword:
case RegistryValueType.DwordBigEndian:
case RegistryValueType.QWord:
return ConvertToObject(GetData(), DataType).ToString();
case RegistryValueType.MultiString:
return string.Join(",", (string[])ConvertToObject(GetData(), DataType));
default:
byte[] data = GetData();
string result = string.Empty;
for (int i = 0; i < Math.Min(data.Length, 8); ++i)
{
result += string.Format(CultureInfo.InvariantCulture, "{0:X2} ", (int)data[i]);
}
return result + string.Format(CultureInfo.InvariantCulture, " ({0} bytes)", data.Length);
}
}
}
} | 36.466887 | 118 | 0.525833 | [
"MIT"
] | ADeltaX/UWPSettingsEditor | src/UWPSettingsEditor/Registry/RegistryValue.cs | 11,013 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the transfer-2018-11-05.normal.json service model.
*/
using System;
using System.Collections.Generic;
using Amazon.Runtime;
using Amazon.Transfer.Model;
namespace Amazon.Transfer
{
/// <summary>
/// Interface for accessing Transfer
///
/// AWS Transfer for SFTP is a fully managed service that enables the transfer of files
/// directly into and out of Amazon S3 using the Secure File Transfer Protocol (SFTP)—also
/// known as Secure Shell (SSH) File Transfer Protocol. AWS helps you seamlessly migrate
/// your file transfer workflows to AWS Transfer for SFTP—by integrating with existing
/// authentication systems, and providing DNS routing with Amazon Route 53—so nothing
/// changes for your customers and partners, or their applications. With your data in
/// S3, you can use it with AWS services for processing, analytics, machine learning,
/// and archiving. Getting started with AWS Transfer for SFTP (AWS SFTP) is easy; there
/// is no infrastructure to buy and set up.
/// </summary>
public partial interface IAmazonTransfer : IAmazonService, IDisposable
{
#region CreateServer
/// <summary>
/// Instantiates an autoscaling virtual server based on Secure File Transfer Protocol
/// (SFTP) in AWS. When you make updates to your server or when you work with users, use
/// the service-generated <code>ServerId</code> property that is assigned to the newly
/// created server.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateServer service method.</param>
///
/// <returns>The response from the CreateServer service method, as returned by Transfer.</returns>
/// <exception cref="Amazon.Transfer.Model.InternalServiceErrorException">
/// This exception is thrown when an error occurs in the AWS Transfer for SFTP service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidRequestException">
/// This exception is thrown when the client submits a malformed request.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ResourceExistsException">
/// The requested resource does not exist.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ServiceUnavailableException">
/// The request has failed because the AWS Transfer for SFTP service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/CreateServer">REST API Reference for CreateServer Operation</seealso>
CreateServerResponse CreateServer(CreateServerRequest request);
/// <summary>
/// Initiates the asynchronous execution of the CreateServer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateServer operation on AmazonTransferClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateServer
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/CreateServer">REST API Reference for CreateServer Operation</seealso>
IAsyncResult BeginCreateServer(CreateServerRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreateServer operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateServer.</param>
///
/// <returns>Returns a CreateServerResult from Transfer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/CreateServer">REST API Reference for CreateServer Operation</seealso>
CreateServerResponse EndCreateServer(IAsyncResult asyncResult);
#endregion
#region CreateUser
/// <summary>
/// Creates a user and associates them with an existing Secure File Transfer Protocol
/// (SFTP) server. You can only create and associate users with SFTP servers that have
/// the <code>IdentityProviderType</code> set to <code>SERVICE_MANAGED</code>. Using parameters
/// for <code>CreateUser</code>, you can specify the user name, set the home directory,
/// store the user's public key, and assign the user's AWS Identity and Access Management
/// (IAM) role. You can also optionally add a scope-down policy, and assign metadata with
/// tags that can be used to group and search for users.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateUser service method.</param>
///
/// <returns>The response from the CreateUser service method, as returned by Transfer.</returns>
/// <exception cref="Amazon.Transfer.Model.InternalServiceErrorException">
/// This exception is thrown when an error occurs in the AWS Transfer for SFTP service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidRequestException">
/// This exception is thrown when the client submits a malformed request.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ResourceExistsException">
/// The requested resource does not exist.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ResourceNotFoundException">
/// This exception is thrown when a resource is not found by the AWS Transfer for SFTP
/// service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ServiceUnavailableException">
/// The request has failed because the AWS Transfer for SFTP service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/CreateUser">REST API Reference for CreateUser Operation</seealso>
CreateUserResponse CreateUser(CreateUserRequest request);
/// <summary>
/// Initiates the asynchronous execution of the CreateUser operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateUser operation on AmazonTransferClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateUser
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/CreateUser">REST API Reference for CreateUser Operation</seealso>
IAsyncResult BeginCreateUser(CreateUserRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the CreateUser operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateUser.</param>
///
/// <returns>Returns a CreateUserResult from Transfer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/CreateUser">REST API Reference for CreateUser Operation</seealso>
CreateUserResponse EndCreateUser(IAsyncResult asyncResult);
#endregion
#region DeleteServer
/// <summary>
/// Deletes the Secure File Transfer Protocol (SFTP) server that you specify.
///
///
/// <para>
/// No response returns from this operation.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteServer service method.</param>
///
/// <returns>The response from the DeleteServer service method, as returned by Transfer.</returns>
/// <exception cref="Amazon.Transfer.Model.InternalServiceErrorException">
/// This exception is thrown when an error occurs in the AWS Transfer for SFTP service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidRequestException">
/// This exception is thrown when the client submits a malformed request.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ResourceNotFoundException">
/// This exception is thrown when a resource is not found by the AWS Transfer for SFTP
/// service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ServiceUnavailableException">
/// The request has failed because the AWS Transfer for SFTP service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/DeleteServer">REST API Reference for DeleteServer Operation</seealso>
DeleteServerResponse DeleteServer(DeleteServerRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeleteServer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteServer operation on AmazonTransferClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteServer
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/DeleteServer">REST API Reference for DeleteServer Operation</seealso>
IAsyncResult BeginDeleteServer(DeleteServerRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeleteServer operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteServer.</param>
///
/// <returns>Returns a DeleteServerResult from Transfer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/DeleteServer">REST API Reference for DeleteServer Operation</seealso>
DeleteServerResponse EndDeleteServer(IAsyncResult asyncResult);
#endregion
#region DeleteSshPublicKey
/// <summary>
/// Deletes a user's Secure Shell (SSH) public key.
///
///
/// <para>
/// No response is returned from this operation.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteSshPublicKey service method.</param>
///
/// <returns>The response from the DeleteSshPublicKey service method, as returned by Transfer.</returns>
/// <exception cref="Amazon.Transfer.Model.InternalServiceErrorException">
/// This exception is thrown when an error occurs in the AWS Transfer for SFTP service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidRequestException">
/// This exception is thrown when the client submits a malformed request.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ResourceNotFoundException">
/// This exception is thrown when a resource is not found by the AWS Transfer for SFTP
/// service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ServiceUnavailableException">
/// The request has failed because the AWS Transfer for SFTP service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/DeleteSshPublicKey">REST API Reference for DeleteSshPublicKey Operation</seealso>
DeleteSshPublicKeyResponse DeleteSshPublicKey(DeleteSshPublicKeyRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeleteSshPublicKey operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteSshPublicKey operation on AmazonTransferClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteSshPublicKey
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/DeleteSshPublicKey">REST API Reference for DeleteSshPublicKey Operation</seealso>
IAsyncResult BeginDeleteSshPublicKey(DeleteSshPublicKeyRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeleteSshPublicKey operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteSshPublicKey.</param>
///
/// <returns>Returns a DeleteSshPublicKeyResult from Transfer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/DeleteSshPublicKey">REST API Reference for DeleteSshPublicKey Operation</seealso>
DeleteSshPublicKeyResponse EndDeleteSshPublicKey(IAsyncResult asyncResult);
#endregion
#region DeleteUser
/// <summary>
/// Deletes the user belonging to the server you specify.
///
///
/// <para>
/// No response returns from this operation.
/// </para>
/// <note>
/// <para>
/// When you delete a user from a server, the user's information is lost.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteUser service method.</param>
///
/// <returns>The response from the DeleteUser service method, as returned by Transfer.</returns>
/// <exception cref="Amazon.Transfer.Model.InternalServiceErrorException">
/// This exception is thrown when an error occurs in the AWS Transfer for SFTP service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidRequestException">
/// This exception is thrown when the client submits a malformed request.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ResourceNotFoundException">
/// This exception is thrown when a resource is not found by the AWS Transfer for SFTP
/// service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ServiceUnavailableException">
/// The request has failed because the AWS Transfer for SFTP service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/DeleteUser">REST API Reference for DeleteUser Operation</seealso>
DeleteUserResponse DeleteUser(DeleteUserRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeleteUser operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteUser operation on AmazonTransferClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteUser
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/DeleteUser">REST API Reference for DeleteUser Operation</seealso>
IAsyncResult BeginDeleteUser(DeleteUserRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DeleteUser operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteUser.</param>
///
/// <returns>Returns a DeleteUserResult from Transfer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/DeleteUser">REST API Reference for DeleteUser Operation</seealso>
DeleteUserResponse EndDeleteUser(IAsyncResult asyncResult);
#endregion
#region DescribeServer
/// <summary>
/// Describes the server that you specify by passing the <code>ServerId</code> parameter.
///
///
/// <para>
/// The response contains a description of the server's properties.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeServer service method.</param>
///
/// <returns>The response from the DescribeServer service method, as returned by Transfer.</returns>
/// <exception cref="Amazon.Transfer.Model.InternalServiceErrorException">
/// This exception is thrown when an error occurs in the AWS Transfer for SFTP service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidRequestException">
/// This exception is thrown when the client submits a malformed request.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ResourceNotFoundException">
/// This exception is thrown when a resource is not found by the AWS Transfer for SFTP
/// service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ServiceUnavailableException">
/// The request has failed because the AWS Transfer for SFTP service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/DescribeServer">REST API Reference for DescribeServer Operation</seealso>
DescribeServerResponse DescribeServer(DescribeServerRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DescribeServer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeServer operation on AmazonTransferClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeServer
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/DescribeServer">REST API Reference for DescribeServer Operation</seealso>
IAsyncResult BeginDescribeServer(DescribeServerRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DescribeServer operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeServer.</param>
///
/// <returns>Returns a DescribeServerResult from Transfer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/DescribeServer">REST API Reference for DescribeServer Operation</seealso>
DescribeServerResponse EndDescribeServer(IAsyncResult asyncResult);
#endregion
#region DescribeUser
/// <summary>
/// Describes the user assigned to a specific server, as identified by its <code>ServerId</code>
/// property.
///
///
/// <para>
/// The response from this call returns the properties of the user associated with the
/// <code>ServerId</code> value that was specified.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeUser service method.</param>
///
/// <returns>The response from the DescribeUser service method, as returned by Transfer.</returns>
/// <exception cref="Amazon.Transfer.Model.InternalServiceErrorException">
/// This exception is thrown when an error occurs in the AWS Transfer for SFTP service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidRequestException">
/// This exception is thrown when the client submits a malformed request.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ResourceNotFoundException">
/// This exception is thrown when a resource is not found by the AWS Transfer for SFTP
/// service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ServiceUnavailableException">
/// The request has failed because the AWS Transfer for SFTP service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/DescribeUser">REST API Reference for DescribeUser Operation</seealso>
DescribeUserResponse DescribeUser(DescribeUserRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DescribeUser operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeUser operation on AmazonTransferClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeUser
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/DescribeUser">REST API Reference for DescribeUser Operation</seealso>
IAsyncResult BeginDescribeUser(DescribeUserRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the DescribeUser operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeUser.</param>
///
/// <returns>Returns a DescribeUserResult from Transfer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/DescribeUser">REST API Reference for DescribeUser Operation</seealso>
DescribeUserResponse EndDescribeUser(IAsyncResult asyncResult);
#endregion
#region ImportSshPublicKey
/// <summary>
/// Adds a Secure Shell (SSH) public key to a user account identified by a <code>UserName</code>
/// value assigned to a specific server, identified by <code>ServerId</code>.
///
///
/// <para>
/// The response returns the <code>UserName</code> value, the <code>ServerId</code> value,
/// and the name of the <code>SshPublicKeyId</code>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ImportSshPublicKey service method.</param>
///
/// <returns>The response from the ImportSshPublicKey service method, as returned by Transfer.</returns>
/// <exception cref="Amazon.Transfer.Model.InternalServiceErrorException">
/// This exception is thrown when an error occurs in the AWS Transfer for SFTP service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidRequestException">
/// This exception is thrown when the client submits a malformed request.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ResourceExistsException">
/// The requested resource does not exist.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ResourceNotFoundException">
/// This exception is thrown when a resource is not found by the AWS Transfer for SFTP
/// service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ServiceUnavailableException">
/// The request has failed because the AWS Transfer for SFTP service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/ImportSshPublicKey">REST API Reference for ImportSshPublicKey Operation</seealso>
ImportSshPublicKeyResponse ImportSshPublicKey(ImportSshPublicKeyRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ImportSshPublicKey operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ImportSshPublicKey operation on AmazonTransferClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndImportSshPublicKey
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/ImportSshPublicKey">REST API Reference for ImportSshPublicKey Operation</seealso>
IAsyncResult BeginImportSshPublicKey(ImportSshPublicKeyRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ImportSshPublicKey operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginImportSshPublicKey.</param>
///
/// <returns>Returns a ImportSshPublicKeyResult from Transfer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/ImportSshPublicKey">REST API Reference for ImportSshPublicKey Operation</seealso>
ImportSshPublicKeyResponse EndImportSshPublicKey(IAsyncResult asyncResult);
#endregion
#region ListServers
/// <summary>
/// Lists the Secure File Transfer Protocol (SFTP) servers that are associated with your
/// AWS account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListServers service method.</param>
///
/// <returns>The response from the ListServers service method, as returned by Transfer.</returns>
/// <exception cref="Amazon.Transfer.Model.InternalServiceErrorException">
/// This exception is thrown when an error occurs in the AWS Transfer for SFTP service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidNextTokenException">
/// The <code>NextToken</code> parameter that was passed is invalid.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidRequestException">
/// This exception is thrown when the client submits a malformed request.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ServiceUnavailableException">
/// The request has failed because the AWS Transfer for SFTP service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/ListServers">REST API Reference for ListServers Operation</seealso>
ListServersResponse ListServers(ListServersRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ListServers operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListServers operation on AmazonTransferClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListServers
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/ListServers">REST API Reference for ListServers Operation</seealso>
IAsyncResult BeginListServers(ListServersRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ListServers operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListServers.</param>
///
/// <returns>Returns a ListServersResult from Transfer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/ListServers">REST API Reference for ListServers Operation</seealso>
ListServersResponse EndListServers(IAsyncResult asyncResult);
#endregion
#region ListTagsForResource
/// <summary>
/// Lists all of the tags associated with the Amazon Resource Number (ARN) you specify.
/// The resource can be a user, server, or role.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListTagsForResource service method.</param>
///
/// <returns>The response from the ListTagsForResource service method, as returned by Transfer.</returns>
/// <exception cref="Amazon.Transfer.Model.InternalServiceErrorException">
/// This exception is thrown when an error occurs in the AWS Transfer for SFTP service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidNextTokenException">
/// The <code>NextToken</code> parameter that was passed is invalid.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidRequestException">
/// This exception is thrown when the client submits a malformed request.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ServiceUnavailableException">
/// The request has failed because the AWS Transfer for SFTP service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
ListTagsForResourceResponse ListTagsForResource(ListTagsForResourceRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ListTagsForResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListTagsForResource operation on AmazonTransferClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListTagsForResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
IAsyncResult BeginListTagsForResource(ListTagsForResourceRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ListTagsForResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListTagsForResource.</param>
///
/// <returns>Returns a ListTagsForResourceResult from Transfer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
ListTagsForResourceResponse EndListTagsForResource(IAsyncResult asyncResult);
#endregion
#region ListUsers
/// <summary>
/// Lists the users for the server that you specify by passing the <code>ServerId</code>
/// parameter.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListUsers service method.</param>
///
/// <returns>The response from the ListUsers service method, as returned by Transfer.</returns>
/// <exception cref="Amazon.Transfer.Model.InternalServiceErrorException">
/// This exception is thrown when an error occurs in the AWS Transfer for SFTP service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidNextTokenException">
/// The <code>NextToken</code> parameter that was passed is invalid.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidRequestException">
/// This exception is thrown when the client submits a malformed request.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ResourceNotFoundException">
/// This exception is thrown when a resource is not found by the AWS Transfer for SFTP
/// service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ServiceUnavailableException">
/// The request has failed because the AWS Transfer for SFTP service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/ListUsers">REST API Reference for ListUsers Operation</seealso>
ListUsersResponse ListUsers(ListUsersRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ListUsers operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListUsers operation on AmazonTransferClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListUsers
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/ListUsers">REST API Reference for ListUsers Operation</seealso>
IAsyncResult BeginListUsers(ListUsersRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the ListUsers operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListUsers.</param>
///
/// <returns>Returns a ListUsersResult from Transfer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/ListUsers">REST API Reference for ListUsers Operation</seealso>
ListUsersResponse EndListUsers(IAsyncResult asyncResult);
#endregion
#region StartServer
/// <summary>
/// Changes the state of a Secure File Transfer Protocol (SFTP) server from <code>OFFLINE</code>
/// to <code>ONLINE</code>. It has no impact on an SFTP server that is already <code>ONLINE</code>.
/// An <code>ONLINE</code> server can accept and process file transfer jobs.
///
///
/// <para>
/// The state of <code>STARTING</code> indicates that the server is in an intermediate
/// state, either not fully able to respond, or not fully online. The values of <code>START_FAILED</code>
/// can indicate an error condition.
/// </para>
///
/// <para>
/// No response is returned from this call.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StartServer service method.</param>
///
/// <returns>The response from the StartServer service method, as returned by Transfer.</returns>
/// <exception cref="Amazon.Transfer.Model.InternalServiceErrorException">
/// This exception is thrown when an error occurs in the AWS Transfer for SFTP service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidRequestException">
/// This exception is thrown when the client submits a malformed request.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ResourceNotFoundException">
/// This exception is thrown when a resource is not found by the AWS Transfer for SFTP
/// service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ServiceUnavailableException">
/// The request has failed because the AWS Transfer for SFTP service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/StartServer">REST API Reference for StartServer Operation</seealso>
StartServerResponse StartServer(StartServerRequest request);
/// <summary>
/// Initiates the asynchronous execution of the StartServer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the StartServer operation on AmazonTransferClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStartServer
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/StartServer">REST API Reference for StartServer Operation</seealso>
IAsyncResult BeginStartServer(StartServerRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the StartServer operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginStartServer.</param>
///
/// <returns>Returns a StartServerResult from Transfer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/StartServer">REST API Reference for StartServer Operation</seealso>
StartServerResponse EndStartServer(IAsyncResult asyncResult);
#endregion
#region StopServer
/// <summary>
/// Changes the state of an SFTP server from <code>ONLINE</code> to <code>OFFLINE</code>.
/// An <code>OFFLINE</code> server cannot accept and process file transfer jobs. Information
/// tied to your server such as server and user properties are not affected by stopping
/// your server. Stopping a server will not reduce or impact your Secure File Transfer
/// Protocol (SFTP) endpoint billing.
///
///
/// <para>
/// The state of <code>STOPPING</code> indicates that the server is in an intermediate
/// state, either not fully able to respond, or not fully offline. The values of <code>STOP_FAILED</code>
/// can indicate an error condition.
/// </para>
///
/// <para>
/// No response is returned from this call.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StopServer service method.</param>
///
/// <returns>The response from the StopServer service method, as returned by Transfer.</returns>
/// <exception cref="Amazon.Transfer.Model.InternalServiceErrorException">
/// This exception is thrown when an error occurs in the AWS Transfer for SFTP service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidRequestException">
/// This exception is thrown when the client submits a malformed request.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ResourceNotFoundException">
/// This exception is thrown when a resource is not found by the AWS Transfer for SFTP
/// service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ServiceUnavailableException">
/// The request has failed because the AWS Transfer for SFTP service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/StopServer">REST API Reference for StopServer Operation</seealso>
StopServerResponse StopServer(StopServerRequest request);
/// <summary>
/// Initiates the asynchronous execution of the StopServer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the StopServer operation on AmazonTransferClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStopServer
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/StopServer">REST API Reference for StopServer Operation</seealso>
IAsyncResult BeginStopServer(StopServerRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the StopServer operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginStopServer.</param>
///
/// <returns>Returns a StopServerResult from Transfer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/StopServer">REST API Reference for StopServer Operation</seealso>
StopServerResponse EndStopServer(IAsyncResult asyncResult);
#endregion
#region TagResource
/// <summary>
/// Attaches a key-value pair to a resource, as identified by its Amazon Resource Name
/// (ARN). Resources are users, servers, roles, and other entities.
///
///
/// <para>
/// There is no response returned from this call.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param>
///
/// <returns>The response from the TagResource service method, as returned by Transfer.</returns>
/// <exception cref="Amazon.Transfer.Model.InternalServiceErrorException">
/// This exception is thrown when an error occurs in the AWS Transfer for SFTP service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidRequestException">
/// This exception is thrown when the client submits a malformed request.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ServiceUnavailableException">
/// The request has failed because the AWS Transfer for SFTP service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/TagResource">REST API Reference for TagResource Operation</seealso>
TagResourceResponse TagResource(TagResourceRequest request);
/// <summary>
/// Initiates the asynchronous execution of the TagResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the TagResource operation on AmazonTransferClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndTagResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/TagResource">REST API Reference for TagResource Operation</seealso>
IAsyncResult BeginTagResource(TagResourceRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the TagResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginTagResource.</param>
///
/// <returns>Returns a TagResourceResult from Transfer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/TagResource">REST API Reference for TagResource Operation</seealso>
TagResourceResponse EndTagResource(IAsyncResult asyncResult);
#endregion
#region TestIdentityProvider
/// <summary>
/// If the <code>IdentityProviderType</code> of the server is <code>API_Gateway</code>,
/// tests whether your API Gateway is set up successfully. We highly recommend that you
/// call this operation to test your authentication method as soon as you create your
/// server. By doing so, you can troubleshoot issues with the API Gateway integration
/// to ensure that your users can successfully use the service.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TestIdentityProvider service method.</param>
///
/// <returns>The response from the TestIdentityProvider service method, as returned by Transfer.</returns>
/// <exception cref="Amazon.Transfer.Model.InternalServiceErrorException">
/// This exception is thrown when an error occurs in the AWS Transfer for SFTP service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidRequestException">
/// This exception is thrown when the client submits a malformed request.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ResourceNotFoundException">
/// This exception is thrown when a resource is not found by the AWS Transfer for SFTP
/// service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ServiceUnavailableException">
/// The request has failed because the AWS Transfer for SFTP service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/TestIdentityProvider">REST API Reference for TestIdentityProvider Operation</seealso>
TestIdentityProviderResponse TestIdentityProvider(TestIdentityProviderRequest request);
/// <summary>
/// Initiates the asynchronous execution of the TestIdentityProvider operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the TestIdentityProvider operation on AmazonTransferClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndTestIdentityProvider
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/TestIdentityProvider">REST API Reference for TestIdentityProvider Operation</seealso>
IAsyncResult BeginTestIdentityProvider(TestIdentityProviderRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the TestIdentityProvider operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginTestIdentityProvider.</param>
///
/// <returns>Returns a TestIdentityProviderResult from Transfer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/TestIdentityProvider">REST API Reference for TestIdentityProvider Operation</seealso>
TestIdentityProviderResponse EndTestIdentityProvider(IAsyncResult asyncResult);
#endregion
#region UntagResource
/// <summary>
/// Detaches a key-value pair from a resource, as identified by its Amazon Resource Name
/// (ARN). Resources are users, servers, roles, and other entities.
///
///
/// <para>
/// No response is returned from this call.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param>
///
/// <returns>The response from the UntagResource service method, as returned by Transfer.</returns>
/// <exception cref="Amazon.Transfer.Model.InternalServiceErrorException">
/// This exception is thrown when an error occurs in the AWS Transfer for SFTP service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidRequestException">
/// This exception is thrown when the client submits a malformed request.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ServiceUnavailableException">
/// The request has failed because the AWS Transfer for SFTP service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/UntagResource">REST API Reference for UntagResource Operation</seealso>
UntagResourceResponse UntagResource(UntagResourceRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UntagResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UntagResource operation on AmazonTransferClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUntagResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/UntagResource">REST API Reference for UntagResource Operation</seealso>
IAsyncResult BeginUntagResource(UntagResourceRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the UntagResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUntagResource.</param>
///
/// <returns>Returns a UntagResourceResult from Transfer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/UntagResource">REST API Reference for UntagResource Operation</seealso>
UntagResourceResponse EndUntagResource(IAsyncResult asyncResult);
#endregion
#region UpdateServer
/// <summary>
/// Updates the server properties after that server has been created.
///
///
/// <para>
/// The <code>UpdateServer</code> call returns the <code>ServerId</code> of the Secure
/// File Transfer Protocol (SFTP) server you updated.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateServer service method.</param>
///
/// <returns>The response from the UpdateServer service method, as returned by Transfer.</returns>
/// <exception cref="Amazon.Transfer.Model.InternalServiceErrorException">
/// This exception is thrown when an error occurs in the AWS Transfer for SFTP service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidRequestException">
/// This exception is thrown when the client submits a malformed request.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ResourceNotFoundException">
/// This exception is thrown when a resource is not found by the AWS Transfer for SFTP
/// service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ServiceUnavailableException">
/// The request has failed because the AWS Transfer for SFTP service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/UpdateServer">REST API Reference for UpdateServer Operation</seealso>
UpdateServerResponse UpdateServer(UpdateServerRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UpdateServer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateServer operation on AmazonTransferClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateServer
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/UpdateServer">REST API Reference for UpdateServer Operation</seealso>
IAsyncResult BeginUpdateServer(UpdateServerRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the UpdateServer operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateServer.</param>
///
/// <returns>Returns a UpdateServerResult from Transfer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/UpdateServer">REST API Reference for UpdateServer Operation</seealso>
UpdateServerResponse EndUpdateServer(IAsyncResult asyncResult);
#endregion
#region UpdateUser
/// <summary>
/// Assigns new properties to a user. Parameters you pass modify any or all of the following:
/// the home directory, role, and policy for the <code>UserName</code> and <code>ServerId</code>
/// you specify.
///
///
/// <para>
/// The response returns the <code>ServerId</code> and the <code>UserName</code> for the
/// updated user.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateUser service method.</param>
///
/// <returns>The response from the UpdateUser service method, as returned by Transfer.</returns>
/// <exception cref="Amazon.Transfer.Model.InternalServiceErrorException">
/// This exception is thrown when an error occurs in the AWS Transfer for SFTP service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.InvalidRequestException">
/// This exception is thrown when the client submits a malformed request.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ResourceNotFoundException">
/// This exception is thrown when a resource is not found by the AWS Transfer for SFTP
/// service.
/// </exception>
/// <exception cref="Amazon.Transfer.Model.ServiceUnavailableException">
/// The request has failed because the AWS Transfer for SFTP service is not available.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/UpdateUser">REST API Reference for UpdateUser Operation</seealso>
UpdateUserResponse UpdateUser(UpdateUserRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UpdateUser operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateUser operation on AmazonTransferClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateUser
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/UpdateUser">REST API Reference for UpdateUser Operation</seealso>
IAsyncResult BeginUpdateUser(UpdateUserRequest request, AsyncCallback callback, object state);
/// <summary>
/// Finishes the asynchronous execution of the UpdateUser operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateUser.</param>
///
/// <returns>Returns a UpdateUserResult from Transfer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/UpdateUser">REST API Reference for UpdateUser Operation</seealso>
UpdateUserResponse EndUpdateUser(IAsyncResult asyncResult);
#endregion
}
} | 56.942238 | 171 | 0.6672 | [
"Apache-2.0"
] | jiabiao/aws-sdk-net | sdk/src/Services/Transfer/Generated/_bcl35/IAmazonTransfer.cs | 63,098 | C# |
using System;
using System.Linq.Expressions;
using TestMapster.Dtos.Dtos;
using TestMapster.Library.Models;
namespace TestMapster.Dtos.Dtos
{
public static partial class SourceMapper
{
public static SourceDto AdaptToDto(this Source p1)
{
return p1 == null ? null : new SourceDto()
{
Prop1 = p1.Prop1,
Prop2 = p1.Prop2
};
}
public static SourceDto AdaptTo(this Source p2, SourceDto p3)
{
if (p2 == null)
{
return null;
}
SourceDto result = p3 ?? new SourceDto();
result.Prop1 = p2.Prop1;
result.Prop2 = p2.Prop2;
return result;
}
public static Expression<Func<Source, SourceDto>> ProjectToDto => p4 => new SourceDto()
{
Prop1 = p4.Prop1,
Prop2 = p4.Prop2
};
}
} | 26.027027 | 95 | 0.504673 | [
"MIT"
] | Philippe-Laval/TestMapster | TestMapster.Dto/Dtos/SourceMapper.g.cs | 963 | C# |
using System;
using System.Collections.Generic;
using Xunit;
using Moq;
using com.brgs.orm.Azure.helpers;
using Microsoft.WindowsAzure.Storage.Table;
using FluentAssertions;
using com.brgs.orm.Azure;
namespace com.brgs.orm.test.Azure.LamdaExpressionParsingTests
{
public class LamdaExpressionParsingShould
{
private readonly AzureStorageFactory _builder;
public LamdaExpressionParsingShould()
{
var mock = new Mock<ICloudStorageAccount>();
_builder = new AzureStorageFactory(mock.Object);
}
[Fact]
public void BuildQueryFilter()
{
var query = _builder.BuildQueryFilter<River>(r => r.StateCode.Equals("WV"));
query.Should().NotBeNull();
}
[Fact]
public void EncodeOperandCorrectly()
{
var query = _builder.BuildQueryFilter<River>(r => r.StateCode.Equals("WV"));
query.Should().BeEquivalentTo("StateCode eq 'WV'");
}
[Fact]
public void ThrowWhenContainsIsCalled()
{
var query = _builder.BuildQueryFilter<River>(r => r.Name.Contains("Gauley"));
query.Should().BeEmpty();
}
[Fact]
public void EncodeNotOperandCorrectly()
{
var query =_builder.BuildQueryFilter<River>(r => !r.StateCode.Equals("WV"));
query.Should().BeEquivalentTo("StateCode ne 'WV'");
}
[Fact]
public void EncodeNullOrEmptyAndEquals()
{
var query = _builder.BuildQueryFilter<River>(r => !r.StateCode.Equals("")
&& r.StateCode == "WV");
query.Should().BeEquivalentTo("StateCode ne '' and StateCode eq 'WV'");
}
[Fact]
public void EncodeNullOrEmptyWithoutMethodCall()
{
var query = _builder.BuildQueryFilter<River>(r => r.StateCode != ""
&& r.StateCode == "WV");
query.Should().BeEquivalentTo("StateCode ne '' and StateCode eq 'WV'");
}
[Fact]
public void EncodeNullOrEmptyUsingStringNullOrEmpty()
{
var query = _builder.BuildQueryFilter<River>(r => (r.StateCode != null || r.StateCode != "")
&& r.StateCode == "WV");
query.Should().BeEquivalentTo("StateCode ne '' or StateCode ne '' and StateCode eq 'WV'");
}
[Fact]
public void EncodeGreaterThanCorrectly()
{
var query = _builder.BuildQueryFilter<River>(r => r.Latitude > 36);
query.Should().BeEquivalentTo("Latitude gt 36");
}
[Fact]
public void EncodeGreatherThanOrEqualCorrectly()
{
var query = _builder.BuildQueryFilter<River>(r => r.Latitude >= 36);
query.Should().BeEquivalentTo("Latitude ge 36");
}
[Fact]
public void EncodeLessThanCorrectly()
{
var query = _builder.BuildQueryFilter<River>(r => r.Latitude < 36);
query.Should().BeEquivalentTo("Latitude lt 36");
}
[Fact]
public void EncodeLessThanOrEqualCorrectly()
{
var query = _builder.BuildQueryFilter<River>(r => r.Latitude <= 36);
query.Should().BeEquivalentTo("Latitude le 36");
}
[Fact]
public void EncodeMultipleOperands()
{
var query = _builder.BuildQueryFilter<River>(r => r.StateCode.Equals("WV")
&& r.Name.Equals("Gauley") && r.Latitude > 36);
Assert.Equal("StateCode eq 'WV' and Name eq 'Gauley' and Latitude gt 36", query);
}
[Fact]
public void EncodeMultipleOrOperands()//OrElse
{
var query = _builder.BuildQueryFilter<River>(r => r.StateCode.Equals("WV")
|| r.Name.Equals("Ohio"));
Assert.Equal("StateCode eq 'WV' or Name eq 'Ohio'", query);
}
[Fact]
public void ChainOrAndAndOperands()
{
var query = _builder.BuildQueryFilter<River>(
r => r.Name.Equals("Gauley") || r.Name.Equals("Meadow") && r.StateCode.Equals("WV")
);
Assert.Equal("Name eq 'Gauley' or Name eq 'Meadow' and StateCode eq 'WV'", query);
}
[Fact]
public void ReturnEmptyString()
{
var query = _builder.BuildQueryFilter<River>(null);
Assert.Equal(string.Empty, query);
}
}
} | 35.916031 | 107 | 0.537938 | [
"Apache-2.0"
] | badgerowluke/NoSQLORM | com.brgs.orm.test/AzureStorageTests/TableQueryBuilderTests/TableQueryBuilderTests.cs | 4,705 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Foundation;
using UIKit;
namespace CallKitSample.iOS
{
public class Application
{
// This is the main entry point of the application.
static void Main(string[] args)
{
try
{
UIApplication.Main(args, null, nameof(AppDelegate));
}
catch (Exception e)
{
try
{
var data = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var filename = Path.Combine(data, String.Format("crash.txt"));
Debug.WriteLine(e.Message);
Debug.WriteLine(e.StackTrace);
Debug.WriteLine(e.Source);
Debug.WriteLine(e.InnerException?.StackTrace);
Debug.WriteLine(e.InnerException?.Source);
File.WriteAllText(filename, e.Message + "\n-----\n" + e.StackTrace ?? "" + "\n-----\n" + e.Source ?? "" + "\n-----\n");
}
catch (DirectoryNotFoundException)
{
}
}
}
}
}
| 28.545455 | 139 | 0.503981 | [
"MIT"
] | NiladriPadhy/callkitsample | CallKitSample.iOS/Main.cs | 1,258 | C# |
/*
* Copyright 2018 JDCLOUD.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.
*
* yunding-datapush
* 云鼎数据推送OPENAPI接口
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
using JDCloudSDK.Core.Service;
using JDCloudSDK.Yundingdatapush.Model;
using JDCloudSDK.Core.Annotation;
namespace JDCloudSDK.Yundingdatapush.Apis
{
/// <summary>
/// 添加数据推送用户
/// </summary>
public class AddDatapushVenderRequest : JdcloudRequest
{
///<summary>
/// 添加数据推送用户对象
///
///Required:true
///</summary>
[Required]
public Vender DatapushVender{ get; set; }
}
} | 25.66 | 76 | 0.690569 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Yundingdatapush/Apis/AddDatapushVenderRequest.cs | 1,335 | 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 Xunit;
namespace System.Linq.Tests
{
public class SelectManyTests : EnumerableTests
{
[Fact]
public void EmptySource()
{
Assert.Empty(Enumerable.Empty<StringWithIntArray>().SelectMany(e => e.total));
}
[Fact]
public void EmptySourceIndexedSelector()
{
Assert.Empty(Enumerable.Empty<StringWithIntArray>().SelectMany((e, i) => e.total));
}
[Fact]
public void EmptySourceResultSelector()
{
Assert.Empty(
Enumerable
.Empty<StringWithIntArray>()
.SelectMany(e => e.total, (e, f) => f.ToString())
);
}
[Fact]
public void EmptySourceResultSelectorIndexedSelector()
{
Assert.Empty(
Enumerable
.Empty<StringWithIntArray>()
.SelectMany((e, i) => e.total, (e, f) => f.ToString())
);
}
[Fact]
public void SingleElement()
{
int?[] expected = { 90, 55, null, 43, 89 };
StringWithIntArray[] source =
{
new StringWithIntArray { name = "Prakash", total = expected }
};
Assert.Equal(expected, source.SelectMany(e => e.total));
}
[Fact]
public void NonEmptySelectingEmpty()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name = "Prakash", total = new int?[0] },
new StringWithIntArray { name = "Bob", total = new int?[0] },
new StringWithIntArray { name = "Chris", total = new int?[0] },
new StringWithIntArray { name = null, total = new int?[0] },
new StringWithIntArray { name = "Prakash", total = new int?[0] }
};
Assert.Empty(source.SelectMany(e => e.total));
}
[Fact]
public void NonEmptySelectingEmptyIndexedSelector()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name = "Prakash", total = new int?[0] },
new StringWithIntArray { name = "Bob", total = new int?[0] },
new StringWithIntArray { name = "Chris", total = new int?[0] },
new StringWithIntArray { name = null, total = new int?[0] },
new StringWithIntArray { name = "Prakash", total = new int?[0] }
};
Assert.Empty(source.SelectMany((e, i) => e.total));
}
[Fact]
public void NonEmptySelectingEmptyWithResultSelector()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name = "Prakash", total = new int?[0] },
new StringWithIntArray { name = "Bob", total = new int?[0] },
new StringWithIntArray { name = "Chris", total = new int?[0] },
new StringWithIntArray { name = null, total = new int?[0] },
new StringWithIntArray { name = "Prakash", total = new int?[0] }
};
Assert.Empty(source.SelectMany(e => e.total, (e, f) => f.ToString()));
}
[Fact]
public void NonEmptySelectingEmptyIndexedSelectorWithResultSelector()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name = "Prakash", total = new int?[0] },
new StringWithIntArray { name = "Bob", total = new int?[0] },
new StringWithIntArray { name = "Chris", total = new int?[0] },
new StringWithIntArray { name = null, total = new int?[0] },
new StringWithIntArray { name = "Prakash", total = new int?[0] }
};
Assert.Empty(source.SelectMany((e, i) => e.total, (e, f) => f.ToString()));
}
[Fact]
public void ResultsSelected()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name = "Prakash", total = new int?[] { 1, 2, 3, 4 } },
new StringWithIntArray { name = "Bob", total = new int?[] { 5, 6 } },
new StringWithIntArray { name = "Chris", total = new int?[0] },
new StringWithIntArray { name = null, total = new int?[] { 8, 9 } },
new StringWithIntArray { name = "Prakash", total = new int?[] { -10, 100 } }
};
int?[] expected = { 1, 2, 3, 4, 5, 6, 8, 9, -10, 100 };
Assert.Equal(expected, source.SelectMany(e => e.total));
}
[Fact]
public void RunOnce()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name = "Prakash", total = new int?[] { 1, 2, 3, 4 } },
new StringWithIntArray { name = "Bob", total = new int?[] { 5, 6 } },
new StringWithIntArray { name = "Chris", total = new int?[0] },
new StringWithIntArray { name = null, total = new int?[] { 8, 9 } },
new StringWithIntArray { name = "Prakash", total = new int?[] { -10, 100 } }
};
int?[] expected = { 1, 2, 3, 4, 5, 6, 8, 9, -10, 100 };
Assert.Equal(expected, source.RunOnce().SelectMany(e => e.total.RunOnce()));
}
[Fact]
public void SourceEmptyIndexUsed()
{
Assert.Empty(Enumerable.Empty<StringWithIntArray>().SelectMany((e, index) => e.total));
}
[Fact]
public void SingleElementIndexUsed()
{
int?[] expected = { 90, 55, null, 43, 89 };
StringWithIntArray[] source =
{
new StringWithIntArray { name = "Prakash", total = expected }
};
Assert.Equal(expected, source.SelectMany((e, index) => e.total));
}
[Fact]
public void NonEmptySelectingEmptyIndexUsed()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name = "Prakash", total = new int?[0] },
new StringWithIntArray { name = "Bob", total = new int?[0] },
new StringWithIntArray { name = "Chris", total = new int?[0] },
new StringWithIntArray { name = null, total = new int?[0] },
new StringWithIntArray { name = "Prakash", total = new int?[0] }
};
Assert.Empty(source.SelectMany((e, index) => e.total));
}
[Fact]
public void ResultsSelectedIndexUsed()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name = "Prakash", total = new int?[] { 1, 2, 3, 4 } },
new StringWithIntArray { name = "Bob", total = new int?[] { 5, 6 } },
new StringWithIntArray { name = "Chris", total = new int?[0] },
new StringWithIntArray { name = null, total = new int?[] { 8, 9 } },
new StringWithIntArray { name = "Prakash", total = new int?[] { -10, 100 } }
};
int?[] expected = { 1, 2, 3, 4, 5, 6, 8, 9, -10, 100 };
Assert.Equal(expected, source.SelectMany((e, index) => e.total));
}
[Fact]
public void IndexCausingFirstToBeSelected()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name = "Prakash", total = new int?[] { 1, 2, 3, 4 } },
new StringWithIntArray { name = "Bob", total = new int?[] { 5, 6 } },
new StringWithIntArray { name = "Chris", total = new int?[0] },
new StringWithIntArray { name = null, total = new int?[] { 8, 9 } },
new StringWithIntArray { name = "Prakash", total = new int?[] { -10, 100 } }
};
Assert.Equal(
source.First().total,
source.SelectMany((e, i) => i == 0 ? e.total : Enumerable.Empty<int?>())
);
}
[Fact]
public void IndexCausingLastToBeSelected()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name = "Prakash", total = new int?[] { 1, 2, 3, 4 } },
new StringWithIntArray { name = "Bob", total = new int?[] { 5, 6 } },
new StringWithIntArray { name = "Chris", total = new int?[0] },
new StringWithIntArray { name = null, total = new int?[] { 8, 9 } },
new StringWithIntArray { name = "Robert", total = new int?[] { -10, 100 } }
};
Assert.Equal(
source.Last().total,
source.SelectMany((e, i) => i == 4 ? e.total : Enumerable.Empty<int?>())
);
}
[ConditionalFact(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))]
public void IndexOverflow()
{
var selected = new FastInfiniteEnumerator<int>().SelectMany(
(e, i) => Enumerable.Empty<int>()
);
using (var en = selected.GetEnumerator())
Assert.Throws<OverflowException>(
() =>
{
while (en.MoveNext()) { }
}
);
}
[Fact]
public void ResultSelector()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name = "Prakash", total = new int?[] { 1, 2, 3, 4 } },
new StringWithIntArray { name = "Bob", total = new int?[] { 5, 6 } },
new StringWithIntArray { name = "Chris", total = new int?[0] },
new StringWithIntArray { name = null, total = new int?[] { 8, 9 } },
new StringWithIntArray { name = "Prakash", total = new int?[] { -10, 100 } }
};
string[] expected = { "1", "2", "3", "4", "5", "6", "8", "9", "-10", "100" };
Assert.Equal(expected, source.SelectMany(e => e.total, (e, f) => f.ToString()));
}
[Fact]
public void NullResultSelector()
{
Func<StringWithIntArray, int?, string> resultSelector = null;
AssertExtensions.Throws<ArgumentNullException>(
"resultSelector",
() =>
Enumerable.Empty<StringWithIntArray>().SelectMany(e => e.total, resultSelector)
);
}
[Fact]
public void NullResultSelectorIndexedSelector()
{
Func<StringWithIntArray, int?, string> resultSelector = null;
AssertExtensions.Throws<ArgumentNullException>(
"resultSelector",
() =>
Enumerable
.Empty<StringWithIntArray>()
.SelectMany((e, i) => e.total, resultSelector)
);
}
[Fact]
public void NullSourceWithResultSelector()
{
StringWithIntArray[] source = null;
AssertExtensions.Throws<ArgumentNullException>(
"source",
() => source.SelectMany(e => e.total, (e, f) => f.ToString())
);
}
[Fact]
public void NullCollectionSelector()
{
Func<StringWithIntArray, IEnumerable<int?>> collectionSelector = null;
AssertExtensions.Throws<ArgumentNullException>(
"collectionSelector",
() =>
Enumerable
.Empty<StringWithIntArray>()
.SelectMany(collectionSelector, (e, f) => f.ToString())
);
}
[Fact]
public void NullIndexedCollectionSelector()
{
Func<StringWithIntArray, int, IEnumerable<int?>> collectionSelector = null;
AssertExtensions.Throws<ArgumentNullException>(
"collectionSelector",
() =>
Enumerable
.Empty<StringWithIntArray>()
.SelectMany(collectionSelector, (e, f) => f.ToString())
);
}
[Fact]
public void NullSource()
{
StringWithIntArray[] source = null;
AssertExtensions.Throws<ArgumentNullException>(
"source",
() => source.SelectMany(e => e.total)
);
}
[Fact]
public void NullSourceIndexedSelector()
{
StringWithIntArray[] source = null;
AssertExtensions.Throws<ArgumentNullException>(
"source",
() => source.SelectMany((e, i) => e.total)
);
}
[Fact]
public void NullSourceIndexedSelectorWithResultSelector()
{
StringWithIntArray[] source = null;
AssertExtensions.Throws<ArgumentNullException>(
"source",
() => source.SelectMany((e, i) => e.total, (e, f) => f.ToString())
);
}
[Fact]
public void NullSelector()
{
Func<StringWithIntArray, int[]> selector = null;
AssertExtensions.Throws<ArgumentNullException>(
"selector",
() => new StringWithIntArray[0].SelectMany(selector)
);
}
[Fact]
public void NullIndexedSelector()
{
Func<StringWithIntArray, int, int[]> selector = null;
AssertExtensions.Throws<ArgumentNullException>(
"selector",
() => new StringWithIntArray[0].SelectMany(selector)
);
}
[Fact]
public void IndexCausingFirstToBeSelectedWithResultSelector()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name = "Prakash", total = new int?[] { 1, 2, 3, 4 } },
new StringWithIntArray { name = "Bob", total = new int?[] { 5, 6 } },
new StringWithIntArray { name = "Chris", total = new int?[0] },
new StringWithIntArray { name = null, total = new int?[] { 8, 9 } },
new StringWithIntArray { name = "Prakash", total = new int?[] { -10, 100 } }
};
string[] expected = { "1", "2", "3", "4" };
Assert.Equal(
expected,
source.SelectMany(
(e, i) => i == 0 ? e.total : Enumerable.Empty<int?>(),
(e, f) => f.ToString()
)
);
}
[Fact]
public void IndexCausingLastToBeSelectedWithResultSelector()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name = "Prakash", total = new int?[] { 1, 2, 3, 4 } },
new StringWithIntArray { name = "Bob", total = new int?[] { 5, 6 } },
new StringWithIntArray { name = "Chris", total = new int?[0] },
new StringWithIntArray { name = null, total = new int?[] { 8, 9 } },
new StringWithIntArray { name = "Robert", total = new int?[] { -10, 100 } }
};
string[] expected = { "-10", "100" };
Assert.Equal(
expected,
source.SelectMany(
(e, i) => i == 4 ? e.total : Enumerable.Empty<int?>(),
(e, f) => f.ToString()
)
);
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerate()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).SelectMany(i => new int[0]);
// Don't insist on this behaviour, but check it's correct if it happens
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerateIndexed()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3)
.SelectMany((e, i) => new int[0]);
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerateResultSel()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3)
.SelectMany(i => new int[0], (e, i) => e);
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerateIndexedResultSel()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3)
.SelectMany((e, i) => new int[0], (e, i) => e);
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Theory]
[MemberData(nameof(ParameterizedTestsData))]
public void ParameterizedTests(
IEnumerable<int> source,
Func<int, IEnumerable<int>> selector
)
{
var expected = source.Select(i => selector(i)).Aggregate((l, r) => l.Concat(r));
var actual = source.SelectMany(selector);
Assert.Equal(expected, actual);
Assert.Equal(expected.Count(), actual.Count()); // SelectMany may employ an optimized Count implementation.
Assert.Equal(expected.ToArray(), actual.ToArray());
Assert.Equal(expected.ToList(), actual.ToList());
}
public static IEnumerable<object[]> ParameterizedTestsData()
{
for (int i = 1; i <= 20; i++)
{
Func<int, IEnumerable<int>> selector = n => Enumerable.Range(i, n);
yield return new object[] { Enumerable.Range(1, i), selector };
}
}
[Theory]
[MemberData(nameof(DisposeAfterEnumerationData))]
public void DisposeAfterEnumeration(int sourceLength, int subLength)
{
int sourceState = 0;
int subIndex = 0; // Index within the arrays the sub-collection is supposed to be at.
int[] subState = new int[sourceLength];
bool sourceDisposed = false;
bool[] subCollectionDisposed = new bool[sourceLength];
var source = new DelegateIterator<int>(
moveNext: () => ++sourceState <= sourceLength,
current: () => 0,
dispose: () => sourceDisposed = true
);
var subCollection = new DelegateIterator<int>(
moveNext: () => ++subState[subIndex] <= subLength, // Return true `subLength` times.
current: () => subState[subIndex],
dispose: () => subCollectionDisposed[subIndex++] = true
); // Record that Dispose was called, and move on to the next index.
var iterator = source.SelectMany(_ => subCollection);
int index = 0; // How much have we gone into the iterator?
IEnumerator<int> e = iterator.GetEnumerator();
using (e)
{
while (e.MoveNext())
{
int item = e.Current;
Assert.Equal(subState[subIndex], item); // Verify Current.
Assert.Equal(index / subLength, subIndex);
Assert.False(sourceDisposed); // Not yet.
// This represents whehter the sub-collection we're iterating thru right now
// has been disposed. Also not yet.
Assert.False(subCollectionDisposed[subIndex]);
// However, all of the sub-collections before us should have been disposed.
// Their indices should also be maxed out.
Assert.All(subState.Take(subIndex), s => Assert.Equal(subLength + 1, s));
Assert.All(subCollectionDisposed.Take(subIndex), t => Assert.True(t));
index++;
}
}
Assert.True(sourceDisposed);
Assert.Equal(sourceLength, subIndex);
Assert.All(subState, s => Assert.Equal(subLength + 1, s));
Assert.All(subCollectionDisposed, t => Assert.True(t));
// .NET Core fixes an oversight where we wouldn't properly dispose
// the SelectMany iterator. See https://github.com/dotnet/corefx/pull/13942.
int expectedCurrent = 0;
Assert.Equal(expectedCurrent, e.Current);
Assert.False(e.MoveNext());
Assert.Equal(expectedCurrent, e.Current);
}
public static IEnumerable<object[]> DisposeAfterEnumerationData()
{
int[] lengths = { 1, 2, 3, 5, 8, 13, 21, 34 };
return lengths.SelectMany(l => lengths, (l1, l2) => new object[] { l1, l2 });
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsSpeedOptimized))]
[SkipOnTargetFramework(
~TargetFrameworkMonikers.Netcoreapp,
".NET Core optimizes SelectMany and throws an OverflowException. On the .NET Framework this takes a long time. See https://github.com/dotnet/corefx/pull/13942."
)]
[InlineData(new[] { int.MaxValue, 1 })]
[InlineData(new[] { 2, int.MaxValue - 1 })]
[InlineData(new[] { 123, 456, int.MaxValue - 100000, 123456 })]
public void ThrowOverflowExceptionOnConstituentLargeCounts(int[] counts)
{
IEnumerable<int> iterator = counts.SelectMany(c => Enumerable.Range(1, c));
Assert.Throws<OverflowException>(() => iterator.Count());
}
[Theory]
[MemberData(nameof(GetToArrayDataSources))]
public void CollectionInterleavedWithLazyEnumerables_ToArray(IEnumerable<int>[] arrays)
{
// See https://github.com/dotnet/runtime/issues/23389
int[] results = arrays.SelectMany(ar => ar).ToArray();
for (int i = 0; i < results.Length; i++)
{
Assert.Equal(i, results[i]);
}
}
[Theory]
[InlineData(10)]
public void EvaluateSelectorOncePerItem(int count)
{
int[] timesCalledMap = new int[count];
IEnumerable<int> source = Enumerable.Range(0, 10);
IEnumerable<int> iterator = source.SelectMany(
index =>
{
timesCalledMap[index]++;
return new[] { index };
}
);
// Iteration
foreach (int index in iterator)
{
Assert.Equal(Enumerable.Repeat(1, index + 1), timesCalledMap.Take(index + 1));
Assert.Equal(
Enumerable.Repeat(0, timesCalledMap.Length - index - 1),
timesCalledMap.Skip(index + 1)
);
}
Array.Clear(timesCalledMap, 0, timesCalledMap.Length);
// ToArray
iterator.ToArray();
Assert.Equal(Enumerable.Repeat(1, timesCalledMap.Length), timesCalledMap);
Array.Clear(timesCalledMap, 0, timesCalledMap.Length);
// ToList
iterator.ToList();
Assert.Equal(Enumerable.Repeat(1, timesCalledMap.Length), timesCalledMap);
Array.Clear(timesCalledMap, 0, timesCalledMap.Length);
// ToHashSet
iterator.ToHashSet();
Assert.Equal(Enumerable.Repeat(1, timesCalledMap.Length), timesCalledMap);
}
public static IEnumerable<object[]> GetToArrayDataSources()
{
// Marker at the end
yield return new object[]
{
new IEnumerable<int>[]
{
new TestEnumerable<int>(new int[] { 0 }),
new TestEnumerable<int>(new int[] { 1 }),
new TestEnumerable<int>(new int[] { 2 }),
new int[] { 3 },
}
};
// Marker at beginning
yield return new object[]
{
new IEnumerable<int>[]
{
new int[] { 0 },
new TestEnumerable<int>(new int[] { 1 }),
new TestEnumerable<int>(new int[] { 2 }),
new TestEnumerable<int>(new int[] { 3 }),
}
};
// Marker in middle
yield return new object[]
{
new IEnumerable<int>[]
{
new TestEnumerable<int>(new int[] { 0 }),
new int[] { 1 },
new TestEnumerable<int>(new int[] { 2 }),
}
};
// Non-marker in middle
yield return new object[]
{
new IEnumerable<int>[]
{
new int[] { 0 },
new TestEnumerable<int>(new int[] { 1 }),
new int[] { 2 },
}
};
// Big arrays (marker in middle)
yield return new object[]
{
new IEnumerable<int>[]
{
new TestEnumerable<int>(Enumerable.Range(0, 100).ToArray()),
Enumerable.Range(100, 100).ToArray(),
new TestEnumerable<int>(Enumerable.Range(200, 100).ToArray()),
}
};
// Big arrays (non-marker in middle)
yield return new object[]
{
new IEnumerable<int>[]
{
Enumerable.Range(0, 100).ToArray(),
new TestEnumerable<int>(Enumerable.Range(100, 100).ToArray()),
Enumerable.Range(200, 100).ToArray(),
}
};
// Interleaved (first marker)
yield return new object[]
{
new IEnumerable<int>[]
{
new int[] { 0 },
new TestEnumerable<int>(new int[] { 1 }),
new int[] { 2 },
new TestEnumerable<int>(new int[] { 3 }),
new int[] { 4 },
}
};
// Interleaved (first non-marker)
yield return new object[]
{
new IEnumerable<int>[]
{
new TestEnumerable<int>(new int[] { 0 }),
new int[] { 1 },
new TestEnumerable<int>(new int[] { 2 }),
new int[] { 3 },
new TestEnumerable<int>(new int[] { 4 }),
}
};
}
}
}
| 37.955119 | 172 | 0.49176 | [
"MIT"
] | belav/runtime | src/libraries/System.Linq/tests/SelectManyTests.cs | 27,062 | C# |
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace Mozlite.Mvc
{
/// <summary>
/// MVC扩展类。
/// </summary>
public static class MvcExtensions
{
/// <summary>
/// 获取当前请求的<see cref="Uri"/>实例。
/// </summary>
/// <param name="request">当前HTTP请求。</param>
/// <returns>返回当前请求的<see cref="Uri"/>实例。</returns>
public static Uri GetUri(this HttpRequest request)
{
var builder = new StringBuilder();
builder.Append(request.Scheme);
builder.Append("://");
builder.Append(request.Host.Value);
builder.Append(request.PathBase.Value);
builder.Append(request.Path.Value);
builder.Append(request.QueryString.Value);
return new Uri(builder.ToString());
}
/// <summary>
/// 获取当前请求的域名或者端口。
/// </summary>
/// <param name="request">当前HTTP请求。</param>
/// <returns>返回当前请求的域名或者端口。</returns>
public static string GetDomain(this HttpRequest request)
{
var uri = request.GetUri();
if (uri.IsDefaultPort)
return uri.DnsSafeHost;
return $"{uri.DnsSafeHost}:{uri.Port}";
}
/// <summary>
/// 判断当前域名是否为本地域名。
/// </summary>
/// <param name="domain">域名实例,可包含端口。</param>
/// <returns>返回判断结果。</returns>
public static bool IsLocal(this string domain)
{
domain = domain.ToLower();
return domain.Equals("localhost")
|| domain.Equals("127.0.0.1")
|| domain.StartsWith("localhost:")
|| domain.StartsWith("127.0.0.1:");
}
/// <summary>
/// 获取或添加当前请求上下文实例。
/// </summary>
/// <typeparam name="TCache">当前缓存类型。</typeparam>
/// <param name="context">HTTP上下文。</param>
/// <param name="key">缓存键。</param>
/// <param name="func">新添加的对象。</param>
/// <returns>返回当前缓存对象。</returns>
public static TCache GetOrCreate<TCache>(this HttpContext context, object key, Func<TCache> func)
{
if (context.Items.TryGetValue(key, out var value) && value is TCache cache)
return cache;
cache = func();
context.Items[key] = cache;
return cache;
}
/// <summary>
/// 获取或添加当前请求上下文实例。
/// </summary>
/// <typeparam name="TCache">当前缓存类型。</typeparam>
/// <param name="context">HTTP上下文。</param>
/// <param name="func">新添加的对象。</param>
/// <returns>返回当前缓存对象。</returns>
public static TCache GetOrCreate<TCache>(this HttpContext context, Func<TCache> func)
{
return context.GetOrCreate(typeof(TCache), func);
}
/// <summary>
/// 获取或添加当前请求上下文实例。
/// </summary>
/// <typeparam name="TCache">当前缓存类型。</typeparam>
/// <param name="context">HTTP上下文。</param>
/// <param name="key">缓存键。</param>
/// <param name="func">新添加的对象。</param>
/// <returns>返回当前缓存对象。</returns>
public static async Task<TCache> GetOrCreateAsync<TCache>(this HttpContext context, object key, Func<Task<TCache>> func)
{
if (context.Items.TryGetValue(key, out var value) && value is TCache cache)
return cache;
cache = await func();
context.Items[key] = cache;
return cache;
}
/// <summary>
/// 获取或添加当前请求上下文实例。
/// </summary>
/// <typeparam name="TCache">当前缓存类型。</typeparam>
/// <param name="context">HTTP上下文。</param>
/// <param name="func">新添加的对象。</param>
/// <returns>返回当前缓存对象。</returns>
public static Task<TCache> GetOrCreateAsync<TCache>(this HttpContext context, Func<Task<TCache>> func)
{
return context.GetOrCreateAsync(typeof(TCache), func);
}
}
} | 34.87069 | 128 | 0.539679 | [
"Apache-2.0"
] | Mozlite/Docs | src/Mozlite.Core/Mvc/MvcExtensions.cs | 4,587 | C# |
// <auto-generated />
using System;
using DiscordBot.Server.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace DiscordBot.Server.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.2.6-servicing-10079")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("DiscordBot.Server.Data.ModelsDb.ChannelDbModel", b =>
{
b.Property<decimal>("Channel_Id")
.ValueGeneratedOnAdd()
.HasConversion(new ValueConverter<decimal, decimal>(v => default(decimal), v => default(decimal), new ConverterMappingHints(precision: 20, scale: 0)));
b.HasKey("Channel_Id");
b.ToTable("TwitchChannel");
});
modelBuilder.Entity("DiscordBot.Server.Data.ModelsDb.GuildMessageDbModel", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreatedAt");
b.Property<string>("Message");
b.HasKey("Id");
b.ToTable("GuildMessages");
});
modelBuilder.Entity("DiscordBot.Server.Data.ModelsDb.GuildNotificationDbModel", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<bool>("Notify");
b.HasKey("Id");
b.ToTable("GuildNotifications");
});
modelBuilder.Entity("DiscordBot.Server.Data.ModelsDb.StreamerDbModel", b =>
{
b.Property<string>("UniqueID")
.ValueGeneratedOnAdd();
b.Property<bool>("IsStreaming");
b.Property<string>("PlayedGame");
b.Property<string>("ProfileImage");
b.Property<bool>("SentMessage");
b.Property<string>("StreamTitle");
b.Property<string>("StreamerId");
b.Property<string>("StreamerLogin");
b.Property<long>("TotalFollows");
b.Property<string>("UrlAddress");
b.Property<int>("Viewers");
b.HasKey("UniqueID");
b.ToTable("TwitchStreamers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasMaxLength(256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict);
});
#pragma warning restore 612, 618
}
}
}
| 34.348993 | 175 | 0.483197 | [
"MIT"
] | Presst0n/GuildDashBot | DiscordBot.Server.LibraryServices/Migrations/ApplicationDbContextModelSnapshot.cs | 10,238 | 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 ASP.NET_Caching_Data.Account {
public partial class Login {
/// <summary>
/// ErrorMessage 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.PlaceHolder ErrorMessage;
/// <summary>
/// FailureText 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.Literal FailureText;
/// <summary>
/// Email 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.TextBox Email;
/// <summary>
/// Password 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.TextBox Password;
/// <summary>
/// RememberMe 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.CheckBox RememberMe;
/// <summary>
/// RegisterHyperLink 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.HyperLink RegisterHyperLink;
/// <summary>
/// OpenAuthLogin control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ASP.NET_Caching_Data.Account.OpenAuthProviders OpenAuthLogin;
}
}
| 34.658228 | 87 | 0.533236 | [
"MIT"
] | NikitoG/TelerikAcademyHomeworks | ASP.NET-MVC/ASP.NET Caching Data/ASP.NET Caching Data/Account/Login.aspx.designer.cs | 2,740 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace MCV
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 25.37037 | 70 | 0.640876 | [
"MIT"
] | NikoRozo/MVC_PICA | Program.cs | 685 | C# |
using System;
using System.Xml.Serialization;
namespace Alipay.AopSdk.Domain
{
/// <summary>
/// AlipayFundTransThirdpartyRewardQueryModel Data Structure.
/// </summary>
[Serializable]
public class AlipayFundTransThirdpartyRewardQueryModel : AopObject
{
/// <summary>
/// 场景码,接入时找业务方分配
/// </summary>
[XmlElement("scene")]
public string Scene { get; set; }
/// <summary>
/// 付款方支付宝UserId
/// </summary>
[XmlElement("sender_user_id")]
public string SenderUserId { get; set; }
/// <summary>
/// 打赏单据号
/// </summary>
[XmlElement("transfer_no")]
public string TransferNo { get; set; }
}
}
| 23.741935 | 70 | 0.567935 | [
"MIT"
] | ArcherTrister/LeXun.Alipay.AopSdk | src/Alipay.AopSdk/Domain/AlipayFundTransThirdpartyRewardQueryModel.cs | 784 | C# |
using BefunCompile.Exceptions;
using BefunCompile.Graph.Vertex;
using BefunCompile.Math;
using System;
using System.Collections.Generic;
using System.Linq;
namespace BefunCompile.Graph
{
public class BCModRule
{
private enum ReorderMode { Impossible, MoveSignificantBackwards, MoveSignificantForwards }
private readonly List<Func<BCVertex, bool>> prerequisites = new List<Func<BCVertex, bool>>();
private readonly List<Func<BCVertex[], Vec2i[], BCVertex>> replacements = new List<Func<BCVertex[], Vec2i[], BCVertex>>();
private readonly List<Func<BCVertex[], bool>> conditions = new List<Func<BCVertex[], bool>>();
private readonly bool allowPathExtraction;
private readonly bool allowSplitCodePathReplacement;
private readonly bool allowNodeReordering;
public List<string> LastRunInfo = new List<string>();
public BCModRule(bool allowExtr = true, bool allowSPC = false, bool allowReorder = true)
{
allowPathExtraction = allowExtr;
allowSplitCodePathReplacement = allowSPC;
allowNodeReordering = allowReorder;
}
public void AddPreq<T>() where T : BCVertex
{
prerequisites.Add(v => v is T);
}
public void AddPreq<T>(Func<T, bool> p) where T : BCVertex
{
prerequisites.Add(v => v is T && p((T)v));
}
public void AddPreq(params Func<BCVertex, bool>[] p)
{
foreach (var preq in p)
{
prerequisites.Add(preq);
}
}
public void AddRep(params Func<BCVertex[], Vec2i[], BCVertex>[] r)
{
foreach (var rep in r)
{
replacements.Add(rep);
}
}
public void AddCond(params Func<BCVertex[], bool>[] c)
{
foreach (var cond in c)
{
conditions.Add(cond);
}
}
public bool ArrayExecute(BCGraph g)
{
foreach (var curr in g.Vertices)
{
if (Execute(g, curr))
return true;
}
return false;
}
public bool Execute(BCGraph g)
{
LastRunInfo.Clear();
HashSet<BCVertex> travelled = new HashSet<BCVertex>();
Stack<BCVertex> untravelled = new Stack<BCVertex>();
untravelled.Push(g.Root);
while (untravelled.Count > 0)
{
BCVertex curr = untravelled.Pop();
if (Execute(g, curr))
return true;
travelled.Add(curr);
foreach (var child in curr.Children.Where(child => !travelled.Contains(child)))
{
untravelled.Push(child);
}
}
return false;
}
private bool Execute(BCGraph g, BCVertex v)
{
var chainlist = allowPathExtraction ? GetMatchingExtractedChain(g, v) : GetMatchingChain(v);
if (chainlist == null && allowNodeReordering) chainlist = GetMatchingReorderedChain(g, v);
if (chainlist == null)
return false;
//##################################################################################
BCVertex[] chain = chainlist.ToArray();
Vec2i[] posarr = chain.SelectMany(p => p.Positions).Distinct().ToArray();
BCVertex[] repChain = replacements.Select(p => p(chain, posarr)).ToArray();
if (chain.Skip(1).Any(p => p.Parents.Count > 1))
{
return false;
}
if (chain.SkipLastN(1).Any(p => p.Children.Count > 1))
{
return false;
}
BCVertex chainFirst = chain[0];
BCVertex chainLast = chain.Last();
bool isRoot = (chainFirst == g.Root);
bool isLeaf = (chainLast.Children.Count == 0);
if (repChain.Length == 0 && (isRoot || isLeaf))
repChain = new BCVertex[] { new BCVertexNOP(BCDirection.UNKNOWN, posarr) };
if (chainLast.Children.Contains(chainFirst))
return false;
BCVertex repChainFirst = repChain.FirstOrDefault();
BCVertex repChainLast = repChain.LastOrDefault();
BCVertex[] prev = chainFirst.Parents.ToArray();
BCVertex[] next = chainLast.Children.ToArray();
if (repChain.Length == 0 && prev.Any(p => p.IsCodePathSplit()) && next.Length == 0)
repChain = new BCVertex[] { new BCVertexNOP(BCDirection.UNKNOWN, posarr) };
if (next.Length > 1 && !allowSplitCodePathReplacement)
return false;
if (repChain.Length == 1 && chain.Length == 1 && repChain[0] is BCVertexNOP && chain[0] is BCVertexNOP)
return false;
for (int i = 0; i < repChain.Length - 1; i++)
{
repChain[i].Children.Add(repChain[i + 1]);
}
for (int i = 1; i < repChain.Length; i++)
{
repChain[i].Parents.Add(repChain[i - 1]);
}
if (repChain.Length > 0)
{
repChainFirst.Parents.AddRange(prev);
repChainLast.Children.AddRange(next);
foreach (var snext in next)
{
snext.Parents.Remove(chainLast);
snext.Parents.Add(repChainLast);
}
foreach (var sprev in prev)
{
sprev.Children.Remove(chainFirst);
sprev.Children.Add(repChainFirst);
if (sprev is IDecisionVertex)
{
if ((sprev as IDecisionVertex).EdgeTrue == chainFirst)
(sprev as IDecisionVertex).EdgeTrue = repChainFirst;
else if ((sprev as IDecisionVertex).EdgeFalse == chainFirst)
(sprev as IDecisionVertex).EdgeFalse = repChainFirst;
else
throw new CodeGenException();
}
}
if (isRoot)
g.Root = repChainFirst;
}
else
{
foreach (var snext in next)
{
snext.Parents.Remove(chainLast);
snext.Parents.AddRange(prev);
}
foreach (var sprev in prev)
{
sprev.Children.Remove(chainFirst);
sprev.Children.AddRange(next);
if (sprev is BCVertexDecision)
{
if ((sprev as BCVertexDecision).EdgeTrue == chainFirst)
(sprev as BCVertexDecision).EdgeTrue = next[0];
else if ((sprev as BCVertexDecision).EdgeFalse == chainFirst)
(sprev as BCVertexDecision).EdgeFalse = next[0];
else
throw new CodeGenException();
}
if (sprev is BCVertexExprDecision)
{
if ((sprev as BCVertexExprDecision).EdgeTrue == chainFirst)
(sprev as BCVertexExprDecision).EdgeTrue = next[0];
else if ((sprev as BCVertexExprDecision).EdgeFalse == chainFirst)
(sprev as BCVertexExprDecision).EdgeFalse = next[0];
else
throw new CodeGenException();
}
}
if (isRoot)
g.Root = next[0];
}
g.Vertices.RemoveAll(p => chain.Contains(p));
g.Vertices.AddRange(repChain);
if (repChain.Length == 0)
{
if (next.Length > 0)
next[0].Positions = next[0].Positions.Concat(posarr).Distinct().ToArray();
else if (prev.Length > 0)
prev[0].Positions = prev[0].Positions.Concat(posarr).Distinct().ToArray();
else
throw new ArgumentException("We lost a code point :( ");
}
LastRunInfo.Add("[Before]: " + string.Join(" -> ", chain.Select(c => "[" + c.ToOneLineString() + "]")));
LastRunInfo.Add("[After]: " + string.Join(" -> ", repChain.Select(c => "[" + c.ToOneLineString() + "]")));
return true;
}
public List<BCVertex> GetMatchingChain(BCGraph g)
{
HashSet<BCVertex> travelled = new HashSet<BCVertex>();
Stack<BCVertex> untravelled = new Stack<BCVertex>();
untravelled.Push(g.Root);
while (untravelled.Count > 0)
{
BCVertex curr = untravelled.Pop();
var chain = GetMatchingChain(0, curr);
if (chain != null)
return chain;
travelled.Add(curr);
foreach (var child in curr.Children)
{
if (!travelled.Contains(child))
untravelled.Push(child);
}
}
return null;
}
private List<BCVertex> GetMatchingChain(BCVertex v)
{
List<BCVertex> chain = GetMatchingChain(0, v);
if (chain == null || !conditions.All(c => c(chain.ToArray()))) return null;
return chain;
}
private List<BCVertex> GetMatchingExtractedChain(BCGraph g, BCVertex v)
{
List<BCVertex> chain = GetMatchingChain(0, v);
if (chain == null || !conditions.All(c => c(chain.ToArray()))) return null;
chain = ExtractChain(g, chain);
if (chain != null) LastRunInfo.Add("EXTRACTED");
return chain;
}
private List<BCVertex> GetMatchingChain(int pos, BCVertex v)
{
if (pos >= prerequisites.Count)
return null;
if (prerequisites[pos](v))
{
if (pos + 1 == prerequisites.Count)
{
return new List<BCVertex>() { v };
}
else
{
List<BCVertex> tail = v.Children
.Aggregate<BCVertex, List<BCVertex>>(null, (current, child) => current ?? GetMatchingChain(pos + 1, child));
if (tail == null)
{
return null;
}
else
{
tail.Insert(0, v);
return tail;
}
}
}
return null;
}
private List<BCVertex> GetMatchingReorderedChain(BCGraph g, BCVertex v)
{
if (prerequisites.Count == 0 || prerequisites.Count == 1) return null;
var match0 = prerequisites[0](v);
if (!match0) return null;
var rawchain = new List<Tuple<BCVertex, bool, int>>();
rawchain.Add(Tuple.Create(v, true, 0));
var vertex = v;
var position = 1;
for (;;)
{
if (vertex.Children.Count != 1) return null;
vertex = vertex.Children.Single();
if (prerequisites[position](vertex))
{
rawchain.Add(Tuple.Create(vertex, true, position));
position++;
if (position >= prerequisites.Count) break;
}
else
{
rawchain.Add(Tuple.Create(vertex, false, -1));
}
}
var realchain = rawchain.Where(c => c.Item2).Select(c => c.Item1).ToArray();
if (!conditions.All(c => c(realchain))) return null;
if (realchain.Length == rawchain.Count) return null;
if (!CanReorderChain(rawchain, out ReorderMode reom)) return null;
bool needsExtraction = rawchain.Skip(1).Any(p => p.Item1.Parents.Count > 1);
if (needsExtraction)
{
if (!allowPathExtraction) return null;
var newchain = ExtractChain(g, rawchain.Select(c => c.Item1).ToList());
var rawchain2 = new List<Tuple<BCVertex, bool, int>>();
for (int i = 0; i < rawchain.Count; i++)
{
rawchain2.Add(Tuple.Create(newchain[i], rawchain[i].Item2, rawchain[i].Item3));
}
LastRunInfo.Add("EXTRACTED");
rawchain = rawchain2;
}
LastRunInfo.Add("REORDERED");
return ReorderChain(g, rawchain, reom);
}
private bool CanReorderChain(List<Tuple<BCVertex, bool, int>> chain, out ReorderMode mode)
{
if (CanReorderChainForward(chain))
{
mode = ReorderMode.MoveSignificantForwards;
return true;
}
if (CanReorderChainBackward(chain))
{
mode = ReorderMode.MoveSignificantBackwards;
return true;
}
mode = ReorderMode.Impossible;
return false;
}
private bool CanReorderChainForward(List<Tuple<BCVertex, bool, int>> chain)
{
// Move used vertices to higher indizies
if (chain.Any(p => p.Item1.IsCodePathSplit())) return false;
if (!chain.First().Item2) return false;
if (!chain.Last().Item2) return false;
for (int i = 0; i < chain.Count-1; i++)
{
if (!chain[i].Item2) continue;
var se = chain[i].Item1.GetSideEffects();
if (chain.Skip(i).Where(c => !c.Item2).Any(c => !BCModAreaHelper.CanSwap(se, c.Item1.GetSideEffects()))) return false;
}
return true;
}
private bool CanReorderChainBackward(List<Tuple<BCVertex, bool, int>> chain)
{
// Move used vertices to lower indizies
if (chain.Any(p => p.Item1.IsCodePathSplit())) return false;
if (!chain.First().Item2) return false;
if (!chain.Last().Item2) return false;
for (int i = 1; i < chain.Count; i++)
{
if (!chain[i].Item2) continue;
var se = chain[i].Item1.GetSideEffects();
if (chain.Take(i).Where(c => !c.Item2).Any(c => !BCModAreaHelper.CanSwap(se, c.Item1.GetSideEffects()))) return false;
}
return true;
}
private List<BCVertex> ReorderChain(BCGraph g, List<Tuple<BCVertex, bool, int>> chain, ReorderMode mode)
{
if (chain.Skip(1).Any(p => p.Item1.Parents.Count > 2)) throw new Exception("Cannot reorder multi-parent vertices");
var parents = chain.First().Item1.Parents.ToList();
var children = chain.Last().Item1.Children.ToList();
var isRoot = (g.Root == chain.First().Item1);
List<Tuple<BCVertex, bool, int>> ordered;
if (mode == ReorderMode.MoveSignificantForwards)
ordered = chain.Where(c1 => !c1.Item2).Concat(chain.Where(c2 => c2.Item2)).ToList();
else if (mode == ReorderMode.MoveSignificantBackwards)
ordered = chain.Where(c1 => c1.Item2).Concat(chain.Where(c2 => !c2.Item2)).ToList();
else
throw new Exception("Invalid order mode: " + mode);
foreach (var o in ordered)
{
o.Item1.Parents.Clear();
o.Item1.Children.Clear();
}
foreach (var pp in parents)
{
pp.Children.Remove(chain.First().Item1);
pp.Children.Add(ordered.First().Item1);
var dec = pp as IDecisionVertex;
if (dec != null)
{
if (dec.EdgeFalse == chain.First().Item1)
dec.EdgeFalse = ordered.First().Item1;
if (dec.EdgeTrue == chain.First().Item1)
dec.EdgeTrue = ordered.First().Item1;
}
ordered.First().Item1.Parents.Add(pp);
}
for (int i = 1; i < ordered.Count; i++)
{
ordered[i].Item1.Parents.Add(ordered[i - 1].Item1);
}
for (int i = 0; i < ordered.Count-1; i++)
{
ordered[i].Item1.Children.Add(ordered[i + 1].Item1);
}
foreach (var cc in children)
{
cc.Parents.Remove(chain.Last().Item1);
cc.Parents.Add(ordered.Last().Item1);
ordered.Last().Item1.Children.Add(cc);
}
if (isRoot)
{
g.Root = ordered.First().Item1;
}
return ordered.Where(p => p.Item2).Select(p => p.Item1).ToList();
}
private List<BCVertex> ExtractChain(BCGraph g, List<BCVertex> chain)
{
if (chain == null)
return null;
if (!chain.Skip(1).Any(p => p.Parents.Count > 1))
return chain;
if (chain.Count <= 1)
return chain;
if (chain.Last().Children.Count > 1)
return chain;
int cutIndex = chain.FindIndex(p => p.Parents.Count > 1 && p != chain[0]);
BCVertex cut = chain[cutIndex];
BCVertex cutPrev = cut.Parents.First(p => p != chain[cutIndex - 1]);
BCVertex next = chain.Last().Children.FirstOrDefault();
cutPrev.Children.Remove(cut);
cut.Parents.Remove(cutPrev);
BCVertex cutCurr = cutPrev;
for (int i = cutIndex; i < chain.Count; i++)
{
BCVertex newVertex = chain[i].Duplicate();
g.Vertices.Add(newVertex);
cutCurr.Children.Add(newVertex);
newVertex.Parents.Add(cutCurr);
if (cutCurr is IDecisionVertex)
{
if ((cutCurr as IDecisionVertex).EdgeTrue == cut)
(cutCurr as IDecisionVertex).EdgeTrue = newVertex;
else if ((cutCurr as IDecisionVertex).EdgeFalse == cut)
(cutCurr as IDecisionVertex).EdgeFalse = newVertex;
else
throw new ArgumentException("We lost a code point :( ");
}
cutCurr = newVertex;
}
if (next != null)
{
cutCurr.Children.Add(next);
next.Parents.Add(cutCurr);
}
return ExtractChain(g, chain);
}
}
}
| 25.769912 | 124 | 0.636264 | [
"MIT"
] | Mikescher/BefunCompile | BefunCompile/Graph/Optimizations/GraphReplace/BCModRule.cs | 14,562 | C# |
// This is an independent project of an individual developer. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Runtime.CompilerServices;
using NetExtender.Types.Collections;
using NetExtender.Utilities.Core;
namespace NetExtender.Utilities.Types
{
public static partial class EnumerableUtilities
{
/// <summary>
/// Gets collection count if <see cref="source"/> is materialized, otherwise null.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
[Pure]
public static Int32? CountIfMaterialized<T>(this IEnumerable<T> source)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
return source switch
{
ICollection<T> collection => collection.Count,
IReadOnlyCollection<T> collection => collection.Count,
ICollection collection => collection.Count,
_ => null
};
}
[Pure]
public static Boolean IsMaterialized<T>(this IEnumerable<T> source)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
return IsMaterialized(source, out _);
}
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Boolean IsMaterialized<T>(this IEnumerable<T> source, [NotNullWhen(true)] out Int32? count)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
count = CountIfMaterialized(source);
return count is not null;
}
public static IReadOnlyCollection<T> Materialize<T>(this IEnumerable<T>? source)
{
return source switch
{
null => Array.Empty<T>(),
IReadOnlyCollection<T> collection => collection,
ICollection<T> collection => new ReadOnlyCollectionWrapper<T>(collection),
_ => source.ToArray()
};
}
[Pure]
public static Int32? CountIfMaterializedByReflection(this IEnumerable source)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
return source.TryGetPropertyValue("Length", out Int32 length) ? length :
source.TryGetPropertyValue("Count", out length) ? length :
source.TryGetPropertyValue("LongLength", out length) ? length :
source.TryGetPropertyValue("LongCount", out length) ? length : default;
}
[Pure]
public static Int64? LongCountIfMaterializedByReflection(this IEnumerable source)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
return source.TryGetPropertyValue("LongLength", out Int64 length) ? length :
source.TryGetPropertyValue("LongCount", out length) ? length :
source.TryGetPropertyValue("Length", out length) ? length :
source.TryGetPropertyValue("Count", out length) ? length : default;
}
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Boolean IsMaterializedByReflection(this IEnumerable source)
{
return IsMaterializedByReflection(source, out Int32? _);
}
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Boolean IsMaterializedByReflection(this IEnumerable source, [NotNullWhen(true)] out Int32? count)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
count = CountIfMaterializedByReflection(source);
return count is not null;
}
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Boolean IsMaterializedByReflection(this IEnumerable source, [NotNullWhen(true)] out Int64? count)
{
return IsLongMaterializedByReflection(source, out count);
}
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Boolean IsLongMaterializedByReflection(this IEnumerable source)
{
return IsLongMaterializedByReflection(source, out _);
}
[Pure]
public static Boolean IsLongMaterializedByReflection(this IEnumerable source, [NotNullWhen(true)] out Int64? count)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
count = LongCountIfMaterializedByReflection(source);
return count is not null;
}
/// <summary>
/// Gets collection if <see cref="source"/> is materialized, otherwise ToArray();ed collection.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="nullToEmpty"></param>
[Pure]
public static IEnumerable<T> Materialize<T>(this IEnumerable<T> source, Boolean nullToEmpty)
{
return source switch
{
null when nullToEmpty => Enumerable.Empty<T>(),
null => throw new ArgumentNullException(nameof(source)),
ICollection<T> => source,
IReadOnlyCollection<T> => source,
_ => source.ToArray()
};
}
public static IEnumerable<T> Dematerialize<T>(this IEnumerable<T> source)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
using IEnumerator<T> enumerator = source.GetEnumerator();
return enumerator.AsEnumerable();
}
}
} | 35.405556 | 123 | 0.579005 | [
"MIT"
] | Rain0Ash/NetExtender | NetExtender.Core/Utilities/Types/Enumerable/CollectionEnumerableUtilities.cs | 6,373 | C# |
using System;
namespace FortifyFprConverter
{
public class ContentFileHandlingController
{
public ContentFileHandlingController() { }
public CMOEViewModel Model { get; set; }
[Dependency]
public ContentFileViewModel ViewModel { get; set; }
[Dependency]
public ICachedDataProvider CachedData { get; set; }
/// <param name="frmContent"> Download form input parameters </param>
/// <returns>Action Result object</returns>
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Download(ContentFileViewModel frmContent)
{
try
{
this.ViewModel = frmContent;
if (ViewModel.DocumentId == Guid.Empty)
{
}
}
catch { }
}
public void SomeMethod()
{
ViewModel.TemplatePath = (ViewModel.DocumentType == Const.DoucmentTypeKeyResults) ? Server.MapPath(Request.ApplicationPath) + Const.KeyResultsDocumentTemplatePath :
Server.MapPath(Request.ApplicationPath) + Const.CompetencyDocumentTemplatePath;
byte[] byteFile = System.IO.File.ReadAllBytes(ViewModel.TemplatePath);
// Write the byte array in a memory stream
System.IO.MemoryStream streamPackage = new System.IO.MemoryStream();
}
}
}
| 31.488889 | 176 | 0.60127 | [
"MIT"
] | LaudateCorpus1/sarif-sdk | src/Test.FunctionalTests.Sarif/v2/ConverterTestData/FortifyFpr/src/Controllers/ContentFileHandlingController.cs | 1,417 | C# |
// <copyright file="AssemblyInfo.cs" company="ConfigR contributors">
// Copyright (c) ConfigR contributors. (configr.net@gmail.com)
// </copyright>
using System.Reflection;
[assembly: AssemblyTitle("ConfigR.Samples.Scheduler")]
[assembly: AssemblyDescription("Simple scheduler built using ConfigR.")]
| 34.777778 | 73 | 0.744409 | [
"MIT"
] | config-r/config-r-samples | src/ConfigR.Samples.Scheduler/Properties/AssemblyInfo.cs | 315 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the kinesisanalytics-2015-08-14.normal.json service model.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.KinesisAnalytics.Model
{
///<summary>
/// KinesisAnalytics exception
/// </summary>
#if !PCL && !NETSTANDARD
[Serializable]
#endif
public class LimitExceededException : AmazonKinesisAnalyticsException
{
/// <summary>
/// Constructs a new LimitExceededException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public LimitExceededException(string message)
: base(message) {}
/// <summary>
/// Construct instance of LimitExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public LimitExceededException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of LimitExceededException
/// </summary>
/// <param name="innerException"></param>
public LimitExceededException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of LimitExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public LimitExceededException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of LimitExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public LimitExceededException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !PCL && !NETSTANDARD
/// <summary>
/// Constructs a new instance of the LimitExceededException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected LimitExceededException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
} | 43.041237 | 178 | 0.649341 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/KinesisAnalytics/Generated/Model/LimitExceededException.cs | 4,175 | C# |
using Castle.Facilities.TypedFactory;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using TBT.Business.Factories.Interfaces;
using TBT.Business.Infrastructure.CastleWindsor.ComponentSelector;
using TBT.DAL.Repository.Interfaces;
namespace TBT.Business.Infrastructure.CastleWindsor
{
public class FactoriesInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.AddFacility<TypedFactoryFacility>();
container.Register(Component.For<IManagerFactory>().AsFactory(c => c.SelectedWith(new FactoryComponentSelector())).LifeStyle.Transient);
container.Register(Component.For<IRepositoryFactory>().AsFactory(r => r.SelectedWith(new FactoryComponentSelector())).LifeStyle.Transient);
}
}
}
| 42.142857 | 151 | 0.771751 | [
"MIT"
] | Brainence/TimeBookingTool-API | src/TBT.Business/Infrastructure/CastleWindsor/FactoriesInstaller.cs | 887 | C# |
using Content.Server.GameObjects.Components.GUI;
using Content.Server.GameObjects.Components.Mobs;
using Content.Server.GameObjects.Components.Weapon.Melee;
using Content.Server.GameObjects.EntitySystems.Click;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
namespace Content.Server.AI.Operators.Combat.Melee
{
public class SwingMeleeWeaponOperator : AiOperator
{
private readonly float _burstTime;
private float _elapsedTime;
private readonly IEntity _owner;
private readonly IEntity _target;
public SwingMeleeWeaponOperator(IEntity owner, IEntity target, float burstTime = 1.0f)
{
_owner = owner;
_target = target;
_burstTime = burstTime;
}
public override bool Startup()
{
if (!base.Startup())
{
return true;
}
if (!_owner.TryGetComponent(out CombatModeComponent combatModeComponent))
{
return false;
}
if (!combatModeComponent.IsInCombatMode)
{
combatModeComponent.IsInCombatMode = true;
}
return true;
}
public override bool Shutdown(Outcome outcome)
{
if (!base.Shutdown(outcome))
return false;
if (_owner.TryGetComponent(out CombatModeComponent combatModeComponent))
{
combatModeComponent.IsInCombatMode = false;
}
return true;
}
public override Outcome Execute(float frameTime)
{
if (_burstTime <= _elapsedTime)
{
return Outcome.Success;
}
if (!_owner.TryGetComponent(out HandsComponent hands) || hands.GetActiveHand == null)
{
return Outcome.Failed;
}
var meleeWeapon = hands.GetActiveHand.Owner;
meleeWeapon.TryGetComponent(out MeleeWeaponComponent meleeWeaponComponent);
if ((_target.Transform.Coordinates.Position - _owner.Transform.Coordinates.Position).Length >
meleeWeaponComponent.Range)
{
return Outcome.Failed;
}
var interactionSystem = IoCManager.Resolve<IEntitySystemManager>().GetEntitySystem<InteractionSystem>();
interactionSystem.UseItemInHand(_owner, _target.Transform.Coordinates, _target.Uid);
_elapsedTime += frameTime;
return Outcome.Continuing;
}
}
}
| 29.747126 | 116 | 0.594668 | [
"MIT"
] | GraniteSidewalk/space-station-14 | Content.Server/AI/Operators/Combat/Melee/SwingMeleeWeaponOperator.cs | 2,588 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using word = Microsoft.Office.Interop.Word;
namespace GutenbergProject
{
public partial class frmLanguage : Form
{
Classes.Connection connection = new Classes.Connection();
DataSet ds = new DataSet();
public frmLanguage()
{
InitializeComponent();
}
private void ShowData()
{
SqlConnection conn = new SqlConnection(connection.conString);
conn.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT BookName, AuthorName, Category, Page, DateOfIssue, Book FROM products WHERE Category = 'Yabancı Dil'", conn);
dataAdapter.Fill(ds, "products");
dataGridView1.DataSource = ds.Tables["products"];
conn.Close();
}
private void frmLanguage_Load(object sender, EventArgs e)
{
ShowData();
}
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
string bookPath = dataGridView1.CurrentRow.Cells["Book"].Value.ToString();
MessageBox.Show(bookPath + " adlı kitap açılıyor.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
word.Application ap = new word.Application();
word.Document document = ap.Documents.Open(@"C:\\Users\\mtyar\\source\\repos\\GutenbergProject\\GutenbergProject\\Books\\" + bookPath + "");
}
#region panelOperations
private void btnMinimize_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
private void btnExit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
this.Close();
}
#endregion
}
}
| 32.171875 | 178 | 0.650801 | [
"MIT"
] | thyrdmc/Gutenberg-Project | GutenbergProject/GutenbergProject/frmLanguage.cs | 2,066 | C# |
using System.Collections.Generic;
using CommandLine;
using CommandLine.Text;
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable AutoPropertyCanBeMadeGetOnly.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
namespace Captura.CmdOptions
{
// ReSharper disable once ClassNeverInstantiated.Global
[Verb("start", HelpText = "Start Recording")]
internal class StartCmdOptions : CommonCmdOptions
{
[Option("delay", HelpText = "Milliseconds to wait before starting recording.")]
public int Delay { get; set; }
[Option('t', "length", HelpText = "Length of Recording in seconds.")]
public int Length { get; set; }
[Option('y', HelpText = "Overwrite existing file")]
public bool Overwrite { get; set; }
[Option("keys", HelpText = "Include Keystrokes in Recording (default = false).")]
public bool Keys { get; set; }
[Option("clicks", HelpText = "Include Mouse Clicks in Recording (default = false).")]
public bool Clicks { get; set; }
[Option("mic", Default = -1, HelpText = "Index of Microphone source. Default = -1 (No Microphone).")]
public int Microphone { get; set; }
[Option("speaker", Default = -1, HelpText = "Index of Speaker output source. Default = -1 (No Speaker).")]
public int Speaker { get; set; }
[Option('r', "framerate", HelpText = "Recording frame rate.")]
public int? FrameRate { get; set; }
[Option("encoder", HelpText = "Video encoder to use.")]
public string Encoder { get; set; }
[Option("vq", HelpText = "Video Quality")]
public int? VideoQuality { get; set; }
[Option("aq", HelpText = "Audio Quality")]
public int? AudioQuality { get; set; }
[Option("webcam", Default = -1, HelpText = "WebCam to use. Default = -1 (No WebCam)")]
public int WebCam { get; set; }
[Usage]
public static IEnumerable<Example> Examples
{
get
{
yield return new Example("Record 10 seconds with cursor and keystrokes and audio from first speaker output.", new StartCmdOptions
{
Cursor = true,
Keys = true,
Length = 10,
Speaker = 0
});
yield return new Example("Record specific region", new StartCmdOptions
{
Source = "100,100,300,400"
});
yield return new Example("Record as Gif to out.gif", new StartCmdOptions
{
Encoder = "gif",
FileName = "out.gif"
});
}
}
}
}
| 35.551282 | 145 | 0.566174 | [
"MIT"
] | Lakritzator/Captura | src/Captura.Console/CmdOptions/StartCmdOptions.cs | 2,775 | C# |
namespace Crash.GOOLIns
{
[GOOLInstruction(7,GameVersion.Crash1)]
[GOOLInstruction(7,GameVersion.Crash1Beta1995)]
[GOOLInstruction(7,GameVersion.Crash1BetaMAR08)]
[GOOLInstruction(7,GameVersion.Crash1BetaMAY11)]
[GOOLInstruction(7,GameVersion.Crash2)]
[GOOLInstruction(7,GameVersion.Crash3)]
public sealed class Andb : GOOLInstruction
{
public Andb(int value,GOOLEntry gool) : base(value,gool) { }
public override string Name => "ANDB";
public override string Format => DefaultFormatLR;
public override string Comment => $"{GetArg('L')} & {GetArg('R')}";
}
}
| 34.944444 | 75 | 0.691574 | [
"MIT",
"BSD-3-Clause"
] | Aedhen/CrashEdit | Crash/Formats/Crash Formats/GOOL/GOOL Instructions/Andb.cs | 631 | C# |
using MediatR;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using MidnightLizard.Commons.Domain.Model;
using MidnightLizard.Commons.Domain.Interfaces;
using MidnightLizard.Commons.Domain.Messaging;
using MidnightLizard.Commons.Domain.Results;
using MidnightLizard.Schemes.Domain.PublicSchemeAggregate;
using MidnightLizard.Schemes.Domain.PublicSchemeAggregate.Requests;
using MidnightLizard.Schemes.Processor.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MidnightLizard.Schemes.Processor.Application.DomainRequestHandlers
{
public class SchemePublishRequestHandler :
DomainRequestHandler<PublicScheme, PublishSchemeRequest, PublicSchemeId>
{
public SchemePublishRequestHandler(
IOptions<AggregatesConfig> cacheConfig,
IMemoryCache memoryCache,
IDomainEventDispatcher<PublicSchemeId> domainEventsDispatcher,
IAggregateSnapshotAccessor<PublicScheme, PublicSchemeId> schemesSnapshot,
IDomainEventStore<PublicSchemeId> eventsAccessor) :
base(cacheConfig, memoryCache, domainEventsDispatcher, schemesSnapshot, eventsAccessor)
{
}
protected override void HandleDomainRequest(PublicScheme aggregate, PublishSchemeRequest request, UserId userId, CancellationToken cancellationToken)
{
aggregate.Publish(userId, request.ColorScheme, request.Description);
}
}
}
| 40.552632 | 157 | 0.782609 | [
"MIT"
] | Midnight-Lizard/Schemes-Processor | app/Application/DomainRequestHandlers/SchemePublishRequestHandler.cs | 1,543 | C# |
//------------------------------------------------------------------------------
// <copyright file="WebHeaderCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net {
using System.Net.Cache;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Globalization;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
internal enum WebHeaderCollectionType : ushort {
Unknown,
WebRequest,
WebResponse,
HttpWebRequest,
HttpWebResponse,
HttpListenerRequest,
HttpListenerResponse,
FtpWebRequest,
FtpWebResponse,
FileWebRequest,
FileWebResponse,
}
//
// HttpHeaders - this is our main HttpHeaders object,
// which is a simple collection of name-value pairs,
// along with additional methods that provide HTTP parsing
// collection to sendable buffer capablities and other enhansments
// We also provide validation of what headers are allowed to be added.
//
/// <devdoc>
/// <para>
/// Contains protocol headers associated with a
/// request or response.
/// </para>
/// </devdoc>
[ComVisible(true), Serializable]
public class WebHeaderCollection : NameValueCollection, ISerializable {
//
// Data and Constants
//
private const int ApproxAveHeaderLineSize = 30;
private const int ApproxHighAvgNumHeaders = 16;
private static readonly HeaderInfoTable HInfo = new HeaderInfoTable();
//
// Common Headers - used only when receiving a response, and internally. If the user ever requests a header,
// all the common headers are moved into the hashtable.
//
private string[] m_CommonHeaders;
private int m_NumCommonHeaders;
// Grouped by first character, so lookup is faster. The table s_CommonHeaderHints maps first letters to indexes in this array.
// After first character, sort by decreasing length. It's ok if two headers have the same first character and length.
private static readonly string[] s_CommonHeaderNames = new string[] {
HttpKnownHeaderNames.AcceptRanges, // "Accept-Ranges" 13
HttpKnownHeaderNames.ContentLength, // "Content-Length" 14
HttpKnownHeaderNames.CacheControl, // "Cache-Control" 13
HttpKnownHeaderNames.ContentType, // "Content-Type" 12
HttpKnownHeaderNames.Date, // "Date" 4
HttpKnownHeaderNames.Expires, // "Expires" 7
HttpKnownHeaderNames.ETag, // "ETag" 4
HttpKnownHeaderNames.LastModified, // "Last-Modified" 13
HttpKnownHeaderNames.Location, // "Location" 8
HttpKnownHeaderNames.ProxyAuthenticate, // "Proxy-Authenticate" 18
HttpKnownHeaderNames.P3P, // "P3P" 3
HttpKnownHeaderNames.SetCookie2, // "Set-Cookie2" 11
HttpKnownHeaderNames.SetCookie, // "Set-Cookie" 10
HttpKnownHeaderNames.Server, // "Server" 6
HttpKnownHeaderNames.Via, // "Via" 3
HttpKnownHeaderNames.WWWAuthenticate, // "WWW-Authenticate" 16
HttpKnownHeaderNames.XAspNetVersion, // "X-AspNet-Version" 16
HttpKnownHeaderNames.XPoweredBy, // "X-Powered-By" 12
"[" }; // This sentinel will never match. (This character isn't in the hint table.)
// Mask off all but the bottom five bits, and look up in this array.
private static readonly sbyte[] s_CommonHeaderHints = new sbyte[] {
-1, 0, -1, 1, 4, 5, -1, -1, // - a b c d e f g
-1, -1, -1, -1, 7, -1, -1, -1, // h i j k l m n o
9, -1, -1, 11, -1, -1, 14, 15, // p q r s t u v w
16, -1, -1, -1, -1, -1, -1, -1 }; // x y z [ - - - -
private const int c_AcceptRanges = 0;
private const int c_ContentLength = 1;
private const int c_CacheControl = 2;
private const int c_ContentType = 3;
private const int c_Date = 4;
private const int c_Expires = 5;
private const int c_ETag = 6;
private const int c_LastModified = 7;
private const int c_Location = 8;
private const int c_ProxyAuthenticate = 9;
private const int c_P3P = 10;
private const int c_SetCookie2 = 11;
private const int c_SetCookie = 12;
private const int c_Server = 13;
private const int c_Via = 14;
private const int c_WwwAuthenticate = 15;
private const int c_XAspNetVersion = 16;
private const int c_XPoweredBy = 17;
// Easy fast lookups for common headers. More can be added.
internal string ContentLength
{
get
{
return m_CommonHeaders != null ? m_CommonHeaders[c_ContentLength] : Get(s_CommonHeaderNames[c_ContentLength]);
}
}
internal string CacheControl
{
get
{
return m_CommonHeaders != null ? m_CommonHeaders[c_CacheControl] : Get(s_CommonHeaderNames[c_CacheControl]);
}
}
internal string ContentType
{
get
{
return m_CommonHeaders != null ? m_CommonHeaders[c_ContentType] : Get(s_CommonHeaderNames[c_ContentType]);
}
}
internal string Date
{
get
{
return m_CommonHeaders != null ? m_CommonHeaders[c_Date] : Get(s_CommonHeaderNames[c_Date]);
}
}
internal string Expires
{
get
{
return m_CommonHeaders != null ? m_CommonHeaders[c_Expires] : Get(s_CommonHeaderNames[c_Expires]);
}
}
internal string ETag
{
get
{
return m_CommonHeaders != null ? m_CommonHeaders[c_ETag] : Get(s_CommonHeaderNames[c_ETag]);
}
}
internal string LastModified
{
get
{
return m_CommonHeaders != null ? m_CommonHeaders[c_LastModified] : Get(s_CommonHeaderNames[c_LastModified]);
}
}
internal string Location
{
get
{
string location = m_CommonHeaders != null
? m_CommonHeaders[c_Location] : Get(s_CommonHeaderNames[c_Location]);
// The normal header parser just casts bytes to chars. Check if there is a UTF8 host name.
return HeaderEncoding.DecodeUtf8FromString(location);
}
}
internal string ProxyAuthenticate
{
get
{
return m_CommonHeaders != null ? m_CommonHeaders[c_ProxyAuthenticate] : Get(s_CommonHeaderNames[c_ProxyAuthenticate]);
}
}
internal string SetCookie2
{
get
{
return m_CommonHeaders != null ? m_CommonHeaders[c_SetCookie2] : Get(s_CommonHeaderNames[c_SetCookie2]);
}
}
internal string SetCookie
{
get
{
return m_CommonHeaders != null ? m_CommonHeaders[c_SetCookie] : Get(s_CommonHeaderNames[c_SetCookie]);
}
}
internal string Server
{
get
{
return m_CommonHeaders != null ? m_CommonHeaders[c_Server] : Get(s_CommonHeaderNames[c_Server]);
}
}
internal string Via
{
get
{
return m_CommonHeaders != null ? m_CommonHeaders[c_Via] : Get(s_CommonHeaderNames[c_Via]);
}
}
private void NormalizeCommonHeaders()
{
if (m_CommonHeaders == null)
return;
for (int i = 0; i < m_CommonHeaders.Length; i++)
if (m_CommonHeaders[i] != null)
InnerCollection.Add(s_CommonHeaderNames[i], m_CommonHeaders[i]);
m_CommonHeaders = null;
m_NumCommonHeaders = 0;
}
//
// To ensure C++ and IL callers can't pollute the underlying collection by calling overridden base members directly, we
// will use a member collection instead.
private NameValueCollection m_InnerCollection;
private NameValueCollection InnerCollection
{
get
{
if (m_InnerCollection == null)
m_InnerCollection = new NameValueCollection(ApproxHighAvgNumHeaders, CaseInsensitiveAscii.StaticInstance);
return m_InnerCollection;
}
}
// this is the object that created the header collection.
private WebHeaderCollectionType m_Type;
#if !FEATURE_PAL
private bool AllowHttpRequestHeader {
get {
if (m_Type==WebHeaderCollectionType.Unknown) {
m_Type = WebHeaderCollectionType.WebRequest;
}
return m_Type==WebHeaderCollectionType.WebRequest || m_Type==WebHeaderCollectionType.HttpWebRequest || m_Type==WebHeaderCollectionType.HttpListenerRequest;
}
}
internal bool AllowHttpResponseHeader {
get {
if (m_Type==WebHeaderCollectionType.Unknown) {
m_Type = WebHeaderCollectionType.WebResponse;
}
return m_Type==WebHeaderCollectionType.WebResponse || m_Type==WebHeaderCollectionType.HttpWebResponse || m_Type==WebHeaderCollectionType.HttpListenerResponse;
}
}
public string this[HttpRequestHeader header] {
get {
if (!AllowHttpRequestHeader) {
throw new InvalidOperationException(SR.GetString(SR.net_headers_req));
}
return this[UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST_HEADER_ID.ToString((int)header)];
}
set {
if (!AllowHttpRequestHeader) {
throw new InvalidOperationException(SR.GetString(SR.net_headers_req));
}
this[UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST_HEADER_ID.ToString((int)header)] = value;
}
}
public string this[HttpResponseHeader header] {
get {
if (!AllowHttpResponseHeader) {
throw new InvalidOperationException(SR.GetString(SR.net_headers_rsp));
}
// Some of these can be mapped to Common Headers. Other cases can be added as needed for perf.
if (m_CommonHeaders != null)
{
switch (header)
{
case HttpResponseHeader.ProxyAuthenticate:
return m_CommonHeaders[c_ProxyAuthenticate];
case HttpResponseHeader.WwwAuthenticate:
return m_CommonHeaders[c_WwwAuthenticate];
}
}
return this[UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE_HEADER_ID.ToString((int)header)];
}
set {
if (!AllowHttpResponseHeader) {
throw new InvalidOperationException(SR.GetString(SR.net_headers_rsp));
}
if (m_Type==WebHeaderCollectionType.HttpListenerResponse) {
if (value!=null && value.Length>ushort.MaxValue) {
throw new ArgumentOutOfRangeException("value", value, SR.GetString(SR.net_headers_toolong, ushort.MaxValue));
}
}
this[UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE_HEADER_ID.ToString((int)header)] = value;
}
}
public void Add(HttpRequestHeader header, string value) {
if (!AllowHttpRequestHeader) {
throw new InvalidOperationException(SR.GetString(SR.net_headers_req));
}
this.Add(UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST_HEADER_ID.ToString((int)header), value);
}
public void Add(HttpResponseHeader header, string value) {
if (!AllowHttpResponseHeader) {
throw new InvalidOperationException(SR.GetString(SR.net_headers_rsp));
}
if (m_Type==WebHeaderCollectionType.HttpListenerResponse) {
if (value!=null && value.Length>ushort.MaxValue) {
throw new ArgumentOutOfRangeException("value", value, SR.GetString(SR.net_headers_toolong, ushort.MaxValue));
}
}
this.Add(UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE_HEADER_ID.ToString((int)header), value);
}
public void Set(HttpRequestHeader header, string value) {
if (!AllowHttpRequestHeader) {
throw new InvalidOperationException(SR.GetString(SR.net_headers_req));
}
this.Set(UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST_HEADER_ID.ToString((int)header), value);
}
public void Set(HttpResponseHeader header, string value) {
if (!AllowHttpResponseHeader) {
throw new InvalidOperationException(SR.GetString(SR.net_headers_rsp));
}
if (m_Type==WebHeaderCollectionType.HttpListenerResponse) {
if (value!=null && value.Length>ushort.MaxValue) {
throw new ArgumentOutOfRangeException("value", value, SR.GetString(SR.net_headers_toolong, ushort.MaxValue));
}
}
this.Set(UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE_HEADER_ID.ToString((int)header), value);
}
internal void SetInternal(HttpResponseHeader header, string value) {
if (!AllowHttpResponseHeader) {
throw new InvalidOperationException(SR.GetString(SR.net_headers_rsp));
}
if (m_Type==WebHeaderCollectionType.HttpListenerResponse) {
if (value!=null && value.Length>ushort.MaxValue) {
throw new ArgumentOutOfRangeException("value", value, SR.GetString(SR.net_headers_toolong, ushort.MaxValue));
}
}
this.SetInternal(UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE_HEADER_ID.ToString((int)header), value);
}
public void Remove(HttpRequestHeader header) {
if (!AllowHttpRequestHeader) {
throw new InvalidOperationException(SR.GetString(SR.net_headers_req));
}
this.Remove(UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST_HEADER_ID.ToString((int)header));
}
public void Remove(HttpResponseHeader header) {
if (!AllowHttpResponseHeader) {
throw new InvalidOperationException(SR.GetString(SR.net_headers_rsp));
}
this.Remove(UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE_HEADER_ID.ToString((int)header));
}
#endif // !FEATURE_PAL
// In general, HttpWebResponse headers aren't modified, so these methods don't support common headers.
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected void AddWithoutValidate(string headerName, string headerValue) {
headerName = CheckBadChars(headerName, false);
headerValue = CheckBadChars(headerValue, true);
GlobalLog.Print("WebHeaderCollection::AddWithoutValidate() calling InnerCollection.Add() key:[" + headerName + "], value:[" + headerValue + "]");
if (m_Type==WebHeaderCollectionType.HttpListenerResponse) {
if (headerValue!=null && headerValue.Length>ushort.MaxValue) {
throw new ArgumentOutOfRangeException("headerValue", headerValue, SR.GetString(SR.net_headers_toolong, ushort.MaxValue));
}
}
NormalizeCommonHeaders();
InvalidateCachedArrays();
InnerCollection.Add(headerName, headerValue);
}
internal void SetAddVerified(string name, string value) {
if(HInfo[name].AllowMultiValues) {
GlobalLog.Print("WebHeaderCollection::SetAddVerified() calling InnerCollection.Add() key:[" + name + "], value:[" + value + "]");
NormalizeCommonHeaders();
InvalidateCachedArrays();
InnerCollection.Add(name, value);
}
else {
GlobalLog.Print("WebHeaderCollection::SetAddVerified() calling InnerCollection.Set() key:[" + name + "], value:[" + value + "]");
NormalizeCommonHeaders();
InvalidateCachedArrays();
InnerCollection.Set(name, value);
}
}
// Below three methods are for fast headers manipulation, bypassing all the checks
internal void AddInternal(string name, string value) {
GlobalLog.Print("WebHeaderCollection::AddInternal() calling InnerCollection.Add() key:[" + name + "], value:[" + value + "]");
NormalizeCommonHeaders();
InvalidateCachedArrays();
InnerCollection.Add(name, value);
}
internal void ChangeInternal(string name, string value) {
GlobalLog.Print("WebHeaderCollection::ChangeInternal() calling InnerCollection.Set() key:[" + name + "], value:[" + value + "]");
NormalizeCommonHeaders();
InvalidateCachedArrays();
InnerCollection.Set(name, value);
}
internal void RemoveInternal(string name) {
GlobalLog.Print("WebHeaderCollection::RemoveInternal() calling InnerCollection.Remove() key:[" + name + "]");
NormalizeCommonHeaders();
if (m_InnerCollection != null)
{
InvalidateCachedArrays();
m_InnerCollection.Remove(name);
}
}
internal void CheckUpdate(string name, string value) {
value = CheckBadChars(value, true);
ChangeInternal(name, value);
}
// This even faster one can be used to add headers when it's known not to be a common header or that common headers aren't active.
private void AddInternalNotCommon(string name, string value)
{
GlobalLog.Print("WebHeaderCollection::AddInternalNotCommon() calling InnerCollection.Add() key:[" + name + "], value:[" + value + "]");
InvalidateCachedArrays();
InnerCollection.Add(name, value);
}
private static readonly char[] HttpTrimCharacters = new char[]{(char)0x09,(char)0xA,(char)0xB,(char)0xC,(char)0xD,(char)0x20};
//
// CheckBadChars - throws on invalid chars to be not found in header name/value
//
internal static string CheckBadChars(string name, bool isHeaderValue) {
if (name == null || name.Length == 0) {
// emtpy name is invlaid
if (!isHeaderValue) {
throw name == null ? new ArgumentNullException("name") :
new ArgumentException(SR.GetString(SR.net_emptystringcall, "name"), "name");
}
//empty value is OK
return string.Empty;
}
if (isHeaderValue) {
// VALUE check
//Trim spaces from both ends
name = name.Trim(HttpTrimCharacters);
//First, check for correctly formed multi-line value
//Second, check for absenece of CTL characters
int crlf = 0;
for(int i = 0; i < name.Length; ++i) {
char c = (char) (0x000000ff & (uint) name[i]);
switch (crlf)
{
case 0:
if (c == '\r')
{
crlf = 1;
}
else if (c == '\n')
{
// Technically this is bad HTTP. But it would be a breaking change to throw here.
// Is there an exploit?
crlf = 2;
}
else if (c == 127 || (c < ' ' && c != '\t'))
{
throw new ArgumentException(SR.GetString(SR.net_WebHeaderInvalidControlChars), "value");
}
break;
case 1:
if (c == '\n')
{
crlf = 2;
break;
}
throw new ArgumentException(SR.GetString(SR.net_WebHeaderInvalidCRLFChars), "value");
case 2:
if (c == ' ' || c == '\t')
{
crlf = 0;
break;
}
throw new ArgumentException(SR.GetString(SR.net_WebHeaderInvalidCRLFChars), "value");
}
}
if (crlf != 0)
{
throw new ArgumentException(SR.GetString(SR.net_WebHeaderInvalidCRLFChars), "value");
}
}
else {
// NAME check
//First, check for absence of separators and spaces
if (name.IndexOfAny(ValidationHelper.InvalidParamChars) != -1) {
throw new ArgumentException(SR.GetString(SR.net_WebHeaderInvalidHeaderChars), "name");
}
//Second, check for non CTL ASCII-7 characters (32-126)
if (ContainsNonAsciiChars(name)) {
throw new ArgumentException(SR.GetString(SR.net_WebHeaderInvalidNonAsciiChars), "name");
}
}
return name;
}
internal static bool IsValidToken(string token) {
return (token.Length > 0)
&& (token.IndexOfAny(ValidationHelper.InvalidParamChars) == -1)
&& !ContainsNonAsciiChars(token);
}
internal static bool ContainsNonAsciiChars(string token) {
for (int i = 0; i < token.Length; ++i) {
if ((token[i] < 0x20) || (token[i] > 0x7e)) {
return true;
}
}
return false;
}
//
// ThrowOnRestrictedHeader - generates an error if the user,
// passed in a reserved string as the header name
//
internal void ThrowOnRestrictedHeader(string headerName)
{
if (m_Type == WebHeaderCollectionType.HttpWebRequest)
{
if (HInfo[headerName].IsRequestRestricted)
{
throw new ArgumentException(SR.GetString(SR.net_headerrestrict, headerName), "name");
}
}
else if (m_Type == WebHeaderCollectionType.HttpListenerResponse)
{
if (HInfo[headerName].IsResponseRestricted)
{
throw new ArgumentException(SR.GetString(SR.net_headerrestrict, headerName), "name");
}
}
}
//
// Our Public METHOD set, most are inherited from NameValueCollection,
// not all methods from NameValueCollection are listed, even though usable -
//
// this includes
// Add(name, value)
// Add(header)
// this[name] {set, get}
// Remove(name), returns bool
// Remove(name), returns void
// Set(name, value)
// ToString()
//
// SplitValue(name, value)
// ToByteArray()
// ParseHeaders(char [], ...)
// ParseHeaders(byte [], ...)
//
// Add more headers; if "name" already exists it will
// add concatenated value
// Add -
// Routine Description:
// Adds headers with validation to see if they are "proper" headers.
// Will cause header to be concat to existing if already found.
// If the header is a special header, listed in RestrictedHeaders object,
// then this call will cause an exception indication as such.
// Arguments:
// name - header-name to add
// value - header-value to add, a header is already there, will concat this value
// Return Value:
// None
/// <devdoc>
/// <para>
/// Adds a new header with the indicated name and value.
/// </para>
/// </devdoc>
public override void Add(string name, string value) {
name = CheckBadChars(name, false);
ThrowOnRestrictedHeader(name);
value = CheckBadChars(value, true);
GlobalLog.Print("WebHeaderCollection::Add() calling InnerCollection.Add() key:[" + name + "], value:[" + value + "]");
if (m_Type==WebHeaderCollectionType.HttpListenerResponse) {
if (value!=null && value.Length>ushort.MaxValue) {
throw new ArgumentOutOfRangeException("value", value, SR.GetString(SR.net_headers_toolong, ushort.MaxValue));
}
}
NormalizeCommonHeaders();
InvalidateCachedArrays();
InnerCollection.Add(name, value);
}
// Add -
// Routine Description:
// Adds headers with validation to see if they are "proper" headers.
// Assumes a combined a "Name: Value" string, and parses the two parts out.
// Will cause header to be concat to existing if already found.
// If the header is a speical header, listed in RestrictedHeaders object,
// then this call will cause an exception indication as such.
// Arguments:
// header - header name: value pair
// Return Value:
// None
/// <devdoc>
/// <para>
/// Adds the indicated header.
/// </para>
/// </devdoc>
public void Add(string header) {
if ( ValidationHelper.IsBlankString(header) ) {
throw new ArgumentNullException("header");
}
int colpos = header.IndexOf(':');
// check for badly formed header passed in
if (colpos<0) {
throw new ArgumentException(SR.GetString(SR.net_WebHeaderMissingColon), "header");
}
string name = header.Substring(0, colpos);
string value = header.Substring(colpos+1);
name = CheckBadChars(name, false);
ThrowOnRestrictedHeader(name);
value = CheckBadChars(value, true);
GlobalLog.Print("WebHeaderCollection::Add(" + header + ") calling InnerCollection.Add() key:[" + name + "], value:[" + value + "]");
if (m_Type==WebHeaderCollectionType.HttpListenerResponse) {
if (value!=null && value.Length>ushort.MaxValue) {
throw new ArgumentOutOfRangeException("value", value, SR.GetString(SR.net_headers_toolong, ushort.MaxValue));
}
}
NormalizeCommonHeaders();
InvalidateCachedArrays();
InnerCollection.Add(name, value);
}
// Set -
// Routine Description:
// Sets headers with validation to see if they are "proper" headers.
// If the header is a special header, listed in RestrictedHeaders object,
// then this call will cause an exception indication as such.
// Arguments:
// name - header-name to set
// value - header-value to set
// Return Value:
// None
/// <devdoc>
/// <para>
/// Sets the specified header to the specified value.
/// </para>
/// </devdoc>
public override void Set(string name, string value) {
if (ValidationHelper.IsBlankString(name)) {
throw new ArgumentNullException("name");
}
name = CheckBadChars(name, false);
ThrowOnRestrictedHeader(name);
value = CheckBadChars(value, true);
GlobalLog.Print("WebHeaderCollection::Set() calling InnerCollection.Set() key:[" + name + "], value:[" + value + "]");
if (m_Type==WebHeaderCollectionType.HttpListenerResponse) {
if (value!=null && value.Length>ushort.MaxValue) {
throw new ArgumentOutOfRangeException("value", value, SR.GetString(SR.net_headers_toolong, ushort.MaxValue));
}
}
NormalizeCommonHeaders();
InvalidateCachedArrays();
InnerCollection.Set(name, value);
}
internal void SetInternal(string name, string value) {
if (ValidationHelper.IsBlankString(name)) {
throw new ArgumentNullException("name");
}
name = CheckBadChars(name, false);
value = CheckBadChars(value, true);
GlobalLog.Print("WebHeaderCollection::Set() calling InnerCollection.Set() key:[" + name + "], value:[" + value + "]");
if (m_Type==WebHeaderCollectionType.HttpListenerResponse) {
if (value!=null && value.Length>ushort.MaxValue) {
throw new ArgumentOutOfRangeException("value", value, SR.GetString(SR.net_headers_toolong, ushort.MaxValue));
}
}
NormalizeCommonHeaders();
InvalidateCachedArrays();
InnerCollection.Set(name, value);
}
// Remove -
// Routine Description:
// Removes give header with validation to see if they are "proper" headers.
// If the header is a speical header, listed in RestrictedHeaders object,
// then this call will cause an exception indication as such.
// Arguments:
// name - header-name to remove
// Return Value:
// None
/// <devdoc>
/// <para>Removes the specified header.</para>
/// </devdoc>
public override void Remove(string name) {
if ( ValidationHelper.IsBlankString(name) ) {
throw new ArgumentNullException("name");
}
ThrowOnRestrictedHeader(name);
name = CheckBadChars(name, false);
GlobalLog.Print("WebHeaderCollection::Remove() calling InnerCollection.Remove() key:[" + name + "]");
NormalizeCommonHeaders();
if (m_InnerCollection != null)
{
InvalidateCachedArrays();
m_InnerCollection.Remove(name);
}
}
// GetValues
// Routine Description:
// This method takes a header name and returns a string array representing
// the individual values for that headers. For example, if the headers
// contained the line Accept: text/plain, text/html then
// GetValues("Accept") would return an array of two strings: "text/plain"
// and "text/html".
// Arguments:
// header - Name of the header.
// Return Value:
// string[] - array of parsed string objects
/// <devdoc>
/// <para>
/// Gets an array of header values stored in a
/// header.
/// </para>
/// </devdoc>
public override string[] GetValues(string header) {
// This method doesn't work with common headers. Dump common headers into the pool.
NormalizeCommonHeaders();
// First get the information about the header and the values for
// the header.
HeaderInfo Info = HInfo[header];
string[] Values = InnerCollection.GetValues(header);
// If we have no information about the header or it doesn't allow
// multiple values, just return the values.
if (Info == null || Values == null || !Info.AllowMultiValues) {
return Values;
}
// Here we have a multi value header. We need to go through
// each entry in the multi values array, and if an entry itself
// has multiple values we'll need to combine those in.
//
// We do some optimazation here, where we try not to copy the
// values unless there really is one that have multiple values.
string[] TempValues;
ArrayList ValueList = null;
int i;
for (i = 0; i < Values.Length; i++) {
// Parse this value header.
TempValues = Info.Parser(Values[i]);
// If we don't have an array list yet, see if this
// value has multiple values.
if (ValueList == null) {
// See if it has multiple values.
if (TempValues.Length > 1) {
// It does, so we need to create an array list that
// represents the Values, then trim out this one and
// the ones after it that haven't been parsed yet.
ValueList = new ArrayList(Values);
ValueList.RemoveRange(i, Values.Length - i);
ValueList.AddRange(TempValues);
}
}
else {
// We already have an ArrayList, so just add the values.
ValueList.AddRange(TempValues);
}
}
// See if we have an ArrayList. If we don't, just return the values.
// Otherwise convert the ArrayList to a string array and return that.
if (ValueList != null) {
string[] ReturnArray = new string[ValueList.Count];
ValueList.CopyTo(ReturnArray);
return ReturnArray;
}
return Values;
}
// ToString() -
// Routine Description:
// Generates a string representation of the headers, that is ready to be sent except for it being in string format:
// the format looks like:
//
// Header-Name: Header-Value\r\n
// Header-Name2: Header-Value2\r\n
// ...
// Header-NameN: Header-ValueN\r\n
// \r\n
//
// Uses the string builder class to Append the elements together.
// Arguments:
// None.
// Return Value:
// string
/// <internalonly/>
/// <devdoc>
/// <para>
/// Obsolete.
/// </para>
/// </devdoc>
public override string ToString() {
string result = GetAsString(this, false, false);
GlobalLog.Print("WebHeaderCollection::ToString: \r\n" + result);
return result;
}
internal string ToString(bool forTrace)
{
return GetAsString(this, false, true);
}
//
// if winInetCompat = true then it will not insert spaces after ':'
// and it will output "~U" header first
//
internal static string GetAsString(NameValueCollection cc,
bool winInetCompat,
bool forTrace) {
#if FEATURE_PAL
if (winInetCompat) {
throw new InvalidOperationException();
}
#endif // FEATURE_PAL
if (cc == null || cc.Count == 0) {
return "\r\n";
}
StringBuilder sb = new StringBuilder(ApproxAveHeaderLineSize*cc.Count);
string statusLine;
statusLine = cc[string.Empty];
if (statusLine != null) {
sb.Append(statusLine).Append("\r\n");
}
for (int i = 0; i < cc.Count ; i++) {
string key = cc.GetKey(i) as string;
string val = cc.Get(i) as string;
/*
if (forTrace)
{
// Put a condition here that if we are using basic auth,
// we shouldn't put the authorization header. Otherwise
// the password will get saved in the trace.
if (using basic)
continue;
}
*/
if (ValidationHelper.IsBlankString(key)) {
continue;
}
sb.Append(key);
if (winInetCompat) {
sb.Append(':');
}
else {
sb.Append(": ");
}
sb.Append(val).Append("\r\n");
}
if (!forTrace)
sb.Append("\r\n");
return sb.ToString();
}
// ToByteArray() -
// Routine Description:
// Generates a byte array representation of the headers, that is ready to be sent.
// So it Serializes our headers into a byte array suitable for sending over the net.
//
// the format looks like:
//
// Header-Name1: Header-Value1\r\n
// Header-Name2: Header-Value2\r\n
// ...
// Header-NameN: Header-ValueN\r\n
// \r\n
//
// Uses the ToString() method to generate, and then performs conversion.
//
// Performance Note: Why are we not doing a single copy/covert run?
// As the code before used to know the size of the output!
// Because according to Demitry, its cheaper to copy the headers twice,
// then it is to call the UNICODE to ANSI conversion code many times.
// Arguments:
// None.
// Return Value:
// byte [] - array of bytes values
/// <internalonly/>
/// <devdoc>
/// <para>
/// Obsolete.
/// </para>
/// </devdoc>
public byte[] ToByteArray() {
// Make sure the buffer is big enough.
string tempStr = ToString();
//
// Use the string of headers, convert to Char Array,
// then convert to Bytes,
// serializing finally into the buffer, along the way.
//
byte[] buffer = HeaderEncoding.GetBytes(tempStr);
return buffer;
}
/// <devdoc>
/// <para>Tests if access to the HTTP header with the provided name is accessible for setting.</para>
/// </devdoc>
public static bool IsRestricted(string headerName)
{
return IsRestricted(headerName, false);
}
public static bool IsRestricted(string headerName, bool response)
{
return response ? HInfo[CheckBadChars(headerName, false)].IsResponseRestricted : HInfo[CheckBadChars(headerName, false)].IsRequestRestricted;
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Net.WebHeaderCollection'/>
/// class.
/// </para>
/// </devdoc>
public WebHeaderCollection() : base(DBNull.Value)
{
}
internal WebHeaderCollection(WebHeaderCollectionType type) : base(DBNull.Value)
{
m_Type = type;
if (type == WebHeaderCollectionType.HttpWebResponse)
m_CommonHeaders = new string[s_CommonHeaderNames.Length - 1]; // Minus one for the sentinel.
}
//This is for Cache
internal WebHeaderCollection(NameValueCollection cc): base(DBNull.Value)
{
m_InnerCollection = new NameValueCollection(cc.Count + 2, CaseInsensitiveAscii.StaticInstance);
int len = cc.Count;
for (int i = 0; i < len; ++i) {
String key = cc.GetKey(i);
String[] values = cc.GetValues(i);
if (values != null) {
for (int j = 0; j < values.Length; j++) {
InnerCollection.Add(key, values[j]);
}
}
else {
InnerCollection.Add(key, null);
}
}
}
//
// ISerializable constructor
//
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected WebHeaderCollection(SerializationInfo serializationInfo, StreamingContext streamingContext) :
base(DBNull.Value)
{
int count = serializationInfo.GetInt32("Count");
m_InnerCollection = new NameValueCollection(count + 2, CaseInsensitiveAscii.StaticInstance);
for (int i = 0; i < count; i++) {
string headerName = serializationInfo.GetString(i.ToString(NumberFormatInfo.InvariantInfo));
string headerValue = serializationInfo.GetString((i+count).ToString(NumberFormatInfo.InvariantInfo));
GlobalLog.Print("WebHeaderCollection::.ctor(ISerializable) calling InnerCollection.Add() key:[" + headerName + "], value:[" + headerValue + "]");
InnerCollection.Add(headerName, headerValue);
}
}
public override void OnDeserialization(object sender) {
//
}
//
// ISerializable method
//
/// <internalonly/>
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) {
//
// for now disregard streamingContext.
//
NormalizeCommonHeaders();
serializationInfo.AddValue("Count", Count);
for (int i = 0; i < Count; i++)
{
serializationInfo.AddValue(i.ToString(NumberFormatInfo.InvariantInfo), GetKey(i));
serializationInfo.AddValue((i + Count).ToString(NumberFormatInfo.InvariantInfo), Get(i));
}
}
// we use this static class as a helper class to encode/decode HTTP headers.
// what we need is a 1-1 correspondence between a char in the range U+0000-U+00FF
// and a byte in the range 0x00-0xFF (which is the range that can hit the network).
// The Latin-1 encoding (ISO-88591-1) (GetEncoding(28591)) works for byte[] to string, but is a little slow.
// It doesn't work for string -> byte[] because of best-fit-mapping problems.
internal static class HeaderEncoding
{
internal static unsafe string GetString(byte[] bytes, int byteIndex, int byteCount)
{
fixed(byte* pBytes = bytes)
return GetString(pBytes + byteIndex, byteCount);
}
internal static unsafe string GetString(byte* pBytes, int byteCount)
{
if (byteCount < 1)
return "";
string s = new String('\0', byteCount);
fixed (char* pStr = s)
{
char* pString = pStr;
while (byteCount >= 8)
{
pString[0] = (char) pBytes[0];
pString[1] = (char) pBytes[1];
pString[2] = (char) pBytes[2];
pString[3] = (char) pBytes[3];
pString[4] = (char) pBytes[4];
pString[5] = (char) pBytes[5];
pString[6] = (char) pBytes[6];
pString[7] = (char) pBytes[7];
pString += 8;
pBytes += 8;
byteCount -= 8;
}
for (int i = 0; i < byteCount; i++)
{
pString[i] = (char) pBytes[i];
}
}
return s;
}
internal static int GetByteCount(string myString) {
return myString.Length;
}
internal unsafe static void GetBytes(string myString, int charIndex, int charCount, byte[] bytes, int byteIndex) {
if (myString.Length==0) {
return;
}
fixed (byte *bufferPointer = bytes) {
byte* newBufferPointer = bufferPointer + byteIndex;
int finalIndex = charIndex + charCount;
while (charIndex<finalIndex) {
*newBufferPointer++ = (byte)myString[charIndex++];
}
}
}
internal unsafe static byte[] GetBytes(string myString) {
byte[] bytes = new byte[myString.Length];
if (myString.Length!=0) {
GetBytes(myString, 0, myString.Length, bytes, 0);
}
return bytes;
}
// The normal client header parser just casts bytes to chars (see GetString).
// Check if those bytes were actually utf-8 instead of ASCII.
// If not, just return the input value.
[System.Runtime.CompilerServices.FriendAccessAllowed]
internal static string DecodeUtf8FromString(string input) {
if (string.IsNullOrWhiteSpace(input)) {
return input;
}
bool possibleUtf8 = false;
for (int i = 0; i < input.Length; i++) {
if (input[i] > (char)255) {
return input; // This couldn't have come from the wire, someone assigned it directly.
}
else if (input[i] > (char)127) {
possibleUtf8 = true;
break;
}
}
if (possibleUtf8) {
byte[] rawBytes = new byte[input.Length];
for (int i = 0; i < input.Length; i++) {
if (input[i] > (char)255) {
return input; // This couldn't have come from the wire, someone assigned it directly.
}
rawBytes[i] = (byte)input[i];
}
try {
// We don't want '?' replacement characters, just fail.
Encoding decoder = Encoding.GetEncoding("utf-8", EncoderFallback.ExceptionFallback,
DecoderFallback.ExceptionFallback);
return decoder.GetString(rawBytes);
}
catch (ArgumentException) { } // Not actually Utf-8
}
return input;
}
}
// ParseHeaders -
// Routine Description:
//
// This code is optimized for the case in which all the headers fit in the buffer.
// we support multiple re-entrance, but we won't save intermediate
// state, we will just roll back all the parsing done for the current header if we can't
// parse a whole one (including multiline) or decide something else ("invalid data" or "done parsing").
//
// we're going to cycle through the loop until we
//
// 1) find an HTTP violation (in this case we return DataParseStatus.Invalid)
// 2) we need more data (in this case we return DataParseStatus.NeedMoreData)
// 3) we found the end of the headers and the beginning of the entity body (in this case we return DataParseStatus.Done)
//
//
// Arguments:
//
// buffer - buffer containing the data to be parsed
// size - size of the buffer
// unparsed - offset of data yet to be parsed
//
// Return Value:
//
// DataParseStatus - status of parsing
//
// Revision:
//
// 02/13/2001 rewrote the method from scratch.
//
// BreakPoint:
//
// b system.dll!System.Net.WebHeaderCollection::ParseHeaders
internal unsafe DataParseStatus ParseHeaders(
byte[] buffer,
int size,
ref int unparsed,
ref int totalResponseHeadersLength,
int maximumResponseHeadersLength,
ref WebParseError parseError) {
fixed (byte * byteBuffer = buffer) {
char ch;
// quick check in the boundaries (as we use unsafe pointer)
if (buffer.Length < size) {
return DataParseStatus.NeedMoreData;
}
int headerNameStartOffset = -1;
int headerNameEndOffset = -1;
int headerValueStartOffset = -1;
int headerValueEndOffset = -1;
int numberOfLf = -1;
int index = unparsed;
bool spaceAfterLf;
string headerMultiLineValue;
string headerName;
string headerValue;
// we need this because this method is entered multiple times.
int localTotalResponseHeadersLength = totalResponseHeadersLength;
WebParseErrorCode parseErrorCode = WebParseErrorCode.Generic;
DataParseStatus parseStatus = DataParseStatus.Invalid;
#if TRAVE
GlobalLog.Enter("WebHeaderCollection::ParseHeaders(): ANSI size:" + size.ToString() + ", unparsed:" + unparsed.ToString() + " buffer:[" + Encoding.ASCII.GetString(buffer, unparsed, Math.Min(256, size-unparsed)) + "]");
#endif
//
// according to RFC216 a header can have the following syntax:
//
// message-header = field-name ":" [ field-value ]
// field-name = token
// field-value = *( field-content | LWS )
// field-content = <the OCTETs making up the field-value and consisting of either *TEXT or combinations of token, separators, and quoted-string>
// TEXT = <any OCTET except CTLs, but including LWS>
// CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
// SP = <US-ASCII SP, space (32)>
// HT = <US-ASCII HT, horizontal-tab (9)>
// CR = <US-ASCII CR, carriage return (13)>
// LF = <US-ASCII LF, linefeed (10)>
// LWS = [CR LF] 1*( SP | HT )
// CHAR = <any US-ASCII character (octets 0 - 127)>
// token = 1*<any CHAR except CTLs or separators>
// separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT
// quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
// qdtext = <any TEXT except <">>
// quoted-pair = "\" CHAR
//
//
// At each iteration of the following loop we expect to parse a single HTTP header entirely.
//
for (;;) {
//
// trim leading whitespaces (LWS) just for extra robustness, in fact if there are leading white spaces then:
// 1) it could be that after the status line we might have spaces. handle this.
// 2) this should have been detected to be a multiline header so there'll be no spaces and we'll spend some time here.
//
headerName = string.Empty;
headerValue = string.Empty;
spaceAfterLf = false;
headerMultiLineValue = null;
if (Count == 0) {
//
// so, restrict this extra trimming only on the first header line
//
while (index < size) {
ch = (char) byteBuffer[index];
if (ch == ' ' || ch == '\t') {
++index;
if (maximumResponseHeadersLength>=0 && ++localTotalResponseHeadersLength>=maximumResponseHeadersLength) {
parseStatus = DataParseStatus.DataTooBig;
goto quit;
}
}
else {
break;
}
}
if (index==size) {
//
// we reached the end of the buffer. ask for more data.
//
parseStatus = DataParseStatus.NeedMoreData;
goto quit;
}
}
//
// what we have here is the beginning of a new header
//
headerNameStartOffset = index;
while (index < size) {
ch = (char) byteBuffer[index];
if (ch != ':' && ch != '\n') {
if (ch > ' ') {
//
// if there's an illegal character we should return DataParseStatus.Invalid
// instead we choose to be flexible, try to trim it, but include it in the string
//
headerNameEndOffset = index;
}
++index;
if (maximumResponseHeadersLength>=0 && ++localTotalResponseHeadersLength>=maximumResponseHeadersLength) {
parseStatus = DataParseStatus.DataTooBig;
goto quit;
}
}
else {
if (ch == ':') {
++index;
if (maximumResponseHeadersLength>=0 && ++localTotalResponseHeadersLength>=maximumResponseHeadersLength) {
parseStatus = DataParseStatus.DataTooBig;
goto quit;
}
}
break;
}
}
if (index==size) {
//
// we reached the end of the buffer. ask for more data.
//
parseStatus = DataParseStatus.NeedMoreData;
goto quit;
}
startOfValue:
//
// skip all [' ','\t','\r','\n'] characters until HeaderValue starts
// if we didn't find any headers yet, we set numberOfLf to 1
// so that we take the '\n' from the status line into account
//
numberOfLf = (Count == 0 && headerNameEndOffset < 0) ? 1 : 0;
while (index<size && numberOfLf<2) {
ch = (char) byteBuffer[index];
if (ch <= ' ') {
if (ch=='\n') {
numberOfLf++;
// In this case, need to check for a space.
if (numberOfLf == 1)
{
if (index + 1 == size)
{
//
// we reached the end of the buffer. ask for more data.
// need to be able to peek after the \n and see if there's some space.
//
parseStatus = DataParseStatus.NeedMoreData;
goto quit;
}
spaceAfterLf = (char) byteBuffer[index + 1] == ' ' || (char) byteBuffer[index + 1] == '\t';
}
}
++index;
if (maximumResponseHeadersLength>=0 && ++localTotalResponseHeadersLength>=maximumResponseHeadersLength) {
parseStatus = DataParseStatus.DataTooBig;
goto quit;
}
}
else {
break;
}
}
if (numberOfLf==2 || (numberOfLf==1 && !spaceAfterLf)) {
//
// if we've counted two '\n' we got at the end of the headers even if we're past the end of the buffer
// if we've counted one '\n' and the first character after that was a ' ' or a '\t'
// no matter if we found a ':' or not, treat this as an empty header name.
//
goto addHeader;
}
if (index==size) {
//
// we reached the end of the buffer. ask for more data.
//
parseStatus = DataParseStatus.NeedMoreData;
goto quit;
}
headerValueStartOffset = index;
while (index<size) {
ch = (char) byteBuffer[index];
if (ch != '\n') {
if (ch > ' ') {
headerValueEndOffset = index;
}
++index;
if (maximumResponseHeadersLength>=0 && ++localTotalResponseHeadersLength>=maximumResponseHeadersLength) {
parseStatus = DataParseStatus.DataTooBig;
goto quit;
}
}
else {
break;
}
}
if (index==size) {
//
// we reached the end of the buffer. ask for more data.
//
parseStatus = DataParseStatus.NeedMoreData;
goto quit;
}
//
// at this point we found either a '\n' or the end of the headers
// hence we are at the end of the Header Line. 4 options:
// 1) need more data
// 2) if we find two '\n' => end of headers
// 3) if we find one '\n' and a ' ' or a '\t' => multiline header
// 4) if we find one '\n' and a valid char => next header
//
numberOfLf = 0;
while (index<size && numberOfLf<2) {
ch = (char) byteBuffer[index];
if (ch =='\r' || ch == '\n') {
if (ch == '\n') {
numberOfLf++;
}
++index;
if (maximumResponseHeadersLength>=0 && ++localTotalResponseHeadersLength>=maximumResponseHeadersLength) {
parseStatus = DataParseStatus.DataTooBig;
goto quit;
}
}
else {
break;
}
}
if (index==size && numberOfLf<2) {
//
// we reached the end of the buffer but not of the headers. ask for more data.
//
parseStatus = DataParseStatus.NeedMoreData;
goto quit;
}
addHeader:
if (headerValueStartOffset>=0 && headerValueStartOffset>headerNameEndOffset && headerValueEndOffset>=headerValueStartOffset) {
//
// Encoding fastest way to build the UNICODE string off the byte[]
//
headerValue = HeaderEncoding.GetString(byteBuffer + headerValueStartOffset, headerValueEndOffset - headerValueStartOffset + 1);
}
//
// if we got here from the beginning of the for loop, headerMultiLineValue will be null
// otherwise it will contain the headerValue constructed for the multiline header
// add this line as well to it, separated by a single space
//
headerMultiLineValue = (headerMultiLineValue==null ? headerValue : headerMultiLineValue + " " + headerValue);
if (index < size && numberOfLf == 1) {
ch = (char) byteBuffer[index];
if (ch == ' ' || ch == '\t') {
//
// since we found only one Lf and the next header line begins with a Lws,
// this is the beginning of a multiline header.
// parse the next line into headerValue later it will be added to headerMultiLineValue
//
++index;
if (maximumResponseHeadersLength>=0 && ++localTotalResponseHeadersLength>=maximumResponseHeadersLength) {
parseStatus = DataParseStatus.DataTooBig;
goto quit;
}
goto startOfValue;
}
}
if (headerNameStartOffset>=0 && headerNameEndOffset>=headerNameStartOffset) {
//
// Encoding is the fastest way to build the UNICODE string off the byte[]
//
headerName = HeaderEncoding.GetString(byteBuffer + headerNameStartOffset, headerNameEndOffset - headerNameStartOffset + 1);
}
//
// now it's finally safe to add the header if we have a name for it
//
if (headerName.Length>0) {
//
// the base clasee will check for pre-existing headerValue and append
// it using commas as indicated in the RFC
//
GlobalLog.Print("WebHeaderCollection::ParseHeaders() calling AddInternal() key:[" + headerName + "], value:[" + headerMultiLineValue + "]");
AddInternal(headerName, headerMultiLineValue);
}
//
// and update unparsed
//
totalResponseHeadersLength = localTotalResponseHeadersLength;
unparsed = index;
if (numberOfLf==2) {
parseStatus = DataParseStatus.Done;
goto quit;
}
} // for (;;)
quit:
GlobalLog.Leave("WebHeaderCollection::ParseHeaders() returning parseStatus:" + parseStatus.ToString());
if (parseStatus == DataParseStatus.Invalid) {
parseError.Section = WebParseErrorSection.ResponseHeader;
parseError.Code = parseErrorCode;
}
return parseStatus;
}
}
//
// Alternative parsing that follows RFC2616. Like the above, this trims both sides of the header value and replaces
// folding with a single space.
//
private enum RfcChar : byte
{
High = 0,
Reg,
Ctl,
CR,
LF,
WS,
Colon,
Delim
}
private static RfcChar[] RfcCharMap = new RfcChar[128]
{
RfcChar.Ctl, RfcChar.Ctl, RfcChar.Ctl, RfcChar.Ctl, RfcChar.Ctl, RfcChar.Ctl, RfcChar.Ctl, RfcChar.Ctl,
RfcChar.Ctl, RfcChar.WS, RfcChar.LF, RfcChar.Ctl, RfcChar.Ctl, RfcChar.CR, RfcChar.Ctl, RfcChar.Ctl,
RfcChar.Ctl, RfcChar.Ctl, RfcChar.Ctl, RfcChar.Ctl, RfcChar.Ctl, RfcChar.Ctl, RfcChar.Ctl, RfcChar.Ctl,
RfcChar.Ctl, RfcChar.Ctl, RfcChar.Ctl, RfcChar.Ctl, RfcChar.Ctl, RfcChar.Ctl, RfcChar.Ctl, RfcChar.Ctl,
RfcChar.WS, RfcChar.Reg, RfcChar.Delim, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg,
RfcChar.Delim, RfcChar.Delim, RfcChar.Reg, RfcChar.Reg, RfcChar.Delim, RfcChar.Reg, RfcChar.Reg, RfcChar.Delim,
RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg,
RfcChar.Reg, RfcChar.Reg, RfcChar.Colon, RfcChar.Delim, RfcChar.Delim, RfcChar.Delim, RfcChar.Delim, RfcChar.Delim,
RfcChar.Delim, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg,
RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg,
RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg,
RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Delim, RfcChar.Delim, RfcChar.Delim, RfcChar.Reg, RfcChar.Reg,
RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg,
RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg,
RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Reg,
RfcChar.Reg, RfcChar.Reg, RfcChar.Reg, RfcChar.Delim, RfcChar.Reg, RfcChar.Delim, RfcChar.Reg, RfcChar.Ctl,
};
internal unsafe DataParseStatus ParseHeadersStrict(
byte[] buffer,
int size,
ref int unparsed,
ref int totalResponseHeadersLength,
int maximumResponseHeadersLength,
ref WebParseError parseError)
{
GlobalLog.Enter("WebHeaderCollection::ParseHeadersStrict(): size:" + size.ToString() + ", unparsed:" + unparsed.ToString() + " buffer:[" + Encoding.ASCII.GetString(buffer, unparsed, Math.Min(256, size-unparsed)) + "]");
WebParseErrorCode parseErrorCode = WebParseErrorCode.Generic;
DataParseStatus parseStatus = DataParseStatus.Invalid;
int i = unparsed;
RfcChar ch;
int effectiveSize = maximumResponseHeadersLength <= 0 ? Int32.MaxValue : maximumResponseHeadersLength - totalResponseHeadersLength + i;
DataParseStatus sizeError = DataParseStatus.DataTooBig;
if (size < effectiveSize)
{
effectiveSize = size;
sizeError = DataParseStatus.NeedMoreData;
}
// Verify the size.
if (i >= effectiveSize)
{
parseStatus = sizeError;
goto quit;
}
fixed (byte* byteBuffer = buffer)
{
while (true)
{
// If this is CRLF, actually we're done.
if (byteBuffer[i] == '\r')
{
if (++i == effectiveSize)
{
parseStatus = sizeError;
goto quit;
}
if (byteBuffer[i++] == '\n')
{
totalResponseHeadersLength += i - unparsed;
unparsed = i;
parseStatus = DataParseStatus.Done;
goto quit;
}
parseStatus = DataParseStatus.Invalid;
parseErrorCode = WebParseErrorCode.CrLfError;
goto quit;
}
// Find the header name; only regular characters allowed.
int iBeginName = i;
for (; i < effectiveSize && (ch = byteBuffer[i] > 127 ? RfcChar.High : RfcCharMap[byteBuffer[i]]) == RfcChar.Reg; i++);
if (i == effectiveSize)
{
parseStatus = sizeError;
goto quit;
}
if (i == iBeginName)
{
parseStatus = DataParseStatus.Invalid;
parseErrorCode = WebParseErrorCode.InvalidHeaderName;
goto quit;
}
// Read to a colon.
int iEndName = i - 1;
int crlf = 0; // 1 = cr, 2 = crlf
for (; i < effectiveSize && (ch = byteBuffer[i] > 127 ? RfcChar.High : RfcCharMap[byteBuffer[i]]) != RfcChar.Colon; i++)
{
switch (ch)
{
case RfcChar.WS:
if (crlf == 1)
{
break;
}
crlf = 0;
continue;
case RfcChar.CR:
if (crlf == 0)
{
crlf = 1;
continue;
}
break;
case RfcChar.LF:
if (crlf == 1)
{
crlf = 2;
continue;
}
break;
}
parseStatus = DataParseStatus.Invalid;
parseErrorCode = WebParseErrorCode.CrLfError;
goto quit;
}
if (i == effectiveSize)
{
parseStatus = sizeError;
goto quit;
}
if (crlf != 0)
{
parseStatus = DataParseStatus.Invalid;
parseErrorCode = WebParseErrorCode.IncompleteHeaderLine;
goto quit;
}
// Skip the colon.
if (++i == effectiveSize)
{
parseStatus = sizeError;
goto quit;
}
// Read the value. crlf = 3 means in the whitespace after a CRLF
int iBeginValue = -1;
int iEndValue = -1;
StringBuilder valueAccumulator = null;
for (; i < effectiveSize && ((ch = byteBuffer[i] > 127 ? RfcChar.High : RfcCharMap[byteBuffer[i]]) == RfcChar.WS || crlf != 2); i++)
{
switch (ch)
{
case RfcChar.WS:
if (crlf == 1)
{
break;
}
if (crlf == 2)
{
crlf = 3;
}
continue;
case RfcChar.CR:
if (crlf == 0)
{
crlf = 1;
continue;
}
break;
case RfcChar.LF:
if (crlf == 1)
{
crlf = 2;
continue;
}
break;
case RfcChar.High:
case RfcChar.Colon:
case RfcChar.Delim:
case RfcChar.Reg:
if (crlf == 1)
{
break;
}
if (crlf == 3)
{
crlf = 0;
if (iBeginValue != -1)
{
string s = HeaderEncoding.GetString(byteBuffer + iBeginValue, iEndValue - iBeginValue + 1);
if (valueAccumulator == null)
{
valueAccumulator = new StringBuilder(s, s.Length * 5);
}
else
{
valueAccumulator.Append(" ");
valueAccumulator.Append(s);
}
}
iBeginValue = -1;
}
if (iBeginValue == -1)
{
iBeginValue = i;
}
iEndValue = i;
continue;
}
parseStatus = DataParseStatus.Invalid;
parseErrorCode = WebParseErrorCode.CrLfError;
goto quit;
}
if (i == effectiveSize)
{
parseStatus = sizeError;
goto quit;
}
// Make the value.
string sValue = iBeginValue == -1 ? "" : HeaderEncoding.GetString(byteBuffer + iBeginValue, iEndValue - iBeginValue + 1);
if (valueAccumulator != null)
{
if (sValue.Length != 0)
{
valueAccumulator.Append(" ");
valueAccumulator.Append(sValue);
}
sValue = valueAccumulator.ToString();
}
// Make the name. See if it's a common header first.
string sName = null;
int headerNameLength = iEndName - iBeginName + 1;
if (m_CommonHeaders != null)
{
int iHeader = s_CommonHeaderHints[byteBuffer[iBeginName] & 0x1f];
if (iHeader >= 0)
{
while (true)
{
string s = s_CommonHeaderNames[iHeader++];
// Not found if we get to a shorter header or one with a different first character.
if (s.Length < headerNameLength || CaseInsensitiveAscii.AsciiToLower[byteBuffer[iBeginName]] != CaseInsensitiveAscii.AsciiToLower[s[0]])
break;
// Keep looking if the common header is too long.
if (s.Length > headerNameLength)
continue;
int j;
byte* pBuffer = byteBuffer + iBeginName + 1;
for (j = 1; j < s.Length; j++)
{
// Avoid the case-insensitive compare in the common case where they match.
if (*(pBuffer++) != s[j] && CaseInsensitiveAscii.AsciiToLower[*(pBuffer - 1)] != CaseInsensitiveAscii.AsciiToLower[s[j]])
break;
}
if (j == s.Length)
{
// Set it to the appropriate index.
m_NumCommonHeaders++;
iHeader--;
if (m_CommonHeaders[iHeader] == null)
{
m_CommonHeaders[iHeader] = sValue;
}
else
{
// Don't currently handle combining multiple header instances in the common header case.
// Nothing to do but punt them all to the NameValueCollection.
NormalizeCommonHeaders();
AddInternalNotCommon(s, sValue);
}
sName = s;
break;
}
}
}
}
// If it wasn't a common header, add it to the hash.
if (sName == null)
{
sName = HeaderEncoding.GetString(byteBuffer + iBeginName, headerNameLength);
AddInternalNotCommon(sName, sValue);
}
totalResponseHeadersLength += i - unparsed;
unparsed = i;
}
}
quit:
GlobalLog.Leave("WebHeaderCollection::ParseHeadersStrict() returning parseStatus:" + parseStatus.ToString());
if (parseStatus == DataParseStatus.Invalid) {
parseError.Section = WebParseErrorSection.ResponseHeader;
parseError.Code = parseErrorCode;
}
return parseStatus;
}
//
// Keeping this version for backwards compatibility (mostly with reflection). Remove some day, along with the interface
// explicit reimplementation.
//
/// <internalonly/>
[SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Justification = "System.dll is still using pre-v4 security model and needs this demand")]
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.SerializationFormatter, SerializationFormatter=true)]
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
GetObjectData(serializationInfo, streamingContext);
}
// Override Get() to check the common headers.
public override string Get(string name)
{
// In this case, need to make sure name doesn't have any Unicode since it's being used as an index into tables.
if (m_CommonHeaders != null && name != null && name.Length > 0 && name[0] < 256)
{
int iHeader = s_CommonHeaderHints[name[0] & 0x1f];
if (iHeader >= 0)
{
while (true)
{
string s = s_CommonHeaderNames[iHeader++];
// Not found if we get to a shorter header or one with a different first character.
if (s.Length < name.Length || CaseInsensitiveAscii.AsciiToLower[name[0]] != CaseInsensitiveAscii.AsciiToLower[s[0]])
break;
// Keep looking if the common header is too long.
if (s.Length > name.Length)
continue;
int j;
for (j = 1; j < s.Length; j++)
{
// Avoid the case-insensitive compare in the common case where they match.
if (name[j] != s[j] && (name[j] > 255 || CaseInsensitiveAscii.AsciiToLower[name[j]] != CaseInsensitiveAscii.AsciiToLower[s[j]]))
break;
}
if (j == s.Length)
{
// Get the appropriate header.
return m_CommonHeaders[iHeader - 1];
}
}
}
}
// Fall back to normal lookup.
if (m_InnerCollection == null)
return null;
return m_InnerCollection.Get(name);
}
//
// Additional overrides required to fully orphan the base implementation.
//
public override IEnumerator GetEnumerator()
{
NormalizeCommonHeaders();
return new NameObjectKeysEnumerator(InnerCollection);
}
public override int Count
{
get
{
return (m_InnerCollection == null ? 0 : m_InnerCollection.Count) + m_NumCommonHeaders;
}
}
public override KeysCollection Keys
{
get
{
NormalizeCommonHeaders();
return InnerCollection.Keys;
}
}
internal override bool InternalHasKeys()
{
NormalizeCommonHeaders();
if (m_InnerCollection == null)
return false;
return m_InnerCollection.HasKeys();
}
public override string Get(int index)
{
NormalizeCommonHeaders();
return InnerCollection.Get(index);
}
public override string[] GetValues(int index)
{
NormalizeCommonHeaders();
return InnerCollection.GetValues(index);
}
public override string GetKey(int index)
{
NormalizeCommonHeaders();
return InnerCollection.GetKey(index);
}
public override string[] AllKeys
{
get
{
NormalizeCommonHeaders();
return InnerCollection.AllKeys;
}
}
public override void Clear()
{
m_CommonHeaders = null;
m_NumCommonHeaders = 0;
InvalidateCachedArrays();
if (m_InnerCollection != null)
m_InnerCollection.Clear();
}
} // class WebHeaderCollection
internal class CaseInsensitiveAscii : IEqualityComparer, IComparer{
// ASCII char ToLower table
internal static readonly CaseInsensitiveAscii StaticInstance = new CaseInsensitiveAscii();
internal static readonly byte[] AsciiToLower = new byte[] {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 97, 98, 99,100,101, // 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
102,103,104,105,106,107,108,109,110,111, // 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
112,113,114,115,116,117,118,119,120,121, // 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
122, 91, 92, 93, 94, 95, 96, 97, 98, 99, // 90, 91, 92, 93, 94, 95, 96, 97, 98, 99,
100,101,102,103,104,105,106,107,108,109,
110,111,112,113,114,115,116,117,118,119,
120,121,122,123,124,125,126,127,128,129,
130,131,132,133,134,135,136,137,138,139,
140,141,142,143,144,145,146,147,148,149,
150,151,152,153,154,155,156,157,158,159,
160,161,162,163,164,165,166,167,168,169,
170,171,172,173,174,175,176,177,178,179,
180,181,182,183,184,185,186,187,188,189,
190,191,192,193,194,195,196,197,198,199,
200,201,202,203,204,205,206,207,208,209,
210,211,212,213,214,215,216,217,218,219,
220,221,222,223,224,225,226,227,228,229,
230,231,232,233,234,235,236,237,238,239,
240,241,242,243,244,245,246,247,248,249,
250,251,252,253,254,255
};
// ASCII string case insensitive hash function
public int GetHashCode(object myObject) {
string myString = myObject as string;
if (myObject == null) {
return 0;
}
int myHashCode = myString.Length;
if (myHashCode == 0) {
return 0;
}
myHashCode ^= AsciiToLower[(byte)myString[0]]<<24 ^ AsciiToLower[(byte)myString[myHashCode-1]]<<16;
return myHashCode;
}
// ASCII string case insensitive comparer
public int Compare(object firstObject, object secondObject) {
string firstString = firstObject as string;
string secondString = secondObject as string;
if (firstString==null) {
return secondString == null ? 0 : -1;
}
if (secondString == null) {
return 1;
}
int result = firstString.Length - secondString.Length;
int comparisons = result > 0 ? secondString.Length : firstString.Length;
int difference, index = 0;
while ( index < comparisons ) {
difference = (int)(AsciiToLower[ firstString[index] ] - AsciiToLower[ secondString[index] ]);
if ( difference != 0 ) {
result = difference;
break;
}
index++;
}
return result;
}
// ASCII string case insensitive hash function
int FastGetHashCode(string myString) {
int myHashCode = myString.Length;
if (myHashCode!=0) {
myHashCode ^= AsciiToLower[(byte)myString[0]]<<24 ^ AsciiToLower[(byte)myString[myHashCode-1]]<<16;
}
return myHashCode;
}
// ASCII string case insensitive comparer
public new bool Equals(object firstObject, object secondObject) {
string firstString = firstObject as string;
string secondString = secondObject as string;
if (firstString==null) {
return secondString==null;
}
if (secondString!=null) {
int index = firstString.Length;
if (index==secondString.Length) {
if (FastGetHashCode(firstString)==FastGetHashCode(secondString)) {
int comparisons = firstString.Length;
while (index>0) {
index--;
if (AsciiToLower[firstString[index]]!=AsciiToLower[secondString[index]]) {
return false;
}
}
return true;
}
}
}
return false;
}
}
internal class HostHeaderString {
private bool m_Converted;
private string m_String;
private byte[] m_Bytes;
internal HostHeaderString() {
Init(null);
}
internal HostHeaderString(string s) {
Init(s);
}
private void Init(string s) {
m_String = s;
m_Converted = false;
m_Bytes = null;
}
private void Convert() {
if (m_String != null && !m_Converted) {
m_Bytes = Encoding.Default.GetBytes(m_String);
string copy = Encoding.Default.GetString(m_Bytes);
if (!(string.Compare(m_String, copy, StringComparison.Ordinal) == 0)) {
m_Bytes = Encoding.UTF8.GetBytes(m_String);
}
}
}
internal string String {
get { return m_String; }
set {
Init(value);
}
}
internal int ByteCount {
get {
Convert();
return m_Bytes.Length;
}
}
internal byte[] Bytes {
get {
Convert();
return m_Bytes;
}
}
internal void Copy(byte[] destBytes, int destByteIndex) {
Convert();
Array.Copy(m_Bytes, 0, destBytes, destByteIndex, m_Bytes.Length);
}
}
}
| 42.377279 | 231 | 0.483413 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/ndp/fx/src/net/System/Net/WebHeaderCollection.cs | 90,645 | C# |
#region
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WinterLeaf.Engine;
using WinterLeaf.Engine.Classes;
using WinterLeaf.Engine.Containers;
using WinterLeaf.Engine.Enums;
using System.ComponentModel;
using System.Threading;
using WinterLeaf.Engine.Classes.Interopt;
using WinterLeaf.Engine.Classes.Decorations;
using WinterLeaf.Engine.Classes.Extensions;
using WinterLeaf.Engine.Classes.Helpers;
using WinterLeaf.Demo.Full.Models.User.Extendable;
#endregion
namespace WinterLeaf.Demo.Full.Models.Base
{
/// <summary>
///
/// </summary>
[TypeConverter(typeof(TypeConverterGeneric<GuiGameListMenuCtrl_Base>))]
public partial class GuiGameListMenuCtrl_Base: GuiControl
{
#region ProxyObjects Operator Overrides
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <param name="simobjectid"></param>
/// <returns></returns>
public static bool operator ==(GuiGameListMenuCtrl_Base ts, string simobjectid)
{
return object.ReferenceEquals(ts, null) ? object.ReferenceEquals(simobjectid, null) : ts.Equals(simobjectid);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
return (this._ID ==(string)myReflections.ChangeType( obj,typeof(string)));
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <param name="simobjectid"></param>
/// <returns></returns>
public static bool operator !=(GuiGameListMenuCtrl_Base ts, string simobjectid)
{
if (object.ReferenceEquals(ts, null))
return !object.ReferenceEquals(simobjectid, null);
return !ts.Equals(simobjectid);
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator string( GuiGameListMenuCtrl_Base ts)
{
if (object.ReferenceEquals(ts, null))
return "0";
return ts._ID;
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator GuiGameListMenuCtrl_Base(string ts)
{
uint simobjectid = resolveobject(ts);
return (GuiGameListMenuCtrl_Base) Omni.self.getSimObject(simobjectid,typeof(GuiGameListMenuCtrl_Base));
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator int( GuiGameListMenuCtrl_Base ts)
{
return (int)ts._iID;
}
/// <summary>
///
/// </summary>
/// <param name="simobjectid"></param>
/// <returns></returns>
public static implicit operator GuiGameListMenuCtrl_Base(int simobjectid)
{
return (GuiGameListMenuCtrl) Omni.self.getSimObject((uint)simobjectid,typeof(GuiGameListMenuCtrl_Base));
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator uint( GuiGameListMenuCtrl_Base ts)
{
return ts._iID;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static implicit operator GuiGameListMenuCtrl_Base(uint simobjectid)
{
return (GuiGameListMenuCtrl_Base) Omni.self.getSimObject(simobjectid,typeof(GuiGameListMenuCtrl_Base));
}
#endregion
#region Init Persists
/// <summary>
/// Script callback when the 'A' button is pressed. 'A' inputs are Keyboard: A, Return, Space; Gamepad: A, Start
/// </summary>
[MemberGroup("")]
public String callbackOnA
{
get
{
return Omni.self.GetVar(_ID + ".callbackOnA").AsString();
}
set
{
Omni.self.SetVar(_ID + ".callbackOnA", value.AsString());
}
}
/// <summary>
/// Script callback when the 'B' button is pressed. 'B' inputs are Keyboard: B, Esc, Backspace, Delete; Gamepad: B, Back
/// </summary>
[MemberGroup("")]
public String callbackOnB
{
get
{
return Omni.self.GetVar(_ID + ".callbackOnB").AsString();
}
set
{
Omni.self.SetVar(_ID + ".callbackOnB", value.AsString());
}
}
/// <summary>
/// Script callback when the 'X' button is pressed. 'X' inputs are Keyboard: X; Gamepad: X
/// </summary>
[MemberGroup("")]
public String callbackOnX
{
get
{
return Omni.self.GetVar(_ID + ".callbackOnX").AsString();
}
set
{
Omni.self.SetVar(_ID + ".callbackOnX", value.AsString());
}
}
/// <summary>
/// Script callback when the 'Y' button is pressed. 'Y' inputs are Keyboard: Y; Gamepad: Y
/// </summary>
[MemberGroup("")]
public String callbackOnY
{
get
{
return Omni.self.GetVar(_ID + ".callbackOnY").AsString();
}
set
{
Omni.self.SetVar(_ID + ".callbackOnY", value.AsString());
}
}
/// <summary>
/// Enable debug rendering
/// </summary>
[MemberGroup("")]
public bool debugRender
{
get
{
return Omni.self.GetVar(_ID + ".debugRender").AsBool();
}
set
{
Omni.self.SetVar(_ID + ".debugRender", value.AsString());
}
}
#endregion
#region Member Functions
/// <summary>
/// Activates the current row. The script callback of the current row will be called (if it has one). )
///
/// </summary>
[MemberFunctionConsoleInteraction(true)]
public void activateRow(){
pInvokes.m_ts.fnGuiGameListMenuCtrl_activateRow(_ID);
}
/// <summary>
/// Add a row to the list control.
/// @param label The text to display on the row as a label.
/// @param callback Name of a script function to use as a callback when this row is activated.
/// @param icon [optional] Index of the icon to use as a marker.
/// @param yPad [optional] An extra amount of height padding before the row. Does nothing on the first row.
/// @param useHighlightIcon [optional] Does this row use the highlight icon?.
/// @param enabled [optional] If this row is initially enabled. )
///
/// </summary>
[MemberFunctionConsoleInteraction(true)]
public void addRow(string label, string callback, int icon = -1, int yPad = 0, bool useHighlightIcon = true, bool enabled = true){
pInvokes.m_ts.fnGuiGameListMenuCtrl_addRow(_ID, label, callback, icon, yPad, useHighlightIcon, enabled);
}
/// <summary>
/// Gets the number of rows on the control.
/// @return (int) The number of rows on the control. )
///
/// </summary>
[MemberFunctionConsoleInteraction(true)]
public int getRowCount(){
return pInvokes.m_ts.fnGuiGameListMenuCtrl_getRowCount(_ID);
}
/// <summary>
/// Gets the label displayed on the specified row.
/// @param row Index of the row to get the label of.
/// @return The label for the row. )
///
/// </summary>
[MemberFunctionConsoleInteraction(true)]
public string getRowLabel(int row){
return pInvokes.m_ts.fnGuiGameListMenuCtrl_getRowLabel(_ID, row);
}
/// <summary>
/// Gets the index of the currently selected row.
/// @return Index of the selected row. )
///
/// </summary>
[MemberFunctionConsoleInteraction(true)]
public int getSelectedRow(){
return pInvokes.m_ts.fnGuiGameListMenuCtrl_getSelectedRow(_ID);
}
/// <summary>
/// Determines if the specified row is enabled or disabled.
/// @param row The row to set the enabled status of.
/// @return True if the specified row is enabled. False if the row is not enabled or the given index was not valid. )
///
/// </summary>
[MemberFunctionConsoleInteraction(true)]
public bool isRowEnabled(int row){
return pInvokes.m_ts.fnGuiGameListMenuCtrl_isRowEnabled(_ID, row);
}
/// <summary>
/// Sets a row's enabled status according to the given parameters.
/// @param row The index to check for validity.
/// @param enabled Indicate true to enable the row or false to disable it. )
///
/// </summary>
[MemberFunctionConsoleInteraction(true)]
public void setRowEnabled(int row, bool enabled){
pInvokes.m_ts.fnGuiGameListMenuCtrl_setRowEnabled(_ID, row, enabled);
}
/// <summary>
/// Sets the label on the given row.
/// @param row Index of the row to set the label on.
/// @param label Text to set as the label of the row. )
///
/// </summary>
[MemberFunctionConsoleInteraction(true)]
public void setRowLabel(int row, string label){
pInvokes.m_ts.fnGuiGameListMenuCtrl_setRowLabel(_ID, row, label);
}
/// <summary>
/// Sets the selected row. Only rows that are enabled can be selected.
/// @param row Index of the row to set as selected. )
///
/// </summary>
[MemberFunctionConsoleInteraction(true)]
public void setSelected(int row){
pInvokes.m_ts.fnGuiGameListMenuCtrl_setSelected(_ID, row);
}
#endregion
#region T3D Callbacks
/// <summary>
/// Called when the selected row changes. )
/// </summary>
[ConsoleInteraction(true)]
public virtual void onChange(){}
#endregion
public GuiGameListMenuCtrl_Base (){}
}}
| 30.807927 | 132 | 0.591588 | [
"MIT",
"Unlicense"
] | RichardRanft/OmniEngine.Net | Templates/C#-Empty/Winterleaf.Demo.Full/Models.Base/GuiGameListMenuCtrl_Base.cs | 9,778 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace BlazorBootstrap.Components
{
public partial class Blockquote
{
protected override void OnParametersSet()
{
this.AddClass(ClassNames.BlockQuotes.Blockquote);
base.OnParametersSet();
}
}
}
| 19.235294 | 61 | 0.657492 | [
"Apache-2.0"
] | MikaBerglund/Blazor-Bootstrap | BlazorBootstrap.Components/Blockquote.razor.cs | 329 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DnD_5e_CharacterSheet.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.709677 | 151 | 0.585502 | [
"Apache-2.0"
] | faha223/Dnd_5e_CharacterSheet | DnD_5e_CharacterSheet/Properties/Settings.Designer.cs | 1,078 | C# |
// This code is part of the Fungus library (https://github.com/snozbot/fungus)
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
namespace Fungus
{
/// <summary>
/// Boolean variable type.
/// </summary>
[VariableInfo("", "Boolean")]
[AddComponentMenu("")]
[System.Serializable]
public class BooleanVariable : VariableBase<bool>
{
public override bool IsArithmeticSupported(SetOperator setOperator)
{
return setOperator == SetOperator.Negate || base.IsArithmeticSupported(setOperator);
}
public override void Apply(SetOperator op, bool value)
{
switch (op)
{
case SetOperator.Negate:
Value = !value;
break;
default:
base.Apply(op, value);
break;
}
}
}
/// <summary>
/// Container for a Boolean variable reference or constant value.
/// </summary>
[System.Serializable]
public struct BooleanData
{
[SerializeField]
[VariableProperty("<Value>", typeof(BooleanVariable))]
public BooleanVariable booleanRef;
[SerializeField]
public bool booleanVal;
public BooleanData(bool v)
{
booleanVal = v;
booleanRef = null;
}
public static implicit operator bool(BooleanData booleanData)
{
return booleanData.Value;
}
public bool Value
{
get { return (booleanRef == null) ? booleanVal : booleanRef.Value; }
set { if (booleanRef == null) { booleanVal = value; } else { booleanRef.Value = value; } }
}
public string GetDescription()
{
if (booleanRef == null)
{
return booleanVal.ToString();
}
else
{
return booleanRef.Key;
}
}
}
} | 27.792208 | 117 | 0.52243 | [
"Unlicense"
] | RenVoc/MindVector | MindVector/Assets/Fungus/Scripts/VariableTypes/BooleanVariable.cs | 2,140 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Crestron.ThirdPartyCommon.Class;
using Crestron.ThirdPartyCommon.ComponentInterfaces;
using Crestron.ThirdPartyCommon.Interfaces;
using Crestron.ThirdPartyCommon.StandardCommands;
using Crestron.ThirdPartyCommon.Transports;
using VTPro.Objects;
using VTPro.SmartObjects;
using myNamespace.Drivers;
using myNamespace.Constants;
namespace myNamespace.Methods
{
public class __Security_MainVTButtons
{
public __Security_MainVTButtons(Panel Panel)
{
this.Panel = Panel;
}
/*
private bool BaseSanityCheck
{
get
{
if (Bluray != ControlSystem.GetSystem._blurayPlayer)
{
Bluray = ControlSystem.GetSystem._blurayPlayer;
}
return Bluray != null;
}
}
*/
public void Button(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Simple_Button(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Simple_Button_1(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Simple_Button_2(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public IBasicBlurayPlayer Bluray;
private Panel Panel;
}
} | 23.087912 | 69 | 0.52832 | [
"MIT"
] | neilsilver/TP_XML-CSharp | bin/Debug/OUTPUT/Callbacks/__Security_Main/VTButtons.cs | 2,101 | C# |
// Copyright (c) Microsoft Corporation, Inc. All rights reserved.
// Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Xunit;
namespace Identity.Test
{
public class ClaimsIdentityFactoryTest
{
[Fact]
public void CreateIdentityNullCheckTest()
{
var factory = new ClaimsIdentityFactory<IdentityUser>();
var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
ExceptionHelper.ThrowsArgumentNull(
() => AsyncHelper.RunSync(() => factory.CreateAsync(null, null, "whatever")), "manager");
ExceptionHelper.ThrowsArgumentNull(
() => AsyncHelper.RunSync(() => factory.CreateAsync(manager, null, "whatever")), "user");
ExceptionHelper.ThrowsArgumentNull(
() => AsyncHelper.RunSync(() => factory.CreateAsync(manager, new IdentityUser(), null)), "value");
ExceptionHelper.ThrowsArgumentNull(() => factory.ConvertIdToString(null), "key");
}
[Fact]
public async Task ClaimsIdentityTest()
{
var db = UnitTestHelper.CreateDefaultDb();
var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
var role = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
var user = new IdentityUser("Hao");
UnitTestHelper.IsSuccess(await manager.CreateAsync(user));
UnitTestHelper.IsSuccess(await role.CreateAsync(new IdentityRole("Admin")));
UnitTestHelper.IsSuccess(await role.CreateAsync(new IdentityRole("Local")));
UnitTestHelper.IsSuccess(await manager.AddToRoleAsync(user.Id, "Admin"));
UnitTestHelper.IsSuccess(await manager.AddToRoleAsync(user.Id, "Local"));
Claim[] userClaims =
{
new Claim("Whatever", "Value"),
new Claim("Whatever2", "Value2")
};
foreach (var c in userClaims)
{
UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c));
}
var identity = await manager.CreateIdentityAsync(user, "test");
var claimsFactory = manager.ClaimsIdentityFactory as ClaimsIdentityFactory<IdentityUser, string>;
Assert.NotNull(claimsFactory);
var claims = identity.Claims;
Assert.NotNull(claims);
Assert.True(
claims.Any(c => c.Type == claimsFactory.UserNameClaimType && c.Value == user.UserName));
Assert.True(claims.Any(c => c.Type == claimsFactory.UserIdClaimType && c.Value == user.Id));
Assert.True(claims.Any(c => c.Type == claimsFactory.RoleClaimType && c.Value == "Admin"));
Assert.True(claims.Any(c => c.Type == claimsFactory.RoleClaimType && c.Value == "Local"));
Assert.True(
claims.Any(
c =>
c.Type == ClaimsIdentityFactory<IdentityUser>.IdentityProviderClaimType &&
c.Value == ClaimsIdentityFactory<IdentityUser>.DefaultIdentityProviderClaimValue));
foreach (var cl in userClaims)
{
Assert.True(claims.Any(c => c.Type == cl.Type && c.Value == cl.Value));
}
}
[Fact]
public void ClaimsIdentitySyncTest()
{
var db = UnitTestHelper.CreateDefaultDb();
var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
var role = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
var user = new IdentityUser("Hao");
var claimsFactory = manager.ClaimsIdentityFactory as ClaimsIdentityFactory<IdentityUser, string>;
Assert.NotNull(claimsFactory);
UnitTestHelper.IsSuccess(manager.Create(user));
UnitTestHelper.IsSuccess(role.Create(new IdentityRole("Admin")));
UnitTestHelper.IsSuccess(role.Create(new IdentityRole("Local")));
UnitTestHelper.IsSuccess(manager.AddToRole(user.Id, "Admin"));
UnitTestHelper.IsSuccess(manager.AddToRole(user.Id, "Local"));
Claim[] userClaims =
{
new Claim("Whatever", "Value"),
new Claim("Whatever2", "Value2")
};
foreach (var c in userClaims)
{
UnitTestHelper.IsSuccess(manager.AddClaim(user.Id, c));
}
var identity = manager.CreateIdentity(user, "test");
var claims = identity.Claims;
Assert.NotNull(claims);
Assert.NotNull(claims);
Assert.True(
claims.Any(c => c.Type == claimsFactory.UserNameClaimType && c.Value == user.UserName));
Assert.True(claims.Any(c => c.Type == claimsFactory.UserIdClaimType && c.Value == user.Id));
Assert.True(claims.Any(c => c.Type == claimsFactory.RoleClaimType && c.Value == "Admin"));
Assert.True(claims.Any(c => c.Type == claimsFactory.RoleClaimType && c.Value == "Local"));
Assert.True(
claims.Any(
c =>
c.Type == ClaimsIdentityFactory<IdentityUser>.IdentityProviderClaimType &&
c.Value == ClaimsIdentityFactory<IdentityUser>.DefaultIdentityProviderClaimValue));
foreach (var cl in userClaims)
{
Assert.True(claims.Any(c => c.Type == cl.Type && c.Value == cl.Value));
}
}
}
} | 50.217391 | 114 | 0.598615 | [
"MIT"
] | MohammadRS/AspNetIdentity | test/Identity.Test/ClaimsIdentityFactoryTest.cs | 5,777 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\shared\ks.h(1758,5)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential)]
public partial struct __struct_ks_364__union_0
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public byte[] __bits;
public uint FileAlignment { get => InteropRuntime.GetUInt32(__bits, 0, 32); set => InteropRuntime.SetUInt32(value, __bits, 0, 32); }
public int FramePitch { get => InteropRuntime.GetInt32(__bits, 0, 32); set => InteropRuntime.SetInt32(value, __bits, 0, 32); }
}
}
| 42.882353 | 140 | 0.716049 | [
"MIT"
] | bbday/DirectN | DirectN/DirectN/Generated/__struct_ks_364__union_0.cs | 731 | C# |
namespace Cached.DistributedCache
{
//public sealed class DistributedCacher : Cacher, IDistributedCacher
//{
// private readonly IDistributedCache _distributedCache;
// private readonly DistributedCacheEntryOptions _options;
// internal DistributedCacher(
// ILock cacheLock,
// IDistributedCache distributedCache,
// DistributedCacheEntryOptions options = null)
// : base(cacheLock)
// {
// _options = options;
// _distributedCache = distributedCache ?? throw new ArgumentNullException(nameof(distributedCache));
// }
// /// <summary>
// /// Creates a new Cacher instance backed by provided DistributedCache instance.
// /// </summary>
// /// <param name="distributedCache">The DistributedCache instance to be used.</param>
// /// <param name="options">(Optional) Entry options that overrides the DistributedCache configuration.</param>
// /// <returns>The new cacher instance.</returns>
// public static IDistributedCacher New(
// IDistributedCache distributedCache,
// DistributedCacheEntryOptions options = null)
// {
// return new DistributedCacher(new KeyBasedLock(), distributedCache, options);
// }
// /// <inheritdoc />
// protected override async Task WriteToCache<T>(string key, T item)
// {
// await _distributedCache.SetAsync(key, item.ToByteArray()).ConfigureAwait(false);
// }
// /// <inheritdoc />
// protected override async Task<CacheResult<T>> TryGetFromCache<T>(string key)
// {
// var itemBytes = await _distributedCache.GetAsync(key).ConfigureAwait(false);
// return itemBytes.TryParseObject(out T castItem)
// ? CacheResult<T>.Hit(castItem)
// : CacheResult<T>.Miss;
// }
//}
} | 41.234043 | 119 | 0.615067 | [
"MIT"
] | ryhled/cached | src/Cached.DistributedCache/DistributedCacher.cs | 1,940 | 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.AzureNative.Network.Latest.Outputs
{
[OutputType]
public sealed class LoadBalancerSkuResponse
{
/// <summary>
/// Name of a load balancer SKU.
/// </summary>
public readonly string? Name;
/// <summary>
/// Tier of a load balancer SKU.
/// </summary>
public readonly string? Tier;
[OutputConstructor]
private LoadBalancerSkuResponse(
string? name,
string? tier)
{
Name = name;
Tier = tier;
}
}
}
| 24.277778 | 81 | 0.599542 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Network/Latest/Outputs/LoadBalancerSkuResponse.cs | 874 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
namespace Veldrid.NeoDemo
{
public class RenderQueue : IEnumerable<Renderable>
{
private const int DefaultCapacity = 250;
private readonly List<RenderItemIndex> _indices = new List<RenderItemIndex>(DefaultCapacity);
private readonly List<Renderable> _renderables = new List<Renderable>(DefaultCapacity);
public void Clear()
{
_indices.Clear();
_renderables.Clear();
}
public void AddRange(List<Renderable> Renderables, Vector3 viewPosition)
{
for (int i = 0; i < Renderables.Count; i++)
{
Renderable Renderable = Renderables[i];
if (Renderable != null)
{
Add(Renderable, viewPosition);
}
}
}
public void AddRange(IEnumerable<Renderable> Renderables, Vector3 viewPosition)
{
foreach (Renderable item in Renderables)
{
if (item != null)
{
Add(item, viewPosition);
}
}
}
public void Add(Renderable item, Vector3 viewPosition)
{
int index = _renderables.Count;
_indices.Add(new RenderItemIndex(item.GetRenderOrderKey(viewPosition), index));
_renderables.Add(item);
Debug.Assert(_renderables.IndexOf(item) == index);
}
public void Sort()
{
_indices.Sort();
}
public void Sort(Comparer<RenderOrderKey> keyComparer)
{
_indices.Sort(
(RenderItemIndex first, RenderItemIndex second)
=> keyComparer.Compare(first.Key, second.Key));
}
public void Sort(Comparer<RenderItemIndex> comparer)
{
_indices.Sort(comparer);
}
public Enumerator GetEnumerator()
{
return new Enumerator(_indices, _renderables);
}
IEnumerator<Renderable> IEnumerable<Renderable>.GetEnumerator() => GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public struct Enumerator : IEnumerator<Renderable>
{
private readonly List<RenderItemIndex> _indices;
private readonly List<Renderable> _Renderables;
private int _nextItemIndex;
private Renderable _currentItem;
public Enumerator(List<RenderItemIndex> indices, List<Renderable> Renderables)
{
_indices = indices;
_Renderables = Renderables;
_nextItemIndex = 0;
_currentItem = null;
}
public Renderable Current => _currentItem;
object IEnumerator.Current => _currentItem;
public void Dispose()
{
}
public bool MoveNext()
{
if (_nextItemIndex >= _indices.Count)
{
_currentItem = null;
return false;
}
else
{
var currentIndex = _indices[_nextItemIndex];
_currentItem = _Renderables[currentIndex.ItemIndex];
_nextItemIndex += 1;
return true;
}
}
public void Reset()
{
_nextItemIndex = 0;
_currentItem = null;
}
}
}
}
| 29.548387 | 101 | 0.527293 | [
"MIT"
] | mellinoe/Veldrid-3.0 | demo/Main/RenderQueue.cs | 3,666 | C# |
namespace DataFlow.EdFi.Models.Resources
{
public class AccountCode
{
/// <summary>
/// The type of the account code (e.g., fund, function, object)
/// </summary>
public string descriptor { get; set; }
}
}
| 19.846154 | 71 | 0.554264 | [
"Apache-2.0"
] | schoolstacks/dataflow | DataFlow.EdFi/Models/Resources/AccountCode.cs | 258 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Reflection;
using System.Resources;
[assembly: AssemblyTitle("Microsoft Azure Automation Management Library")]
[assembly: AssemblyDescription("Provides Microsoft Azure Automation management operations.")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
| 38 | 93 | 0.759868 | [
"Apache-2.0"
] | CerebralMischief/azure-sdk-for-net | src/ResourceManagement/Automation/AutomationManagement/Properties/AssemblyInfo.cs | 1,216 | C# |
using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace HandyControl.Controls
{
public class LoadingLine : LoadingBase
{
private const double MoveLength = 80;
private const double UniformScale = .6;
public LoadingLine()
{
SetBinding(HeightProperty, new Binding("DotDiameter") { Source = this });
}
protected sealed override void UpdateDots()
{
var dotCount = DotCount;
var dotInterval = DotInterval;
var dotDiameter = DotDiameter;
var dotSpeed = DotSpeed;
var dotDelayTime = DotDelayTime;
if (dotCount < 1) return;
PrivateCanvas.Children.Clear();
//计算相关尺寸
var centerWidth = dotDiameter * dotCount + dotInterval * (dotCount - 1) + MoveLength;
var speedDownLength = (ActualWidth - MoveLength) / 2;
var speedUniformLength = centerWidth / 2;
//定义动画
Storyboard = new Storyboard
{
RepeatBehavior = RepeatBehavior.Forever
};
//创建圆点
for (var i = 0; i < dotCount; i++)
{
var ellipse = CreateEllipse(i, dotInterval, dotDiameter);
var frames = new ThicknessAnimationUsingKeyFrames
{
BeginTime = TimeSpan.FromMilliseconds(dotDelayTime * i)
};
//开始位置
var frame0 = new LinearThicknessKeyFrame
{
Value = new Thickness(ellipse.Margin.Left, 0, 0, 0),
KeyTime = KeyTime.FromTimeSpan(TimeSpan.Zero)
};
//开始位置到匀速开始
var frame1 = new EasingThicknessKeyFrame
{
EasingFunction = new PowerEase
{
EasingMode = EasingMode.EaseOut
},
Value = new Thickness(speedDownLength + ellipse.Margin.Left, 0, 0, 0),
KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(dotSpeed * (1 - UniformScale) / 2))
};
//匀速开始到匀速结束
var frame2 = new LinearThicknessKeyFrame
{
Value = new Thickness(speedDownLength + speedUniformLength + ellipse.Margin.Left, 0, 0, 0),
KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(dotSpeed * (1 + UniformScale) / 2))
};
//匀速结束到匀加速结束
var frame3 = new EasingThicknessKeyFrame
{
EasingFunction = new PowerEase
{
EasingMode = EasingMode.EaseIn
},
Value = new Thickness(ActualWidth + ellipse.Margin.Left + speedUniformLength, 0, 0, 0),
KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(dotSpeed))
};
frames.KeyFrames.Add(frame0);
frames.KeyFrames.Add(frame1);
frames.KeyFrames.Add(frame2);
frames.KeyFrames.Add(frame3);
Storyboard.SetTarget(frames, ellipse);
Storyboard.SetTargetProperty(frames, new PropertyPath(MarginProperty));
Storyboard.Children.Add(frames);
PrivateCanvas.Children.Add(ellipse);
}
Storyboard.Begin();
}
private Ellipse CreateEllipse(int index, double dotInterval, double dotDiameter)
{
var ellipse = base.CreateEllipse(index);
ellipse.HorizontalAlignment = HorizontalAlignment.Left;
ellipse.VerticalAlignment = VerticalAlignment.Top;
ellipse.Margin = new Thickness(-(dotInterval + dotDiameter) * index, 0, 0, 0);
return ellipse;
}
}
}
| 35.106195 | 111 | 0.53214 | [
"MIT"
] | Epacik/HandyControl | src/Shared/HandyControl_Shared/Controls/Loading/LoadingLine.cs | 4,061 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Programmer.Environment.Conditions
{
public enum CondType
{
None,
Invalid,
HasOption,
HasNotOption,
OptionEquals,
OptionNotEquals
}
}
| 16.166667 | 43 | 0.642612 | [
"MIT"
] | teplofizik/nyaprog | NyaProg/Programmer/Environment/Conditions/CondType.cs | 293 | C# |
using Application.DTOs.Account;
using Application.Wrappers;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Application.Interfaces
{
public interface IAccountService
{
Task<Response<AuthenticationResponse>> AuthenticateAsync(AuthenticationRequest request, string ipAddress);
Task<Response<string>> RegisterAsync(RegisterRequest request, string origin);
Task<Response<string>> ConfirmEmailAsync(string userId, string code);
Task ForgotPassword(ForgotPasswordRequest model, string origin);
Task<Response<string>> ResetPassword(ResetPasswordRequest model);
}
}
| 35.5 | 114 | 0.778873 | [
"MIT"
] | AhmedAboughosen/CleanArchitecture | Application/Interfaces/IAccountService.cs | 712 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.