Here are the examples of the csharp api System.Collections.Generic.IEnumerable.FirstOrDefault(System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
13333 Examples
19
View Source File : Frontend.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
private void HandleRequest(HttpRequestEventArgs c) {
Logger.Log(LogLevel.VVV, "frontend", $"{c.Request.RemoteEndPoint} requested: {c.Request.RawUrl}");
string url = c.Request.RawUrl;
int indexOfSplit = url.IndexOf('?');
if (indexOfSplit != -1)
url = url.Substring(0, indexOfSplit);
RCEndpoint? endpoint =
EndPoints.FirstOrDefault(ep => ep.Path == c.Request.RawUrl) ??
EndPoints.FirstOrDefault(ep => ep.Path == url) ??
EndPoints.FirstOrDefault(ep => ep.Path.ToLowerInvariant() == c.Request.RawUrl.ToLowerInvariant()) ??
EndPoints.FirstOrDefault(ep => ep.Path.ToLowerInvariant() == url.ToLowerInvariant());
if (endpoint == null) {
RespondContent(c, "frontend/" + url.Substring(1));
return;
}
c.Response.Headers.Set("Cache-Control", "no-store, max-age=0, s-maxage=0, no-cache, no-transform");
if (endpoint.Auth && !IsAuthorized(c)) {
c.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
RespondJSON(c, new {
Error = "Unauthorized."
});
return;
}
endpoint.Handle(this, c);
}
19
View Source File : CelesteNetClientRC.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
private static void HandleRequest(HttpListenerContext c) {
Logger.Log(LogLevel.VVV, "rc", $"Requested: {c.Request.RawUrl}");
string url = c.Request.RawUrl;
int indexOfSplit = url.IndexOf('?');
if (indexOfSplit != -1)
url = url.Substring(0, indexOfSplit);
RCEndPoint endpoint =
EndPoints.FirstOrDefault(ep => ep.Path == c.Request.RawUrl) ??
EndPoints.FirstOrDefault(ep => ep.Path == url) ??
EndPoints.FirstOrDefault(ep => ep.Path.ToLowerInvariant() == c.Request.RawUrl.ToLowerInvariant()) ??
EndPoints.FirstOrDefault(ep => ep.Path.ToLowerInvariant() == url.ToLowerInvariant()) ??
EndPoints.FirstOrDefault(ep => ep.Path == "/404");
endpoint.Handle(c);
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public static IReadOnlyList<NodeModel> BuildModelRoslyn(string projectFolder)
{
List<NodeModel> result = new List<NodeModel>();
var files = Directory.EnumerateFiles(Path.Combine(projectFolder, "Syntax"), "*.cs", SearchOption.AllDirectories);
files = files.Concat(Directory.EnumerateFiles(projectFolder, "IExpr*.cs"));
var trees = files.Select(f => CSharpSyntaxTree.ParseText(File.ReadAllText(f))).ToList();
var cSharpCompilation = CSharpCompilation.Create("Syntax", trees);
foreach (var tree in trees)
{
var semantic = cSharpCompilation.GetSemanticModel(tree);
foreach (var clreplacedDeclarationSyntax in tree.GetRoot().DescendantNodesAndSelf().OfType<ClreplacedDeclarationSyntax>())
{
var clreplacedSymbol = semantic.GetDeclaredSymbol(clreplacedDeclarationSyntax);
var isSuitable = clreplacedSymbol != null
&& !clreplacedSymbol.IsAbstract
&& clreplacedSymbol.DeclaredAccessibility == Accessibility.Public
&& IsExpr(clreplacedSymbol)
&& clreplacedSymbol.Name.StartsWith("Expr");
if (!isSuitable)
{
continue;
}
var properties = GetProperties(clreplacedSymbol);
var subNodes = new List<SubNodeModel>();
var modelProps = new List<SubNodeModel>();
foreach (var constructor in clreplacedSymbol.Constructors)
{
foreach (var parameter in constructor.Parameters)
{
INamedTypeSymbol pType = (INamedTypeSymbol)parameter.Type;
var correspondingProperty = properties.FirstOrDefault(prop =>
string.Equals(prop.Name,
parameter.Name,
StringComparison.CurrentCultureIgnoreCase));
if (correspondingProperty == null)
{
throw new Exception(
$"Could not find a property for the constructor arg: '{parameter.Name}'");
}
var ta = replacedyzeSymbol(ref pType);
var subNodeModel = new SubNodeModel(correspondingProperty.Name,
parameter.Name,
pType.Name,
ta.ListName,
ta.IsNullable,
ta.HostTypeName);
if (ta.Expr)
{
subNodes.Add(subNodeModel);
}
else
{
modelProps.Add(subNodeModel);
}
}
}
result.Add(new NodeModel(clreplacedSymbol.Name,
modelProps.Count == 0 && subNodes.Count == 0,
subNodes,
modelProps));
}
}
result.Sort((a, b) => string.CompareOrdinal(a.TypeName, b.TypeName));
return result;
bool IsExpr(INamedTypeSymbol symbol)
{
if (symbol.Name == "IExpr")
{
return true;
}
while (symbol != null)
{
if (symbol.Interfaces.Any(HasA))
{
return true;
}
symbol = symbol.BaseType;
}
return false;
bool HasA(INamedTypeSymbol iSym)
{
if (iSym.Name == "IExpr")
{
return true;
}
return IsExpr(iSym);
}
}
List<ISymbol> GetProperties(INamedTypeSymbol symbol)
{
List<ISymbol> result = new List<ISymbol>();
while (symbol != null)
{
result.AddRange(symbol.GetMembers().Where(m => m.Kind == SymbolKind.Property));
symbol = symbol.BaseType;
}
return result;
}
Symbolreplacedysis replacedyzeSymbol(ref INamedTypeSymbol typeSymbol)
{
string listName = null;
string hostType = null;
if (typeSymbol.ContainingType != null)
{
var host = typeSymbol.ContainingType;
hostType = host.Name;
}
var nullable = typeSymbol.NullableAnnotation == NullableAnnotation.Annotated;
if (nullable && typeSymbol.Name == "Nullable")
{
typeSymbol = (INamedTypeSymbol)typeSymbol.TypeArguments.Single();
}
if (typeSymbol.IsGenericType)
{
if (typeSymbol.Name.Contains("List"))
{
listName = typeSymbol.Name;
}
if (typeSymbol.Name == "Nullable")
{
nullable = true;
}
typeSymbol = (INamedTypeSymbol)typeSymbol.TypeArguments.Single();
}
return new Symbolreplacedysis(nullable, listName, IsExpr(typeSymbol), hostType);
}
}
19
View Source File : CompressionMessageHandler.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (isServer && request.Content?.Headers?.ContentEncoding != null)
{
var encoding = request.Content.Headers.ContentEncoding.FirstOrDefault();
if (encoding != null)
{
var compressor = Compressors.FirstOrDefault(c => c.EncodingType.Equals(encoding, StringComparison.InvariantCultureIgnoreCase));
if (compressor != null)
request.Content = new DecompressedContent(request.Content, compressor);
}
}
if (isClient && (request.Method == HttpMethod.Post || request.Method == HttpMethod.Put) && request.Content != null && request.Headers != null && request.Headers.Contains(PostCompressionFlag))
{
var encoding = request.Headers.GetValues(PostCompressionFlag).FirstOrDefault();
if (encoding != null)
{
var compressor = Compressors.FirstOrDefault(c => c.EncodingType.Equals(encoding, StringComparison.InvariantCultureIgnoreCase));
if (compressor != null)
request.Content = new CompressedContent(request.Content, compressor);
}
}
request.Headers?.Remove(PostCompressionFlag);
var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
if (isClient && response.Content?.Headers?.ContentEncoding != null)
{
var encoding = response.Content.Headers.ContentEncoding.FirstOrDefault();
if (encoding != null)
{
var compressor = Compressors.FirstOrDefault(c => c.EncodingType.Equals(encoding, StringComparison.InvariantCultureIgnoreCase));
if (compressor != null)
response.Content = new DecompressedContent(response.Content, compressor);
}
}
if (isServer && response.Content != null && request.Headers?.AcceptEncoding != null)
{
var encoding = request.Headers.AcceptEncoding.FirstOrDefault();
if (encoding == null)
return response;
var compressor = Compressors.FirstOrDefault(c => c.EncodingType.Equals(encoding.Value, StringComparison.InvariantCultureIgnoreCase));
if (compressor == null)
return response;
response.Content = new CompressedContent(response.Content, compressor);
}
return response;
}
19
View Source File : IPHelper.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public static IPAddress GetLocalInternetIp()
{
return NetworkInterface
.GetAllNetworkInterfaces()
.Select(p => p.GetIPProperties())
.SelectMany(p =>
p.UnicastAddresses
).FirstOrDefault(p => p.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(p.Address) && InternalIp(p.Address))?.Address;
}
19
View Source File : ReflectHelper.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public static Type Find(string typeFullName)
{
return Types.FirstOrDefault(p => p.FullName == typeFullName);
}
19
View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public async Task DumpAsync(string output)
{
// check and create output folder
var dumpPath = output;
while (!string.IsNullOrEmpty(dumpPath) && !Directory.Exists(dumpPath))
{
var parent = Path.GetDirectoryName(dumpPath);
if (parent == null || parent == dumpPath)
dumpPath = null;
else
dumpPath = parent;
}
if (filesystemStructure is null)
(filesystemStructure, emptyDirStructure) = GetFilesystemStructure();
var validators = GetValidationInfo();
if (!string.IsNullOrEmpty(dumpPath))
{
var root = Path.GetPathRoot(Path.GetFullPath(output));
var drive = DriveInfo.GetDrives().FirstOrDefault(d => d?.RootDirectory.FullName.StartsWith(root) ?? false);
if (drive != null)
{
var spaceAvailable = drive.AvailableFreeSpace;
TotalFileSize = filesystemStructure.Sum(f => f.Length);
var diff = TotalFileSize + 100 * 1024 - spaceAvailable;
if (diff > 0)
Log.Warn($"Target drive might require {diff.replacedtorageUnit()} of additional free space");
}
}
foreach (var dir in emptyDirStructure)
Log.Trace($"Empty dir: {dir}");
foreach (var file in filesystemStructure)
Log.Trace($"0x{file.StartSector:x8}: {file.Filename} ({file.Length})");
var outputPathBase = Path.Combine(output, OutputDir);
if (!Directory.Exists(outputPathBase))
Directory.CreateDirectory(outputPathBase);
TotalFileCount = filesystemStructure.Count;
TotalSectors = discReader.TotalClusters;
Log.Debug("Using decryption key: " + allMatchingKeys.First().DecryptedKeyId);
var decryptionKey = allMatchingKeys.First().DecryptedKey;
var sectorSize = (int)discReader.ClusterSize;
var unprotectedRegions = driveStream.GetUnprotectedRegions();
ValidationStatus = true;
foreach (var dir in emptyDirStructure)
{
try
{
if (Cts.IsCancellationRequested)
return;
var convertedName = Path.DirectorySeparatorChar == '\\' ? dir : dir.Replace('\\', Path.DirectorySeparatorChar);
var outputName = Path.Combine(outputPathBase, convertedName);
if (!Directory.Exists(outputName))
{
Log.Debug("Creating empty directory " + outputName);
Directory.CreateDirectory(outputName);
}
}
catch (Exception ex)
{
Log.Error(ex);
BrokenFiles.Add((dir, "Unexpected error: " + ex.Message));
}
}
foreach (var file in filesystemStructure)
{
try
{
if (Cts.IsCancellationRequested)
return;
Log.Info($"Reading {file.Filename} ({file.Length.replacedtorageUnit()})");
CurrentFileNumber++;
var convertedFilename = Path.DirectorySeparatorChar == '\\' ? file.Filename : file.Filename.Replace('\\', Path.DirectorySeparatorChar);
var inputFilename = Path.Combine(input, convertedFilename);
if (!File.Exists(inputFilename))
{
Log.Error($"Missing {file.Filename}");
BrokenFiles.Add((file.Filename, "missing"));
continue;
}
var outputFilename = Path.Combine(outputPathBase, convertedFilename);
var fileDir = Path.GetDirectoryName(outputFilename);
if (!Directory.Exists(fileDir))
{
Log.Debug("Creating directory " + fileDir);
Directory.CreateDirectory(fileDir);
}
var error = false;
var expectedHashes = (
from v in validators
where v.Files.ContainsKey(file.Filename)
select v.Files[file.Filename].Hashes
).ToList();
var lastHash = "";
var tries = 2;
do
{
try
{
tries--;
using var outputStream = File.Open(outputFilename, FileMode.Create, FileAccess.Write, FileShare.Read);
using var inputStream = File.Open(inputFilename, FileMode.Open, FileAccess.Read, FileShare.Read);
using var decrypter = new Decrypter(inputStream, driveStream, decryptionKey, file.StartSector, sectorSize, unprotectedRegions);
Decrypter = decrypter;
await decrypter.CopyToAsync(outputStream, 8 * 1024 * 1024, Cts.Token).ConfigureAwait(false);
outputStream.Flush();
var resultHashes = decrypter.GetHashes();
var resultMd5 = resultHashes["MD5"];
if (decrypter.WasEncrypted && decrypter.WasUnprotected)
Log.Debug("Partially decrypted " + file.Filename);
else if (decrypter.WasEncrypted)
Log.Debug("Decrypted " + file.Filename);
if (!expectedHashes.Any())
{
if (ValidationStatus == true)
ValidationStatus = null;
}
else if (!IsMatch(resultHashes, expectedHashes))
{
error = true;
var msg = "Unexpected hash: " + resultMd5;
if (resultMd5 == lastHash || decrypter.LastBlockCorrupted)
{
Log.Error(msg);
BrokenFiles.Add((file.Filename, "corrupted"));
break;
}
Log.Warn(msg + ", retrying");
}
lastHash = resultMd5;
}
catch (Exception e)
{
Log.Error(e, e.Message);
error = true;
}
} while (error && tries > 0 && !Cts.IsCancellationRequested);
}
catch (Exception ex)
{
Log.Error(ex);
BrokenFiles.Add((file.Filename, "Unexpected error: " + ex.Message));
}
}
Log.Info("Completed");
}
19
View Source File : DefaultConfigProvider.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public TConfig Get<TConfig>() where TConfig : IConfig, new()
{
var item = Configs.FirstOrDefault(m => m.Key.Value == typeof(TConfig).TypeHandle.Value);
if (item.Value != null)
{
return (TConfig)item.Value;
}
return new TConfig();
}
19
View Source File : SqlServerCodeFirstProvider.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
private void UpdateColumn(IEnreplacedyDescriptor descriptor, IDbConnection con)
{
var columns = Context.SchemaProvider.GetColumns(con.Database, descriptor.TableName);
//保存删除后的列信息
var cleanColumns = new List<ColumnSchema>();
//删除列
foreach (var column in columns)
{
//如果列名称、列类型或者可空配置不一样,则删除重建
var deleted = descriptor.Columns.FirstOrDefault(m => m.Name.Equals(column.Name));
if (deleted == null || CompareColumnInfo(deleted, column))
{
//删除主键约束
if (column.IsPrimaryKey)
{
var key = con.ExecuteScalar<string>($"SELECT name FROM sys.key_constraints WHERE parent_object_id = OBJECT_ID('{descriptor.TableName}')");
if (key.NotNull())
{
con.Execute($"ALTER TABLE {AppendQuote(descriptor.TableName)} DROP CONSTRAINT {key}");
}
}
//删除默认值约束
if (column.DefaultValue.NotNull())
{
var key = con.ExecuteScalar<string>($"SELECT name FROM sys.default_constraints WHERE parent_object_id = OBJECT_ID('{descriptor.TableName}') AND parent_column_id=(SELECT column_id FROM sys.columns WHERE [object_id] = OBJECT_ID('{descriptor.TableName}') AND name = '{column.Name}')");
if (key.NotNull())
{
con.Execute($"ALTER TABLE {AppendQuote(descriptor.TableName)} DROP CONSTRAINT {key}");
}
}
var deleteSql = $"ALTER TABLE {AppendQuote(descriptor.TableName)} DROP COLUMN {AppendQuote(column.Name)};";
con.Execute(deleteSql);
}
else
{
cleanColumns.Add(column);
}
}
//添加列
foreach (var column in descriptor.Columns)
{
var add = cleanColumns.FirstOrDefault(m => m.Name.Equals(column.Name));
if (add == null)
{
var addSql = $"ALTER TABLE {AppendQuote(descriptor.TableName)} ADD {GenerateColumnAddSql(column, descriptor)};";
addSql += $"EXECUTE sp_addextendedproperty N'MS_Description','{column.Description}',N'user',N'dbo',N'table',N'{descriptor.TableName}',N'column',N'{column.Name}';";
con.Execute(addSql);
}
}
}
19
View Source File : ModuleDescriptor.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public ModuleEnumDescriptor GetEnum(string enumName)
{
return EnumDescriptors.FirstOrDefault(m => m.Name.Equals(enumName));
}
19
View Source File : TestSite.cs
License : MIT License
Project Creator : 188867052
License : MIT License
Project Creator : 188867052
public IList<RouteInfo> GetAllRouteInfo()
{
var dllFile = Directory.GetFiles(Environment.CurrentDirectory, $"{this.projectName}.dll", SearchOption.AllDirectories).FirstOrDefault();
if (string.IsNullOrEmpty(dllFile))
{
throw new ArgumentException($"No {this.projectName}.dll file found under the directory: {Environment.CurrentDirectory}.");
}
Console.WriteLine($"the project name:{this.projectName}.");
Console.WriteLine($"find dll file:{dllFile}.");
replacedembly replacedembly = replacedembly.LoadFile(dllFile);
Type type = replacedembly.GetTypes().FirstOrDefault(o => o.Name == "Startup");
if (type == null)
{
throw new ArgumentException($"No Startup.cs clreplaced found under the dll file: {dllFile}.");
}
var builder = new WebHostBuilder()
.UseEnvironment("Development")
.UseContentRoot(AppContext.BaseDirectory)
.UseStartup(type);
TestServer server = new TestServer(builder);
IRoutereplacedyzer services = (IRoutereplacedyzer)server.Host.Services.GetService(typeof(IRoutereplacedyzer));
var client = server.CreateClient();
return services.GetAllRouteInfo();
}
19
View Source File : ControllerResolver.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public List<ActionDescriptor> GetActions(string area, string name)
{
return Controllers.FirstOrDefault(m => m.Area.EqualsIgnoreCase(area) && m.Name.EqualsIgnoreCase(name))?.Actions;
}
19
View Source File : MySqlCodeFirstProvider.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
private void UpdateColumn(IEnreplacedyDescriptor descriptor, IDbConnection con)
{
var columns = Context.SchemaProvider.GetColumns(con.Database, descriptor.TableName);
//保存删除后的列信息
var cleanColumns = new List<ColumnSchema>();
//删除列
foreach (var column in columns)
{
//如果列名称、列类型或者可空配置不一样,则删除重建
var deleted = descriptor.Columns.FirstOrDefault(m => m.Name.Equals(column.Name));
if (deleted == null || CompareColumnInfo(deleted, column))
{
var deleteSql = $"ALTER TABLE {AppendQuote(descriptor.TableName)} DROP COLUMN {AppendQuote(column.Name)};";
con.Execute(deleteSql);
}
else
{
cleanColumns.Add(column);
}
}
//添加列
foreach (var column in descriptor.Columns)
{
var add = cleanColumns.FirstOrDefault(m => m.Name.Equals(column.Name));
if (add == null)
{
var addSql = $"ALTER TABLE {AppendQuote(descriptor.TableName)} ADD COLUMN {GenerateColumnAddSql(column, descriptor)}";
con.Execute(addSql);
}
}
}
19
View Source File : Globals.cs
License : MIT License
Project Creator : 1ZouLTReX1
License : MIT License
Project Creator : 1ZouLTReX1
public static IPAddress GetLocalIPAddress()
{
var cards = NetworkInterface.GetAllNetworkInterfaces().ToList();
foreach (var card in cards)
{
if (card.NetworkInterfaceType != NetworkInterfaceType.Ethernet)
continue;
var props = card.GetIPProperties();
if (props == null)
continue;
var gateways = props.GatewayAddresses;
if (!gateways.Any())
continue;
var gateway = gateways.FirstOrDefault(g => g.Address.AddressFamily == AddressFamily.InterNetwork);
if (gateway == null)
continue;
foreach (IPAddress ip in props.UnicastAddresses.Select(x => x.Address))
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip;
}
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
19
View Source File : FauxDeployCMAgent.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne
License : GNU General Public License v3.0
Project Creator : 1RedOne
public static void SendDiscovery(string CMServerName, string clientName, string domainName, string SiteCode,
string CertPath, SecureString preplaced, SmsClientId clientId, ILog log, bool enumerateAndAddCustomDdr = false)
{
using (MessageCertificateX509Volatile certificate = new MessageCertificateX509Volatile(CertPath, preplaced))
{
//X509Certificate2 thisCert = new X509Certificate2(CertPath, preplaced);
log.Info($"Got SMSID from registration of: {clientId}");
// create base DDR Message
ConfigMgrDataDiscoveryRecordMessage ddrMessage = new ConfigMgrDataDiscoveryRecordMessage
{
// Add necessary discovery data
SmsId = clientId,
ADSiteName = "Default-First-Site-Name", //Changed from 'My-AD-SiteName
SiteCode = SiteCode,
DomainName = domainName,
NetBiosName = clientName
};
ddrMessage.Discover();
// Add our certificate for message signing
ddrMessage.AddCertificateToMessage(certificate, CertificatePurposes.Signing);
ddrMessage.AddCertificateToMessage(certificate, CertificatePurposes.Encryption);
ddrMessage.Settings.HostName = CMServerName;
ddrMessage.Settings.Compression = MessageCompression.Zlib;
ddrMessage.Settings.ReplyCompression = MessageCompression.Zlib;
Debug.WriteLine("Sending [" + ddrMessage.DdrInstances.Count + "] instances of Discovery data to CM");
if (enumerateAndAddCustomDdr)
{
//see current value for the DDR message
var OSSetting = ddrMessage.DdrInstances.OfType<InventoryInstance>().Where(m => m.Clreplaced == "CCM_DiscoveryData");
////retrieve actual setting
string osCaption = (from x in new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem").Get().Cast<ManagementObject>()
select x.GetPropertyValue("Caption")).FirstOrDefault().ToString();
XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
////retrieve reported value
xmlDoc.LoadXml(ddrMessage.DdrInstances.OfType<InventoryInstance>().FirstOrDefault(m => m.Clreplaced == "CCM_DiscoveryData")?.InstanceDataXml.ToString());
////Set OS to correct setting
xmlDoc.SelectSingleNode("/CCM_DiscoveryData/PlatformID").InnerText = "Microsoft Windows NT Server 10.0";
////Remove the instance
ddrMessage.DdrInstances.Remove(ddrMessage.DdrInstances.OfType<InventoryInstance>().FirstOrDefault(m => m.Clreplaced == "CCM_DiscoveryData"));
CMFauxStatusViewClreplacedesFixedOSRecord FixedOSRecord = new CMFauxStatusViewClreplacedesFixedOSRecord
{
PlatformId = osCaption
};
InventoryInstance instance = new InventoryInstance(FixedOSRecord);
////Add new instance
ddrMessage.DdrInstances.Add(instance);
}
ddrMessage.SendMessage(Sender);
ConfigMgrHardwareInventoryMessage hinvMessage = new ConfigMgrHardwareInventoryMessage();
hinvMessage.Settings.HostName = CMServerName;
hinvMessage.SmsId = clientId;
hinvMessage.Settings.Compression = MessageCompression.Zlib;
hinvMessage.Settings.ReplyCompression = MessageCompression.Zlib;
//hinvMessage.Settings.Security.EncryptMessage = true;
hinvMessage.Discover();
var Clreplacedes = CMFauxStatusViewClreplacedes.GetWMIClreplacedes();
foreach (string Clreplaced in Clreplacedes)
{
try { hinvMessage.AddInstancesToInventory(WmiClreplacedToInventoryReportInstance.WmiClreplacedToInventoryInstances(@"root\cimv2", Clreplaced)); }
catch { log.Info($"!!!Adding clreplaced : [{Clreplaced}] :( not found on this system"); }
}
var SMSClreplacedes = new List<string> { "SMS_Processor", "CCM_System", "SMS_LogicalDisk" };
foreach (string Clreplaced in SMSClreplacedes)
{
log.Info($"---Adding clreplaced : [{Clreplaced}]");
try { hinvMessage.AddInstancesToInventory(WmiClreplacedToInventoryReportInstance.WmiClreplacedToInventoryInstances(@"root\cimv2\sms", Clreplaced)); }
catch { log.Info($"!!!Adding clreplaced : [{Clreplaced}] :( not found on this system"); }
}
hinvMessage.AddCertificateToMessage(certificate, CertificatePurposes.Signing | CertificatePurposes.Encryption);
hinvMessage.Validate(Sender);
hinvMessage.SendMessage(Sender);
};
}
19
View Source File : WorldState.cs
License : MIT License
Project Creator : 1ZouLTReX1
License : MIT License
Project Creator : 1ZouLTReX1
public static void Interp(List<PlayerState> prevStates, List<PlayerState> nextStates, float f,
ref List<PlayerState> playerStates)
{
playerStates.Clear();
PlayerState temp;
foreach (var nextState in nextStates)
{
var prevState = prevStates.FirstOrDefault(x => x.playerId == nextState.playerId);
// Check whether the end result is also contained in the start snapshot
// if so we can interpolate otherwise we simply set the value.
if (!nextState.Equals(default(PlayerState))) {
// interpolate
var interpPosition = Vector2.Lerp(prevState.pos, nextState.pos, f);
var interpRotation = Mathf.LerpAngle(prevState.zAngle, nextState.zAngle, f);
temp = new PlayerState(nextState.playerId, interpRotation, interpPosition);
playerStates.Add(temp);
}
else
{
// set the value directly
playerStates.Add(nextState);
}
}
}
19
View Source File : JcApiHelper.cs
License : MIT License
Project Creator : 279328316
License : MIT License
Project Creator : 279328316
public static ControllerModel GetController(string controllerId)
{
ControllerModel controller = controllerList.FirstOrDefault(a=>a.Id== controllerId);
if (controller != null)
{
SetControllerNote(controller);
}
return controller;
}
19
View Source File : JcApiHelper.cs
License : MIT License
Project Creator : 279328316
License : MIT License
Project Creator : 279328316
public static ActionModel GetAction(string actionId)
{
ActionModel actionModel = null;
ControllerModel controllerModel = controllerList.FirstOrDefault(controller =>
controller.ActionList.Any(action => action.Id == actionId));
if (controllerModel != null)
{
SetControllerNote(controllerModel);
actionModel = controllerModel.ActionList.FirstOrDefault(action => action.Id == actionId);
}
return actionModel;
}
19
View Source File : JcApiHelper.cs
License : MIT License
Project Creator : 279328316
License : MIT License
Project Creator : 279328316
private static void InitAllControllerNote()
{
List<replacedemblyNoteModel> noteList = new List<replacedemblyNoteModel>();
#region 处理replacedemblyNote
List<string> moduleList = controllerList.Select(controller => controller.ModuleName).Distinct().ToList();
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
DirectoryInfo dirInfo = new DirectoryInfo(baseDir);
for (int i = 0; i < moduleList.Count; i++)
{
string xmlNoteFileName = moduleList[i].Replace(".dll", ".xml");
FileInfo fileInfo = dirInfo.GetFiles(xmlNoteFileName, SearchOption.AllDirectories).FirstOrDefault();
if (fileInfo != null)
{
replacedemblyNoteModel noteModel = replacedemblyHelper.GetreplacedemblyNote(fileInfo.FullName);
noteList.Add(noteModel);
}
}
#endregion
for (int i = 0; i < controllerList.Count; i++)
{
ControllerModel controller = controllerList[i];
replacedemblyNoteModel noteModel = noteList.FirstOrDefault(note => note.ModuleName == controller.ModuleName);
if (noteModel == null)
{
continue;
}
//Controller 注释
controller.NoteModel = noteModel.MemberList.FirstOrDefault(member => member.Name == controller.Id);
foreach (ActionModel action in controller.ActionList)
{ //Action注释
action.NoteModel = noteModel.MemberList.FirstOrDefault(member => member.Name == action.Id);
if (action.NoteModel != null)
{
foreach (ParamModel param in action.InputParameters)
{ //输入参数注释
if (action.NoteModel.ParamList.Keys.Contains(param.Name))
{
param.Summary = action.NoteModel.ParamList[param.Name];
}
}
//返回参数注释
action.ReturnParameter.Summary = action.NoteModel.Returns;
}
}
}
}
19
View Source File : XmlHelper.cs
License : MIT License
Project Creator : 279328316
License : MIT License
Project Creator : 279328316
public T DeserializeNode<T>(XmlNode node = null) where T : clreplaced, new()
{
T model = new T();
XmlNode firstChild;
if (node == null)
{
node = root;
}
firstChild = node.FirstChild;
Dictionary<string, string> dict = new Dictionary<string, string>();
XmlAttributeCollection xmlAttribute = node.Attributes;
if (node.Attributes.Count > 0)
{
for (int i = 0; i < node.Attributes.Count; i++)
{
if (!dict.Keys.Contains(node.Attributes[i].Name))
{
dict.Add(node.Attributes[i].Name, node.Attributes[i].Value);
}
}
}
if (!dict.Keys.Contains(firstChild.Name))
{
dict.Add(firstChild.Name, firstChild.InnerText);
}
XmlNode next = firstChild.NextSibling;
while (next != null)
{
if (!dict.Keys.Contains(next.Name))
{
dict.Add(next.Name, next.InnerText);
}
else
{
throw new Exception($"重复的属性Key:{next.Name}");
}
next = next.NextSibling;
}
#region 为对象赋值
Type modelType = typeof(T);
List<PropertyInfo> piList = modelType.GetProperties().Where(pro => (pro.PropertyType.Equals(typeof(string)) || pro.PropertyType.IsValueType) && pro.CanRead && pro.CanWrite).ToList();
foreach (PropertyInfo pi in piList)
{
string dictKey = dict.Keys.FirstOrDefault(key => key.ToLower() == pi.Name.ToLower());
if (!string.IsNullOrEmpty(dictKey))
{
string value = dict[dictKey];
TypeConverter typeConverter = TypeDescriptor.GetConverter(pi.PropertyType);
if (typeConverter != null)
{
if (typeConverter.CanConvertFrom(typeof(string)))
pi.SetValue(model, typeConverter.ConvertFromString(value));
else
{
if (typeConverter.CanConvertTo(pi.PropertyType))
pi.SetValue(model, typeConverter.ConvertTo(value, pi.PropertyType));
}
}
}
}
#endregion
return model;
}
19
View Source File : ApiHelperController.cs
License : MIT License
Project Creator : 279328316
License : MIT License
Project Creator : 279328316
[HttpPost]
[AllowAnonymous]
[Route("[action]")]
public IActionResult GetApiVersion()
{
Robj<string> robj = new Robj<string>();
List<replacedembly> replacedemblyList = AppDomain.CurrentDomain.Getreplacedemblies().ToList();
AppDomain currentDomain = AppDomain.CurrentDomain;
replacedembly replacedembly = replacedemblyList.FirstOrDefault(a=>a.GetName().Name==currentDomain.FriendlyName);
if (replacedembly != null)
{
//replacedemblyFileVersionAttribute fileVersionAttr = replacedembly.GetCustomAttribute<replacedemblyFileVersionAttribute>();
replacedemblyInformationalVersionAttribute versionAttr = replacedembly.GetCustomAttribute<replacedemblyInformationalVersionAttribute>();
robj.Result = versionAttr?.InformationalVersion;
}
return new JsonResult(robj);
}
19
View Source File : UCGeneratedCode.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
void InitTableInfo()
{
dbTableInfos = _node.Parent.Nodes.Cast<Node>()
.Select(a => a.Tag as DbTableInfo).ToList();
//G.GetTablesByDatabase(_node.Parent.DataKey, _node.Parent.Text);
dbTableInfo = dbTableInfos.FirstOrDefault(a => a.Name == _node.Text);
dataGridViewX1.DataSource = dbTableInfo?.Columns;
}
19
View Source File : VRHeightOffset.cs
License : MIT License
Project Creator : 39M
License : MIT License
Project Creator : 39M
void Start() {
if (VRDevice.isPresent && VRSettings.enabled && _deviceOffsets != null) {
#if UNITY_5_4_OR_NEWER
string deviceName = VRSettings.loadedDeviceName;
#else
string deviceName = VRDevice.family;
#endif
var deviceHeightPair = _deviceOffsets.FirstOrDefault(d => deviceName.ToLower().Contains(d.DeviceName.ToLower()));
if (deviceHeightPair != null) {
transform.Translate(Vector3.up * deviceHeightPair.HeightOffset);
}
}
}
19
View Source File : ProjectReferences.cs
License : MIT License
Project Creator : 3F
License : MIT License
Project Creator : 3F
private string ExtarctProjectGuid(Item item)
{
const string _PK = "Project";
if(item.meta.ContainsKey(_PK)) return item.meta[_PK].evaluated;
return XProjects.FirstOrDefault(
p => p.Projecreplacedem.project.fullPath == p.GetFullPath(item.evaluatedInclude)
)?
.ProjectGuid;
}
19
View Source File : ExampleScript.cs
License : GNU Affero General Public License v3.0
Project Creator : 3drepo
License : GNU Affero General Public License v3.0
Project Creator : 3drepo
private void SearchMetadata(RepoForUnity.Model[] models)
{
/**
* The following illustrates how you would perform a metadata search.
* Here, I search for all metadata which has a property "Floor".
*/
var model = models.FirstOrDefault(item => item.modelId == subModelID);
var results = model.GetAllMetadataWithField("Floor");
Debug.Log(results.Length + " entries have the property \"Floor\"");
}
19
View Source File : ExampleScript.cs
License : GNU Affero General Public License v3.0
Project Creator : 3drepo
License : GNU Affero General Public License v3.0
Project Creator : 3drepo
private void IdentifyAMeshAndFetchMetadata(RepoForUnity.Model[] models)
{
/**
* The following illustrate how you can identify a sub mesh within a supermesh after
* you have found it's supermesh ID and index.
*
* As meshes are batched into supermeshes, identifying a single mesh can be tricky.
* All meshes are encoded with an index within the UV2 element.
*
* In order to find a submesh from view (e.g. if you're trying to implement object selection), first
* do a Raycast to the point to identify index from the UV2.y value.
*
* Then identify the supermesh it belongs to. This is the name of the parent GameObject.
*/
var model = models.FirstOrDefault(item => item.modelId == subModelID);
var superMesh = "2967230f-67fa-45dc-9686-161e45c7c8a2";
var meshID = model.GetSubMeshId(superMesh, 0);
Debug.Log("[" + model.teamspace + "." + model.name + "]The first mesh within " + superMesh + " is " + meshID);
GetMetadataInfo(model, meshID);
}
19
View Source File : Guids.cs
License : MIT License
Project Creator : 3F
License : MIT License
Project Creator : 3F
public static ProjectType ProjectTypeBy(string guid)
{
return projectTypeGuids.FirstOrDefault(p => p.Value == guid).Key;
}
19
View Source File : XProjectEnv.cs
License : MIT License
Project Creator : 3F
License : MIT License
Project Creator : 3F
public IXProject XProjectByGuid(string guid, IConfPlatform cfg)
{
return Projects?.FirstOrDefault(p =>
Eq(p.Projecreplacedem.projectConfig, cfg) && (p.ProjectGuid == guid)
);
}
19
View Source File : XProjectEnv.cs
License : MIT License
Project Creator : 3F
License : MIT License
Project Creator : 3F
protected IXProject XProjectByFile(string file, IConfPlatform cfg, bool tryLoad, IDictionary<string, string> props)
{
var found = Projects?.FirstOrDefault(p =>
Eq(p.Projecreplacedem.projectConfig, cfg) && (p.ProjectFullPath == file)
);
if(found != null || !tryLoad || string.IsNullOrWhiteSpace(file)) {
return found;
}
return AddOrGet(GetOrLoadProject
(
GetProjecreplacedem(file, props),
DefProperties(cfg, slnProperties.ToDictionary(k => k.Key, v => v.Value).AddOrUpdate(props))
));
}
19
View Source File : FileExt.cs
License : MIT License
Project Creator : 3F
License : MIT License
Project Creator : 3F
public static ProjectType GetProjectTypeByExt(string ext)
{
return projectTypeFileExt.FirstOrDefault(p => p.Value == ext).Key;
}
19
View Source File : ExternalLoginInfoHelper.cs
License : MIT License
Project Creator : 52ABP
License : MIT License
Project Creator : 52ABP
public static (string name, string surname) GetNameAndSurnameFromClaims(List<Claim> claims)
{
string name = null;
string surname = null;
var givennameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName);
if (givennameClaim != null && !givennameClaim.Value.IsNullOrEmpty())
{
name = givennameClaim.Value;
}
var surnameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname);
if (surnameClaim != null && !surnameClaim.Value.IsNullOrEmpty())
{
surname = surnameClaim.Value;
}
if (name == null || surname == null)
{
var nameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.Name);
if (nameClaim != null)
{
var nameSurName = nameClaim.Value;
if (!nameSurName.IsNullOrEmpty())
{
var lastSpaceIndex = nameSurName.LastIndexOf(' ');
if (lastSpaceIndex < 1 || lastSpaceIndex > (nameSurName.Length - 2))
{
name = surname = nameSurName;
}
else
{
name = nameSurName.Substring(0, lastSpaceIndex);
surname = nameSurName.Substring(lastSpaceIndex);
}
}
}
}
return (name, surname);
}
19
View Source File : AwaitExpression.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public static AwaitExpression Await(Expression task)
{
Requires.NotNull(task, nameof(task));
MethodInfo method = task.Type.GetRuntimeMethods()
.FirstOrDefault(x => x.ReturnType == typeof(TaskAwaiter) ||
x.ReturnType.IsConstructedGenericType &&
x.ReturnType.GetGenericTypeDefinition() == typeof(TaskAwaiter<>));
if (method == null)
throw new ArgumentException("The given argument must be awaitable.", nameof(task));
return new AwaitExpression(task, method);
}
19
View Source File : MacroExpander.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
{
IOperation operation = semanticModel.GetOperation(node, cancellationToken);
if (operation == null || !operation.IsInvalid)
return base.VisitMemberAccessExpression(node);
// Expression is invalid, might be a late-bound object
IOperation expression = semanticModel.GetOperation(node.Expression, cancellationToken);
if (expression.IsInvalid)
return base.VisitMemberAccessExpression(node);
// Find out if it is a late-bound object...
INamedTypeSymbol type = expression.Type as INamedTypeSymbol;
if (type == null)
return base.VisitMemberAccessExpression(node);
// ... by finding its Bind method
object[] arguments = null;
bool IsValidBindMethod(MethodInfo mi)
{
if (!mi.IsStatic || mi.IsAbstract || mi.Name != "Bind")
return false;
if (!typeof(ExpressionSyntax).IsreplacedignableFrom(mi.ReturnType))
return false;
ParameterInfo[] parameters = mi.GetParameters();
object[] args = new object[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
Type paramType = parameters[i].ParameterType;
if (paramType.IsreplacedignableFrom(typeof(MemberAccessExpressionSyntax)))
args[i] = node;
else if (paramType == typeof(IOperation))
args[i] = expression;
else
return false;
}
arguments = args;
return true;
}
Type correspondingType = type.GetCorrespondingType();
if (correspondingType == null)
return base.VisitMemberAccessExpression(node);
MethodInfo bindMethod = correspondingType
.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
.FirstOrDefault(IsValidBindMethod);
if (bindMethod == null)
return base.VisitMemberAccessExpression(node);
// We do have a binder!
// Call the method
try
{
ExpressionSyntax result = bindMethod.Invoke(null, arguments) as ExpressionSyntax;
return result == null
? SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)
: base.Visit(result);
}
catch (Exception e)
{
throw new DiagnosticException("Error thrown by binding method.", e, node.GetLocation());
}
}
19
View Source File : SelfEditor.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
private CompilationEditor[] GetreplacedemblyChildren(replacedembly replacedembly)
{
// Find the SelfEdit attribute on replacedembly
string attrFullName = typeof(EditSelfAttribute).FullName;
CustomAttributeData attrData = replacedembly.CustomAttributes.FirstOrDefault(x => x.AttributeType.FullName == attrFullName);
if (attrData == null)
{
Report(Diagnostic.Create(LoadError, Location.None, "Could not find EditSelf attribute on compiled replacedembly."));
return null;
}
// Construct its args
var editorTypes = (IReadOnlyList<CustomAttributeTypedArgument>)attrData.ConstructorArguments[0].Value;
CompilationEditor[] editors = new CompilationEditor[editorTypes.Count];
bool failed = false;
for (int i = 0; i < editors.Length; i++)
{
if (Activator.CreateInstance(editorTypes[i].Value as Type, true) is CompilationEditor editor)
{
editors[i] = editor;
continue;
}
Report(Diagnostic.Create(LoadError, Location.None, $"Could not create editor of type '{editorTypes[i].Value}'."));
failed = true;
}
return failed ? null : editors;
}
19
View Source File : NpcCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
private async Task<bool> CheckIf(PlayerEnreplacedy player, string condition, List<CaseAttribute> attrs, string input)
{
var field = attrs.FirstOrDefault(x => x.Attr == "Field")?.Val;
var relation = attrs.FirstOrDefault(x => x.Attr == "Relation")?.Val;
var value = attrs.FirstOrDefault(x => x.Attr == "Value")?.Val;
var wareName = attrs.FirstOrDefault(x => x.Attr == "WareName")?.Val;
var number = attrs.FirstOrDefault(x => x.Attr == "Number")?.Val;
int.TryParse(attrs.FirstOrDefault(x => x.Attr == "QuestId")?.Val, out int questId);
if (string.IsNullOrEmpty(condition))
{
return true;
}
if (!Enum.TryParse(condition, true, out ConditionTypeEnum conditionEnum))
{
return true;
}
switch (conditionEnum)
{
case ConditionTypeEnum.角色属性:
if (!CheckField(player, field, value, relation))
{
return false;
}
break;
case ConditionTypeEnum.是否拥有物品:
if (!await CheckWare(player.Id, wareName, number, relation))
{
return false;
}
break;
case ConditionTypeEnum.是否领取任务:
var playerQuest = await _playerQuestDomainService.Get(x => x.QuestId == questId && x.PlayerId == player.Id);
if (playerQuest == null)
{
return false;
}
break;
case ConditionTypeEnum.是否完成任务:
break;
case ConditionTypeEnum.活动记录:
break;
}
return true;
}
19
View Source File : NpcCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
private async Task DoCommand(PlayerEnreplacedy player, NpcEnreplacedy npc, int scriptId, string command, List<CaseAttribute> attrs, string input)
{
var replacedle = attrs.FirstOrDefault(x => x.Attr == "replacedle")?.Val;
var message = attrs.FirstOrDefault(x => x.Attr == "Message")?.Val;
var tips = attrs.FirstOrDefault(x => x.Attr == "Tips")?.Val;
int.TryParse(attrs.FirstOrDefault(x => x.Attr == "CommandId")?.Val, out int commandId);
int.TryParse(attrs.FirstOrDefault(x => x.Attr == "QuestId")?.Val, out int questId);
var key = $"commandIds_{player.Id}_{npc.Id}_{scriptId}";
var commandIds = await _redisDb.StringGet<List<int>>(key) ?? new List<int>();
if (commandId > 0 && !commandIds.Contains(commandId))
{
commandIds.Add(commandId);
}
await _redisDb.StringSet(key, commandIds);
var commandEnum = (CommandTypeEnum)Enum.Parse(typeof(CommandTypeEnum), command, true);
//await _bus.RaiseEvent(new DomainNotification($"command= {command}"));
switch (commandEnum)
{
case CommandTypeEnum.播放对话:
await _mudProvider.ShowMessage(player.Id, $"{npc.Name}:{message}", MessageTypeEnum.聊天);
break;
case CommandTypeEnum.对话选项:
await _mudProvider.ShowMessage(player.Id, $" → <a href='javascript:;' clreplaced='chat' npcId='{npc.Id}' scriptId='{scriptId}' commandId='{commandId}'>{replacedle}</a><br />", MessageTypeEnum.指令);
break;
case CommandTypeEnum.输入选项:
await _mudProvider.ShowMessage(player.Id, $" → <a href = 'javascript:;'>{tips}</a> <input type = 'text' name='input' style='width:120px;margin-left:10px;' /> <button type = 'button' clreplaced='input' style='padding:1px 3px;' npcId='{npc.Id}' scriptId='{scriptId}' commandId='{commandId}'> 确定 </button><br />", MessageTypeEnum.指令);
break;
case CommandTypeEnum.跳转到分支:
await DoScript(player, npc, scriptId, commandId);
break;
case CommandTypeEnum.领取任务:
await TakeQuest(player, questId);
break;
case CommandTypeEnum.完成任务:
await ComplateQuest(player, questId);
break;
}
}
19
View Source File : ToolsService.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public bool CreateServices(string strPath, string strSolutionName, string tableName)
{
try
{
string saveFileName = $"{tableName.Replace("_", "")}Service.cs";
#region 遍历子目录查找相同IService
List<string> sourecFiles = new List<string>();
GetFiles(strPath, sourecFiles);
string readFilePath = sourecFiles.FirstOrDefault(m => m.Contains(saveFileName));
string value = "";
if (!string.IsNullOrEmpty(readFilePath))
{
value = GetCustomValue(File.ReadAllText(readFilePath), "#region CustomInterface \r\n", " #endregion\r\n");
}
#endregion
#region 模板样式
var clreplacedTemplate = $"" +
$"//------------------------------------------------------------------------------\r\n" +
$"// <auto-generated>\r\n" +
$"// 此代码已从模板生成手动更改此文件可能导致应用程序出现意外的行为。\r\n" +
$"// 如果重新生成代码,将覆盖对此文件的手动更改。\r\n" +
$"// author MEIAM\r\n" +
$"// </auto-generated>\r\n" +
$"//------------------------------------------------------------------------------\r\n" +
$"using { strSolutionName }.Model;\r\n" +
$"using { strSolutionName }.Model.Dto;\r\n" +
$"using { strSolutionName }.Model.View;\r\n" +
$"using System.Collections.Generic;\r\n" +
$"using System.Threading.Tasks;\r\n" +
$"using SqlSugar;\r\n" +
$"using System.Linq;\r\n" +
$"using System;\r\n" +
$"\r\n" +
$"namespace { strSolutionName }.Interfaces\r\n" +
$"{{\r\n" +
$" public clreplaced {tableName.Replace("_", "")}Service : BaseService<{tableName}>, I{tableName.Replace("_", "")}Service\r\n" +
$" {{\r\n" +
$"\r\n" +
$" public {tableName.Replace("_", "")}Service(IUnitOfWork unitOfWork) : base(unitOfWork)\r\n" +
$" {{\r\n" +
$" }}\r\n" +
$"\r\n" +
$" #region CustomInterface \r\n" +
$"{(string.IsNullOrWhiteSpace(value) ? "" : value)}" +
$" #endregion\r\n" +
$"\r\n" +
$" }}\r\n" +
$"}}\r\n";
#endregion
File.WriteAllText($"{ strPath }\\{saveFileName}", clreplacedTemplate);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
19
View Source File : CustomerRepository.cs
License : MIT License
Project Creator : 99x
License : MIT License
Project Creator : 99x
public CustomerModel GetCustomerById(int id)
{
return this.customers.FirstOrDefault(c => c.Id == id);
}
19
View Source File : PlayerStatusHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
public async Task<Unit> Handle(FightWithNpcCommand command, CancellationToken cancellationToken)
{
var playerId = command.PlayerId;
var player = await _playerDomainService.Get(playerId);
if (player == null)
{
return Unit.Value;
}
var npcId = command.NpcId;
var npc = await _npcDomainService.Get(npcId);
if (npc == null)
{
return Unit.Value;
}
if (!npc.CanFight)
{
await _bus.RaiseEvent(new DomainNotification($"你不能与[{npc.Name}]切磋!"));
return Unit.Value;
}
if (player.RoomId != npc.RoomId)
{
await _bus.RaiseEvent(new DomainNotification($"[{npc.Name}]已经离开此地,无法发起切磋!"));
return Unit.Value;
}
if (npc.IsDead)
{
await _bus.RaiseEvent(new DomainNotification($"[{npc.Name}]已经死了,无法发起切磋!"));
return Unit.Value;
}
var npcFightingPlayerId = await _redisDb.StringGet<int>(string.Format(RedisKey.NpcFighting, npc.Id));
if (npcFightingPlayerId > 0 && npcFightingPlayerId != playerId)
{
await _bus.RaiseEvent(new DomainNotification($"[{npc.Name}]拒绝了你的切磋请求!"));
return Unit.Value;
}
var hasChangedStatus= await BeginChangeStatus(new PlayerStatusModel
{
PlayerId = playerId,
Status = PlayerStatusEnum.切磋,
TargetType = TargetTypeEnum.Npc,
TargetId = npcId
});
if (hasChangedStatus)
{
await _mudProvider.ShowMessage(playerId, $"【切磋】你对着[{npc.Name}]说道:在下[{player.Name}],领教阁下的高招!");
await _mudProvider.ShowMessage(playerId, $"【切磋】[{npc.Name}]说道:「既然阁下赐教,在下只好奉陪,我们点到为止。」");
await _redisDb.StringSet(string.Format(RedisKey.NpcFighting, npc.Id), playerId, DateTime.Now.AddSeconds(20));
int minDelay = npc.Speed;
int maxDelay = minDelay + 1000;
var actionPoint = await _redisDb.StringGet<int>(string.Format(RedisKey.ActionPoint, playerId));
await _mudProvider.ShowActionPoint(playerId, actionPoint);
await _recurringQueue.Publish($"npc_{npc.Id}", new NpcStatusModel
{
NpcId = npc.Id,
Status = NpcStatusEnum.切磋,
TargetId = playerId,
TargetType = TargetTypeEnum.玩家
}, minDelay, maxDelay);
await _mudProvider.ShowBox(playerId, new { boxName = "fighting" });
var myWeapons = await _playerWareDomainService.GetAllWeapon(playerId);
var myWeaponIds = myWeapons.Select(x => x.WareId);
var weapons = (await _wareDomainService.GetAll()).Where(x => x.Category == WareCategoryEnum.武器 && myWeaponIds.Contains(x.Id)).ToList();
var skillModels = new List<SkillModel>();
var playerSkills = await _playerSkillDomainService.GetAll(player.Id);
var ids = playerSkills?.Select(x => x.SkillId);
var skills = (await _skillDomainService.GetAll()).Where(x => x.Category == SkillCategoryEnum.外功 && ids.Contains(x.Id));
foreach (var playerSkill in playerSkills)
{
var skill = skills.FirstOrDefault(x => x.Id == playerSkill.SkillId);
if (skill != null)
{
switch (skill.Type)
{
case SkillTypeEnum.刀法:
if (weapons.Count(x => x.Type == WareTypeEnum.刀) == 0)
{
continue;
}
break;
case SkillTypeEnum.剑法:
if (weapons.Count(x => x.Type == WareTypeEnum.剑) == 0)
{
continue;
}
break;
case SkillTypeEnum.枪棍:
if (weapons.Count(x => x.Type == WareTypeEnum.枪) == 0)
{
continue;
}
break;
}
var skillModel = _mapper.Map<SkillModel>(skill);
skillModel.ObjectSkillId = playerSkill.Id;
skillModel.Level = playerSkill.Level;
skillModel.Exp = playerSkill.Exp;
skillModel.IsDefault = playerSkill.IsDefault;
skillModels.Add(skillModel);
}
}
if (skillModels.Count(x => (x.Type == SkillTypeEnum.刀法 || x.Type == SkillTypeEnum.剑法 || x.Type == SkillTypeEnum.枪棍) && x.IsDefault) == 0)
{
skillModels.FirstOrDefault(x => x.Type == SkillTypeEnum.拳脚).IsDefault = true;
}
await _mudProvider.ShowFightingSkill(playerId, skillModels);
}
return Unit.Value;
}
19
View Source File : SkillCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
public async Task<Unit> Handle(ShowFightingSkillCommand command, CancellationToken cancellationToken)
{
var playerId = command.PlayerId;
var player = await _playerDomainService.Get(playerId);
if (player == null)
{
return Unit.Value;
}
var myWeapons = await _playerWareDomainService.GetAllWeapon(playerId);
var myWeaponIds = myWeapons.Select(x => x.WareId);
var weapons = (await _wareDomainService.GetAll()).Where(x => x.Category == WareCategoryEnum.武器 && myWeaponIds.Contains(x.Id)).ToList();
var skillModels = new List<SkillModel>();
var playerSkills = await _playerSkillDomainService.GetAll(player.Id);
var ids = playerSkills?.Select(x => x.SkillId);
var skills = (await _skillDomainService.GetAll()).Where(x => x.Category == SkillCategoryEnum.外功 && ids.Contains(x.Id));
foreach (var playerSkill in playerSkills)
{
var skill = skills.FirstOrDefault(x => x.Id == playerSkill.SkillId);
if (skill != null)
{
switch (skill.Type)
{
case SkillTypeEnum.刀法:
if (weapons.Count(x => x.Type == WareTypeEnum.刀) == 0)
{
continue;
}
break;
case SkillTypeEnum.剑法:
if (weapons.Count(x => x.Type == WareTypeEnum.剑) == 0)
{
continue;
}
break;
case SkillTypeEnum.枪棍:
if (weapons.Count(x => x.Type == WareTypeEnum.枪) == 0)
{
continue;
}
break;
}
var skillModel = _mapper.Map<SkillModel>(skill);
skillModel.ObjectSkillId = playerSkill.Id;
skillModel.Level = playerSkill.Level;
skillModel.Exp = playerSkill.Exp;
skillModel.IsDefault = playerSkill.IsDefault;
skillModels.Add(skillModel);
}
}
if (skillModels.Count(x => (x.Type == SkillTypeEnum.刀法 || x.Type == SkillTypeEnum.剑法 || x.Type == SkillTypeEnum.枪棍) && x.IsDefault) == 0)
{
skillModels.FirstOrDefault(x => x.Type == SkillTypeEnum.拳脚).IsDefault = true;
}
await _mudProvider.ShowFightingSkill(playerId, skillModels);
return Unit.Value;
}
19
View Source File : ToolsService.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public bool CreateIServices(string strPath, string strSolutionName, string tableName)
{
try
{
string saveFileName = $"I{tableName.Replace("_", "")}Service.cs";
#region 遍历子目录查找相同IService
List<string> sourecFiles = new List<string>();
GetFiles(strPath, sourecFiles);
string readFilePath = sourecFiles.FirstOrDefault(m => m.Contains(saveFileName));
string value = "";
if (!string.IsNullOrEmpty(readFilePath))
{
value = GetCustomValue(File.ReadAllText(readFilePath), "#region CustomInterface \r\n", " #endregion");
}
#endregion
#region 模板样式
var clreplacedTemplate = $"" +
$"//------------------------------------------------------------------------------\r\n" +
$"// <auto-generated>\r\n" +
$"// 此代码已从模板生成手动更改此文件可能导致应用程序出现意外的行为。\r\n" +
$"// 如果重新生成代码,将覆盖对此文件的手动更改。\r\n" +
$"// author MEIAM\r\n" +
$"// </auto-generated>\r\n" +
$"//------------------------------------------------------------------------------\r\n" +
$"using { strSolutionName }.Model;\r\n" +
$"using { strSolutionName }.Model.Dto;\r\n" +
$"using { strSolutionName }.Model.View;\r\n" +
$"using System.Collections.Generic;\r\n" +
$"using System.Threading.Tasks;\r\n" +
$"using SqlSugar;\r\n" +
$"using System.Linq;\r\n" +
$"using System;\r\n" +
$"\r\n" +
$"namespace { strSolutionName }.Interfaces\r\n" +
$"{{\r\n" +
$" public interface I{tableName.Replace("_", "")}Service : IBaseService<{tableName}>\r\n" +
$" {{\r\n" +
$"\r\n" +
$" #region CustomInterface \r\n" +
$"{(string.IsNullOrWhiteSpace(value) ? "" : value)}" +
$" #endregion\r\n" +
$"\r\n" +
$" }}\r\n" +
$"}}\r\n";
#endregion
File.WriteAllText($"{ strPath }\\{ saveFileName }", clreplacedTemplate);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
19
View Source File : MockDataStore.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
public async Task<Item> GereplacedemAsync(string id)
{
return await Task.FromResult(items.FirstOrDefault(s => s.Id == id));
}
19
View Source File : TestController.cs
License : MIT License
Project Creator : a3geek
License : MIT License
Project Creator : a3geek
private void Update()
{
if(this.spawned == false)
{
return;
}
if(Input.GetKeyDown(KeyCode.Space))
{
this.collisions[LayersManager.UnityLayerCount]
.ForEach(coll => coll.GetComponent<Rigidbody2D>().simulated = !coll.GetComponent<Rigidbody2D>().simulated);
}
if(Input.GetKeyDown(KeyCode.V))
{
this.collisions[LayersManager.UnityLayerCount]
.ForEach(coll => coll.gameObject.SetActive(!coll.gameObject.activeSelf));
}
if(Input.GetKeyDown(KeyCode.A))
{
var colls = this.collisions[LayersManager.UnityLayerCount];
for(var i = 0; i < colls.Count; i++)
{
colls[i].Layer.ChangeLayer(LayersManager.UnityLayerCount + 1);
colls[i].UpdateIgnoreLayers();
}
}
if(this.autoRespawn == false || Random.value > this.respawnRate)
{
return;
}
var keys = this.collisions.Keys.ToList();
var layerID = keys[Random.Range(0, keys.Count)];
if(Random.value <= 0.5f)
{
Debug.Log("Destroy");
var colls = this.collisions[layerID];
var coll = colls[Random.Range(0, colls.Count)];
this.collisions[layerID].Remove(coll);
Destroy(coll.gameObject);
}
else
{
Debug.Log("Create");
var info = this.fieldInfo.Infos.FirstOrDefault(e => e.Prefab.LayerID == layerID);
this.Create(info.Prefab, info.Parent, info.Color);
}
}
19
View Source File : ClientData.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public bool ApplyChats(ModelUpdateChat updateDate)
{
//переводим сообщения с сервера
for (int ic = 0; ic < updateDate.Chats.Count; ic++)
{
for (int ip = 0; ip < updateDate.Chats[ic].Posts.Count; ip++)
{
updateDate.Chats[ic].Posts[ip].Message = ChatController.ServerCharTranslate(updateDate.Chats[ic].Posts[ip].Message);
}
}
int newPost = 0;
var newStr = "";
if (Chats != null)
{
lock (Chats)
{
foreach (var chat in updateDate.Chats)
{
var cur = Chats.FirstOrDefault(c => c.Id == chat.Id);
if (cur != null)
{
cur.Posts.AddRange(chat.Posts);
var newPosts = chat.Posts.Where(p => p.OwnerLogin != SessionClientController.My.Login).ToList();
newPost += newPosts.Count;
if (newStr == "" && newPosts.Count > 0) newStr = chat.Name + ": " + newPosts[0].Message;
chat.Posts = cur.Posts;
cur.Name = chat.Name;
// это только для ускорения, сервер не передает список пати логинов, если ничего не изменилось
// т.к. передать 3000+ логинов по 8 байт, это уже несколько пакетов
if (chat.PartyLogin != null && chat.PartyLogin.Count > 0)
{
cur.PartyLogin = chat.PartyLogin;
}
}
else
{
Chats.Add(chat);
}
}
var ids = updateDate.Chats.Select(x => x.Id);
Chats.RemoveAll(x => !ids.Contains(x.Id));
}
}
else
{
Chats = updateDate.Chats;
}
if (UIInteraction && newPost > 0)
{
GameMessage(newStr);
}
ChatNotReadPost += newPost;
return newPost > 0;
}
19
View Source File : ClientData.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public bool ApplyChats(ModelUpdateChat updateDate, ref string newStr)
{
int newPost = 0;
newStr = "";
if (Chats != null)
{
foreach (var chat in updateDate.Chats)
{
var cur = Chats.FirstOrDefault(c => c.Id == chat.Id);
if (cur != null)
{
cur.Posts.AddRange(chat.Posts);
var newPosts = chat.Posts.Where(p => p.OwnerLogin != _myLogin).ToList();
newPost += newPosts.Count;
if (newStr == "" && newPosts.Count > 0) newStr = chat.Name + ": " + newPosts[0].Message;
chat.Posts = cur.Posts;
if (chat.PartyLogin != null)
{
cur.PartyLogin = chat.PartyLogin;
}
}
}
}
else
{
Chats = updateDate.Chats;
}
ChatNotReadPost += newPost;
return newPost > 0;
}
19
View Source File : AppenderFactory.cs
License : MIT License
Project Creator : Abc-Arbitrage
License : MIT License
Project Creator : Abc-Arbitrage
private static Type? GetAppenderType(AppenderDefinition definition)
{
if (string.IsNullOrEmpty(definition.AppenderTypeName))
return null;
// Check if we have an replacedembly-qualified name of a type
if (definition.AppenderTypeName!.Contains(","))
return Type.GetType(definition.AppenderTypeName, true, false);
return AppDomain.CurrentDomain.Getreplacedemblies()
.Select(x => x.GetType(definition.AppenderTypeName))
.FirstOrDefault(x => x != null);
}
19
View Source File : ObjectAggregator.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
private DownstreamObjectsListDto ReplaceUserIdWithUser(UpstreamObjectsListDto objects, List<UserDto> users)
{
var downStreamObjects = new List<DownstreamObjectDto>();
foreach (var @object in objects.Objects)
{
downStreamObjects.Add(new DownstreamObjectDto
{
CountOfImpressions = @object.CountOfImpressions,
CountOfViews = @object.CountOfViews,
Description = @object.Description,
Id = @object.Id,
Name = @object.Name,
Owner = users?.FirstOrDefault(u => u.Id.EqualsIC(@object.OwnerId)),
Photos = @object.Photos,
Rating = @object.Rating,
Tags = @object.Tags,
Type = @object.Type
});
}
return new DownstreamObjectsListDto
{
Objects = downStreamObjects,
FreeObjectsCount = objects.FreeObjectsCount,
LendingObjectsCount = objects.LendingObjectsCount,
RentingObjectsCount = objects.RentingObjectsCount,
};
}
19
View Source File : CommentAggregator.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
public async Task<DownstreamCommentListDto> AggregateCommentsWithUsers(UpstreamCommentListDto comments, List<UserDto> users = null)
{
if(users is null)
{
var originalUserIds = comments.Comments.Select(o => o.UserId).ToList();
users = await _userService.GetUsersAsync(originalUserIds);
}
var downComments = _mapper.Map<DownstreamCommentListDto>(comments);
downComments.Comments.ForEach(downComment =>
{
var upComment = comments.Comments.FirstOrDefault(c => downComment.CommentId == c.CommentId);
downComment.Commenter = users.FirstOrDefault(u => u.Id.EqualsIC(upComment.UserId));
});
return downComments;
}
19
View Source File : CommentAggregator.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
public async Task<List<DownstreamCommentDto>> AggregateCommentsWithUsers(List<UpstreamCommentDto> comments, List<UserDto> users = null)
{
if(users is null)
{
var originalUserIds = comments.Select(o => o.UserId).ToList();
users = await _userService.GetUsersAsync(originalUserIds);
}
var downComments = _mapper.Map<List<DownstreamCommentDto>>(comments);
downComments.ForEach(downComment =>
{
var upComment = comments.FirstOrDefault(c => downComment.CommentId == c.CommentId);
downComment.Commenter = users.FirstOrDefault(u => u.Id.EqualsIC(upComment.UserId));
});
return downComments;
}
19
View Source File : CatalogAggregator.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
private List<DownstreamObjectDto> ReplaceUserIdWithUser(List<UpstreamObjectDto> objects, List<UserDto> users)
{
var downstreamObjects = _mapper.Map<List<DownstreamObjectDto>>(objects);
downstreamObjects.ForEach(downObject =>
{
var upObject = objects.Find(o => o.Id == downObject.Id);
downObject.Owner = users.FirstOrDefault(u => u.Id.EqualsIC(upObject.OwnerId));
});
return downstreamObjects;
}
See More Examples