content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using BinaryDiff.Input.Domain.Models;
using BinaryDiff.Shared.Infrastructure.MongoDb.Context;
using BinaryDiff.Shared.Infrastructure.MongoDb.Repositories;
namespace BinaryDiff.Input.Infrastructure.Repositories
{
public class DiffRepository : MongoDbRepository<Diff>, IDiffRepository
{
const string COLLECTION_NAME = "diffs";
public DiffRepository(IMongoDbContext mongoDbContext)
: base(mongoDbContext, COLLECTION_NAME)
{
}
}
}
| 28.588235 | 74 | 0.738683 | [
"MIT"
] | CaioCavalcanti/binary-diff-api | Services/BinaryDiff.Input/BinaryDiff.Input.Infrastructure/Repositories/DiffRepository.cs | 488 | C# |
using System.Collections.Generic;
using Essensoft.AspNetCore.Payment.Alipay.Response;
namespace Essensoft.AspNetCore.Payment.Alipay.Request
{
/// <summary>
/// alipay.open.app.silan.apigraythirteen.query
/// </summary>
public class AlipayOpenAppSilanApigraythirteenQueryRequest : IAlipayRequest<AlipayOpenAppSilanApigraythirteenQueryResponse>
{
#region IAlipayRequest Members
private bool needEncrypt = true;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "alipay.open.app.silan.apigraythirteen.query";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary();
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.008621 | 127 | 0.56538 | [
"MIT"
] | lzw316/payment | src/Essensoft.AspNetCore.Payment.Alipay/Request/AlipayOpenAppSilanApigraythirteenQueryRequest.cs | 2,671 | C# |
namespace Play.Inputs
{
public class GlobalStringVaribles
{
#region Input vars
public const string HORIZONTAL_AXIS = "Horizontal";
public const string VERTICAL_AXIS = "Vertical";
public const string JUMP_AXIS = "Jump";
public const string Fire_AXIS = "Fire1";
#endregion
}
} | 22.466667 | 59 | 0.637982 | [
"Unlicense"
] | PaveSafronov/Games2D | Games/Assets/Scriptes/Knight/GlobalStringVaribles.cs | 337 | C# |
namespace PnP.Framework.Enums
{
/// <summary>
/// Defines the TLS versions a Microsoft Graph subscription supports calling into when an event for which a subscription exists gets triggered
/// </summary>
public enum GraphSubscriptionTlsVersion : short
{
v1_0,
v1_1,
v1_2,
v1_3
}
}
| 24.142857 | 146 | 0.639053 | [
"MIT"
] | jackpoz/pnpframework | src/lib/PnP.Framework/Enums/GraphSubscriptionTlsVersion.cs | 340 | C# |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
namespace Alachisoft.NCache.Common.Locking
{
public enum LockAccessType:byte
{
/// <summary>Indicates that lock is to be acquired.</summary>
ACQUIRE = 1,
/// <summary>Perform the operation only if item is not locked but dont acquire the lock</summary>
DONT_ACQUIRE,
/// <summary>Indicates that lock is to be released.</summary>
RELEASE,
/// <summary>Indicates that lock is not to be released.</summary>
DONT_RELEASE,
/// <summary>Perform the operation as if there is no lock.</summary>
IGNORE_LOCK,
/// <summary>Optimistic locking; update the item in the cache only if the version is same.</summary>
//muds:
//this helps to preserve the version of the cache item when in case of client cache we
//remove the local copy of the item before updating the remote copy of the cache item.
//this is for internal use only.
PRESERVE_VERSION,
DEFAULT
}
}
| 41.230769 | 108 | 0.672886 | [
"Apache-2.0"
] | Alachisoft/NCache | Src/NCCommon/Locking/LockAccessType.cs | 1,608 | C# |
using UnityEngine;
using System.Collections;
namespace Ist
{
public class MPGPGPUSort
{
public struct KIP
{
public uint key;
public uint index;
}
public struct SortCB
{
public uint level;
public uint levelMask;
public uint width;
public uint height;
}
ComputeShader m_cs_bitonic_sort;
ComputeBuffer[] m_buf_consts = new ComputeBuffer[2];
ComputeBuffer[] m_buf_dummies = new ComputeBuffer[2];
SortCB[] m_consts = new SortCB[1];
public void Initialize(ComputeShader sh_bitonic_sort)
{
m_cs_bitonic_sort = sh_bitonic_sort;
m_buf_consts[0] = new ComputeBuffer(1, 16);
m_buf_consts[1] = new ComputeBuffer(1, 16);
m_buf_dummies[0] = new ComputeBuffer(1, 16);
m_buf_dummies[1] = new ComputeBuffer(1, 16);
}
public void Release()
{
m_buf_dummies[0].Release();
m_buf_dummies[1].Release();
m_buf_consts[0].Release();
m_buf_consts[1].Release();
}
public void BitonicSort(ComputeBuffer kip, ComputeBuffer kip_tmp, uint num)
{
uint BITONIC_BLOCK_SIZE = 512;
uint TRANSPOSE_BLOCK_SIZE = 16;
uint NUM_ELEMENTS = num;
uint MATRIX_WIDTH = BITONIC_BLOCK_SIZE;
uint MATRIX_HEIGHT = NUM_ELEMENTS / BITONIC_BLOCK_SIZE;
for (uint level = 2; level <= BITONIC_BLOCK_SIZE; level <<= 1)
{
m_consts[0].level = level;
m_consts[0].levelMask = level;
m_consts[0].width = MATRIX_HEIGHT; // not a mistake!
m_consts[0].height = MATRIX_WIDTH; //
m_buf_consts[0].SetData(m_consts);
m_cs_bitonic_sort.SetBuffer(0, "consts", m_buf_consts[0]);
m_cs_bitonic_sort.SetBuffer(0, "kip_rw", kip);
m_cs_bitonic_sort.Dispatch(0, (int)(NUM_ELEMENTS / BITONIC_BLOCK_SIZE), 1, 1);
}
// Then sort the rows and columns for the levels > than the block size
// Transpose. Sort the Columns. Transpose. Sort the Rows.
for (uint level = (BITONIC_BLOCK_SIZE << 1); level <= NUM_ELEMENTS; level <<= 1)
{
m_consts[0].level = (level / BITONIC_BLOCK_SIZE);
m_consts[0].levelMask = (level & ~NUM_ELEMENTS) / BITONIC_BLOCK_SIZE;
m_consts[0].width = MATRIX_WIDTH;
m_consts[0].height = MATRIX_HEIGHT;
m_buf_consts[0].SetData(m_consts);
// Transpose the data from buffer 1 into buffer 2
m_cs_bitonic_sort.SetBuffer(1, "consts", m_buf_consts[0]);
m_cs_bitonic_sort.SetBuffer(1, "kip", kip);
m_cs_bitonic_sort.SetBuffer(1, "kip_rw", kip_tmp);
m_cs_bitonic_sort.Dispatch(1, (int)(MATRIX_WIDTH / TRANSPOSE_BLOCK_SIZE), (int)(MATRIX_HEIGHT / TRANSPOSE_BLOCK_SIZE), 1);
// Sort the transposed column data
m_cs_bitonic_sort.SetBuffer(0, "consts", m_buf_consts[0]);
m_cs_bitonic_sort.SetBuffer(0, "kip_rw", kip_tmp);
m_cs_bitonic_sort.Dispatch(0, (int)(NUM_ELEMENTS / BITONIC_BLOCK_SIZE), 1, 1);
m_consts[0].level = BITONIC_BLOCK_SIZE;
m_consts[0].levelMask = level;
m_consts[0].width = MATRIX_HEIGHT;
m_consts[0].height = MATRIX_WIDTH;
m_buf_consts[0].SetData(m_consts);
// Transpose the data from buffer 2 back into buffer 1
m_cs_bitonic_sort.SetBuffer(1, "consts", m_buf_consts[0]);
m_cs_bitonic_sort.SetBuffer(1, "kip", kip_tmp);
m_cs_bitonic_sort.SetBuffer(1, "kip_rw", kip);
m_cs_bitonic_sort.Dispatch(1, (int)(MATRIX_HEIGHT / TRANSPOSE_BLOCK_SIZE), (int)(MATRIX_WIDTH / TRANSPOSE_BLOCK_SIZE), 1);
// Sort the row data
m_cs_bitonic_sort.SetBuffer(0, "consts", m_buf_consts[0]);
m_cs_bitonic_sort.SetBuffer(0, "kip_rw", kip);
m_cs_bitonic_sort.Dispatch(0, (int)(NUM_ELEMENTS / BITONIC_BLOCK_SIZE), 1, 1);
}
}
}
}
| 42.009346 | 139 | 0.552836 | [
"MIT"
] | phamngocanit82/PNA-Unity3D | LightEffects/Assets/Ist/MassParticle/GPUParticle/Scripts/MPGPGPUSort.cs | 4,497 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.scdn;
using Aliyun.Acs.scdn.Transform;
using Aliyun.Acs.scdn.Transform.V20171115;
namespace Aliyun.Acs.scdn.Model.V20171115
{
public class DescribeScdnCcTopIpRequest : RpcAcsRequest<DescribeScdnCcTopIpResponse>
{
public DescribeScdnCcTopIpRequest()
: base("scdn", "2017-11-15", "DescribeScdnCcTopIp")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.scdn.Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.scdn.Endpoint.endpointRegionalType, null);
}
}
private string startTime;
private string pageNumber;
private string pageSize;
private string domainName;
private string endTime;
private long? ownerId;
public string StartTime
{
get
{
return startTime;
}
set
{
startTime = value;
DictionaryUtil.Add(QueryParameters, "StartTime", value);
}
}
public string PageNumber
{
get
{
return pageNumber;
}
set
{
pageNumber = value;
DictionaryUtil.Add(QueryParameters, "PageNumber", value);
}
}
public string PageSize
{
get
{
return pageSize;
}
set
{
pageSize = value;
DictionaryUtil.Add(QueryParameters, "PageSize", value);
}
}
public string DomainName
{
get
{
return domainName;
}
set
{
domainName = value;
DictionaryUtil.Add(QueryParameters, "DomainName", value);
}
}
public string EndTime
{
get
{
return endTime;
}
set
{
endTime = value;
DictionaryUtil.Add(QueryParameters, "EndTime", value);
}
}
public long? OwnerId
{
get
{
return ownerId;
}
set
{
ownerId = value;
DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString());
}
}
public override DescribeScdnCcTopIpResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return DescribeScdnCcTopIpResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 23.654676 | 134 | 0.657238 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-scdn/Scdn/Model/V20171115/DescribeScdnCcTopIpRequest.cs | 3,288 | C# |
using Microsoft.VisualStudio.Text.Operations;
namespace Vim.EditorHost
{
/// <summary>
/// In certain hosted scenarios the default ITextUndoHistoryRegistry won't be
/// available. This is a necessary part of editor composition though and some
/// implementation needs to be provided. Importing this type will provide a
/// very basic implementation
///
/// This type intentionally doesn't ever export ITextUndoHistoryRegistry. Doing
/// this would conflict with Visual Studios export and cause a MEF composition
/// error. It's instead exposed via this interface
///
/// In general this type won't be used except in testing
/// </summary>
public interface IBasicUndoHistoryRegistry
{
/// <summary>
/// Get the basic implementation of the ITextUndoHistoryRegistry
/// </summary>
ITextUndoHistoryRegistry TextUndoHistoryRegistry { get; }
/// <summary>
/// Try and get the IBasicUndoHistory for the given context
/// </summary>
bool TryGetBasicUndoHistory(object context, out IBasicUndoHistory basicUndoHistory);
}
public interface IBasicUndoHistory : ITextUndoHistory
{
/// <summary>
/// Clear out all of the state including the undo and redo stacks
/// </summary>
void Clear();
}
}
| 36.815789 | 93 | 0.649035 | [
"Apache-2.0"
] | EAirPeter/VsVim | Src/VimEditorHost/IBasicUndoHistoryRegistry.cs | 1,401 | C# |
using System;
namespace Ceen.PaaS.Services
{
public static class PasswordPolicy
{
/// <summary>
/// The random number generator to use
/// </summary>
private static readonly Random _rnd = new Random();
/// <summary>
/// The lock guarding the random number generator
/// </summary>
private static readonly object _rndlock = new object();
/// <summary>
/// Enforces the password policy
/// </summary>
/// <param name="password">The password to validate</param>
public static void ValidatePassword(string password)
{
if (string.IsNullOrWhiteSpace(password) || password.Length < 8)
throw new Ceen.HttpException(Ceen.HttpStatusCode.BadRequest, "Password must be at least 8 characters");
}
/// <summary>
/// Generates an activation code
/// </summary>
/// <returns>The activation code</returns>
public static string GenerateActivationCode()
{
// We do not use a PRNG because the code is not used for encryption
// and we do not have a high security standard for the activation
// codes.
byte[] buf;
lock(_rndlock)
{
buf = new byte[_rnd.Next(20, 28)];
_rnd.NextBytes(buf);
}
// Make it URL-safe
return Convert
.ToBase64String(buf)
.TrimEnd('=')
.Replace('+', '-')
.Replace('/', '_'); ;
}
/// <summary>
/// Basic email format validation
/// </summary>
private static readonly System.Text.RegularExpressions.Regex EMAIL_VALIDATOR = new System.Text.RegularExpressions.Regex(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
/// <summary>
/// Does a rudimentary check for the email format
/// </summary>
/// <param name="email">The string to validate</param>
/// <returns><c>true</c> if the email looks valid; <c>false</c> otherwise</returns>
public static bool IsValidEmail(string email)
{
try
{
// Use the built-in .Net email address validation
return email == new System.Net.Mail.MailAddress(email).Address;
}
catch
{
return false;
}
}
}
}
| 32.710526 | 179 | 0.519308 | [
"MIT"
] | Peckmore/ceenhttpd | Ceen.PaaS/Services/PasswordPolicy.cs | 2,486 | C# |
using CssUI.DOM.Enums;
using CssUI.DOM.Exceptions;
using CssUI.DOM.Nodes;
using System;
using System.Collections.Generic;
namespace CssUI.DOM
{
public class NodeIterator
{/* Docs: */
public static LinkedList<WeakReference<NodeIterator>> ALL = new LinkedList<WeakReference<NodeIterator>>();
#region Properties
public readonly Node root = null;
public readonly ENodeFilterMask whatToShow = 0x0;
public readonly NodeFilter Filter = null;
// XXX: Still dont know where this collection comes from
private IList<Node> iterCollection;// = new ICollection<Node>();
private Node referenceNode = null;
private bool pointerBeforeReferenceNode = false;
private bool isActive = false;
#endregion
#region Constructor
public NodeIterator(Node root, ENodeFilterMask whatToShow)
{
this.root = root;
this.referenceNode = root;
this.whatToShow = whatToShow;
this.iterCollection = Array.Empty<Node>();
}
public NodeIterator(Node root, IList<Node> Collection, ENodeFilterMask whatToShow, NodeFilter Filter = null)
{
this.root = root;
this.referenceNode = root;
this.whatToShow = whatToShow;
this.iterCollection = Collection;
this.Filter = Filter;
}
~NodeIterator()
{
/* Remove us from the list */
foreach (WeakReference<NodeIterator> weakRef in ALL)
{
if (weakRef.TryGetTarget(out NodeIterator target))
{
if (ReferenceEquals(this, target))
{
ALL.Remove(weakRef);
break;
}
}
}
}
#endregion
#region Internal Utility
internal static void pre_removing_steps(NodeIterator nodeIterator, Node toBeRemovedNode)
{/* Docs: https://dom.spec.whatwg.org/#nodeiterator-pre-removing-steps */
/* 1) If toBeRemovedNode is not an inclusive ancestor of nodeIterator’s reference, or toBeRemovedNode is nodeIterator’s root, then return. */
if (!DOMCommon.Is_Inclusive_Ancestor(toBeRemovedNode, nodeIterator.referenceNode) || ReferenceEquals(toBeRemovedNode, nodeIterator.root))
return;
/* 2) If nodeIterator’s pointer before reference is true, then: */
if (nodeIterator.pointerBeforeReferenceNode)
{
/* 1) Let next be toBeRemovedNode’s first following node that is an inclusive descendant of nodeIterator’s root and is not an inclusive descendant of toBeRemovedNode, and null if there is no such node. */
Node next = null;
var tree = new TreeWalker(toBeRemovedNode, ENodeFilterMask.SHOW_ALL);
Node n = tree.nextSibling();
while(!ReferenceEquals(n, null))
{
if (DOMCommon.Is_Inclusive_Descendant(n, nodeIterator.root) && !DOMCommon.Is_Inclusive_Descendant(n, toBeRemovedNode))
{
next = n;
break;
}
n = tree.nextSibling();
}
/* 2) If next is non-null, then set nodeIterator’s reference to next and return. */
if (!ReferenceEquals(next, null))
{
nodeIterator.referenceNode = next;
return;
}
/* 3) Otherwise, set nodeIterator’s pointer before reference to false. */
nodeIterator.pointerBeforeReferenceNode = false;
}
/* 3) Set nodeIterator’s reference to toBeRemovedNode’s parent, if toBeRemovedNode’s previous sibling is null, and to the inclusive descendant of toBeRemovedNode’s previous sibling that appears last in tree order otherwise. */
if (toBeRemovedNode.previousSibling == null)
{
nodeIterator.referenceNode = toBeRemovedNode.parentNode;
}
else
{
/*
* "the inclusive descendant of toBeRemovedNode’s previous sibling that appears last in tree order"
* That would just be the previous sibling itsself yea? or is it the most-descended last child? wtf
*/
var tree = new TreeWalker(toBeRemovedNode.previousSibling, ENodeFilterMask.SHOW_ALL);
Node n = tree.lastChild();
Node newNode = toBeRemovedNode.previousSibling;
/* Find the most-descended last child */
while (n != null)
{
/* We keep going deeper until the traversal stops going deeper */
if (!DOMCommon.Is_Descendant(n, newNode))
break;
newNode = n;
n = tree.lastChild();
}
nodeIterator.referenceNode = newNode;
}
}
#endregion
private ENodeFilterResult filterNode(Node node)
{
/* To filter a node node within a NodeIterator or TreeWalker object traverser, run these steps: */
/* 1) If traverser’s active flag is set, then throw an "InvalidStateError" DOMException. */
if (isActive) throw new InvalidStateError();
/* 2) Let n be node’s nodeType attribute value − 1. */
int n = (int)node.nodeType;
/* 3) If the nth bit (where 0 is the least significant bit) of traverser’s whatToShow is not set, then return FILTER_SKIP. */
ulong mask = (1UL << n);
if (0 == ((ulong)this.whatToShow & mask))
return ENodeFilterResult.FILTER_SKIP;
/* If traverser’s filter is null, then return FILTER_ACCEPT. */
if (this.Filter == null)
return ENodeFilterResult.FILTER_ACCEPT;
/* Set traverser’s active flag. */
isActive = true;
/* Let result be the return value of call a user object’s operation with traverser’s filter, "acceptNode", and « node ». If this throws an exception, then unset traverser’s active flag and rethrow the exception. */
ENodeFilterResult result;
try
{
result = this.Filter.acceptNode(node);
}
catch(DOMException)
{
/* Unset traverser’s active flag. */
isActive = false;
throw;
}
/* Unset traverser’s active flag. */
isActive = false;
return result;
}
public Node nextNode()
{/* Docs: https://dom.spec.whatwg.org/#concept-traversal-active */
Node node = referenceNode;
bool beforeNode = pointerBeforeReferenceNode;
while (true)
{
/* 1) If beforeNode is false, then set node to the first node following node in iterator’s iterator collection. If there is no such node, then return null. */
if (!beforeNode)
{
int i = iterCollection.IndexOf(node);
if (i < (iterCollection.Count - 1))
return null;
node = iterCollection[i + 1];
}
else
beforeNode = false;
/* 2) Let result be the result of filtering node within iterator. */
ENodeFilterResult result = filterNode(node);
/* 3) If result is FILTER_ACCEPT, then break. */
if (result == ENodeFilterResult.FILTER_ACCEPT) break;
}
/* 4) Set iterator’s reference to node. */
referenceNode = node;
/* 5) Set iterator’s pointer before reference to beforeNode. */
pointerBeforeReferenceNode = beforeNode;
/* 6) Return node. */
return node;
}
public Node previousNode()
{/* Docs: https://dom.spec.whatwg.org/#concept-traversal-active */
Node node = referenceNode;
bool beforeNode = pointerBeforeReferenceNode;
while (true)
{
/* 1) If beforeNode is true, then set node to the first node preceding node in iterator’s iterator collection. If there is no such node, then return null. */
if (beforeNode)
{
int i = iterCollection.IndexOf(node);
if (i <= 0)
return null;
node = iterCollection[i - 1];
}
else
beforeNode = true;
/* 2) Let result be the result of filtering node within iterator. */
ENodeFilterResult result = filterNode(node);
/* 3) If result is FILTER_ACCEPT, then break. */
if (result == ENodeFilterResult.FILTER_ACCEPT) break;
}
/* 4) Set iterator’s reference to node. */
referenceNode = node;
/* 5) Set iterator’s pointer before reference to beforeNode. */
pointerBeforeReferenceNode = beforeNode;
/* 6) Return node. */
return node;
}
}
}
| 41.942222 | 238 | 0.547102 | [
"MIT"
] | dsisco11/CssUI | CssUI/DOM/Traversal/NodeIterator.cs | 9,499 | C# |
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.ServiceModel.Web;
using System.Text;
using CodeProbe.Sensing;
using CodeProbe.HealthChecks;
using CodeProbe.Reporting.Reporters;
using CodeProbe.Reporting.Extractors;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace CodeProbe.Reporting.Remote
{
/// <summary>
/// Default implementation of a ProbeService.
/// </summary>
public abstract class ProbeServiceBase : IProbeService
{
protected ILog _logger;
protected ICheckAllPolicy _checkAllPolicy;
protected DirectSampleExtractor _extractor;
protected virtual string AuditName { get { return GetType().FullName; } }
public ProbeServiceBase()
{
_logger = LogManager.GetLogger(AuditName);
Tuple<DirectSampleExtractor, ICheckAllPolicy> tmp=RemoteReportingManager.Ask().GetProbeServiceExtractor(GetType().FullName);
_extractor = tmp.Item1;
_checkAllPolicy = tmp.Item2;
if (ProbeManager.Ask().SystemTimer(AuditName + ".IsActive") == null)
ProbeManager.Ask().SystemTimer(AuditName + ".IsActive", ProbeManager.Ask().GetDefaultReservoir<long>());
if (ProbeManager.Ask().SystemTimer(AuditName + ".Probe") == null)
ProbeManager.Ask().SystemTimer(AuditName + ".Probe", ProbeManager.Ask().GetDefaultReservoir<long>());
if (ProbeManager.Ask().SystemTimer(AuditName + ".HealthReport") == null)
ProbeManager.Ask().SystemTimer(AuditName + ".HealthReport", ProbeManager.Ask().GetDefaultReservoir<long>());
if (ProbeManager.Ask().SystemTimer(AuditName + ".IsHealthy") == null)
ProbeManager.Ask().SystemTimer(AuditName + ".IsHealthy", ProbeManager.Ask().GetDefaultReservoir<long>());
}
public virtual void IsAlive()
{
using (ProbeManager.Ask().SystemTimer(AuditName + "." + MethodBase.GetCurrentMethod().Name).Time())
{
_logger.InfoFormat("Called {0}", MethodBase.GetCurrentMethod().Name);
_logger.InfoFormat("Executed {0}", MethodBase.GetCurrentMethod().Name);
}
}
public virtual List<SampleResult> Probe(string filter)
{
using (ProbeManager.Ask().SystemTimer(AuditName + "." + MethodBase.GetCurrentMethod().Name).Time())
{
_logger.InfoFormat("Called {0}", MethodBase.GetCurrentMethod().Name);
WebOperationContext ctx = WebOperationContext.Current;
List<SampleResult> result = new List<SampleResult>();
try
{
if (string.IsNullOrEmpty(filter))
filter = ".*";
_extractor.Extract(filter);
foreach (KeyValuePair<string, object> item in _extractor.Current)
{
result.Add(new SampleResult() { Name = item.Key, Value = item.Value });
}
_logger.InfoFormat("Executed {0}", MethodBase.GetCurrentMethod().Name);
}
catch (Exception e)
{
_logger.Error(string.Format("Error executing method {0}", MethodBase.GetCurrentMethod().Name), e);
ctx.OutgoingResponse.StatusCode = (System.Net.HttpStatusCode)520;
}
return result;
}
}
public virtual List<HealthCheckResult> HealthReport(string filter)
{
using (ProbeManager.Ask().SystemTimer(AuditName + "." + MethodBase.GetCurrentMethod().Name).Time())
{
_logger.InfoFormat("Called {0}", MethodBase.GetCurrentMethod().Name);
WebOperationContext ctx = WebOperationContext.Current;
ConcurrentBag<HealthCheckResult> result = new ConcurrentBag<HealthCheckResult>();
if (string.IsNullOrEmpty(filter))
filter = ".*";
try
{
Parallel.ForEach(HealthCheckManager.Ask().GetAll(filter), new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount }, p =>
{
try
{
bool? ch = p.Check();
result.Add(new HealthCheckResult() { Name = p.Name, Severity = p.Severity, Value = ch });
}
catch (Exception e)
{
_logger.Warn(string.Format("Error checking healthcheck: {0}", p.Name), e);
result.Add(new HealthCheckResult() { Name = p.Name, Severity = p.Severity, Value = null });
}
});
_logger.InfoFormat("Executed {0}", MethodBase.GetCurrentMethod().Name);
}
catch (Exception e)
{
_logger.Error(string.Format("Error executing method {0}", MethodBase.GetCurrentMethod().Name), e);
ctx.OutgoingResponse.StatusCode = (System.Net.HttpStatusCode)520;
}
return result.ToList();
}
}
public virtual bool IsHealthy()
{
using (ProbeManager.Ask().SystemTimer(AuditName + "." + MethodBase.GetCurrentMethod().Name).Time())
{
_logger.InfoFormat("Called {0}", MethodBase.GetCurrentMethod().Name);
WebOperationContext ctx = WebOperationContext.Current;
bool result = false;
try
{
result = HealthCheckManager.Ask().CheckAll(_checkAllPolicy);
_logger.InfoFormat("Executed {0}", MethodBase.GetCurrentMethod().Name);
}
catch (Exception e)
{
_logger.Error(string.Format("Error executing method {0}", MethodBase.GetCurrentMethod().Name), e);
ctx.OutgoingResponse.StatusCode = (System.Net.HttpStatusCode)520;
}
if (!result)
{
ctx.OutgoingResponse.StatusCode = (System.Net.HttpStatusCode)530;
}
return result;
}
}
}
}
| 40.4625 | 161 | 0.554526 | [
"MIT"
] | aliaslab-1984/CodeProbe | src/CodeProbe.Reporting.Remote/ProbeServiceBase.cs | 6,476 | C# |
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using System;
[Serializable, VolumeComponentMenu("Post-processing/Custom/Snow")]
public sealed class Snow : CustomPostProcessVolumeComponent, IPostProcessComponent
{
[Tooltip("Controls the intensity of the effect.")]
public ClampedFloatParameter intensity = new ClampedFloatParameter(0f, 0f, 1f);
Material m_Material;
public bool IsActive() => m_Material != null && intensity.value > 0f;
// Do not forget to add this post process in the Custom Post Process Orders list (Project Settings > HDRP Default Settings).
public override CustomPostProcessInjectionPoint injectionPoint => CustomPostProcessInjectionPoint.AfterPostProcess;
const string kShaderName = "Hidden/Shader/Snow";
public override void Setup()
{
if (Shader.Find(kShaderName) != null)
m_Material = new Material(Shader.Find(kShaderName));
else
Debug.LogError($"Unable to find shader '{kShaderName}'. Post Process Volume Snow is unable to load.");
}
public override void Render(CommandBuffer cmd, HDCamera camera, RTHandle source, RTHandle destination)
{
if (m_Material == null)
return;
m_Material.SetFloat("_Intensity", intensity.value);
m_Material.SetTexture("_InputTexture", source);
HDUtils.DrawFullScreen(cmd, m_Material, destination);
}
public override void Cleanup()
{
CoreUtils.Destroy(m_Material);
}
}
| 35.704545 | 129 | 0.693826 | [
"MIT"
] | Takata1128/SSKK_Hackathon2021_Takata | Assets/SampleSceneAssets/Scripts/SamplePostProcess/Snow/Snow.cs | 1,571 | C# |
using System.IO;
using System.Runtime.Serialization;
using GameEstate.Red.Formats.Red.CR2W.Reflection;
using FastMember;
using static GameEstate.Red.Formats.Red.Records.Enums;
namespace GameEstate.Red.Formats.Red.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CAINpcReactionLeadEscape : CAINpcReaction
{
public CAINpcReactionLeadEscape(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CAINpcReactionLeadEscape(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 32.782609 | 136 | 0.753316 | [
"MIT"
] | bclnet/GameEstate | src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/CAINpcReactionLeadEscape.cs | 754 | C# |
using System.Windows;
using System.Windows.Controls;
namespace PTWpf.Modules.Resource
{
/// <summary>
/// Interaction logic for ResourceList.xaml
/// </summary>
public partial class ResourceListView : UserControl
{
public ResourceListView()
{
InitializeComponent();
}
}
} | 20.235294 | 56 | 0.604651 | [
"MIT"
] | MarimerLLC/cslacontrib | branches/2010.11.001/ProjectTrackerPrism/PTWpf.Modules.Resource/ResourceListView.xaml.cs | 346 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.ML.Calibrators;
using Microsoft.ML.Trainers.FastTree;
namespace Microsoft.ML.StaticPipe
{
/// <summary>
/// FastTree <see cref="TrainCatalogBase"/> extension methods.
/// </summary>
public static class TreeRegressionExtensions
{
/// <summary>
/// FastTree <see cref="RegressionCatalog"/> extension method.
/// Predicts a target using a decision tree regression model trained with the <see cref="FastTreeRegressionTrainer"/>.
/// </summary>
/// <param name="catalog">The <see cref="RegressionCatalog"/>.</param>
/// <param name="label">The label column.</param>
/// <param name="features">The features column.</param>
/// <param name="weights">The optional weights column.</param>
/// <param name="numTrees">Total number of decision trees to create in the ensemble.</param>
/// <param name="numLeaves">The maximum number of leaves per decision tree.</param>
/// <param name="minDatapointsInLeaves">The minimal number of datapoints allowed in a leaf of a regression tree, out of the subsampled data.</param>
/// <param name="learningRate">The learning rate.</param>
/// <param name="onFit">A delegate that is called every time the
/// <see cref="Estimator{TInShape, TOutShape, TTransformer}.Fit(DataView{TInShape})"/> method is called on the
/// <see cref="Estimator{TInShape, TOutShape, TTransformer}"/> instance created out of this. This delegate will receive
/// the linear model that was trained. Note that this action cannot change the result in any way;
/// it is only a way for the caller to be informed about what was learnt.</param>
/// <returns>The Score output column indicating the predicted value.</returns>
/// <example>
/// <format type="text/markdown">
/// <]
/// ]]></format>
/// </example>
public static Scalar<float> FastTree(this RegressionCatalog.RegressionTrainers catalog,
Scalar<float> label, Vector<float> features, Scalar<float> weights = null,
int numLeaves = Defaults.NumLeaves,
int numTrees = Defaults.NumTrees,
int minDatapointsInLeaves = Defaults.MinDocumentsInLeaves,
double learningRate = Defaults.LearningRates,
Action<FastTreeRegressionModelParameters> onFit = null)
{
CheckUserValues(label, features, weights, numLeaves, numTrees, minDatapointsInLeaves, learningRate, onFit);
var rec = new TrainerEstimatorReconciler.Regression(
(env, labelName, featuresName, weightsName) =>
{
var trainer = new FastTreeRegressionTrainer(env, labelName, featuresName, weightsName, numLeaves,
numTrees, minDatapointsInLeaves, learningRate);
if (onFit != null)
return trainer.WithOnFitDelegate(trans => onFit(trans.Model));
return trainer;
}, label, features, weights);
return rec.Score;
}
/// <summary>
/// FastTree <see cref="RegressionCatalog"/> extension method.
/// Predicts a target using a decision tree regression model trained with the <see cref="FastTreeRegressionTrainer"/>.
/// </summary>
/// <param name="catalog">The <see cref="RegressionCatalog"/>.</param>
/// <param name="label">The label column.</param>
/// <param name="features">The features column.</param>
/// <param name="weights">The optional weights column.</param>
/// <param name="options">Algorithm advanced settings.</param>
/// <param name="onFit">A delegate that is called every time the
/// <see cref="Estimator{TInShape, TOutShape, TTransformer}.Fit(DataView{TInShape})"/> method is called on the
/// <see cref="Estimator{TInShape, TOutShape, TTransformer}"/> instance created out of this. This delegate will receive
/// the linear model that was trained. Note that this action cannot change the result in any way;
/// it is only a way for the caller to be informed about what was learnt.</param>
/// <returns>The Score output column indicating the predicted value.</returns>
/// <example>
/// <format type="text/markdown">
/// <]
/// ]]></format>
/// </example>
public static Scalar<float> FastTree(this RegressionCatalog.RegressionTrainers catalog,
Scalar<float> label, Vector<float> features, Scalar<float> weights,
FastTreeRegressionTrainer.Options options,
Action<FastTreeRegressionModelParameters> onFit = null)
{
Contracts.CheckValueOrNull(options);
CheckUserValues(label, features, weights, onFit);
var rec = new TrainerEstimatorReconciler.Regression(
(env, labelName, featuresName, weightsName) =>
{
options.LabelColumnName = labelName;
options.FeatureColumnName = featuresName;
options.ExampleWeightColumnName = weightsName;
var trainer = new FastTreeRegressionTrainer(env, options);
if (onFit != null)
return trainer.WithOnFitDelegate(trans => onFit(trans.Model));
return trainer;
}, label, features, weights);
return rec.Score;
}
/// <summary>
/// FastTree <see cref="BinaryClassificationCatalog"/> extension method.
/// Predict a target using a decision tree binary classification model trained with the <see cref="FastTreeBinaryClassificationTrainer"/>.
/// </summary>
/// <param name="catalog">The <see cref="BinaryClassificationCatalog"/>.</param>
/// <param name="label">The label column.</param>
/// <param name="features">The features column.</param>
/// <param name="weights">The optional weights column.</param>
/// <param name="numTrees">Total number of decision trees to create in the ensemble.</param>
/// <param name="numLeaves">The maximum number of leaves per decision tree.</param>
/// <param name="minDatapointsInLeaves">The minimal number of datapoints allowed in a leaf of the tree, out of the subsampled data.</param>
/// <param name="learningRate">The learning rate.</param>
/// <param name="onFit">A delegate that is called every time the
/// <see cref="Estimator{TInShape, TOutShape, TTransformer}.Fit(DataView{TInShape})"/> method is called on the
/// <see cref="Estimator{TInShape, TOutShape, TTransformer}"/> instance created out of this. This delegate will receive
/// the linear model that was trained. Note that this action cannot change the result in any way;
/// it is only a way for the caller to be informed about what was learnt.</param>
/// <returns>The set of output columns including in order the predicted binary classification score (which will range
/// from negative to positive infinity), the calibrated prediction (from 0 to 1), and the predicted label.</returns>
/// <example>
/// <format type="text/markdown">
/// <]
/// ]]></format>
/// </example>
public static (Scalar<float> score, Scalar<float> probability, Scalar<bool> predictedLabel) FastTree(this BinaryClassificationCatalog.BinaryClassificationTrainers catalog,
Scalar<bool> label, Vector<float> features, Scalar<float> weights = null,
int numLeaves = Defaults.NumLeaves,
int numTrees = Defaults.NumTrees,
int minDatapointsInLeaves = Defaults.MinDocumentsInLeaves,
double learningRate = Defaults.LearningRates,
Action<CalibratedModelParametersBase<FastTreeBinaryModelParameters, PlattCalibrator>> onFit = null)
{
CheckUserValues(label, features, weights, numLeaves, numTrees, minDatapointsInLeaves, learningRate, onFit);
var rec = new TrainerEstimatorReconciler.BinaryClassifier(
(env, labelName, featuresName, weightsName) =>
{
var trainer = new FastTreeBinaryClassificationTrainer(env, labelName, featuresName, weightsName, numLeaves,
numTrees, minDatapointsInLeaves, learningRate);
if (onFit != null)
return trainer.WithOnFitDelegate(trans => onFit(trans.Model));
else
return trainer;
}, label, features, weights);
return rec.Output;
}
/// <summary>
/// FastTree <see cref="BinaryClassificationCatalog"/> extension method.
/// Predict a target using a decision tree binary classification model trained with the <see cref="FastTreeBinaryClassificationTrainer"/>.
/// </summary>
/// <param name="catalog">The <see cref="BinaryClassificationCatalog"/>.</param>
/// <param name="label">The label column.</param>
/// <param name="features">The features column.</param>
/// <param name="weights">The optional weights column.</param>
/// <param name="options">Algorithm advanced settings.</param>
/// <param name="onFit">A delegate that is called every time the
/// <see cref="Estimator{TInShape, TOutShape, TTransformer}.Fit(DataView{TInShape})"/> method is called on the
/// <see cref="Estimator{TInShape, TOutShape, TTransformer}"/> instance created out of this. This delegate will receive
/// the linear model that was trained. Note that this action cannot change the result in any way;
/// it is only a way for the caller to be informed about what was learnt.</param>
/// <returns>The set of output columns including in order the predicted binary classification score (which will range
/// from negative to positive infinity), the calibrated prediction (from 0 to 1), and the predicted label.</returns>
/// <example>
/// <format type="text/markdown">
/// <]
/// ]]></format>
/// </example>
public static (Scalar<float> score, Scalar<float> probability, Scalar<bool> predictedLabel) FastTree(this BinaryClassificationCatalog.BinaryClassificationTrainers catalog,
Scalar<bool> label, Vector<float> features, Scalar<float> weights,
FastTreeBinaryClassificationTrainer.Options options,
Action<CalibratedModelParametersBase<FastTreeBinaryModelParameters, PlattCalibrator>> onFit = null)
{
Contracts.CheckValueOrNull(options);
CheckUserValues(label, features, weights, onFit);
var rec = new TrainerEstimatorReconciler.BinaryClassifier(
(env, labelName, featuresName, weightsName) =>
{
options.LabelColumnName = labelName;
options.FeatureColumnName = featuresName;
options.ExampleWeightColumnName = weightsName;
var trainer = new FastTreeBinaryClassificationTrainer(env, options);
if (onFit != null)
return trainer.WithOnFitDelegate(trans => onFit(trans.Model));
else
return trainer;
}, label, features, weights);
return rec.Output;
}
/// <summary>
/// FastTree <see cref="RankingCatalog"/>.
/// Ranks a series of inputs based on their relevance, training a decision tree ranking model through the <see cref="FastTreeRankingTrainer"/>.
/// </summary>
/// <param name="catalog">The <see cref="RegressionCatalog"/>.</param>
/// <param name="label">The label column.</param>
/// <param name="features">The features column.</param>
/// <param name="groupId">The groupId column.</param>
/// <param name="weights">The optional weights column.</param>
/// <param name="numTrees">Total number of decision trees to create in the ensemble.</param>
/// <param name="numLeaves">The maximum number of leaves per decision tree.</param>
/// <param name="minDatapointsInLeaves">The minimal number of datapoints allowed in a leaf of a regression tree, out of the subsampled data.</param>
/// <param name="learningRate">The learning rate.</param>
/// <param name="onFit">A delegate that is called every time the
/// <see cref="Estimator{TInShape, TOutShape, TTransformer}.Fit(DataView{TInShape})"/> method is called on the
/// <see cref="Estimator{TInShape, TOutShape, TTransformer}"/> instance created out of this. This delegate will receive
/// the linear model that was trained. Note that this action cannot change the result in any way;
/// it is only a way for the caller to be informed about what was learnt.</param>
/// <returns>The Score output column indicating the predicted value.</returns>
public static Scalar<float> FastTree<TVal>(this RankingCatalog.RankingTrainers catalog,
Scalar<float> label, Vector<float> features, Key<uint, TVal> groupId, Scalar<float> weights = null,
int numLeaves = Defaults.NumLeaves,
int numTrees = Defaults.NumTrees,
int minDatapointsInLeaves = Defaults.MinDocumentsInLeaves,
double learningRate = Defaults.LearningRates,
Action<FastTreeRankingModelParameters> onFit = null)
{
CheckUserValues(label, features, weights, numLeaves, numTrees, minDatapointsInLeaves, learningRate, onFit);
var rec = new TrainerEstimatorReconciler.Ranker<TVal>(
(env, labelName, featuresName, groupIdName, weightsName) =>
{
var trainer = new FastTreeRankingTrainer(env, labelName, featuresName, groupIdName, weightsName, numLeaves,
numTrees, minDatapointsInLeaves, learningRate);
if (onFit != null)
return trainer.WithOnFitDelegate(trans => onFit(trans.Model));
return trainer;
}, label, features, groupId, weights);
return rec.Score;
}
/// <summary>
/// FastTree <see cref="RankingCatalog"/>.
/// Ranks a series of inputs based on their relevance, training a decision tree ranking model through the <see cref="FastTreeRankingTrainer"/>.
/// </summary>
/// <param name="catalog">The <see cref="RegressionCatalog"/>.</param>
/// <param name="label">The label column.</param>
/// <param name="features">The features column.</param>
/// <param name="groupId">The groupId column.</param>
/// <param name="weights">The optional weights column.</param>
/// <param name="options">Algorithm advanced settings.</param>
/// <param name="onFit">A delegate that is called every time the
/// <see cref="Estimator{TInShape, TOutShape, TTransformer}.Fit(DataView{TInShape})"/> method is called on the
/// <see cref="Estimator{TInShape, TOutShape, TTransformer}"/> instance created out of this. This delegate will receive
/// the linear model that was trained. Note that this action cannot change the result in any way;
/// it is only a way for the caller to be informed about what was learnt.</param>
/// <returns>The Score output column indicating the predicted value.</returns>
public static Scalar<float> FastTree<TVal>(this RankingCatalog.RankingTrainers catalog,
Scalar<float> label, Vector<float> features, Key<uint, TVal> groupId, Scalar<float> weights,
FastTreeRankingTrainer.Options options,
Action<FastTreeRankingModelParameters> onFit = null)
{
Contracts.CheckValueOrNull(options);
CheckUserValues(label, features, weights, onFit);
var rec = new TrainerEstimatorReconciler.Ranker<TVal>(
(env, labelName, featuresName, groupIdName, weightsName) =>
{
options.LabelColumnName = labelName;
options.FeatureColumnName = featuresName;
options.RowGroupColumnName = groupIdName;
options.ExampleWeightColumnName = weightsName;
var trainer = new FastTreeRankingTrainer(env, options);
if (onFit != null)
return trainer.WithOnFitDelegate(trans => onFit(trans.Model));
return trainer;
}, label, features, groupId, weights);
return rec.Score;
}
internal static void CheckUserValues(PipelineColumn label, Vector<float> features, Scalar<float> weights,
int numLeaves,
int numTrees,
int minDatapointsInLeaves,
double learningRate,
Delegate onFit)
{
Contracts.CheckValue(label, nameof(label));
Contracts.CheckValue(features, nameof(features));
Contracts.CheckValueOrNull(weights);
Contracts.CheckParam(numLeaves >= 2, nameof(numLeaves), "Must be at least 2.");
Contracts.CheckParam(numTrees > 0, nameof(numTrees), "Must be positive");
Contracts.CheckParam(minDatapointsInLeaves > 0, nameof(minDatapointsInLeaves), "Must be positive");
Contracts.CheckParam(learningRate > 0, nameof(learningRate), "Must be positive");
Contracts.CheckValueOrNull(onFit);
}
internal static void CheckUserValues(PipelineColumn label, Vector<float> features, Scalar<float> weights,
Delegate onFit)
{
Contracts.CheckValue(label, nameof(label));
Contracts.CheckValue(features, nameof(features));
Contracts.CheckValueOrNull(weights);
Contracts.CheckValueOrNull(onFit);
}
}
}
| 59.411392 | 179 | 0.638223 | [
"MIT"
] | endintiers/machinelearning | src/Microsoft.ML.StaticPipe/TreeTrainersStatic.cs | 18,776 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using HuaweiCloud.SDK.Core;
namespace HuaweiCloud.SDK.Kafka.V2.Model
{
/// <summary>
/// Response Object
/// </summary>
public class UpdateInstanceAutoCreateTopicResponse : SdkResponse
{
}
}
| 18.904762 | 68 | 0.740554 | [
"Apache-2.0"
] | cnblogs/huaweicloud-sdk-net-v3 | Services/Kafka/V2/Model/UpdateInstanceAutoCreateTopicResponse.cs | 397 | C# |
using System;
using System.Collections.Generic;
using UniJSON;
namespace UniGLTF
{
/// <summary>
/// https://github.com/KhronosGroup/glTF/issues/1036
/// </summary>
[Serializable]
public partial class glTFMesh_extras : ExtraBase<glTFMesh_extras>
{
[JsonSchema(Required = true, MinItems = 1)]
public List<string> targetNames = new List<string>();
[JsonSerializeMembers]
void PrimitiveMembers(GLTFJsonFormatter f)
{
if (targetNames.Count > 0)
{
f.Key("targetNames");
f.BeginList();
foreach (var x in targetNames)
{
f.Value(x);
}
f.EndList();
}
}
}
}
| 23.636364 | 69 | 0.516667 | [
"MIT"
] | DanielHands008/VTuber-App | Assets/VRM/UniGLTF/Scripts/Format/ExtensionsAndExtras/glTFMesh.extras.targetNames.cs | 782 | C# |
// Copyright (C) 2007 Jesse Jones
//
// 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 Mono.Cecil;
using Mono.Cecil.Cil;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Smokey.Framework;
using Smokey.Framework.Instructions;
using Smokey.Framework.Support;
namespace Smokey.Internal.Rules
{
internal sealed class ArgumentException2Rule : Rule
{
public ArgumentException2Rule(AssemblyCache cache, IReportViolations reporter)
: base(cache, reporter, "C1032")
{
}
public override void Register(RuleDispatcher dispatcher)
{
dispatcher.Register(this, "VisitBegin");
dispatcher.Register(this, "VisitNew");
dispatcher.Register(this, "VisitEnd");
}
public void VisitBegin(BeginMethod begin)
{
Log.DebugLine(this, "-----------------------------------");
Log.DebugLine(this, "{0:F}", begin.Info.Instructions);
m_offset = -1;
m_info = begin.Info;
m_args.Clear();
bool badNames = false;
for (int i = 0; i < begin.Info.Method.Parameters.Count; ++i)
{
ParameterReference p = begin.Info.Method.Parameters[i];
if (!p.Name.StartsWith("A_"))
{
Log.DebugLine(this, "adding {0}", p.Name);
m_args.Add(p.Name);
}
else
{
Log.DebugLine(this, "skipping {0}", p.Name);
badNames = true;
}
}
if (begin.Info.Method.Name.StartsWith("set_"))
{
m_args.Add(begin.Info.Method.Name.Substring(4));
m_args.Add("value");
Log.DebugLine(this, "added value and {0}", begin.Info.Method.Name.Substring(4));
}
if (badNames)
m_args.Clear();
}
public void VisitNew(NewObj obj)
{
if (m_offset < 0 && m_args.Count > 0)
{
if (obj.Ctor.ToString() == "System.Void System.ArgumentNullException::.ctor(System.String)" || obj.Ctor.ToString() == "System.Void System.ArgumentOutOfRangeException::.ctor(System.String)")
{
LoadString load = m_info.Instructions[obj.Index - 1] as LoadString;
if (load != null)
{
if (m_args.IndexOf(load.Value) < 0)
{
m_offset = obj.Untyped.Offset;
Log.DebugLine(this, "bad new at {0:X2}", m_offset);
}
}
}
}
}
public void VisitEnd(EndMethod end)
{
if (m_offset >= 0)
{
Reporter.MethodFailed(end.Info.Method, CheckID, m_offset, string.Empty);
}
}
private int m_offset;
private MethodInfo m_info;
private List<string> m_args = new List<string>();
}
}
| 30.286957 | 193 | 0.674706 | [
"MIT"
] | dbremner/smokey | source/internal/rules/correctness/ArgumentException2Rule.cs | 3,483 | C# |
using DelegationPokerApp.Dtos;
using System.Collections.Generic;
namespace DelegationPokerApp.Services
{
public interface ITeamService
{
TeamAddOrUpdateResponseDto AddOrUpdate(TeamAddOrUpdateRequestDto request);
ICollection<TeamDto> Get();
TeamDto GetById(int id);
dynamic Remove(int id);
}
}
| 24.142857 | 82 | 0.724852 | [
"MIT"
] | QuinntyneBrown/delegation-poker-app | DelegationPokerApp/Services/ITeamService.cs | 338 | C# |
using System.Collections.Generic;
namespace Dukkan.Authorization.Roles.Dto
{
public class GetRoleForEditOutput
{
public RoleEditDto Role { get; set; }
public List<FlatPermissionDto> Permissions { get; set; }
public List<string> GrantedPermissionNames { get; set; }
}
} | 23.692308 | 64 | 0.685065 | [
"MIT"
] | dukkan/dukkan | aspnet-core/src/Dukkan.Application.Shared/Authorization/Roles/Dto/GetRoleForEditOutput.cs | 310 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.TypeInfos;
using System.Reflection.Runtime.CustomAttributes;
using Internal.Reflection.Core;
using Internal.Reflection.Core.Execution;
using FieldAccessException = System.MemberAccessException;
namespace System.Reflection.Runtime.FieldInfos
{
internal sealed class LiteralFieldAccessor : FieldAccessor
{
public LiteralFieldAccessor(Object value)
{
_value = value;
}
public sealed override Object GetField(Object obj)
{
return _value;
}
public sealed override void SetField(Object obj, Object value)
{
throw new FieldAccessException(SR.Acc_ReadOnly);
}
private readonly Object _value;
}
}
| 26.190476 | 71 | 0.716364 | [
"MIT"
] | LaudateCorpus1/corert | src/System.Private.Reflection.Core/src/System/Reflection/Runtime/FieldInfos/LiteralFieldAccessor.cs | 1,100 | C# |
using Cysharp.Threading.Tasks;
using Cysharp.Threading.Tasks.Linq;
using Millennium.InGame.Effect;
using Millennium.InGame.Entity.Bullet;
using Millennium.Mathematics;
using Millennium.Sound;
using System;
using System.Threading;
using UnityEngine;
namespace Millennium.InGame.Entity.Enemy
{
public class MidBossAkane : BossBase
{
[SerializeField]
private GameObject m_NormalShotPrefab;
[SerializeField]
private GameObject m_RewardItemPrefab;
private void Start()
{
OnStart().Forget();
}
private async UniTaskVoid OnStart()
{
var destroyToken = this.GetCancellationTokenOnDestroy();
SetupHealthGauge(1, destroyToken);
DamageWhenEnter(destroyToken).Forget();
SuppressEnemySpawn(destroyToken);
await RandomMove(2, destroyToken);
Health = HealthMax = 8000;
await RunPhase(async token =>
{
await foreach (var _ in UniTaskAsyncEnumerable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(1), PlayerLoopTiming.FixedUpdate)
.Take(4)
.WithCancellation(token))
{
await ReflectionShot(token);
}
await UniTask.Delay(TimeSpan.FromSeconds(4), cancellationToken: token);
}, destroyToken);
await OnEndPhaseShort(destroyToken);
await EscapeEvent(m_RewardItemPrefab, destroyToken);
destroyToken.ThrowIfCancellationRequested();
Destroy(gameObject);
}
private async UniTask ReflectionShot(CancellationToken token)
{
if (token.IsCancellationRequested)
return;
async UniTask Phase(float direction, float leftRight, CancellationToken token)
{
int ways = 25;
float wayRadian = 6 * Mathf.Deg2Rad;
await UniTaskAsyncEnumerable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(0.05), PlayerLoopTiming.FixedUpdate)
.Select((_, i) => i)
.Take(ways)
.ForEachAsync(i =>
{
var bullet = BulletBase.Instantiate(m_NormalShotPrefab, transform.position, BallisticMath.FromPolar((i & 1) != 0 ? 48 : 32, direction + i * wayRadian * leftRight));
ReflectionBullet(bullet, bullet.GetCancellationTokenOnDestroy()).Forget();
SoundManager.I.PlaySe(SeType.EnemyShot).Forget();
EffectManager.I.Play(EffectType.MuzzleFlash, transform.position);
}, token);
await RandomMove(2, token);
}
await Phase(-Mathf.PI / 2, -1, token);
await Phase(-Mathf.PI / 2, +1, token);
}
private async UniTaskVoid ReflectionBullet(BulletBase bullet, CancellationToken token)
{
await UniTask.WaitUntil(() => bullet.transform.position.x < InGameConstants.FieldArea.xMin || bullet.transform.position.x > InGameConstants.FieldArea.xMax,
PlayerLoopTiming.FixedUpdate, cancellationToken: token);
if (token.IsCancellationRequested)
return;
bullet.Speed = new Vector3(-bullet.Speed.x, bullet.Speed.y);
SoundManager.I.PlaySe(SeType.PlayerBulletImmune).Forget();
}
}
}
| 32.660377 | 188 | 0.593876 | [
"MIT"
] | andanteyk/Millennium | Assets/Millennium/Scripts/InGame/Entity/Enemy/MidBossAkane.cs | 3,462 | C# |
using System;
namespace Abc.Zebus.Tests.Dispatch.DispatchMessages
{
public class AsyncFailingCommand : ICommand
{
public Exception Exception { get; }
public bool ThrowSynchronously { get; set; }
public AsyncFailingCommand(Exception exception)
{
Exception = exception;
}
}
}
| 21.3125 | 55 | 0.636364 | [
"MIT"
] | Abc-Arbitrage/Zebus | src/Abc.Zebus.Tests/Dispatch/DispatchMessages/AsyncFailingCommand.cs | 343 | C# |
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class LoadFirstLevel : MonoBehaviour
{
private bool levelLoaded = false;
void Update()
{
KinectManager manager = KinectManager.Instance;
if(!levelLoaded && manager && KinectManager.IsKinectInitialized())
{
levelLoaded = true;
SceneManager.LoadScene(1);
}
}
}
| 18.045455 | 69 | 0.690176 | [
"MIT"
] | KevinWu57/EmbodiedAI-Gesture | 3rd-Party/Kinect/KinectScripts/MultiScene/LoadFirstLevel.cs | 397 | C# |
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using AGS.API;
using AGS.Engine;
namespace AGS.Editor
{
public static class BreakDebuggerForm
{
private static API.IComponent _component;
private static string _property;
public static async Task Show(AGSEditor editor)
{
if (_component != null)
{
_component.PropertyChanged -= onPropertyChanged;
}
var gameSelector = new ComboboxboxField("Game", "Game", "Editor");
var entitySelector = new TextboxField("Entity ID");
var componentSelector = new TextboxField("Component");
var propertySelector = new TextboxField("Property Name");
var simpleForm = new SimpleForm(editor.Editor, gameSelector, entitySelector, componentSelector, propertySelector);
await simpleForm.ShowAsync("Break Debugger when property changes");
var game = gameSelector.Value == "Game" ? editor.Game : editor.Editor;
var entity = game.Find<IEntity>(entitySelector.Value);
if (entity == null)
{
await AGSMessageBox.DisplayAsync($"Did not find entity id {entitySelector.Value}", editor.Editor);
return;
}
var component = entity.FirstOrDefault(c => c.Name == componentSelector.Value);
if (component == null)
{
await AGSMessageBox.DisplayAsync($"Did not find component {componentSelector.Value} for entity id {entitySelector.Value}", editor.Editor);
return;
}
_component = component;
_property = propertySelector.Value;
component.PropertyChanged += onPropertyChanged;
}
private static void onPropertyChanged(object sender, PropertyChangedEventArgs args)
{
if (args.PropertyName == _property)
{
Debugger.Break();
}
}
}
} | 38.679245 | 154 | 0.607317 | [
"Artistic-2.0"
] | tzachshabtay/MonoAGS | Source/Editor/AGS.Editor/Debugging/BreakDebuggerForm.cs | 2,052 | C# |
using System.Linq;
using Dfc.CourseDirectory.Core.DataStore.CosmosDb.Queries;
using OneOf;
using OneOf.Types;
namespace Dfc.CourseDirectory.Testing.DataStore.CosmosDb.QueryHandlers
{
public class UpdateProviderFromUkrlpDataHandler :
ICosmosDbQueryHandler<UpdateProviderFromUkrlpData, OneOf<NotFound, Success>>
{
public OneOf<NotFound, Success> Execute(
InMemoryDocumentStore inMemoryDocumentStore,
UpdateProviderFromUkrlpData request)
{
var provider = inMemoryDocumentStore.Providers.All.SingleOrDefault(p => p.Id == request.ProviderId);
if (provider == null)
{
return new NotFound();
}
provider.ProviderName = request.ProviderName;
provider.ProviderAliases = request.Aliases.ToList();
provider.ProviderContact = request.Contacts.ToList();
provider.Alias = request.Alias;
provider.ProviderStatus = request.ProviderStatus;
provider.DateUpdated = request.DateUpdated;
provider.UpdatedBy = request.UpdatedBy;
inMemoryDocumentStore.Providers.Save(provider);
return new Success();
}
}
}
| 34.111111 | 112 | 0.659609 | [
"MIT"
] | SkillsFundingAgency/dfc-coursedirectory | tests/Dfc.CourseDirectory.Testing/DataStore/CosmosDb/QueryHandlers/UpdateProviderFromUkrlpDataHandler.cs | 1,230 | C# |
using System.Windows.Input;
using Windows.UI.Xaml;
namespace ArtCat.Services.DragAndDrop
{
public class ListViewDropConfiguration : DropConfiguration
{
public static readonly DependencyProperty DragItemsStartingCommandProperty =
DependencyProperty.Register("DragItemsStartingCommand", typeof(ICommand), typeof(DropConfiguration), new PropertyMetadata(null));
public static readonly DependencyProperty DragItemsCompletedCommandProperty =
DependencyProperty.Register("DragItemsCompletedCommand", typeof(ICommand), typeof(DropConfiguration), new PropertyMetadata(null));
public ICommand DragItemsStartingCommand
{
get { return (ICommand)GetValue(DragItemsStartingCommandProperty); }
set { SetValue(DragItemsStartingCommandProperty, value); }
}
public ICommand DragItemsCompletedCommand
{
get { return (ICommand)GetValue(DragItemsCompletedCommandProperty); }
set { SetValue(DragItemsCompletedCommandProperty, value); }
}
}
}
| 38.392857 | 142 | 0.724651 | [
"MIT"
] | marsscotia/ArtCat | ArtCat/Services/DragAndDrop/ListViewDropConfiguration.cs | 1,077 | C# |
public class DiagnosticEventCollector : MonoBehaviour // TypeDefIndex: 4508
{
// Fields
private static DiagnosticEventCollector s_Collector; // 0x0
// Properties
public static Guid PlayerConnectionGuid { get; }
// Methods
// RVA: 0x19D6CB0 Offset: 0x19D6DB1 VA: 0x19D6CB0
public static Guid get_PlayerConnectionGuid() { }
// RVA: 0x19D6DD0 Offset: 0x19D6ED1 VA: 0x19D6DD0
public static DiagnosticEventCollector FindOrCreateGlobalInstance() { }
// RVA: 0x19D6F80 Offset: 0x19D7081 VA: 0x19D6F80
public static bool RegisterEventHandler(Action<DiagnosticEvent> handler, bool register, bool create) { }
// RVA: 0x19D7070 Offset: 0x19D7171 VA: 0x19D7070
public void UnregisterEventHandler(Action<DiagnosticEvent> handler) { }
// RVA: 0x19D7180 Offset: 0x19D7281 VA: 0x19D7180
public void PostEvent(DiagnosticEvent diagnosticEvent) { }
// RVA: 0x19D7400 Offset: 0x19D7501 VA: 0x19D7400
public void .ctor() { }
}
| 31.066667 | 105 | 0.76824 | [
"MIT"
] | SinsofSloth/RF5-global-metadata | UnityEngine/ResourceManagement/Diagnostics/DiagnosticEventCollector.cs | 932 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
public class Enemy : MonoBehaviour
{
[SerializeField] private float speed;
private GameObject player;
private Rigidbody enemyRigidbody;
// Start is called before the first frame update
void Start()
{
enemyRigidbody = GetComponent<Rigidbody>();
player = GameObject.Find("Player");
}
// Update is called once per frame
void Update()
{
Vector3 lookDirection = (player.transform.position - transform.position).normalized;
enemyRigidbody.AddForce(lookDirection * speed);
if (transform.position.y < -10)
{
Destroy(gameObject);
}
}
}
| 23.393939 | 92 | 0.65285 | [
"MIT"
] | OmerKilicc/CreateWithCode | Prototype4/Assets/Prototype4/Scripts/Enemy.cs | 772 | C# |
namespace Microsoft.NetConf2021.Maui.Pages
{
public partial class ShowDetailPage : ContentPage
{
private ShowDetailViewModel viewModel => BindingContext as ShowDetailViewModel;
public ShowDetailPage(ShowDetailViewModel vm)
{
InitializeComponent();
BindingContext = vm;
}
protected override async void OnAppearing()
{
base.OnAppearing();
this.player.OnAppearing();
await viewModel.InitializeAsync();
}
protected override void OnDisappearing()
{
this.player.OnDisappearing();
base.OnDisappearing();
}
}
}
| 25.296296 | 87 | 0.594436 | [
"MIT"
] | JoonghyunCho/dotnet-podcasts | src/Mobile/Pages/ShowDetailPage.xaml.cs | 685 | C# |
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using ISSU.Data.UoW;
using ISSU.Models;
using ISSU.Web.Models;
using ISSU.Data;
using Microsoft.Owin.Security;
using System.Web;
namespace ISSU.Web.Areas.API.Controllers
{
public class AccountController : ApiController
{
[HttpPost]
public HttpResponseMessage Login(LoginViewModel model)
{
UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ISSUContext()));
if (ModelState.IsValid)
{
ApplicationUser user = userManager.Find(model.UserName, model.Password);
if (user != null)
return Request.CreateResponse(HttpStatusCode.OK, user);
return Request.CreateResponse(HttpStatusCode.NotModified, model);
}
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
}
| 28.575 | 139 | 0.688539 | [
"MIT"
] | betrakiss/ISSU | ISSU.Web/Areas/API/Controllers/AccountController.cs | 1,145 | C# |
#region license
// Copyright (c) HatTrick Labs, LLC. 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.
//
// The latest version of this file can be found at https://github.com/HatTrickLabs/db-ex
#endregion
using System;
namespace HatTrick.DbEx.Sql.Expression
{
public abstract partial class NullableInt64FieldExpression :
NullableFieldExpression<long,long?>,
NullableInt64Element,
AnyInt64Element,
IEquatable<NullableInt64FieldExpression>
{
#region constructors
protected NullableInt64FieldExpression(string identifier, string name, EntityExpression entity) : base(identifier, name, entity)
{
}
#endregion
#region as
public abstract NullableInt64Element As(string alias);
#endregion
#region equals
public bool Equals(NullableInt64FieldExpression obj)
=> obj is NullableInt64FieldExpression && base.Equals(obj);
public override bool Equals(object obj)
=> obj is NullableInt64FieldExpression exp && base.Equals(exp);
public override int GetHashCode()
=> base.GetHashCode();
#endregion
}
}
| 32.788462 | 136 | 0.697947 | [
"Apache-2.0"
] | HatTrickLabs/dbExpression | src/HatTrick.DbEx.Sql/Expression/_Field/NullableInt64FieldExpression.cs | 1,705 | C# |
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//[assembly: AssemblyTitle("CRA.ClientLibrary")]
[assembly: AssemblyDescription("")]
//[assembly: AssemblyConfiguration("")]
//[assembly: AssemblyCompany("")]
//[assembly: AssemblyProduct("CRA.ClientLibrary")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ef23eb6a-e329-496d-9b7a-8cad66ea4e3a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyVersion("1.0.0.0")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
[module: SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Scope = "member", Target = "CRA.ClientLibrary.VertexTable.#.ctor(System.String,System.String,System.String,System.String,System.Int32,System.Linq.Expressions.Expression`1<System.Func`1<CRA.ClientLibrary.IVertex>>,System.Object)")]
[module: SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Scope = "member", Target = "CRA.ClientLibrary.CRAClientLibrary.#DefineVertex(System.String,System.Linq.Expressions.Expression`1<System.Func`1<CRA.ClientLibrary.IVertex>>)")]
| 50.25 | 325 | 0.763682 | [
"MIT"
] | ArcadeMode/CRA | src/CRA.ClientLibrary/Properties/AssemblyInfo.cs | 2,013 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// Static class that contains static glm functions
/// </summary>
public static partial class glm
{
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public static uint[,] Values(umat5x2 m) => m.Values;
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public static uint[] Values1D(umat5x2 m) => m.Values1D;
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public static IEnumerator<uint> GetEnumerator(umat5x2 m) => m.GetEnumerator();
}
}
| 27.333333 | 86 | 0.626016 | [
"MIT"
] | akriegman/GlmSharpN | GlmSharp/GlmSharpCompat5/Mat5x2/umat5x2.glm.cs | 984 | C# |
using System.Threading.Tasks;
using Abp.Configuration;
using Abp.Zero.Configuration;
using Azmoon.Authorization.Accounts.Dto;
using Azmoon.Authorization.Users;
namespace Azmoon.Authorization.Accounts
{
public class AccountAppService : AzmoonAppServiceBase, IAccountAppService
{
// from: http://regexlib.com/REDetails.aspx?regexp_id=1923
public const string PasswordRegex = "(?=^.{8,}$)(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\\s)[0-9a-zA-Z!@#$%^&*()]*$";
private readonly UserRegistrationManager _userRegistrationManager;
public AccountAppService(
UserRegistrationManager userRegistrationManager)
{
_userRegistrationManager = userRegistrationManager;
}
public async Task<IsTenantAvailableOutput> IsTenantAvailable(IsTenantAvailableInput input)
{
var tenant = await TenantManager.FindByTenancyNameAsync(input.TenancyName);
if (tenant == null)
{
return new IsTenantAvailableOutput(TenantAvailabilityState.NotFound);
}
if (!tenant.IsActive)
{
return new IsTenantAvailableOutput(TenantAvailabilityState.InActive);
}
return new IsTenantAvailableOutput(TenantAvailabilityState.Available, tenant.Id);
}
public async Task<RegisterOutput> Register(RegisterInput input)
{
var user = await _userRegistrationManager.RegisterAsync(
input.Name,
input.Surname,
input.EmailAddress,
input.UserName,
input.Password,
true // Assumed email address is always confirmed. Change this if you want to implement email confirmation.
);
var isEmailConfirmationRequiredForLogin = await SettingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin);
return new RegisterOutput
{
CanLogin = user.IsActive && (user.IsEmailConfirmed || !isEmailConfirmationRequiredForLogin)
};
}
}
}
| 37.068966 | 174 | 0.64093 | [
"MIT"
] | mahdighorbanpour/Azmoon | aspnet-core/src/Azmoon.Application/Authorization/Accounts/AccountAppService.cs | 2,150 | C# |
#region License
/*
Copyright © 2014-2022 European Support Limited
Licensed under the Apache License, Version 2.0 (the "License")
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion
using System;
namespace Ginger.UserControlsLib.TextEditor.WebBrowser
{
public partial class WebBrowserDocumentPage : System.Windows.Controls.Page, ITextEditorPage
{
public WebBrowserDocumentPage()
{
InitializeComponent();
}
public bool Load(string FileName)
{
FileNameLabel.Content = FileName;
string s = "file://" + FileName;
webbrowser.Navigate(new Uri(s));
return true;
}
public void Save()
{
throw new NotImplementedException();
}
}
}
| 26.695652 | 96 | 0.667752 | [
"Apache-2.0"
] | FOSSAware/Ginger | Ginger/Ginger/UserControlsLib/TextEditor/WebBrowser/WebBrowserDocumentPage.xaml.cs | 1,229 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using JabboServerCMD.Core.Sockets;
using JabboServerCMD.Core.Systems;
using JabboServerCMD.Core.Instances.User;
using JabboServerCMD.Core.Instances.Room;
namespace JabboServerCMD.Core.Managers
{
public static class RoomManager
{
public static Hashtable _Rooms = new Hashtable();
public static Room joinRoom(ConnectedUser User, int roomID)
{
if (!containsRoom(roomID))
{
addRoom(roomID, new PrivateRoom(roomID));
getRoom(roomID).addUser(User);
return getRoom(roomID);
}
else
{
getRoom(roomID).addUser(User);
return getRoom(roomID);
}
}
public static void addRoom(int roomID, Room Room)
{
_Rooms.Add(roomID, Room);
}
public static void removeRoom(int roomID)
{
_Rooms.Remove(roomID);
GC.Collect();
}
public static bool containsRoom(int roomID)
{
return _Rooms.ContainsKey(roomID);
}
public static Room getRoom(int roomID)
{
return (Room)_Rooms[roomID];
}
public static int countBots()
{
int onlineBots = 0;
foreach (Room room in _Rooms.Values)
{
onlineBots += room._Bots.Count;
}
return onlineBots;
}
}
}
| 24.246154 | 67 | 0.550127 | [
"MIT"
] | jabbo/Jabbo | server/JabboServerCMD/Core/Managers/RoomManager.cs | 1,578 | C# |
using Bucket.EventBus.Abstractions;
using Bucket.EventBus.Attributes;
using Bucket.EventBus.Events;
using Bucket.EventBus.Util;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Polly;
using Polly.Retry;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ.Client.Exceptions;
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Bucket.EventBus.RabbitMQ
{
public class EventBusRabbitMQ : IEventBus, IDisposable
{
private readonly string _exchangeName = "bucket_event_bus";
private readonly IRabbitMQPersistentConnection _persistentConnection;
private readonly ILogger<EventBusRabbitMQ> _logger;
private readonly IEventBusSubscriptionsManager _subsManager;
private readonly IServiceProvider _autofac;
private readonly EventBusRabbitMqOptions _options;
private readonly int _retryCount;
private readonly ushort _prefetchCount;
private readonly string _queueName;
private IDictionary<string, IModel> _consumerChannels;
/// <summary>
/// Ctor
/// </summary>
/// <param name="persistentConnection"></param>
/// <param name="logger"></param>
/// <param name="autofac"></param>
/// <param name="subsManager"></param>
/// <param name="options"></param>
public EventBusRabbitMQ(IRabbitMQPersistentConnection persistentConnection, ILogger<EventBusRabbitMQ> logger, IServiceProvider autofac,
IEventBusSubscriptionsManager subsManager, IOptions<EventBusRabbitMqOptions> options)
{
_persistentConnection = persistentConnection ?? throw new ArgumentNullException(nameof(persistentConnection));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_subsManager = subsManager ?? throw new ArgumentNullException(nameof(subsManager));
_options = options.Value;
_exchangeName = _options.ExchangeName;
_queueName = _options.QueueName;
_consumerChannels = new Dictionary<string, IModel>();
_autofac = autofac;
_prefetchCount = _options.PrefetchCount;
_retryCount = _options.RetryCount;
_subsManager.OnEventRemoved += SubsManager_OnEventRemoved;
}
/// <summary>
/// RabbitMQ取消订阅
/// </summary>
/// <param name="sender"></param>
/// <param name="eventName"></param>
private void SubsManager_OnEventRemoved(object sender, string eventName)
{
if (!_persistentConnection.IsConnected)
{
_persistentConnection.TryConnect();
}
using (var channel = _persistentConnection.CreateModel())
{
foreach (var queueName in _consumerChannels.Keys)
{
channel.QueueUnbind(queue: queueName,
exchange: _exchangeName,
routingKey: eventName);
}
}
}
/// <summary>
/// 推送
/// </summary>
/// <param name="event"></param>
public void Publish(IntegrationEvent @event)
{
if (!_persistentConnection.IsConnected)
{
_persistentConnection.TryConnect();
}
var policy = Policy.Handle<BrokerUnreachableException>()
.Or<SocketException>()
.WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
{
// 防止logging走事件
// _logger.LogWarning(ex, "Could not publish event: {EventId} after {Timeout}s ({ExceptionMessage})", @event.Id, $"{time.TotalSeconds:n1}", ex.Message);
Console.WriteLine($"Could not publish event: {@event.Id} after {time.TotalSeconds:n1}s ({ex.Message})");
});
var eventName = @event.GetType().Name;
var message = JsonConvert.SerializeObject(@event);
var body = Encoding.UTF8.GetBytes(message);
using (var channel = _persistentConnection.CreateModel())
{
channel.ExchangeDeclare(exchange: _exchangeName, type: "direct");
policy.Execute(() =>
{
var properties = channel.CreateBasicProperties();
properties.DeliveryMode = 2; // persistent
channel.BasicPublish(exchange: _exchangeName, routingKey: eventName, mandatory: true, basicProperties: properties, body: body);
});
}
}
/// <summary>
/// 动态内容订阅
/// </summary>
/// <typeparam name="TH"></typeparam>
/// <param name="eventName"></param>
public void SubscribeDynamic<TH>(string eventName)
where TH : IDynamicIntegrationEventHandler
{
var (QueueName, PrefetchCount) = ConvertConsumerInfo<TH>();
DoInternalSubscription(eventName, QueueName, PrefetchCount);
_subsManager.AddDynamicSubscription<TH>(eventName);
}
/// <summary>
/// 订阅注册
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TH"></typeparam>
public void Subscribe<T, TH>()
where T : IntegrationEvent
where TH : IIntegrationEventHandler<T>
{
var eventName = _subsManager.GetEventKey<T>();
var (QueueName, PrefetchCount) = ConvertConsumerInfo<TH>();
DoInternalSubscription(eventName, QueueName, PrefetchCount);
_subsManager.AddSubscription<T, TH>();
}
/// <summary>
/// 转换事件处理器队列名
/// </summary>
/// <typeparam name="TH"></typeparam>
/// <returns></returns>
private (string QueueName, ushort PrefetchCount) ConvertConsumerInfo<TH>()
{
var queueName = _queueName;
var prefetchCount = _prefetchCount;
var consumerAttr = typeof(TH).GetCustomAttribute<QueueConsumerAttribute>();
if (consumerAttr != null)
{
queueName = consumerAttr.QueueName;
prefetchCount = consumerAttr.PrefetchCount <= 0 ? prefetchCount : consumerAttr.PrefetchCount;
}
return (queueName, prefetchCount);
}
private void DoInternalSubscription(string eventName, string queueName, ushort prefetchCount)
{
var containsKey = _subsManager.HasSubscriptionsForEvent(eventName);
if (!containsKey)
{
if (!_persistentConnection.IsConnected)
{
_persistentConnection.TryConnect();
}
if (!_consumerChannels.ContainsKey(queueName))
{
_consumerChannels.Add(queueName, CreateConsumerChannel(queueName, prefetchCount));
}
using (var channel = _persistentConnection.CreateModel())
{
channel.QueueBind(queue: queueName, exchange: _exchangeName, routingKey: eventName, arguments: new Dictionary<string, object> { { "x-queue-mode", "lazy" } });
}
}
}
/// <summary>
/// 取消订阅
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TH"></typeparam>
public void Unsubscribe<T, TH>()
where TH : IIntegrationEventHandler<T>
where T : IntegrationEvent
{
_subsManager.RemoveSubscription<T, TH>();
}
/// <summary>
/// 取消订阅
/// </summary>
/// <typeparam name="TH"></typeparam>
/// <param name="eventName"></param>
public void UnsubscribeDynamic<TH>(string eventName)
where TH : IDynamicIntegrationEventHandler
{
_subsManager.RemoveDynamicSubscription<TH>(eventName);
}
/// <summary>
/// 释放
/// </summary>
public void Dispose()
{
foreach (var key in _consumerChannels.Keys)
{
if (_consumerChannels.TryGetValue(key, out var _consumerChannel) && _consumerChannel != null)
{
_consumerChannel.Dispose();
}
}
_subsManager.Clear();
}
/// <summary>
/// 创建消费监听
/// </summary>
/// <returns></returns>
private IModel CreateConsumerChannel(string queueName, ushort prefetchCount)
{
if (!_persistentConnection.IsConnected)
{
_persistentConnection.TryConnect();
}
var channel = _persistentConnection.CreateModel();
channel.ExchangeDeclare(exchange: _exchangeName, type: "direct");
channel.QueueDeclare(queue: queueName, durable: true, exclusive: false, autoDelete: false, arguments: new Dictionary<string, object> { { "x-queue-mode", "lazy" } });
channel.BasicQos(0, prefetchCount, false);
channel.CallbackException += (sender, ea) =>
{
channel.Dispose();
channel = CreateConsumerChannel(queueName, prefetchCount);
};
return channel;
}
/// <summary>
/// 存在未订阅已消费误差,另外拎出来,事件执行器注册完成调用
/// </summary>
public void StartSubscribe()
{
foreach (var queueName in _consumerChannels.Keys)
{
_consumerChannels.TryGetValue(queueName, out var _consumerChannel);
if (_consumerChannel == null || _consumerChannel.IsClosed)
_consumerChannel = CreateConsumerChannel(queueName, _prefetchCount);
var consumer = new EventingBasicConsumer(_consumerChannel);
consumer.Received += async (model, ea) =>
{
var eventName = ea.RoutingKey;
var message = Encoding.UTF8.GetString(ea.Body);
try
{
await ProcessEvent(eventName, message);
}
catch (Exception exception)
{
_logger.LogError(exception, $"{DnsHelper.GetLanIp()}|{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}|{message}");
}
_consumerChannel.BasicAck(ea.DeliveryTag, multiple: false);
};
_consumerChannel.BasicConsume(queue: queueName, autoAck: false, consumer: consumer);
}
}
/// <summary>
/// 执行器
/// </summary>
/// <param name="eventName"></param>
/// <param name="message"></param>
/// <returns></returns>
private async Task ProcessEvent(string eventName, string message)
{
if (_subsManager.HasSubscriptionsForEvent(eventName))
{
using (var scope = _autofac.CreateScope())
{
var subscriptions = _subsManager.GetHandlersForEvent(eventName);
foreach (var subscription in subscriptions)
{
if (subscription.IsDynamic)
{
if (!(scope.ServiceProvider.GetRequiredService(subscription.HandlerType) is IDynamicIntegrationEventHandler handler)) continue;
await Task.Yield();
await handler.Handle(message);
}
else
{
var eventType = _subsManager.GetEventTypeByName(eventName);
if (eventType == null) continue;
var handler = scope.ServiceProvider.GetRequiredService(subscription.HandlerType);
if (handler == null) continue;
var integrationEvent = JsonConvert.DeserializeObject(message, eventType);
var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);
await Task.Yield();
await (Task)concreteType.GetMethod("Handle").Invoke(handler, new object[] { integrationEvent });
}
}
}
}
}
}
} | 40.956113 | 179 | 0.545121 | [
"MIT"
] | q315523275/.net-core- | src/EventBus/Bucket.EventBus.RabbitMQ/EventBusRabbitMQ.cs | 13,221 | C# |
using System.Text.Json.Serialization;
using Money;
using OrchardCore.Commerce.Serialization;
namespace OrchardCore.Commerce.Models
{
/// <summary>
/// A price and its priority.
/// </summary>
[JsonConverter(typeof(PrioritizedPriceConverter))]
public class PrioritizedPrice
{
/// <summary>
/// The priority for the price (higher takes precedence).
/// </summary>
public int Priority { get; }
/// <summary>
/// The price.
/// </summary>
public Amount Price { get; }
public PrioritizedPrice(int priority, Amount price)
{
Priority = priority;
Price = price;
}
}
}
| 24.206897 | 65 | 0.579772 | [
"MIT"
] | TRiV07/OrchardCore.Commerce | Models/PrioritizedPrice.cs | 702 | C# |
using System;
using System.Windows;
using System.Timers;
using System.Diagnostics;
using DiscordRPC.Main.ViewModels;
namespace DiscordRPC.Main.UI
{
public partial class GoAFKWindow : Window
{
public GoAFKWindow()
{
InitializeComponent();
BeginAFKTimer();
}
private static Timer TimeOutTimer;
private void BeginAFKTimer()
{
int timeout_value = 3000;
TimeOutTimer = new Timer(timeout_value);
TimeOutTimer.Elapsed += OnTimedEvent;
TimeOutTimer.Enabled = true;
}
private void OnTimedEvent(Object source, ElapsedEventArgs e)
{
StopTimer();
StartAFK();
}
private void StartAFK()
{
PresenceManager presenceManager = new PresenceManager();
presenceManager.useTimeStamp = true;
presenceManager.discordPresenceDetail = JsonConfig.settings.discordUsername;
presenceManager.discordPresenceState = (string)Application.Current.FindResource("discord_status_afk");
presenceManager.discordLargeImageKey = JsonConfig.settings.discordLargeImageKey;
presenceManager.discordLargeImageText = JsonConfig.settings.discordLargeImageText;
presenceManager.discordSmallImageKey = JsonConfig.settings.discordSmallImageText;
presenceManager.discordSmallImageText = JsonConfig.settings.discordSmallImageText;
presenceManager.UpdatePresence();
UpdateMainWindowViewModel.UpdateUserStatus("AFK (" + (string)Application.Current.FindResource("mw_label_status_placeholder_afk") + " " + DateTime.Now + ")");
Process.Start(@"C:\WINDOWS\system32\rundll32.exe", "user32.dll,LockWorkStation");
this.Dispatcher.Invoke((Action)(() =>
{
this.Close();
}));
}
private void Button_Click(object sender, RoutedEventArgs e)
{
StopTimer();
this.Close();
}
protected void StopTimer()
{
TimeOutTimer.Stop();
TimeOutTimer.Elapsed -= OnTimedEvent;
TimeOutTimer.Dispose();
}
}
}
| 31.549296 | 169 | 0.622768 | [
"Unlicense"
] | ddasutein/Discord-RPC-Customizer | src/DiscordRPC.Main/UI/GoAFKWindow.xaml.cs | 2,242 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LegoUI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Swinburne University")]
[assembly: AssemblyProduct("LegoUI")]
[assembly: AssemblyCopyright("Copyright © Swinburne University 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 42.857143 | 98 | 0.712083 | [
"Apache-2.0"
] | BAStevens/Lego-Ev3 | LegoUI/Properties/AssemblyInfo.cs | 2,403 | C# |
using System.Collections.Generic;
using cv19ResSupportV3.V3.Domain;
using cv19ResSupportV3.V3.Domain.Commands;
namespace cv19ResSupportV3.V3.Gateways
{
public interface ICallHandlerGateway
{
List<CallHandlerResponse> GetCallHandlers();
CallHandlerResponse GetCallHandler(int id);
CallHandlerResponse CreateCallHandler(CallHandlerCommand request);
CallHandlerResponse UpdateCallHandler(CallHandlerCommand request);
bool DeleteCallHandler(int id);
}
}
| 25.35 | 74 | 0.765286 | [
"MIT"
] | LBHSPreston/cv-19-res-support-v3 | cv19ResSupportV3/V3/Gateways/ICallHandlerGateway.cs | 507 | C# |
using BusinessLayer.DTO;
using Mapster;
using Riganti.Utils.Infrastructure.Core;
using System.Linq;
namespace BusinessLayer.Queries
{
public class BandInfoesQuery : AppQuery<BandInfoDTO>
{
public BandInfoesQuery(IUnitOfWorkProvider provider) : base(provider) { }
protected override IQueryable<BandInfoDTO> GetQueryable()
{
return Context.Bands.Where(x => x.Approved).ProjectToType<BandInfoDTO>();
}
}
}
| 25.666667 | 85 | 0.701299 | [
"Apache-2.0"
] | Arcidev/MusicLibrary | src/BusinessLayer/Queries/BandInfoesQuery.cs | 464 | C# |
using System;
using System.Threading.Tasks;
using BurnForMoney.Domain;
using BurnForMoney.Functions.Infrastructure.Queues;
using BurnForMoney.Functions.Shared.Extensions;
using BurnForMoney.Functions.Shared.Functions.Extensions;
using BurnForMoney.Functions.Shared.Helpers;
using BurnForMoney.Functions.Strava.Commands;
using BurnForMoney.Functions.Strava.Configuration;
using BurnForMoney.Functions.Strava.Exceptions;
using BurnForMoney.Functions.Strava.External.Strava.Api;
using BurnForMoney.Functions.Strava.External.Strava.Api.Model;
using BurnForMoney.Functions.Strava.Functions.EventsHub.Dto;
using BurnForMoney.Functions.Strava.Security;
using BurnForMoney.Identity;
using BurnForMoney.Infrastructure.Persistence.Repositories;
using BurnForMoney.Infrastructure.Persistence.Repositories.Dto;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Queue;
using Newtonsoft.Json;
namespace BurnForMoney.Functions.Strava.Functions.EventsHub
{
public static class EventsRouter
{
private static readonly StravaService StravaService = new StravaService();
[FunctionName(FunctionsNames.EventsRouter)]
public static async Task EventsHub([QueueTrigger(QueueNames.StravaEvents)] StravaWebhookEvent @event,
ILogger log, ExecutionContext executionContext,
[Queue(QueueNames.StravaEventsActivityAdd)] CloudQueue addActivityQueue,
[Queue(QueueNames.StravaEventsActivityUpdate)] CloudQueue updateActivityQueue,
[Queue(QueueNames.StravaEventsActivityDelete)] CloudQueue deleteActivityQueue,
[Queue(QueueNames.DeactivateAthleteRequests)] CloudQueue deauthorizationQueue,
[Configuration] ConfigurationRoot configuration)
{
var stravaAthleteId = @event.OwnerId.ToString();
var repository = new AthleteReadRepository(configuration.ConnectionStrings.SqlDbConnectionString);
var athlete = await repository.GetAthleteByStravaIdAsync(stravaAthleteId);
if (athlete == null)
{
// This can happen when the athlete is either deactivated (but authenticated) or has not yet been authorized.
log.LogWarning($"Athlete with strava id: {stravaAthleteId} does not exists.");
return;
}
if (athlete == AthleteRow.NonActive)
{
log.LogInformation($"Received an event from inactive athlete [{athlete.Id}].");
return;
}
var message = new ActivityData(athlete.Id, @event.ObjectId.ToString());
var json = JsonConvert.SerializeObject(message);
if (@event.ObjectType == ObjectType.Activity)
{
switch (@event.AspectType)
{
case AspectType.Create:
log.LogInformation(FunctionsNames.EventsRouter, $"Adding message to {QueueNames.StravaEventsActivityAdd} queue.");
await addActivityQueue.AddMessageAsync(new CloudQueueMessage(json));
break;
case AspectType.Update:
log.LogInformation(FunctionsNames.EventsRouter, $"Adding message to {QueueNames.StravaEventsActivityUpdate} queue.");
await updateActivityQueue.AddMessageAsync(new CloudQueueMessage(json), TimeSpan.FromDays(7), TimeSpan.FromMinutes(2), null, null); // Handle quick add->update operation. An event informing about the addition of activity may appear later.
break;
case AspectType.Delete:
log.LogInformation(FunctionsNames.EventsRouter, $"Adding message to {QueueNames.StravaEventsActivityDelete} queue.");
await deleteActivityQueue.AddMessageAsync(new CloudQueueMessage(json), TimeSpan.FromDays(7), TimeSpan.FromMinutes(2), null, null); // Handle quick add->delete operation. An event informing about the addition of activity may appear later.
break;
default:
throw new ArgumentOutOfRangeException();
}
log.LogInformation(FunctionsNames.EventsRouter, "Event message has been processed.");
}
else if (@event.ObjectType == ObjectType.Athlete)
{
log.LogInformation(FunctionsNames.EventsRouter, $"Adding message to {QueueNames.DeactivateAthleteRequests} queue.");
await deauthorizationQueue.AddMessageAsync(new CloudQueueMessage(message.AthleteId.ToString("D")));
}
else
{
throw new Exception($"Unknown event type: {@event.ObjectType}");
}
}
[FunctionName(FunctionsNames.Events_NewActivity)]
public static async Task Events_NewActivity([QueueTrigger(QueueNames.StravaEventsActivityAdd)] ActivityData activityData,
ILogger log,
[Queue(AppQueueNames.AddActivityRequests, Connection = "AppQueuesStorage")] CloudQueue addActivitiesRequestsQueue,
[Configuration] ConfigurationRoot configuration)
{
var accessToken = await GetAccessTokenAsync(activityData.AthleteId, configuration.Strava.AccessTokensKeyVaultUrl);
StravaActivity activity;
try
{
activity = StravaService.GetActivity(accessToken, activityData.StravaActivityId);
}
catch (ActivityNotFoundException ex)
{
log.LogWarning(ex.Message);
return;
}
var command = new AddActivityCommand
{
Id = ActivityIdentity.Next(),
ExternalId = activity.Id.ToString(),
AthleteId = activityData.AthleteId,
ActivityType = activity.Type.ToString(),
StartDate = activity.StartDate,
DistanceInMeters = activity.Distance,
MovingTimeInMinutes = UnitsConverter.ConvertSecondsToMinutes(activity.MovingTime),
Source = Source.Strava
};
var json = JsonConvert.SerializeObject(command);
var message = new CloudQueueMessage(json);
await addActivitiesRequestsQueue.AddMessageAsync(message);
}
[FunctionName(FunctionsNames.Events_UpdateActivity)]
public static async Task Events_UpdateActivity([QueueTrigger(QueueNames.StravaEventsActivityUpdate)] ActivityData activityData,
ILogger log,
[Queue(AppQueueNames.UpdateActivityRequests, Connection = "AppQueuesStorage")] CloudQueue updateActivityRequestsQueue,
[Configuration] ConfigurationRoot configuration)
{
var activityRepository = new ActivityReadRepository(configuration.ConnectionStrings.SqlDbConnectionString);
var accessToken = await GetAccessTokenAsync(activityData.AthleteId, configuration.Strava.AccessTokensKeyVaultUrl);
StravaActivity activity;
try
{
activity = StravaService.GetActivity(accessToken, activityData.StravaActivityId);
}
catch (ActivityNotFoundException ex)
{
log.LogWarning(ex.Message);
return;
}
var activityRow = await activityRepository.GetByExternalIdAsync(activityData.StravaActivityId);
var command = new UpdateActivityCommand
{
Id = activityRow.Id,
AthleteId = activityData.AthleteId,
ActivityType = activity.Type.ToString(),
StartDate = activity.StartDate,
DistanceInMeters = activity.Distance,
MovingTimeInMinutes = UnitsConverter.ConvertSecondsToMinutes(activity.MovingTime)
};
var json = JsonConvert.SerializeObject(command);
var message = new CloudQueueMessage(json);
await updateActivityRequestsQueue.AddMessageAsync(message);
}
private static async Task<string> GetAccessTokenAsync(Guid athleteId, string keyVaultBaseUrl)
{
var secret = await AccessTokensStore.GetAccessTokenForAsync(athleteId, keyVaultBaseUrl);
return secret.Value;
}
[FunctionName(FunctionsNames.Events_DeleteActivity)]
public static async Task Events_DeleteActivity([QueueTrigger(QueueNames.StravaEventsActivityDelete)] ActivityData @event,
ILogger log, ExecutionContext executionContext,
[Queue(AppQueueNames.DeleteActivityRequests, Connection = "AppQueuesStorage")] CloudQueue deleteActivitiesQueue,
[Configuration] ConfigurationRoot configuration)
{
var activityRepository = new ActivityReadRepository(configuration.ConnectionStrings.SqlDbConnectionString);
var activity = await activityRepository.GetByExternalIdAsync(@event.StravaActivityId);
var json = JsonConvert.SerializeObject(new DeleteActivityCommand { Id = activity.Id, AthleteId = @event.AthleteId });
var message = new CloudQueueMessage(json);
await deleteActivitiesQueue.AddMessageAsync(message);
}
}
} | 51.17033 | 261 | 0.666595 | [
"MIT"
] | makingwaves/BurnForMoney | src/BurnForMoney.Functions.Strava/Functions/EventsHub/EventsRouter.cs | 9,315 | C# |
using System.Collections.Generic;
namespace Reface.NPI.Generators
{
public class SqlCommandDescription : ICopy
{
public SqlCommandExecuteModes Mode { get; set; }
public string SqlCommand { get; set; }
public Dictionary<string, SqlParameterInfo> Parameters { get; private set; }
public void AddParameter(SqlParameterInfo info)
{
this.Parameters[info.Name] = info;
}
public SqlCommandDescription()
{
this.Parameters = new Dictionary<string, SqlParameterInfo>();
}
public override string ToString()
{
return $"Sql : {SqlCommand} \nParameterValues : \n{Parameters.Join("\n", x => $"\t{x.Value.ToString()}")}";
}
public object Copy()
{
return new SqlCommandDescription()
{
SqlCommand = this.SqlCommand,
Mode = this.Mode,
Parameters = new Dictionary<string, SqlParameterInfo>(this.Parameters)
};
}
}
}
| 27.763158 | 119 | 0.569668 | [
"MIT"
] | ShimizuShiori/Reface.NPI | src/Reface.NPI/Generators/SqlCommandDescription.cs | 1,057 | C# |
// T4 code generation is enabled for model 'D:\Lockdown E-commarace(MVC)\Lockdown-E-commarace--MVC-\Application\BaustManagementSys\Database\Baustmgt.edmx'.
// To enable legacy code generation, change the value of the 'Code Generation Strategy' designer
// property to 'Legacy ObjectContext'. This property is available in the Properties Window when the model
// is open in the designer.
// If no context and entity classes have been generated, it may be because you created an empty model but
// have not yet chosen which version of Entity Framework to use. To generate a context class and entity
// classes for your model, open the model in the designer, right-click on the designer surface, and
// select 'Update Model from Database...', 'Generate Database from Model...', or 'Add Code Generation
// Item...'. | 81.4 | 157 | 0.767813 | [
"MIT"
] | Abed0711/Lockdown-BAUST-Management-System--MVC- | Application/BaustManagementSys/Database/Baustmgt.Designer.cs | 816 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Cognitive Services: http://www.microsoft.com/cognitive
//
// Microsoft Cognitive Services Github:
// https://github.com/Microsoft/Cognitive
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// 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.Linq;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Media;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
namespace IntelligentKioskSample.Controls
{
public sealed partial class UpDownVerticalBarControl : UserControl
{
static SolidColorBrush BackgroundColor = new SolidColorBrush(Colors.Transparent);
public UpDownVerticalBarControl()
{
this.InitializeComponent();
}
public void DrawDataPoint(double value, Brush barColor, Image toolTip = null)
{
if (value > 0)
{
value *= 0.5;
topRowDefinition.Height = new GridLength(0.5 - value, GridUnitType.Star);
upBarRowDefinition.Height = new GridLength(value, GridUnitType.Star);
downBarRowDefinition.Height = new GridLength(0);
bottomRowDefinition.Height = new GridLength(0.5, GridUnitType.Star);
}
else
{
value *= -0.5;
topRowDefinition.Height = new GridLength(0.5, GridUnitType.Star);
upBarRowDefinition.Height = new GridLength(0);
downBarRowDefinition.Height = new GridLength(value, GridUnitType.Star);
bottomRowDefinition.Height = new GridLength(0.5 - value, GridUnitType.Star);
}
Border slice = new Border { Background = BackgroundColor };
Grid.SetRow(slice, 0);
graph.Children.Add(slice);
slice = new Border { Background = barColor };
Grid.SetRow(slice, 1);
graph.Children.Add(slice);
slice = new Border { Background = barColor };
Grid.SetRow(slice, 2);
graph.Children.Add(slice);
slice = new Border { Background = BackgroundColor };
Grid.SetRow(slice, 3);
graph.Children.Add(slice);
AddFlyoutToElement(graph, toolTip);
}
private void AddFlyoutToElement(FrameworkElement element, Image toolTip)
{
if (toolTip != null)
{
FlyoutBase.SetAttachedFlyout(element, new Flyout { Content = toolTip });
element.PointerReleased += (s, e) =>
{
FlyoutBase.ShowAttachedFlyout(element);
};
}
}
}
}
| 36.841121 | 96 | 0.643328 | [
"MIT"
] | Bhaskers-Blu-Org2/intelligent-apps | AlpineSkiHouseHappinessMeter/Controls/UpDownVerticalBarControl.xaml.cs | 3,944 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace CommandCenter.Models
{
/// <summary>
/// Actions enum.
/// </summary>
public enum ActionsEnum
{
/// <summary>
/// Activate the subscription.
/// </summary>
Activate,
/// <summary>
/// Update the subscription.
/// </summary>
Update,
/// <summary>
/// Ack.
/// </summary>
Ack,
/// <summary>
/// Unsubscribe.
/// </summary>
Unsubscribe,
}
} | 21.580645 | 101 | 0.5142 | [
"MIT"
] | Azure-Samples/Commercial-Marketplace-SaaS-Manual-On-Boarding | src/CommandCenter/Models/ActionsEnum.cs | 671 | C# |
namespace BeerApp.Web.Areas.Administration.ViewModels.Place
{
using System;
using System.ComponentModel.DataAnnotations;
using AutoMapper;
using BeerApp.Web.Infrastructure.Mapping;
using Data.Models;
public class AdminPlaceViewModel : IMapFrom<Place>, IHaveCustomMappings
{
public int Id { get; set; }
[Required]
[MaxLength(100)]
public string Name { get; set; }
public PlaceType Type { get; set; }
public int? CountryId { get; set; }
public string CountryName { get; set; }
[Required]
[MaxLength(100)]
public string City { get; set; }
[MaxLength(500)]
public string Address { get; set; }
[MaxLength(50)]
public string Phone { get; set; }
public string PhotoUrl { get; set; }
[Required]
public string CreatorId { get; set; }
public string CreatorName { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime? ModifiedOn { get; set; }
public bool IsDeleted { get; set; }
public DateTime? DeletedOn { get; set; }
public void CreateMappings(IMapperConfiguration configuration)
{
configuration.CreateMap<Place, AdminPlaceViewModel>()
.ForMember(x => x.CountryName, opt => opt.MapFrom(x => x.Country.Name))
.ForMember(x => x.CreatorName, opt => opt.MapFrom(x => x.Creator.UserName));
}
}
} | 28.363636 | 104 | 0.569231 | [
"MIT"
] | ahansb/BeerApp | Source/Web/BeerApp.Web/Areas/Administration/ViewModels/Place/AdminPlaceViewModel.cs | 1,562 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PerfectDiamond
{
class PerfectDiamond
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
if (n == 1)
{
Console.WriteLine("*");
}
else
{
// Draws the upper part of diamond:
int spaces = n - 1;
Console.WriteLine("{0}*", new string(' ', spaces));
spaces--;
for (int i = 1; i <= n - 1; i++)
{
Console.Write("{0}*", new string(' ', spaces));
for (int j = 1; j <= i; j++)
{
Console.Write("-*");
}
Console.WriteLine();
spaces--;
}
spaces = 1;
// Draws the down part of diamond:
for (int i = 1; i <= n - 2; i++)
{
Console.Write("{0}*", new string(' ', spaces));
spaces++;
for (int j = 1; j <= n - i - 1; j++)
{
Console.Write("-*");
}
Console.WriteLine();
}
Console.WriteLine("{0}*", new string(' ', spaces));
}
}
}
}
| 27.703704 | 67 | 0.349599 | [
"MIT"
] | msotiroff/Softuni-learning | Programming Basics/Practice_old_Exams/PerfectDiamond/PerfectDiamond.cs | 1,498 | C# |
using System;
using System.Collections.Generic;
using Xamarin.Forms;
using GalaSoft.MvvmLight.Messaging;
using Smartphone.Driver.Messages;
namespace Smartphone.Driver
{
public partial class OrderDetailsPage : ContentPage
{
public OrderDetailsPage ()
{
InitializeComponent ();
BindingContext = App.Locator.OrderDetails;
}
protected override bool OnBackButtonPressed ()
{
Messenger.Default.Send<MsgSwitchOrdersPage> (new MsgSwitchOrdersPage ());
return true;
}
}
}
| 17.75 | 76 | 0.754527 | [
"Unlicense",
"MIT"
] | dowe/Project2 | Smartphone/Smartphone.Driver/Views/OrderDetailsPage.xaml.cs | 499 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using GTFS;
using GTFS.Entities;
using GTFS.Entities.Enumerations;
using Itinero.Transit.Data;
using Itinero.Transit.Data.Core;
using Itinero.Transit.Logging;
using Itinero.Transit.Utils;
using Stop = GTFS.Entities.Stop;
using Trip = GTFS.Entities.Trip;
namespace Itinero.Transit.IO.GTFS
{
/// <summary>
/// Contains extension methods for the transit db.
/// </summary>
public static class TransitDbExtensions
{
/// <summary>
/// Loads a GTFS into the given transit db.
/// </summary>
/// <param name="transitDb">The transit db.</param>
/// <param name="path">The path to the archive containing the GTFS data.</param>
/// <param name="startDate">The start date/time of the data to load.</param>
/// <param name="endDate">The end date/time of the data to load</param>
/// <param name="settings">The settings.</param>
public static void LoadGTFS(this TransitDb transitDb, string path, DateTime startDate, DateTime endDate,
GTFSLoadSettings settings = null)
{
if (startDate.Date != startDate) throw new ArgumentException($"{nameof(startDate)} should only contain a date component.", $"{nameof(startDate)}");
if (endDate.Date != endDate) throw new ArgumentException($"{nameof(startDate)} should only contain a date component.", $"{nameof(startDate)}");
// read GTFS feed.
IGTFSFeed feed = null;
try
{
feed = new GTFSReader<GTFSFeed>().Read(path);
}
catch (Exception e)
{
Log.Error($"Failed to read GTFS feed: {e}");
throw;
}
// load feed.
transitDb.LoadGTFS(feed, startDate, endDate, settings);
}
/// <summary>
/// Loads a GTFS into the given transit db.
/// </summary>
/// <param name="transitDb">The transit db.</param>
/// <param name="feed">The path to the archive containing the GTFS data.</param>
/// <param name="startDate">The start date/time of the data to load.</param>
/// <param name="endDate">The end date/time of the data to load.</param>
/// <param name="settings">The settings.</param>
public static void LoadGTFS(this TransitDb transitDb, IGTFSFeed feed, DateTime startDate, DateTime endDate,
GTFSLoadSettings settings = null)
{
if (startDate.Date != startDate)
throw new ArgumentException($"{nameof(startDate)} should only contain a date component.",
$"{nameof(startDate)}");
if (endDate.Date != endDate)
throw new ArgumentException($"{nameof(endDate)} should only contain a date component.",
$"{nameof(endDate)}");
settings ??= new GTFSLoadSettings();
// get the transit db writer.
var writer = transitDb.GetWriter();
// add agency first.
var agencyMap = writer.AddAgencies(feed, out var idPrefix, out var timeZone);
// convert to proper timezome.
startDate = startDate.ToUniversalTime().ConvertTo(timeZone).Date;
endDate = endDate.ToUniversalTime().ConvertTo(timeZone).Date;
try
{
// get the stops and index them or add them.
var stops = feed.GetStops(idPrefix: idPrefix);
var stopIndex = new Dictionary<string, (Itinero.Transit.Data.Core.Stop stop, StopId? stopDbId)>();
foreach (var (stopId, stop) in stops)
{
if (settings.AddUnusedStops)
{
var stopDbId = writer.AddOrUpdateStop(stop);
stopIndex[stopId] = (stop, stopDbId);
}
else
{
stopIndex[stopId] = (stop, null);
}
}
// get the routes index.
var routes = feed.GetRoutes();
// check and build service schedules.
var services = feed.GetDatePatterns();
// sort items in feed to ease loading the data.
// sort by trip id.
using var trips = feed.Trips.OrderBy(x => x.Id).ThenBy(x => x.ServiceId).GetEnumerator();
// sort by trip id / sequence.
var stopTimes = feed.StopTimes.OrderBy(x => x.TripId).ThenBy(x => x.StopSequence).GetEnumerator();
var stopTime = stopTimes.MoveNext() ? stopTimes.Current : null;
Log.Verbose($"Parsing trips...");
var days = (int) (endDate - startDate).TotalDays + 1;
var dbTrips = new (string tripId, TripId? tripDbId)[days];
while (trips.MoveNext())
{
var trip = trips.Current;
if (trip == null) continue;
// get service if any.
if (!services.TryGetValue(trip.ServiceId, out var service)) continue;
// get route if any.
var operatorId = OperatorId.Invalid;
if (!routes.TryGetValue(trip.RouteId, out var route))
{
Log.Warning($"Route {trip.RouteId} not found for trip {trip.Id}: No route details will be available on this trip.");
}
else if (!string.IsNullOrEmpty(route.AgencyId))
{
if (!agencyMap.TryGetValue(route.AgencyId, out operatorId))
{
Log.Warning($"Route {trip.RouteId} has an unknown agency: {route.AgencyId}");
}
}
else if (agencyMap.Count == 1)
{
operatorId = agencyMap.First().Value;
}
// TODO: check if this is ok to continue with.
// build the trips for each day one.
// add here if all trips should be added.
for (var d = 0; d < days; d++)
{
var day = startDate.AddDays(d);
if (!service.IsActiveOn(day))
{
dbTrips[d] = (null, null);
}
else
{
if (settings.AddUnusedTrips)
{
var tripDb = trip.ToItineroTrip(day, idPrefix: idPrefix, route: route, op: operatorId);
dbTrips[d] = (trip.ToItineroTripId(day, idPrefix: idPrefix),
writer.AddOrUpdateTrip(tripDb));
}
else
{
dbTrips[d] = (trip.ToItineroTripId(day, idPrefix: idPrefix), null);
}
}
}
// skip stoptimes with non-existent trips.
while (stopTime != null &&
string.Compare(stopTime.TripId, trip.Id, StringComparison.CurrentCulture) < 0)
{
stopTime = stopTimes.MoveNext() ? stopTimes.Current : null;
}
// loop over the trips stop times.
StopTime previous = null;
while (stopTime != null && stopTime.TripId == trip.Id)
{
//Log.Verbose($"StopTime - [{stopTime.TripId}|{stopTime.StopSequence}]: {stopTime}");
if (previous != null)
{
if (previous.StopSequence >= stopTime.StopSequence)
{
Log.Verbose($"StopTime - [{stopTime.TripId}|{stopTime.StopSequence}]: {stopTime}");
}
Itinero.Transit.Data.Core.StopId? fromStopDbId = null;
Itinero.Transit.Data.Core.StopId? toStopDbId = null;
for (var d = 0; d < days; d++)
{
if (previous.DepartureTime == null)
{
Log.Warning(
$"A stoptime object was found without an departure time: {previous}");
continue;
}
if (stopTime.ArrivalTime == null)
{
Log.Warning(
$"A stoptime object was found without an arrival time: {stopTime}");
continue;
}
var day = startDate.AddDays(d);
// make sure the trip is there.
var tripDbPair = dbTrips[d];
if (tripDbPair.tripId == null) continue;
if (!tripDbPair.tripDbId.HasValue)
{
tripDbPair = (tripDbPair.tripId,
writer.AddOrUpdateTrip(trip.ToItineroTrip(day, idPrefix: idPrefix, route: route, op: operatorId)));
dbTrips[d] = tripDbPair;
}
var departureTime =
day.AddSeconds(previous.DepartureTime.Value.TotalSeconds);
// make sure the stops are there.
if (fromStopDbId == null)
{
if (!stopIndex.TryGetValue(previous.StopId, out var fromStopData))
{
Log.Warning(
$"A stoptime object was found with a stop that doesn't exist: {previous}");
break;
}
if (!fromStopData.stopDbId.HasValue)
{
fromStopDbId = writer.AddOrUpdateStop(fromStopData.stop);
stopIndex[previous.StopId] = (fromStopData.stop, fromStopDbId);
}
else
{
fromStopDbId = fromStopData.stopDbId.Value;
}
}
if (toStopDbId == null)
{
if (!stopIndex.TryGetValue(stopTime.StopId, out var toStopData))
{
Log.Warning(
$"A stoptime object was found with a stop that doesn't exist: {stopTime}");
break;
}
if (!toStopData.stopDbId.HasValue)
{
toStopDbId = writer.AddOrUpdateStop(toStopData.stop);
stopIndex[stopTime.StopId] = (toStopData.stop, toStopDbId);
}
else
{
toStopDbId = toStopData.stopDbId.Value;
}
}
// create mode.
var mode = Connection.CreateMode(
previous.PickupType == PickupType.Regular,
stopTime.DropOffType == DropOffType.Regular,
false // again: static data, not the messy realworld
);
var travelTime = stopTime.ArrivalTime.Value.TotalSeconds - previous.DepartureTime.Value.TotalSeconds;
var connection = new Connection(
$"{idPrefix}connection/{trip.Id}/{day:yyyyMMdd}/{previous.StopSequence}",
fromStopDbId.Value,
toStopDbId.Value,
DateTimeExtensions.ToUnixTime(departureTime.ConvertToUtcFrom(timeZone)),
(ushort) travelTime,
mode,
tripDbPair.tripDbId.Value);
writer.AddOrUpdateConnection(connection);
if (writer.ConnectionsDb.Count % 100000 == 0)
Log.Verbose($"Added {writer.ConnectionsDb.Count} connections with " +
$"{writer.StopsDb.Count} stops and {writer.TripsDb.Count} trips.");
}
}
previous = stopTime;
stopTime = stopTimes.MoveNext() ? stopTimes.Current : null;
}
}
}
finally
{
writer.Close();
}
}
internal static string ToItineroTripId(this Trip gtfsTrip, DateTime day, string idPrefix = null)
{
idPrefix ??= string.Empty;
return $"{idPrefix}trip/{gtfsTrip.Id}/{day:yyyyMMdd}";
}
internal static Itinero.Transit.Data.Core.Trip ToItineroTrip(this Trip gtfsTrip, DateTime day, string idPrefix = null,
Route route = null, OperatorId? op = null)
{
if (day.Date != day)
throw new ArgumentException($"{nameof(day)} should only contain a date component.",
$"{nameof(day)}");
idPrefix ??= string.Empty;
op ??= OperatorId.Invalid;
var attributes = new Dictionary<string, string>
{
{"headsign", gtfsTrip.Headsign},
{"blockid", gtfsTrip.BlockId},
{"shapeid", gtfsTrip.ShapeId},
{"shortname", gtfsTrip.ShortName}
};
if (route != null)
{
attributes["route_id"] = route.Id;
attributes["route_description"] = route.Description;
attributes["route_url"] = route.Url;
attributes["route_type"] = string.Empty;
if (route.Type.TryToRouteType(out var routeType))
{
var routeTypeString = routeType.ToInvariantString();
if (!string.IsNullOrWhiteSpace(routeTypeString))
{
attributes["route_type"] = routeTypeString.ToLowerInvariant();
}
}
var routeTypeExtendedString = route.Type.ToInvariantString();
if (!string.IsNullOrWhiteSpace(routeTypeExtendedString))
{
attributes["route_type_extended"] = routeTypeExtendedString.ToLowerInvariant();
}
attributes["route_longname"] = route.LongName;
attributes["route_shortname"] = route.ShortName;
attributes["route_color"] = route.Color.ToHexColorString();
attributes["route_textcolor"] = route.TextColor.ToHexColorString();
}
return new Transit.Data.Core.Trip(gtfsTrip.ToItineroTripId(day, idPrefix), op.Value,
attributes);
}
internal static Dictionary<string, OperatorId> AddAgencies(this TransitDbWriter writer, IGTFSFeed feed,
out string idPrefix, out TimeZoneInfo timeZoneInfo)
{
if (feed == null) throw new ArgumentNullException(nameof(feed));
if (writer == null) throw new ArgumentNullException(nameof(writer));
timeZoneInfo = TimeZoneInfo.Utc;
var agencyUrls = new HashSet<string>();
foreach (var agency in feed.Agencies)
{
if (string.IsNullOrEmpty(agency.URL))
{
continue;
}
agencyUrls.Add(agency.URL);
}
idPrefix = string.Empty;
if (agencyUrls.Count == 1)
{
// only this is very unique case we can use the agency url as a global id prefix.
idPrefix = agencyUrls.First();
if (!idPrefix.EndsWith("/"))
{
idPrefix += "/";
}
}
var agencyMap = new Dictionary<string, OperatorId>();
foreach (var agency in feed.Agencies)
{
var globalId =$"{idPrefix}";
if (string.IsNullOrEmpty(globalId))
{
globalId = agency.Id;
}
if (!string.IsNullOrWhiteSpace(agency.Timezone))
{
try
{
timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(agency.Timezone);
}
catch (Exception ex)
{
Log.Warning(ex, $"Time zone info for '{agency.Timezone}' could not be found.");
}
finally
{
timeZoneInfo = TimeZoneInfo.Utc;
}
}
var attributes = new Dictionary<string, string>
{
{"email", agency.Email},
{"id", agency.Id},
{"name", agency.Name},
{"phone", agency.Phone},
{"timezone", agency.Timezone},
{"languagecode", agency.LanguageCode},
{"url", agency.URL},
{"website", agency.URL},
{"charge:url", agency.FareURL}
};
var op = new Operator(globalId, attributes);
var opId = writer.AddOrUpdateOperator(op);
agencyMap[agency.Id] = opId;
}
return agencyMap;
}
}
} | 45.652482 | 159 | 0.437212 | [
"MIT"
] | openplannerteam/Itinero-Transit | src/Itinero.Transit.IO.GTFS/TransitDbExtensions.cs | 19,311 | C# |
//-----------------------------------------------------------------------
// ETP DevKit, 1.2
//
// Copyright 2021 Energistics
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use 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.
//-----------------------------------------------------------------------
//
//-----------------------------------------------------------------------
// code has been automatically generated.
// Changes will be lost the next time it is regenerated.
//-----------------------------------------------------------------------
using System;
using System.Globalization;
namespace Energistics.Avro.Encoding.Converter
{
/// <summary>
/// Static methods to support encoding and decoding .NET primitives.
/// </summary>
public static partial class AvroConverter
{
public static readonly DateTimeOffset UtcMinDateTimeOffset = new DateTimeOffset(0L, TimeSpan.Zero);
/// <summary>
/// Converts an ISO 8601 string to a <see cref="DateTimeOffset"/>.
/// </summary>
/// <param name="timestamp">The ISO 8601 string.</param>
/// <returns>The <see cref="DateTimeOffset"/>.</returns>
public static DateTimeOffset Iso8601StringToDateTimeOffset(string timestamp)
{
return DateTimeOffset.Parse(timestamp, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts a <see cref="DateTimeOffset"/> to an ISO 8601 string.
/// </summary>
/// <param name="timestamp">The <see cref="DateTimeOffset"/> timestamp.</param>
/// <returns>The ISO 8601 string.</returns>
public static string DateTimeOffsetToIso8601String(DateTimeOffset timestamp)
{
return timestamp.ToString("O", CultureInfo.InvariantCulture).Replace("+00:00", "Z");
}
/// <summary>
/// Converts an Avro date value to a UTC <see cref="DateTimeOffset"/>.
/// </summary>
/// <param name="date">The Avro date value.</param>
/// <returns>The <see cref="DateTimeOffset"/>.</returns>
public static DateTimeOffset DateToDateTimeOffset(int date)
{
var ticks = UnixEpochTicks + date * TimeSpan.TicksPerDay;
return new DateTimeOffset(ticks, TimeSpan.Zero);
}
/// <summary>
/// Converts a <see cref="DateTimeOffset"/> to a date value.
/// The <see cref="DateTimeOffset"/> is not converted before creating the date value.
/// </summary>
/// <param name="date">The <see cref="DateTimeOffset"/> date.</param>
/// <returns>The Avro date.</returns>
public static int DateTimeOffsetToDate(DateTimeOffset date)
{
var ticks = date.Ticks - UnixEpochTicks;
return (int)(ticks / TimeSpan.TicksPerDay);
}
/// <summary>
/// Converts an Avro time-millis value to a UTC <see cref="DateTimeOffset"/>.
/// </summary>
/// <param name="time">The Avro time-millis value.</param>
/// <returns>The <see cref="DateTimeOffset"/>.</returns>
public static DateTimeOffset TimeMillisToDateTimeOffset(int time)
{
var ticks = time * TimeSpan.TicksPerMillisecond;
return new DateTimeOffset(ticks, TimeSpan.Zero);
}
/// <summary>
/// Converts a <see cref="DateTimeOffset"/> to a time-millis value.
/// The <see cref="DateTimeOffset"/> is not converted before creating the time-millis value.
/// </summary>
/// <param name="time">The <see cref="DateTimeOffset"/> time.</param>
/// <returns>The time-millis.</returns>
public static int DateTimeOffsetToTimeMillis(DateTimeOffset time)
{
var ticks = time.Ticks % TimeSpan.TicksPerDay;
return (int)(ticks / TimeSpan.TicksPerMillisecond);
}
/// <summary>
/// Converts an Avro time-micros value to a UTC <see cref="DateTimeOffset"/>.
/// </summary>
/// <param name="time">The Avro time-micros value.</param>
/// <returns>The <see cref="DateTimeOffset"/>.</returns>
public static DateTimeOffset TimeMicrosToDateTimeOffset(long time)
{
var ticks = time * TicksPerMicrosecond;
return new DateTimeOffset(ticks, TimeSpan.Zero);
}
/// <summary>
/// Converts a <see cref="DateTimeOffset"/> to a time-micros value.
/// The <see cref="DateTimeOffset"/> is not converted before creating the time-micros value.
/// </summary>
/// <param name="time">The <see cref="DateTimeOffset"/> time.</param>
/// <returns>The time-micros.</returns>
public static long DateTimeOffsetToTimeMicros(DateTimeOffset time)
{
var ticks = time.Ticks % TimeSpan.TicksPerDay;
return ticks / TicksPerMicrosecond;
}
/// <summary>
/// Converts an Avro timestamp-millis value to a UTC <see cref="DateTimeOffset"/>.
/// </summary>
/// <param name="timestamp">The Avro timestamp-millis value.</param>
/// <returns>The <see cref="DateTimeOffset"/>.</returns>
public static DateTimeOffset TimestampMillisUtcToDateTimeOffset(long timestamp)
{
var ticks = timestamp * TimeSpan.TicksPerMillisecond;
return new DateTimeOffset(ticks + UnixEpochTicks, TimeSpan.Zero);
}
/// <summary>
/// Converts a <see cref="DateTimeOffset"/> to a UTC timestamp-millis value.
/// The <see cref="DateTimeOffset"/> is converted to universal time before creating the timestamp-millis value.
/// </summary>
/// <param name="timestamp">The <see cref="DateTimeOffset"/> timestamp.</param>
/// <returns>The UTC timestamp-millis.</returns>
public static long DateTimeOffsetToTimestampMillisUtc(DateTimeOffset timestamp)
{
var ticks = timestamp.ToUniversalTime().Ticks - UnixEpochTicks;
return ticks / TimeSpan.TicksPerMillisecond;
}
/// <summary>
/// Converts an Avro timestamp-micros value to a UTC <see cref="DateTimeOffset"/>.
/// </summary>
/// <param name="timestamp">The Avro timestamp-micros value.</param>
/// <returns>The <see cref="DateTimeOffset"/>.</returns>
public static DateTimeOffset TimestampMicrosUtcToDateTimeOffset(long timestamp)
{
var ticks = timestamp * TicksPerMicrosecond;
return new DateTimeOffset(ticks + UnixEpochTicks, TimeSpan.Zero);
}
/// <summary>
/// Converts a <see cref="DateTimeOffset"/> to a UTC timestamp-micros value.
/// The <see cref="DateTimeOffset"/> is converted to universal time before creating the timestamp-micros value.
/// </summary>
/// <param name="timestamp">The <see cref="DateTimeOffset"/> timestamp.</param>
/// <returns>The UTC timestamp-micros.</returns>
public static long DateTimeOffsetToTimestampMicrosUtc(DateTimeOffset timestamp)
{
var ticks = timestamp.ToUniversalTime().Ticks - UnixEpochTicks;
return ticks / TicksPerMicrosecond;
}
/// <summary>
/// Converts an Avro timestamp-millis-local value to a local <see cref="DateTimeOffset"/>.
/// </summary>
/// <param name="timestamp">The Avro timestamp-millis-local value.</param>
/// <returns>The <see cref="DateTimeOffset"/>.</returns>
public static DateTimeOffset TimestampMillisLocalToDateTimeOffset(long timestamp)
{
return new DateTimeOffset(TimestampMillisLocalToDateTime(timestamp));
}
/// <summary>
/// Converts a <see cref="DateTimeOffset"/> to a timestamp-millis-local value.
/// The current timezone offset for the <see cref="DateTimeOffset"/> is treated as the local timezone for the timestamp-millis-local value.
/// </summary>
/// <param name="timestamp">The <see cref="DateTimeOffset"/> timestamp.</param>
/// <returns>The timestamp-millis-local.</returns>
public static long DateTimeOffsetToTimestampMillisLocal(DateTimeOffset timestamp)
{
var ticks = timestamp.Ticks - UnixEpochTicks;
return ticks / TimeSpan.TicksPerMillisecond;
}
/// <summary>
/// Converts an Avro timestamp-micros-local value to a local <see cref="DateTimeOffset"/>.
/// </summary>
/// <param name="timestamp">The Avro timestamp-micros-local value.</param>
/// <returns>The <see cref="DateTimeOffset"/>.</returns>
public static DateTimeOffset TimestampMicrosLocalToDateTimeOffset(long timestamp)
{
return new DateTimeOffset(TimestampMicrosLocalToDateTime(timestamp));
}
/// <summary>
/// Converts a <see cref="DateTimeOffset"/> to a timestamp-micros-local value.
/// The current timezone offset for the <see cref="DateTimeOffset"/> is treated as the local timezone for the timestamp-micros-local value.
/// </summary>
/// <param name="timestamp">The <see cref="DateTimeOffset"/> timestamp.</param>
/// <returns>The timestamp-micros-local.</returns>
public static long DateTimeOffsetToTimestampMicrosLocal(DateTimeOffset timestamp)
{
var ticks = timestamp.Ticks - UnixEpochTicks;
return ticks / TicksPerMicrosecond;
}
}
}
| 45.986111 | 147 | 0.613208 | [
"Apache-2.0"
] | pds-technology/etp.net | src/Energistics.Avro/Encoding/Converter/AvroConverter.DateTimeOffset.cs | 9,935 | C# |
#if APPSETTINGS
using System;
using System.Linq;
using Serilog.Debugging;
using Serilog.Events;
using Serilog.Tests.Support;
using TestDummies;
using Xunit;
using Xunit.Abstractions;
namespace Serilog.Settings.Combined.Tests
{
public class CombinedSettingsMixTests
{
readonly ITestOutputHelper _outputHelper;
public CombinedSettingsMixTests(ITestOutputHelper outputHelper)
{
_outputHelper = outputHelper;
}
[Fact]
public void CombinedCanMixAndMatchMultipleSources()
{
LogEvent evt = null;
// typical scenario : doing most of the config in code / default value
// .... and override a few things from config files
var log = new LoggerConfiguration()
.ReadFrom.Combined(builder => builder
.AddExpression(lc => lc
.MinimumLevel.Verbose()
.Enrich.WithProperty("AppName", "DeclaredInInitial", /*destructureObjects:*/ false)
.WriteTo.DummyRollingFile(/*Formatter*/ null, /*pathFormat*/ "overridenInConfigFile", /*restrictedToMinimumLevel*/ LogEventLevel.Verbose)
)
.AddAppSettings(filePath: "Samples/ConfigOverrides.config")
.AddKeyValuePair("enrich:with-property:ExtraProp", "AddedAtTheVeryEnd")
)
.WriteTo.Sink(new DelegatingSink(e => evt = e))
.CreateLogger();
log.Information("Has a test property");
Assert.True(DummyRollingFileSink.Emitted.Any(), "Events should be written to DummyRollingFile");
Assert.Equal("DefinedInConfigFile", DummyRollingFileSink.PathFormat);
Assert.NotNull(evt);
Assert.Equal("DeclaredInInitial", evt.Properties["AppName"].LiteralValue());
Assert.Equal("DeclaredInConfigFile", evt.Properties["ServerName"].LiteralValue());
Assert.Equal("AddedAtTheVeryEnd", evt.Properties["ExtraProp"].LiteralValue());
}
[Fact]
public void CombinedSettingsCanBeInspected()
{
new LoggerConfiguration()
.ReadFrom.Combined(builder => builder
.AddExpression(lc => lc
.MinimumLevel.Verbose()
.Enrich.WithProperty("AppName", "DeclaredInInitial", /*destructureObjects:*/ false)
.WriteTo.DummyRollingFile( /*Formatter*/ null, /*pathFormat*/ "overridenInConfigFile", /*restrictedToMinimumLevel*/ LogEventLevel.Verbose)
)
.AddAppSettings(filePath: "Samples/ConfigOverrides.config")
.AddKeyValuePair("enrich:with-property:ExtraProp", "AddedAtTheVeryEnd")
.Inspect(kvps =>
{
_outputHelper.WriteLine("====Settings DUMP====");
_outputHelper.WriteLine(String.Join(Environment.NewLine, kvps.Select(kvp => kvp.ToString())));
})
);
}
}
}
#endif
| 42.60274 | 162 | 0.590675 | [
"Apache-2.0"
] | serilog/serilog-settings-combined | test/Serilog.Settings.Combined.Tests/CombinedSettingsMixTests.cs | 3,110 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CalcLang;
using CalcLang.Interpreter;
namespace Base
{
internal static class MathLib
{
[CalcCallableMethod("Acos", 1)]
public static object Acos(ScriptThread thread, object instance, object[] parameters) => (decimal)Math.Acos(Convert.ToDouble(parameters[0]));
[CalcCallableMethod("Asin", 1)]
public static object Asin(ScriptThread thread, object instance, object[] parameters) => (decimal)Math.Asin(Convert.ToDouble(parameters[0]));
[CalcCallableMethod("Atan", 1)]
public static object Atan(ScriptThread thread, object instance, object[] parameters) => (decimal)Math.Atan(Convert.ToDouble(parameters[0]));
[CalcCallableMethod("Atan2", 2)]
public static object Atan2(ScriptThread thread, object instance, object[] parameters) =>
(decimal)Math.Atan2(Convert.ToDouble(parameters[0]), Convert.ToDouble(parameters[1]));
[CalcCallableMethod("Ceiling", 1)]
public static object Ceiling(ScriptThread thread, object instance, object[] parameters) => Math.Ceiling(Convert.ToDecimal(parameters[0]));
[CalcCallableMethod("Cos", 1)]
public static object Cos(ScriptThread thread, object instance, object[] parameters) => (decimal)Math.Cos(Convert.ToDouble(parameters[0]));
[CalcCallableMethod("Cosh", 1)]
public static object Cosh(ScriptThread thread, object instance, object[] parameters) => (decimal)Math.Cosh(Convert.ToDouble(parameters[0]));
[CalcCallableMethod("Floor", 1)]
public static object Floor(ScriptThread thread, object instance, object[] parameters) => Math.Floor(Convert.ToDecimal(parameters[0]));
[CalcCallableMethod("Sin", 1)]
public static object Sin(ScriptThread thread, object thisRef, object[] parameters) => (decimal)Math.Sin(Convert.ToDouble(parameters[0]));
[CalcCallableMethod("Tan", 1)]
public static object Tan(ScriptThread thread, object instance, object[] parameters) => (decimal)Math.Tan(Convert.ToDouble(parameters[0]));
[CalcCallableMethod("Sinh", 1)]
public static object Sinh(ScriptThread thread, object instance, object[] parameters) => (decimal)Math.Sinh(Convert.ToDouble(parameters[0]));
[CalcCallableMethod("Tanh", 1)]
public static object Tanh(ScriptThread thread, object instance, object[] parameters) => (decimal)Math.Tanh(Convert.ToDouble(parameters[0]));
[CalcCallableMethod("Sqrt", 1)]
public static object Sqrt(ScriptThread thread, object instance, object[] parameters) => (decimal)Math.Sqrt(Convert.ToDouble(parameters[0]));
[CalcCallableMethod("Log", 1)]
public static object Log(ScriptThread thread, object instance, object[] parameters)
{
var param = Convert.ToDouble(parameters[0]);
if (param <= 0)
thread.ThrowScriptException("ArithmeticException");
return (decimal)Math.Log(param);
}
[CalcCallableMethod("Log10", 1)]
public static object Log10(ScriptThread thread, object instance, object[] parameters)
{
var param = Convert.ToDouble(parameters[0]);
if (param <= 0)
thread.ThrowScriptException("ArithmeticException");
return (decimal)Math.Log10(param);
}
[CalcCallableMethod("Exp", 1)]
public static object Exp(ScriptThread thread, object instance, object[] parameters) => (decimal)Math.Exp(Convert.ToDouble(parameters[0]));
[CalcCallableMethod("Pow", 2)]
public static object Pow(ScriptThread thread, object instance, object[] parameters) => (decimal)Math.Pow(Convert.ToDouble(parameters[0]), Convert.ToDouble(parameters[1]));
[CalcCallableMethod("Int", 1)]
public static object Int(ScriptThread thread, object thisRef, object[] parameters) => (long)Convert.ToDecimal(parameters[0]);
[CalcCallableMethod("Round", 1)]
public static object Round(ScriptThread thread, object instance, object[] parameters) => (decimal)Math.Round(Convert.ToDecimal(parameters[0]));
}
}
| 50.130952 | 179 | 0.686535 | [
"MIT"
] | hstde/Calc2 | Base/Math.cs | 4,213 | C# |
///-------------------------------------------------------------------------------------------------
/// <file> Fomantic.Blazor.UI\Features\Base\UIFeatureDefinition.cs </file>
///
/// <copyright file="UIFeatureDefinition.cs" company="MyCompany.com">
/// Copyright (c) 2020 MyCompany.com. All rights reserved.
/// </copyright>
///
/// <summary> Implements the feature definition class. </summary>
///-------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
namespace Fomantic.Blazor.UI.Features
{
///-------------------------------------------------------------------------------------------------
/// <summary> A feature definition. </summary>
///
/// <typeparam name="TFeatureInterface"> Type of the feature interface. </typeparam>
///
/// <seealso cref="IFeatureDefinition{TFeatureInterface}"/>
///-------------------------------------------------------------------------------------------------
public abstract class UIFeatureDefinition<TFeatureInterface> : IFeatureDefinition<TFeatureInterface> where TFeatureInterface : IFomanticComponent
{
/// <inheritdoc/>
public List<ComponentFragment> AdditionalFragments { get; set; } = new List<ComponentFragment>();
/// <inheritdoc/>
public Type Type => typeof(TFeatureInterface);
///-------------------------------------------------------------------------------------------------
/// <summary> Dispose asynchronous. </summary>
///
/// <param name="component"> The component. </param>
///
/// <returns> A ValueTask. </returns>
///-------------------------------------------------------------------------------------------------
public async virtual ValueTask DisposeAsync(TFeatureInterface component)
{
}
/// <inheritdoc/>
public async virtual ValueTask<bool> OnAfterEachRender(TFeatureInterface component)
{
return false;
}
/// <inheritdoc/>
public async virtual ValueTask<bool> OnAfterFirstRender(TFeatureInterface component)
{
return false;
}
/// <inheritdoc/>
public virtual string[] ProvideCssClasses(TFeatureInterface component)
{
return Array.Empty<string>();
}
/// <inheritdoc/>
public virtual string ProvideCssClass(TFeatureInterface component)
{
return string.Empty;
}
/// <inheritdoc/>
public async virtual ValueTask OnInitialized(TFeatureInterface component)
{
component.AdditionalFragments.AddRange(this.AdditionalFragments);
}
/// <inheritdoc/>
ValueTask<bool> IFeatureDefinition.OnAfterEachRender(IFomanticComponent component)
{
return OnAfterEachRender((TFeatureInterface)component);
}
/// <inheritdoc/>
ValueTask<bool> IFeatureDefinition.OnAfterFirstRender(IFomanticComponent component)
{
return OnAfterFirstRender((TFeatureInterface)component);
}
/// <inheritdoc/>
string[] IFeatureDefinition.ProvideCssClasses(IFomanticComponent component)
{
return ProvideCssClasses((TFeatureInterface)component);
}
/// <inheritdoc/>
string IFeatureDefinition.ProvideCssClass(IFomanticComponent component)
{
return ProvideCssClass((TFeatureInterface)component);
}
/// <inheritdoc/>
ValueTask IFeatureDefinition.OnInitialized(IFomanticComponent component)
{
return OnInitialized((TFeatureInterface)component);
}
///-------------------------------------------------------------------------------------------------
/// <summary> Dispose asynchronous. </summary>
///
/// <param name="component"> The component. </param>
///
/// <returns> A ValueTask. </returns>
///-------------------------------------------------------------------------------------------------
ValueTask IFeatureDefinition.DisposeAsync(IFomanticComponent component)
{
return DisposeAsync((TFeatureInterface)component);
}
}
}
| 36.306452 | 149 | 0.507774 | [
"MIT"
] | DotFomanticNet/fomantic-blazor | src/Fomantic.Blazor.UI/Features/Base/UIFeatureDefinition.cs | 4,504 | C# |
namespace XPlat
{
using System.Collections.Generic;
/// <summary>
/// Defines a collection of extensions for collections.
/// </summary>
public static partial class Extensions
{
/// <summary>
/// Takes a number of elements from the specified collection from the specified starting index.
/// </summary>
/// <param name="list">
/// The <see cref="List{T}"/> to take items from.
/// </param>
/// <param name="startingIndex">
/// The index to start at in the <see cref="List{T}"/>.
/// </param>
/// <param name="takeCount">
/// The number of items to take from the starting index of the <see cref="List{T}"/>.
/// </param>
/// <typeparam name="T">
/// The type of elements in the collection.
/// </typeparam>
/// <returns>
/// Returns a collection of <see cref="T"/> items.
/// </returns>
public static IEnumerable<T> Take<T>(this List<T> list, int startingIndex, int takeCount)
{
List<T> results = new List<T>();
int itemsToTake = takeCount;
if (list.Count - 1 - startingIndex > itemsToTake)
{
List<T> items = list.GetRange(startingIndex, itemsToTake);
results.AddRange(items);
}
else
{
itemsToTake = list.Count - startingIndex;
if (itemsToTake > 0)
{
List<T> items = list.GetRange(startingIndex, itemsToTake);
results.AddRange(items);
}
}
return results;
}
/// <summary>
/// Takes a number of elements from the specified collection from the specified starting index.
/// </summary>
/// <param name="list">
/// The <see cref="List{T}"/> to take items from.
/// </param>
/// <param name="startingIndex">
/// The index to start at in the <see cref="List{T}"/>.
/// </param>
/// <param name="takeCount">
/// The number of items to take from the starting index of the <see cref="List{T}"/>.
/// </param>
/// <typeparam name="T">
/// The type of elements in the collection.
/// </typeparam>
/// <returns>
/// Returns a collection of <see cref="T"/> items.
/// </returns>
public static IEnumerable<T> Take<T>(this IReadOnlyList<T> list, int startingIndex, int takeCount)
{
List<T> results = new List<T>();
int itemsToTake = takeCount;
if (list.Count - 1 - startingIndex > itemsToTake)
{
IEnumerable<T> items = list.GetRange(startingIndex, itemsToTake);
results.AddRange(items);
}
else
{
itemsToTake = list.Count - startingIndex;
if (itemsToTake > 0)
{
IEnumerable<T> items = list.GetRange(startingIndex, itemsToTake);
results.AddRange(items);
}
}
return results;
}
/// <summary>
/// Creates a copy of a range of elements in a <see cref="IReadOnlyList{T}"/>.
/// </summary>
/// <param name="list">
/// The list to get a range from.
/// </param>
/// <param name="index">
/// The index to start at.
/// </param>
/// <param name="count">
/// The number of items to get in the range.
/// </param>
/// <typeparam name="T">
/// The type of item in the list.
/// </typeparam>
/// <returns>
/// The range as a collection.
/// </returns>
public static IEnumerable<T> GetRange<T>(this IReadOnlyList<T> list, int index, int count)
{
List<T> range = new List<T>();
for (int i = 0; i < count; i++)
{
int j = i + index;
if (j >= index + count)
{
break;
}
range.Add(list[j]);
}
return range;
}
}
} | 33.566929 | 106 | 0.479944 | [
"MIT"
] | jasells/XPlat-Windows-APIs | XPlat.Core/Extensions/Extensions.Collection.cs | 4,265 | 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;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.TestHost;
using Moq;
using Xunit;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
namespace Microsoft.AspNetCore.Diagnostics.HealthChecks
{
public class HealthCheckEndpointRouteBuilderExtensionsTest
{
[Fact]
public void ThrowFriendlyErrorWhenServicesNotRegistered()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHealthChecks("/healthz");
});
})
.ConfigureServices(services =>
{
services.AddRouting();
});
}).Build();
var ex = Assert.Throws<InvalidOperationException>(() => host.Start());
Assert.Equal(
"Unable to find the required services. Please add all the required services by calling " +
"'IServiceCollection.AddHealthChecks' inside the call to 'ConfigureServices(...)' " +
"in the application startup code.",
ex.Message);
}
[Fact]
public async Task MapHealthChecks_ReturnsOk()
{
// Arrange
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHealthChecks("/healthz");
});
})
.ConfigureServices(services =>
{
services.AddRouting();
services.AddHealthChecks();
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var client = server.CreateClient();
// Act
var response = await client.GetAsync("/healthz");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString());
Assert.Equal("Healthy", await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task MapHealthChecks_WithOptions_ReturnsOk()
{
// Arrange
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHealthChecks("/healthz", new HealthCheckOptions
{
ResponseWriter = async (context, report) =>
{
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync("Custom!");
}
});
});
})
.ConfigureServices(services =>
{
services.AddRouting();
services.AddHealthChecks();
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var client = server.CreateClient();
// Act
var response = await client.GetAsync("/healthz");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString());
Assert.Equal("Custom!", await response.Content.ReadAsStringAsync());
}
}
}
| 35.211679 | 106 | 0.47699 | [
"MIT"
] | 48355746/AspNetCore | src/Middleware/HealthChecks/test/UnitTests/HealthCheckEndpointRouteBuilderExtensionsTest.cs | 4,824 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.Core.Query.InternalTrees
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
// <summary>
// The RuleProcessor helps apply a set of rules to a query tree
// </summary>
internal class RuleProcessor
{
#region private state
// <summary>
// A lookup table for rules.
// The lookup table is an array indexed by OpType and each entry has a list of rules.
// </summary>
private readonly Dictionary<SubTreeId, SubTreeId> m_processedNodeMap;
#endregion
#region constructors
// <summary>
// Initializes a new RuleProcessor
// </summary>
internal RuleProcessor()
{
// Build up the accelerator tables
m_processedNodeMap = new Dictionary<SubTreeId, SubTreeId>();
}
#endregion
#region private methods
private static bool ApplyRulesToNode(
RuleProcessingContext context, ReadOnlyCollection<ReadOnlyCollection<Rule>> rules, Node currentNode, out Node newNode)
{
newNode = currentNode;
// Apply any pre-rule delegates
context.PreProcess(currentNode);
foreach (var r in rules[(int)currentNode.Op.OpType])
{
if (!r.Match(currentNode))
{
continue;
}
// Did the rule modify the subtree?
if (r.Apply(context, currentNode, out newNode))
{
// The node has changed; don't try to apply any more rules
context.PostProcess(newNode, r);
return true;
}
else
{
Debug.Assert(newNode == currentNode, "Liar! This rule should have returned 'true'");
}
}
context.PostProcess(currentNode, null);
return false;
}
// <summary>
// Apply rules to the current subtree in a bottom-up fashion.
// </summary>
// <param name="context"> Current rule processing context </param>
// <param name="rules"> The look-up table with the rules to be applied </param>
// <param name="subTreeRoot"> Current subtree </param>
// <param name="parent"> Parent node </param>
// <param name="childIndexInParent"> Index of this child within the parent </param>
// <returns> the result of the transformation </returns>
private Node ApplyRulesToSubtree(
RuleProcessingContext context,
ReadOnlyCollection<ReadOnlyCollection<Rule>> rules,
Node subTreeRoot, Node parent, int childIndexInParent)
{
var loopCount = 0;
var localProcessedMap = new Dictionary<SubTreeId, SubTreeId>();
SubTreeId subTreeId;
while (true)
{
// Am I looping forever
Debug.Assert(loopCount < 12, "endless loops?");
loopCount++;
//
// We may need to update state regardless of whether this subTree has
// changed after it has been processed last. For example, it may be
// affected by transformation in its siblings due to external references.
//
context.PreProcessSubTree(subTreeRoot);
subTreeId = new SubTreeId(context, subTreeRoot, parent, childIndexInParent);
// Have I seen this subtree already? Just return, if so
if (m_processedNodeMap.ContainsKey(subTreeId))
{
break;
}
// Avoid endless loops here - avoid cycles of 2 or more
if (localProcessedMap.ContainsKey(subTreeId))
{
// mark this subtree as processed
m_processedNodeMap[subTreeId] = subTreeId;
break;
}
// Keep track of this one
localProcessedMap[subTreeId] = subTreeId;
// Walk my children
for (var i = 0; i < subTreeRoot.Children.Count; i++)
{
var childNode = subTreeRoot.Children[i];
if (ShouldApplyRules(childNode, subTreeRoot))
{
subTreeRoot.Children[i] = ApplyRulesToSubtree(context, rules, childNode, subTreeRoot, i);
}
}
// Apply rules to myself. If no transformations were performed,
// then mark this subtree as processed, and break out
Node newSubTreeRoot;
if (!ApplyRulesToNode(context, rules, subTreeRoot, out newSubTreeRoot))
{
Debug.Assert(subTreeRoot == newSubTreeRoot);
// mark this subtree as processed
m_processedNodeMap[subTreeId] = subTreeId;
break;
}
context.PostProcessSubTree(subTreeRoot);
subTreeRoot = newSubTreeRoot;
}
context.PostProcessSubTree(subTreeRoot);
return subTreeRoot;
}
private static bool ShouldApplyRules(Node node, Node parent)
{
// For performance reasons skip the OpType.Constant child nodes of an OpType.In parent node.
return parent.Op.OpType != OpType.In || node.Op.OpType != OpType.Constant;
}
#endregion
#region public methods
// <summary>
// Apply a set of rules to the subtree
// </summary>
// <param name="context"> Rule processing context </param>
// <param name="subTreeRoot"> current subtree </param>
// <returns> transformed subtree </returns>
internal Node ApplyRulesToSubtree(
RuleProcessingContext context, ReadOnlyCollection<ReadOnlyCollection<Rule>> rules, Node subTreeRoot)
{
return ApplyRulesToSubtree(context, rules, subTreeRoot, null, 0);
}
#endregion
}
}
| 37.121387 | 132 | 0.554812 | [
"Apache-2.0"
] | CZEMacLeod/EntityFramework6 | src/EntityFramework/Core/Query/InternalTrees/RuleProcessor.cs | 6,422 | C# |
using ProcessingBlock.Core;
using System;
using System.Collections.Generic;
using System.Text;
namespace ProcessingBlock.Runtime
{
public class ManualReceiver<T>:QueueEndPointReceiverBase<T>
{
public void Add(T value)
{
add(value);
}
public void Complete()
{
complete();
}
}
}
| 16.590909 | 63 | 0.589041 | [
"MIT"
] | JohnMasen/ProcessingBlock | src/ProcessingBlock.Runtime/ManualReceiver.cs | 367 | C# |
using System;
namespace Identifiers
{
interface @I1
{
void @Method1(int @param1);
}
struct @S1
{
}
class @C1 : @I1
{
int @field1;
@S1 @field2;
int field3;
public void @Method1(int @param1)
{
object @local1;
Func<int, int> @local2 = @x => @x;
object local3;
}
}
}
| 14.107143 | 46 | 0.437975 | [
"MIT"
] | 00mjk/codeql | csharp/ql/test/library-tests/tokens/tokens.cs | 395 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0) {
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if(Input.GetButtonDown("Jump") && isGrounded) {
velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
} | 25.738095 | 91 | 0.641073 | [
"MIT"
] | justinamaple/FPSPrototype | Assets/Scripts/PlayerMovement.cs | 1,081 | C# |
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
namespace EventStore.Transport.Http
{
public static class ContentType
{
public const string Any = "*/*";
public const string Json = "application/json";
public const string Xml = "text/xml";
public const string ApplicationXml = "application/xml";
public const string PlainText = "text/plain";
public const string Html = "text/html";
public const string Atom = "application/atom+xml";
public const string AtomJson = "application/vnd.eventstore.atom+json";
public const string AtomServiceDoc = "application/atomsvc+xml";
public const string AtomServiceDocJson = "application/vnd.eventstore.atomsvc+json";
public const string EventJson = "application/vnd.eventstore.event+json";
public const string EventXml = "application/vnd.eventstore.event+xml";
public const string EventsJson = "application/vnd.eventstore.events+json";
public const string EventsXml = "application/vnd.eventstore.events+xml";
}
} | 48.716981 | 91 | 0.741673 | [
"BSD-3-Clause"
] | ianbattersby/EventStore | src/EventStore/EventStore.Transport.Http/ContentType.cs | 2,584 | C# |
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
namespace webapp.Authentication
{
/// <summary>
/// 在 SignInAsync 中将用户的Claim序列化后保存到Cookie中,在 AuthenticateAsync 中从Cookie中读取并反序列化成用户Claim。
///
/// //然后在DI系统中注册我们的Handler和Scheme
/// </summary>
public class MyAuthHandler : IAuthenticationHandler, IAuthenticationSignInHandler, IAuthenticationSignOutHandler
{
public AuthenticationScheme Scheme { get; private set; }
protected HttpContext Context { get; private set; }
public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
{
Scheme = scheme;
Context = context;
return Task.CompletedTask;
//AuthenticationTicket a = new AuthenticationTicket();
}
public async Task<AuthenticateResult> AuthenticateAsync()
{
var cookie = Context.Request.Cookies["mycookie"];
if (string.IsNullOrEmpty(cookie))
{
return AuthenticateResult.NoResult();
}
return AuthenticateResult.Success(Deserialize(cookie));
}
public Task ChallengeAsync(AuthenticationProperties properties)
{
Context.Response.Redirect("/login");
return Task.CompletedTask;
}
public Task ForbidAsync(AuthenticationProperties properties)
{
Context.Response.StatusCode = 403;
return Task.CompletedTask;
}
public Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
{
var ticket = new AuthenticationTicket(user, properties, Scheme.Name);
Context.Response.Cookies.Append("myCookie", Serialize(ticket));
return Task.CompletedTask;
}
public Task SignOutAsync(AuthenticationProperties properties)
{
Context.Response.Cookies.Delete("myCookie");
return Task.CompletedTask;
}
//TODO
AuthenticationTicket Deserialize(string cookie)
{
return null;
}
//TODO
string Serialize(AuthenticationTicket ticket)
{
return null;
}
}
} | 30.394737 | 116 | 0.62987 | [
"MIT"
] | AtwindYu/Asp.NetCore2 | sources/webapp/Authentication/MyAuthHandler.cs | 2,396 | C# |
using System;
using System.Runtime.InteropServices;
namespace AnsiCodes
{
/// <summary>
/// This hack enables ANSI codes in modern Windows terminals.
/// Original author: https://www.jerriepelser.com/blog/using-ansi-color-codes-in-net-console-apps/
/// TODO: Add extra checks to determine if using a modern version of Windows and an ANSI-compatible windows console
/// </summary>
internal static class WindowsHelper
{
private const int STD_OUTPUT_HANDLE = -11;
private const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
private const uint DISABLE_NEWLINE_AUTO_RETURN = 0x0008;
[DllImport("kernel32.dll")]
private static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
[DllImport("kernel32.dll")]
private static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll")]
private static extern uint GetLastError();
internal static bool IsWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
internal static bool AnsiEnabled { get; private set; } = false;
static WindowsHelper()
{
if (IsWindows)
{
var iStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (!GetConsoleMode(iStdOut, out uint outConsoleMode))
{
Console.WriteLine("failed to get output console mode");
}
outConsoleMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN;
if (!SetConsoleMode(iStdOut, outConsoleMode))
{
Console.WriteLine($"failed to set output console mode, error code: {GetLastError()}");
}
AnsiEnabled = true;
}
}
}
} | 37.207547 | 119 | 0.634381 | [
"MIT"
] | phil-harmoniq/AnsiCodes | AnsiCodes/WindowsHelper.cs | 1,972 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Microsoft.Extensions.Configuration.Ini
{
/// <summary>
/// Represents an INI file as an <see cref="IConfigurationSource"/>.
/// Files are simple line structures (<a href="https://en.wikipedia.org/wiki/INI_file">INI Files on Wikipedia</a>)
/// </summary>
/// <examples>
/// [Section:Header]
/// key1=value1
/// key2 = " value2 "
/// ; comment
/// # comment
/// / comment
/// </examples>
public class IniStreamConfigurationSource : StreamConfigurationSource
{
/// <summary>
/// Builds the <see cref="IniConfigurationProvider"/> for this source.
/// </summary>
/// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
/// <returns>An <see cref="IniConfigurationProvider"/></returns>
public override IConfigurationProvider Build(IConfigurationBuilder builder) =>
new IniStreamConfigurationProvider(this);
}
}
| 37.62069 | 118 | 0.644363 | [
"MIT"
] | belav/runtime | src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniStreamConfigurationSource.cs | 1,091 | C# |
namespace SalesSystem.Areas.HelpPage.ModelDescriptions
{
public class CollectionModelDescription : ModelDescription
{
public ModelDescription ElementDescription { get; set; }
}
} | 28.285714 | 64 | 0.752525 | [
"MIT"
] | cristiano2005reis/sales_system | SalesSystem/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs | 198 | C# |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Cluster.Codecs {
public class JoinClusterEncoder
{
public const ushort BLOCK_LENGTH = 12;
public const ushort TEMPLATE_ID = 74;
public const ushort SCHEMA_ID = 1;
public const ushort SCHEMA_VERSION = 1;
private JoinClusterEncoder _parentMessage;
private IMutableDirectBuffer _buffer;
protected int _offset;
protected int _limit;
public JoinClusterEncoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IMutableDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public JoinClusterEncoder Wrap(IMutableDirectBuffer buffer, int offset)
{
this._buffer = buffer;
this._offset = offset;
Limit(offset + BLOCK_LENGTH);
return this;
}
public JoinClusterEncoder WrapAndApplyHeader(
IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder)
{
headerEncoder
.Wrap(buffer, offset)
.BlockLength(BLOCK_LENGTH)
.TemplateId(TEMPLATE_ID)
.SchemaId(SCHEMA_ID)
.Version(SCHEMA_VERSION);
return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH);
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int LeadershipTermIdEncodingOffset()
{
return 0;
}
public static int LeadershipTermIdEncodingLength()
{
return 8;
}
public static long LeadershipTermIdNullValue()
{
return -9223372036854775808L;
}
public static long LeadershipTermIdMinValue()
{
return -9223372036854775807L;
}
public static long LeadershipTermIdMaxValue()
{
return 9223372036854775807L;
}
public JoinClusterEncoder LeadershipTermId(long value)
{
_buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian);
return this;
}
public static int MemberIdEncodingOffset()
{
return 8;
}
public static int MemberIdEncodingLength()
{
return 4;
}
public static int MemberIdNullValue()
{
return -2147483648;
}
public static int MemberIdMinValue()
{
return -2147483647;
}
public static int MemberIdMaxValue()
{
return 2147483647;
}
public JoinClusterEncoder MemberId(int value)
{
_buffer.PutInt(_offset + 8, value, ByteOrder.LittleEndian);
return this;
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
JoinClusterDecoder writer = new JoinClusterDecoder();
writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION);
return writer.AppendTo(builder);
}
}
}
| 19.780899 | 84 | 0.628799 | [
"Apache-2.0"
] | Horusiath/aeron.net | src/Adaptive.Cluster/Codecs/JoinClusterEncoder.cs | 3,521 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Globalization;
namespace DataGridFilterLibrary.Support
{
public class FontSizeToHeightConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double height;
if (value != null)
{
if(Double.TryParse(value.ToString(), out height))
{
return height * 2;
}
else
{
return Double.NaN;
}
}
else
{
return value;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
}
| 24.65 | 104 | 0.48783 | [
"MIT"
] | MaxReinerAAE/Kundenverwaltung | DataGridFilterLibrary/Support/FontSizeToHeightConverter.cs | 988 | 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 WindowsMalwareOverview.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
[JsonConverter(typeof(DerivedTypeConverter))]
public partial class WindowsMalwareOverview
{
/// <summary>
/// Gets or sets malwareDetectedDeviceCount.
/// Count of devices with malware detected in the last 30 days
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "malwareDetectedDeviceCount", Required = Newtonsoft.Json.Required.Default)]
public Int32? MalwareDetectedDeviceCount { get; set; }
/// <summary>
/// Gets or sets malwareStateSummary.
/// Count of devices per malware state
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "malwareStateSummary", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<WindowsMalwareStateCount> MalwareStateSummary { get; set; }
/// <summary>
/// Gets or sets malwareExecutionStateSummary.
/// Count of devices per malware execution state
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "malwareExecutionStateSummary", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<WindowsMalwareExecutionStateCount> MalwareExecutionStateSummary { get; set; }
/// <summary>
/// Gets or sets malwareCategorySummary.
/// Count of devices per malware category
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "malwareCategorySummary", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<WindowsMalwareCategoryCount> MalwareCategorySummary { get; set; }
/// <summary>
/// Gets or sets malwareNameSummary.
/// Count of devices per malware
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "malwareNameSummary", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<WindowsMalwareNameCount> MalwareNameSummary { get; set; }
/// <summary>
/// Gets or sets osVersionsSummary.
/// Count of devices with malware per windows OS version
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "osVersionsSummary", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<OsVersionCount> OsVersionsSummary { 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; }
}
}
| 45.829268 | 160 | 0.648749 | [
"MIT"
] | gurry/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Models/Generated/WindowsMalwareOverview.cs | 3,758 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AntChain.SDK.BLOCKCHAIN.Models
{
public class SaveBlockchainBrowserPrivilegeRequest : TeaModel {
// OAuth模式下的授权token
[NameInMap("auth_token")]
[Validation(Required=false)]
public string AuthToken { get; set; }
[NameInMap("product_instance_id")]
[Validation(Required=false)]
public string ProductInstanceId { get; set; }
// 链id
[NameInMap("bizid")]
[Validation(Required=true)]
public string Bizid { get; set; }
// ORGJC1CN
[NameInMap("tenantid")]
[Validation(Required=true)]
public string Tenantid { get; set; }
}
}
| 23.294118 | 67 | 0.628788 | [
"MIT"
] | alipay/antchain-openapi-prod-sdk | blockchain/csharp/core/Models/SaveBlockchainBrowserPrivilegeRequest.cs | 806 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace CustomDI.Models.Contracts
{
public interface IWriter
{
void Write(string text);
}
}
| 16.166667 | 36 | 0.659794 | [
"MIT"
] | Gandjurov/AdvancedOOP_CSharp | 06.Workshop-DependancyInjention/01.CustomDI/Models/Contracts/IWriter.cs | 196 | C# |
// The MIT License (MIT)
//
// Copyright (c) 2013 Jacob Dufault
//
// 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 Newtonsoft.Json;
namespace Forge.Entities {
/// <summary>
/// Input that is given to the game manager.
/// </summary>
[JsonObject(MemberSerialization.OptIn)]
public interface IGameInput {
}
} | 46.689655 | 100 | 0.748892 | [
"MIT"
] | Mephistofeles/forge | Forge.Entities/API/IGameInput.cs | 1,356 | C# |
using System;
using System.Runtime.InteropServices;
#pragma warning disable CA1051
namespace OpenCvSharp
{
/// <summary>
/// 3-Tuple of byte (System.Byte)
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
// ReSharper disable once InconsistentNaming
public struct Vec3b : IVec<byte>, IEquatable<Vec3b>
{
/// <summary>
/// The value of the first component of this object.
/// </summary>
public byte Item0;
/// <summary>
/// The value of the second component of this object.
/// </summary>
public byte Item1;
/// <summary>
/// The value of the third component of this object.
/// </summary>
public byte Item2;
#if !DOTNET_FRAMEWORK
/// <summary>
/// Deconstructing a Vector
/// </summary>
/// <param name="item0"></param>
/// <param name="item1"></param>
/// <param name="item2"></param>
public void Deconstruct(out byte item0, out byte item1, out byte item2) => (item0, item1, item2) = (Item0, Item1, Item2);
#endif
/// <summary>
/// Initializer
/// </summary>
/// <param name="item0"></param>
/// <param name="item1"></param>
/// <param name="item2"></param>
public Vec3b(byte item0, byte item1, byte item2)
{
Item0 = item0;
Item1 = item1;
Item2 = item2;
}
/// <summary>
/// Indexer
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public byte this[int i]
{
get
{
switch (i)
{
case 0: return Item0;
case 1: return Item1;
case 2: return Item2;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
set
{
switch (i)
{
case 0: Item0 = value; break;
case 1: Item1 = value; break;
case 2: Item2 = value; break;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
}
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(Vec3b other)
{
return Item0 == other.Item0 && Item1 == other.Item1 && Item2 == other.Item2;
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object? obj)
{
if (obj is null) return false;
return obj is Vec3b b && Equals(b);
}
/// <summary>
///
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static bool operator ==(Vec3b a, Vec3b b)
{
return a.Equals(b);
}
/// <summary>
///
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static bool operator !=(Vec3b a, Vec3b b)
{
return !(a == b);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
unchecked
{
var hashCode = Item0.GetHashCode();
hashCode = (hashCode * 397) ^ Item1.GetHashCode();
hashCode = (hashCode * 397) ^ Item2.GetHashCode();
return hashCode;
}
}
/// <inheritdoc />
public override string ToString()
{
return $"{GetType().Name} ({Item0}, {Item1}, {Item2})";
}
}
} | 27.255034 | 129 | 0.443979 | [
"BSD-3-Clause"
] | AJEETX/opencvsharp | src/OpenCvSharp/Modules/core/Struct/Vec/Vec3b.cs | 4,063 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace _2.ChapterTwo2._9
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "_2.ChapterTwo2._9", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "_2.ChapterTwo2._9 v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 30.416667 | 110 | 0.609315 | [
"MIT"
] | bpbpublications/Implementing-Design-Patterns-in-C-and-.NET-5 | Chapter 02/2.ChapterTwo2.9/Startup.cs | 1,825 | 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.
using Microsoft.EntityFrameworkCore.Specification.Tests;
using Microsoft.EntityFrameworkCore.Specification.Tests.TestModels.Northwind;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Microsoft.EntityFrameworkCore.InMemory.FunctionalTests
{
public class NorthwindQueryInMemoryFixture : NorthwindQueryFixtureBase
{
private readonly DbContextOptions _options;
private readonly TestLoggerFactory _testLoggerFactory = new TestLoggerFactory();
public NorthwindQueryInMemoryFixture()
{
_options = BuildOptions();
using (var context = CreateContext())
{
NorthwindData.Seed(context);
}
}
public override DbContextOptions BuildOptions(IServiceCollection serviceCollection = null)
=> new DbContextOptionsBuilder()
.UseInMemoryDatabase(nameof(NorthwindQueryInMemoryFixture))
.UseInternalServiceProvider(
(serviceCollection ?? new ServiceCollection())
.AddEntityFrameworkInMemoryDatabase()
.AddSingleton(TestModelSource.GetFactory(OnModelCreating))
.AddSingleton<ILoggerFactory>(_testLoggerFactory)
.BuildServiceProvider()).Options;
public override NorthwindContext CreateContext(
QueryTrackingBehavior queryTrackingBehavior = QueryTrackingBehavior.TrackAll)
=> new NorthwindContext(_options, queryTrackingBehavior);
}
}
| 41.52381 | 111 | 0.692087 | [
"Apache-2.0"
] | pmiddleton/EntityFramework | test/EFCore.InMemory.FunctionalTests/NorthwindQueryInMemoryFixture.cs | 1,744 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Bdo.Objects.Base
{
/// <summary>
/// Classe base per oggetti Business
/// </summary>
public abstract class BusinessObjectBase: SlotAwareObject
{
/// <summary>
/// Ritorna rappresentazione JSON
/// </summary>
/// <returns></returns>
public string ToJSON()
{
return Utils.JSONWriter.ToJson(this);
}
}
}
| 19.75 | 61 | 0.582278 | [
"MIT"
] | simonep77/bdo | Business.Data.Objects/Objects/Base/BusinessObjectBase.cs | 476 | C# |
namespace MassTransit.InMemoryTransport
{
using System.Collections.Generic;
using System.Threading.Tasks;
using Fabric;
using Transports;
public class InMemoryMessageErrorTransport :
InMemoryMessageMoveTransport,
IErrorTransport
{
public InMemoryMessageErrorTransport(IInMemoryExchange exchange)
: base(exchange)
{
}
public Task Send(ExceptionReceiveContext context)
{
void PreSend(InMemoryTransportMessage message, IDictionary<string, object> headers)
{
headers.SetExceptionHeaders(context);
}
return Move(context, PreSend);
}
}
}
| 24.275862 | 95 | 0.632102 | [
"ECL-2.0",
"Apache-2.0"
] | sinch/MassTransit | src/MassTransit/InMemoryTransport/InMemoryTransport/InMemoryMessageErrorTransport.cs | 704 | C# |
/*
* Copyright 2018 James Courtney
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace FlatSharp.CodeGen;
/// <summary>
/// Some C# codegen helpers.
/// </summary>
internal static class CSharpHelpers
{
internal static string GetGlobalCompilableTypeName(this Type t)
{
return $"global::{GetCompilableTypeName(t)}";
}
internal static string GetCompilableTypeName(this Type t)
{
FlatSharpInternal.Assert(!string.IsNullOrEmpty(t.FullName), $"{t} has null/empty full name.");
string name;
if (t.IsGenericType)
{
List<string> parameters = new List<string>();
foreach (var generic in t.GetGenericArguments())
{
parameters.Add(GetCompilableTypeName(generic));
}
name = $"{t.FullName.Split('`')[0]}<{string.Join(", ", parameters)}>";
}
else if (t.IsArray)
{
name = $"{GetCompilableTypeName(t.GetElementType()!)}[]";
}
else
{
name = t.FullName;
}
name = name.Replace('+', '.');
return name;
}
internal static (AccessModifier propertyModifier, AccessModifier? getModifer, AccessModifier? setModifier) GetPropertyAccessModifiers(
AccessModifier getModifier,
AccessModifier? setModifier)
{
if (setModifier is null || getModifier == setModifier.Value)
{
return (getModifier, null, null);
}
FlatSharpInternal.Assert(
getModifier < setModifier.Value,
"Getter expected to be more visible than setter");
return (getModifier, null, setModifier);
}
internal static (AccessModifier propertyModifier, AccessModifier? getModifer, AccessModifier? setModifier) GetPropertyAccessModifiers(
PropertyInfo property,
bool convertProtectedInternalToProtected)
{
FlatSharpInternal.Assert(property.GetMethod is not null, $"Property {property.DeclaringType?.Name}.{property.Name} has null get method.");
var getModifier = GetAccessModifier(property.GetMethod, convertProtectedInternalToProtected);
if (property.SetMethod is null)
{
return (getModifier, null, null);
}
var setModifier = GetAccessModifier(property.SetMethod, convertProtectedInternalToProtected);
return GetPropertyAccessModifiers(getModifier, setModifier);
}
internal static string ToCSharpString(this AccessModifier? modifier)
{
return modifier switch
{
null => string.Empty,
_ => modifier.Value.ToCSharpString(),
};
}
internal static string ToCSharpString(this AccessModifier modifier)
{
return modifier switch
{
AccessModifier.Public => "public",
AccessModifier.Protected => "protected",
AccessModifier.ProtectedInternal => "protected internal",
AccessModifier.Private => "private",
_ => throw new InvalidOperationException($"Unexpected access modifier: '{modifier}'.")
};
}
internal static AccessModifier GetAccessModifier(this MethodInfo method, bool convertProtectedInternalToProtected)
{
if (method.IsPublic)
{
return AccessModifier.Public;
}
if (method.IsFamilyOrAssembly)
{
if (convertProtectedInternalToProtected)
{
return AccessModifier.Protected;
}
return AccessModifier.ProtectedInternal;
}
if (method.IsFamily)
{
return AccessModifier.Protected;
}
if (method.IsPrivate)
{
return AccessModifier.Private;
}
throw new InvalidOperationException("Unexpected method visibility: " + method.Name);
}
}
| 31.141844 | 146 | 0.631519 | [
"Apache-2.0"
] | mattico/FlatSharp | src/FlatSharp/Serialization/CSharpHelpers.cs | 4,393 | C# |
using CodeNav.Helpers;
using CodeNav.Models;
using CodeNav.Shared.ViewModels;
using Microsoft.VisualStudio.PlatformUI;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace CodeNav.Windows
{
public partial class FilterWindow : DialogWindow
{
private DataGridCell _cell;
public FilterWindow()
{
InitializeComponent();
Loaded += FilterWindow_Loaded;
}
private void FilterWindow_Loaded(object sender, RoutedEventArgs e)
{
DataContext = new FilterWindowViewModel
{
FilterRules = SettingsHelper.FilterRules
};
}
private FilterWindowViewModel ViewModel => DataContext as FilterWindowViewModel;
private void OkClick(object sender, RoutedEventArgs e)
{
SettingsHelper.SaveFilterRules(ViewModel.FilterRules);
Close();
}
private void CancelClick(object sender, RoutedEventArgs e)
{
Close();
}
private void AddClick(object sender, RoutedEventArgs e)
{
ViewModel.FilterRules.Add(new FilterRule());
}
private void DeleteClick(object sender, RoutedEventArgs e)
{
if (_cell == null)
{
return;
}
ViewModel.FilterRules.Remove(_cell.DataContext as FilterRule);
}
private void DataGrid_Selected(object sender, RoutedEventArgs e)
{
if (e.OriginalSource.GetType() == typeof(DataGridCell))
{
var grid = sender as DataGrid;
grid.BeginEdit(e);
var cell = e.OriginalSource as DataGridCell;
_cell = cell;
var comboBox = WpfHelper
.FindChildrenByType<ComboBox>(cell)
.FirstOrDefault();
if (comboBox != null)
{
comboBox.IsDropDownOpen = true;
}
var checkBox = WpfHelper
.FindChildrenByType<CheckBox>(cell)
.FirstOrDefault();
if (checkBox != null)
{
checkBox.IsChecked = !checkBox.IsChecked;
}
var textBox = WpfHelper
.FindChildrenByType<TextBox>(cell)
.FirstOrDefault();
if (textBox != null)
{
textBox.SelectAll();
}
}
}
private void DataGrid_Unloaded(object sender, RoutedEventArgs e)
{
var grid = sender as DataGrid;
grid.CancelEdit(DataGridEditingUnit.Row);
}
}
} | 26.590476 | 88 | 0.527221 | [
"MIT"
] | sboulema/CodeNav | CodeNav.Shared/Windows/FilterWindow.xaml.cs | 2,794 | C# |
namespace CWMII.lib.Enums {
public enum Win32_PerfRawData_WSearchIdxPi_SearchIndexer {
Caption,
Description,
Name,
Frequency_Object,
Frequency_PerfTime,
Frequency_Sys100NS,
Timestamp_Object,
Timestamp_PerfTime,
Timestamp_Sys100NS,
ActiveConnections,
CleanWidSets,
DirtyWidSets,
DocumentsFiltered,
IndexSize,
L0IndexesWordlists,
L0MergeFlushCount,
L0MergeFlushSpeedAverage,
L0MergeFlushSpeedLast,
L0MergesflushesNow,
L1MergeCount,
L1MergesNow,
L1MergeSpeedaverage,
L1MergeSpeedlast,
L2MergeCount,
L2MergesNow,
L2MergeSpeedaverage,
L2MergeSpeedlast,
L3MergeCount,
L3MergesNow,
L3MergeSpeedaverage,
L3MergeSpeedlast,
L4MergeCount,
L4MergesNow,
L4MergeSpeedaverage,
L4MergeSpeedlast,
L5MergeCount,
L5MergesNow,
L5MergeSpeedaverage,
L5MergeSpeedlast,
L6MergeCount,
L6MergesNow,
L6MergeSpeedaverage,
L6MergeSpeedlast,
L7MergeCount,
L7MergesNow,
L7MergeSpeedaverage,
L7MergeSpeedlast,
L8MergeCount,
L8MergesNow,
L8MergeSpeedaverage,
L8MergeSpeedlast,
MasterIndexLevel,
MasterMergeProgress,
MasterMergesNow,
MasterMergestoDate,
PersistentIndexes,
PersistentIndexesL1,
PersistentIndexesL2,
PersistentIndexesL3,
PersistentIndexesL4,
PersistentIndexesL5,
PersistentIndexesL6,
PersistentIndexesL7,
PersistentIndexesL8,
Queries,
QueriesFailed,
QueriesSucceeded,
ShadowMergeLevels,
ShadowMergeLevelsThreshold,
UniqueKeys,
WorkItemsCreated,
WorkItemsDeleted
}
public static class Win32_PerfRawData_WSearchIdxPi_SearchIndexerExtension {
public static string GetWMIValue(this Win32_PerfRawData_WSearchIdxPi_SearchIndexer enumOption) => lib.CWMII.GetSingleProperty($"SELECT * FROM Win32_PerfRawData_WSearchIdxPi_SearchIndexer", enumOption.ToString());
}
} | 22.35 | 214 | 0.807047 | [
"MIT"
] | jcapellman/CWMII | CWMII.lib/Enums/Win32_PerfRawData_WSearchIdxPi_SearchIndexer.cs | 1,788 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using GwApiNET;
using GwApiNET.ResponseObjects;
using GwApiNETExample.Managers;
namespace GwApiNETExample.Controls
{
public partial class RecipeViewerUserControl : UserControlBase
{
public RecipeViewerUserControl()
{
InitializeComponent();
recipeSearchUserControl1.ComboBoxIdList.SelectedValueChanged += ComboBoxIdList_SelectedValueChanged;
recipeSearchUserControl1.SearchResultsBox.SelectedValueChanged +=SearchResultsBox_SelectedValueChanged;
}
async void ComboBoxIdList_SelectedValueChanged(object sender, EventArgs e)
{
int id = (int) recipeSearchUserControl1.ComboBoxIdList.SelectedValue;
var recipe = await RecipeManager.Instance.GetRecipe(id);
await SetRecipe(recipe).ConfigureAwait(false);
}
async void SearchResultsBox_SelectedValueChanged(object sender, EventArgs e)
{
try
{
var recipe = RecipeManager.Recipes[(int)recipeSearchUserControl1.SelectedResult.Id];
await SetRecipe(recipe).ConfigureAwait(false);
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
public async Task SetRecipe(RecipeDetailsEntry recipe)
{
await recipeDetailsUserControl1.SetRecipe(recipe).ConfigureAwait(false);
}
public override string Status
{
get { return recipeSearchUserControl1.Status; }
}
}
}
| 31.589286 | 115 | 0.671566 | [
"MIT"
] | prbarcelon/GwApiNET | GwApiNET/GwApiNETExample/Controls/RecipeViewerUserControl.cs | 1,771 | C# |
// Copyright 2020 The Tilt Brush 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 UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using Newtonsoft.Json;
#if USE_DOTNETZIP
using ZipSubfileReader = ZipSubfileReader_DotNetZip;
using ZipLibrary = Ionic.Zip;
#else
using ZipSubfileReader = TiltBrush.ZipSubfileReader_SharpZipLib;
using ZipLibrary = ICSharpCode.SharpZipLibUnityPort.Zip;
#endif
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor")]
namespace TiltBrush {
public class App : MonoBehaviour {
// ------------------------------------------------------------
// Constants and types
// ------------------------------------------------------------
public const float METERS_TO_UNITS = 10f;
public const float UNITS_TO_METERS = .1f;
// These control the naming of various things related to the app. If you distribute your own
// build, you need to call is something other that 'Tilt Brush', as that if a Google trademark -
// see the BRANDING file for details.
// As a minimum, you should change kAppDisplayName.
// This is the name of the app, as displayed to the users running it.
public const string kAppDisplayName = "BiltTrush";
// The vendor name - used for naming android builds - shouldn't have spaces.
public const string kVendorName = "Doogle";
// The vendor name - used for the company name in builds and fbx output. Can have spaces.
public const string kDisplayVendorName = "Doogle";
// This is the App name used when speaking to Google services
public const string kGoogleServicesAppName = kAppDisplayName;
// The name of the configuration file. You may want to change this if you think your users may
// want to have a different config file for your edition of the app.
public const string kConfigFileName = "Bilt Trush.cfg";
// The name of the App folder (In the user's Documents folder) - you may want to share this with
// the original Tilt Brush, or not.
public const string kAppFolderName = "Bilt Trush";
// The data folder used on Google Drive.
public const string kDriveFolderName = kAppDisplayName;
// Executable Base
public const string kGuiBuildExecutableName = "BiltTrush";
// Windows Executable
public const string kGuiBuildWindowsExecutableName = kGuiBuildExecutableName + ".exe";
// OSX Executable
public const string kGuiBuildOSXExecutableName = kGuiBuildExecutableName + ".app";
// Android Executable
public const string kGuiBuildAndroidExecutableName =
"com." + kVendorName + "." + kGuiBuildExecutableName + ".apk";
public const string kPlayerPrefHasPlayedBefore = "Has played before";
public const string kReferenceImagesSeeded = "Reference Images seeded";
private const string kDefaultConfigPath = "DefaultConfig";
private const int kHttpListenerPort = 40074;
private const string kProtocolHandlerPrefix = "tiltbrush://remix/";
private const string kFileMoveFilename = "WhereHaveMyFilesGone.txt";
private const string kFileMoveContents =
"All your " + kAppDisplayName + " files have been moved to\n" +
"/sdcard/" + kAppFolderName + ".\n";
public enum AppState {
Error,
LoadingBrushesAndLighting,
FadeFromBlack,
FirstRunIntro,
Intro,
Loading,
QuickLoad,
Standard,
MemoryExceeded,
Saving,
Reset,
Uploading,
AutoProfiling,
OfflineRendering,
}
// ------------------------------------------------------------
// Static API
// ------------------------------------------------------------
private static App m_Instance;
// Accessible at all times after config is initialized.
public static Config Config {
get { return Config.m_SingletonState; }
}
public static UserConfig UserConfig {
get { return m_Instance.m_UserConfig; }
}
public static PlatformConfig PlatformConfig {
get { return Config.PlatformConfig; }
}
public static VrSdk VrSdk {
get { return m_Instance.m_VrSdk; }
}
public static SceneScript Scene {
get { return m_Instance.m_SceneScript; }
}
public static CanvasScript ActiveCanvas {
get { return Scene.ActiveCanvas; }
}
public static PolyAssetCatalog PolyAssetCatalog {
get { return m_Instance.m_PolyAssetCatalog; }
}
public static Switchboard Switchboard {
get { return m_Instance.m_Switchboard; }
}
public static BrushColorController BrushColor {
get { return m_Instance.m_BrushColorController; }
}
public static GroupManager GroupManager {
get { return m_Instance.m_GroupManager; }
}
public static HttpServer HttpServer => m_Instance.m_HttpServer;
public static DriveAccess DriveAccess => m_Instance.m_DriveAccess;
public static DriveSync DriveSync => m_Instance.m_DriveSync;
public static OAuth2Identity GoogleIdentity => m_Instance.m_GoogleIdentity;
public static OAuth2Identity SketchfabIdentity => m_Instance.m_SketchfabIdentity;
public static GoogleUserSettings GoogleUserSettings => m_Instance.m_GoogleUserSettings;
/// Returns the App instance, or null if the app has not been initialized
/// with Awake(). Note that the App may not have had Start() called yet.
///
/// Do not modify the script execution order if you only need inspector
/// data from App.Instance. Put the inspector data in App.Config instead.
public static App Instance {
get { return m_Instance; }
#if UNITY_EDITOR
// Bleh. Needed by BuildTiltBrush.cs
set { m_Instance = value; }
#endif
}
public static AppState CurrentState {
get {
return m_Instance == null ? AppState.Loading : m_Instance.m_CurrentAppState;
}
}
public static OAuth2Identity GetIdentity(Cloud cloud) {
switch (cloud) {
case Cloud.Poly: return GoogleIdentity;
case Cloud.Sketchfab: return SketchfabIdentity;
default: throw new InvalidOperationException($"No identity for {cloud}");
}
}
// ------------------------------------------------------------
// Events
// ------------------------------------------------------------
public event Action<AppState, AppState> StateChanged;
// ------------------------------------------------------------
// Inspector data
// ------------------------------------------------------------
// Unless otherwise stated, intended to be read-only even if public
[Header("External References")]
[SerializeField] VrSdk m_VrSdk;
[SerializeField] SceneScript m_SceneScript;
[Header("General inspector")]
[SerializeField] float m_FadeFromBlackDuration;
[SerializeField] float m_QuickLoadHintDelay = 2f;
[SerializeField] GpuIntersector m_GpuIntersector;
public TiltBrushManifest m_Manifest;
#if (UNITY_EDITOR || EXPERIMENTAL_ENABLED)
[SerializeField] private TiltBrushManifest m_ManifestExperimental;
#endif
[SerializeField] private SelectionEffect m_SelectionEffect;
/// The root object for the "Room" coordinate system
public Transform m_RoomTransform { get { return transform; } }
/// The root object for the "Scene" coordinate system ("/SceneParent")
public Transform m_SceneTransform;
/// The root object for the "Canvas" coordinate system ("/SceneParent/Canvas")
/// TODO: remove, in favor of .ActiveCanvas.transform
public Transform m_CanvasTransform;
/// The object "/SceneParent/EnvironmentParent"
public Transform m_EnvironmentTransform;
[SerializeField] GameObject m_SketchSurface;
[SerializeField] GameObject m_ErrorDialog;
[SerializeField] GameObject m_OdsPrefab;
GameObject m_OdsPivot;
[Header("Intro")]
[SerializeField] float m_IntroSketchFadeInDuration = 5.0f;
[SerializeField] float m_IntroSketchFadeOutDuration = 1.5f;
[SerializeField] float m_IntroSketchMobileFadeInDuration = 3.0f;
[SerializeField] float m_IntroSketchMobileFadeOutDuration = 1.5f;
[SerializeField] FrameCountDisplay m_FrameCountDisplay;
[SerializeField] private GameObject m_ShaderWarmup;
[Header("Identities")]
[SerializeField] private OAuth2Identity m_GoogleIdentity;
[SerializeField] private OAuth2Identity m_SketchfabIdentity;
// ------------------------------------------------------------
// Private data
// ------------------------------------------------------------
/// Use C# event in preference to Unity callbacks because
/// Unity doesn't send callbacks to disabled objects
public event Action AppExit;
private Queue m_RequestedTiltFileQueue = Queue.Synchronized(new Queue());
private HttpServer m_HttpServer;
private SketchSurfacePanel m_SketchSurfacePanel;
private UserConfig m_UserConfig;
private string m_UserPath;
private string m_OldUserPath;
private PolyAssetCatalog m_PolyAssetCatalog;
private Switchboard m_Switchboard;
private BrushColorController m_BrushColorController;
private GroupManager m_GroupManager;
/// Time origin of sketch in seconds for case when drawing is not sync'd to media.
private double m_sketchTimeBase = 0;
private float m_AppStateCountdown;
private float m_QuickLoadHintCountdown;
private bool m_QuickLoadInputWasValid;
private bool m_QuickLoadEatInput;
private AppState m_CurrentAppState;
// Temporary: to narrow down b/37256058
private AppState m_DesiredAppState_;
private AppState m_DesiredAppState {
get { return m_DesiredAppState_; }
set {
if (m_DesiredAppState_ != value) {
Console.WriteLine("State <- {0}", value);
}
m_DesiredAppState_ = value;
}
}
private int m_TargetFrameRate;
private float m_RoomRadius;
private bool m_AutosaveRestoreFileExists;
private bool m_ShowAutosaveHint = false;
private bool? m_ShowControllers;
private int m_QuickloadStallFrames;
private GameObject m_IntroSketch;
private Renderer[] m_IntroSketchRenderers;
private float m_IntroFadeTimer;
private bool m_FirstRunExperience;
private bool m_RequestingAudioReactiveMode;
private DriveAccess m_DriveAccess;
private DriveSync m_DriveSync;
private GoogleUserSettings m_GoogleUserSettings;
// ------------------------------------------------------------
// Properties
// ------------------------------------------------------------
/// Time spent in current sketch, in seconds.
/// On load, this is restored to the timestamp of the last stroke.
/// Updated per-frame.
public double CurrentSketchTime {
// Unity's Time.time has useful precision probably <= 1ms, and unknown
// drift/accuracy. It is a single (but is a double, internally), so its
// raw precision drops to ~2ms after ~4 hours and so on.
// Time.timeSinceLevelLoad is also an option.
//
// C#'s DateTime API has low-ish precision (10+ ms depending on OS)
// but likely the highest accuracy with respect to wallclock, since
// it's reading from an RTC.
//
// High-precision timers are the opposite: high precision, but are
// subject to drift.
//
// For realtime sync, Time.time is probably the best thing to use.
// For postproduction sync, probably C# DateTime.
get {
// If you change this, also modify SketchTimeToLevelLoadTime
return Time.timeSinceLevelLoad - m_sketchTimeBase;
}
set {
if (value < 0) { throw new ArgumentException("negative"); }
m_sketchTimeBase = Time.timeSinceLevelLoad - value;
}
}
public float RoomRadius {
get { return m_RoomRadius; }
}
public SelectionEffect SelectionEffect {
get { return m_SelectionEffect; }
}
public bool IsFirstRunExperience { get { return m_FirstRunExperience; } }
public bool HasPlayedBefore {
get;
private set;
}
public bool StartupError { get; set; }
public bool ShowControllers {
get { return m_ShowControllers.GetValueOrDefault(true); }
set {
InputManager.m_Instance.ShowControllers(value);
m_ShowControllers = value;
}
}
public bool AutosaveRestoreFileExists {
get { return m_AutosaveRestoreFileExists; }
set {
if (value != m_AutosaveRestoreFileExists) {
try {
string filePath = AutosaveRestoreFilePath();
if (value) {
var autosaveFile = File.Create(filePath);
autosaveFile.Close();
} else {
if (File.Exists(filePath)) {
File.Delete(filePath);
}
}
}
catch (IOException) { return; }
catch (UnauthorizedAccessException) { return; }
m_AutosaveRestoreFileExists = value;
}
}
}
public GpuIntersector GpuIntersector {
get { return m_GpuIntersector; }
}
public TrTransform OdsHeadPrimary { get; set; }
public TrTransform OdsScenePrimary { get; set; }
public TrTransform OdsHeadSecondary { get; set; }
public TrTransform OdsSceneSecondary { get; set; }
public FrameCountDisplay FrameCountDisplay {
get { return m_FrameCountDisplay; }
}
// ------------------------------------------------------------
// Implementation
// ------------------------------------------------------------
public bool RequestingAudioReactiveMode {
get { return m_RequestingAudioReactiveMode; }
}
public void ToggleAudioReactiveModeRequest() {
m_RequestingAudioReactiveMode ^= true;
}
public void ToggleAudioReactiveBrushesRequest() {
ToggleAudioReactiveModeRequest();
AudioCaptureManager.m_Instance.CaptureAudio(m_RequestingAudioReactiveMode);
VisualizerManager.m_Instance.EnableVisuals(m_RequestingAudioReactiveMode);
Switchboard.TriggerAudioReactiveStateChanged();
}
public double SketchTimeToLevelLoadTime(double sketchTime) {
return sketchTime + m_sketchTimeBase;
}
public void SetOdsCameraTransforms(TrTransform headXf, TrTransform sceneXf) {
if (Config.m_SdkMode != SdkMode.Ods) { return; }
OdsScenePrimary = sceneXf;
OdsHeadPrimary = headXf;
// To simplify down-stream code, copy primary into secondary.
if (OdsHeadSecondary == new TrTransform()) {
OdsHeadSecondary = headXf;
OdsSceneSecondary = sceneXf;
}
}
// Tilt Brush code assumes the current directory is next to the Support/
// folder. Enforce that assumption
static void SetCurrentDirectoryToApplication() {
// dataPath is:
// Editor - <project folder>/Assets
// Windows - TiltBrush_Data/
// Linux - TiltBrush_Data/
// OSX - TiltBrush.app/Contents/
#if UNITY_STANDALONE_WIN
string oldDir = Directory.GetCurrentDirectory();
string dataDir = UnityEngine.Application.dataPath;
string appDir = Path.GetDirectoryName(dataDir);
try {
Directory.SetCurrentDirectory(appDir);
} catch (Exception e) {
Debug.LogErrorFormat("Couldn't set dir to {0}: {1}", appDir, e);
}
string curDir = Directory.GetCurrentDirectory();
Debug.LogFormat("Dir {0} -> {1}", oldDir, curDir);
#endif
}
void CreateIntroSketch() {
m_IntroSketch = Instantiate(PlatformConfig.IntroSketchPrefab);
m_IntroSketchRenderers = m_IntroSketch.GetComponentsInChildren<Renderer>();
for (int i = 0; i < m_IntroSketchRenderers.Length; ++i) {
m_IntroSketchRenderers[i].material.SetFloat("_IntroDissolve", 1);
m_IntroSketchRenderers[i].material.SetFloat("_GreyScale", 0);
}
}
void DestroyIntroSketch() {
Destroy(m_IntroSketch);
m_IntroSketchRenderers = null;
// Eject the (rather large) intro sketch from memory.
// TODO: The Unity Way would be to put these prefab references and instantiations
// in an additive scene.
// Don't do this in the editor, because it mutates the asset on disk!
#if !UNITY_EDITOR
PlatformConfig.IntroSketchPrefab = null;
#endif
Resources.UnloadUnusedAssets();
}
static string GetStartupString() {
string stamp = Config.m_BuildStamp;
#if UNITY_ANDROID
stamp += string.Format(" code {0}", AndroidUtils.GetVersionCode());
#endif
#if DEBUG
stamp += string.Format(" platcfg {0}", PlatformConfig.name);
#endif
return $"{App.kAppDisplayName} {Config.m_VersionNumber}\nBuild {stamp}";
}
void Awake() {
m_Instance = this;
Debug.Log(GetStartupString());
// Begone, physics! You were using 0.3 - 1.3ms per frame on Quest!
Physics.autoSimulation = false;
// See if this is the first time
HasPlayedBefore = PlayerPrefs.GetInt(kPlayerPrefHasPlayedBefore, 0) == 1;
// Copy files into Support directory
CopySupportFiles();
InitUserPath();
SetCurrentDirectoryToApplication();
Coords.Init(this);
Scene.Init();
CreateDefaultConfig();
RefreshUserConfig();
CameraConfig.Init();
if (!string.IsNullOrEmpty(m_UserConfig.Profiling.SketchToLoad)) {
Config.m_SketchFiles = new string[] { m_UserConfig.Profiling.SketchToLoad };
}
if (m_UserConfig.Testing.FirstRun) {
PlayerPrefs.DeleteKey(kPlayerPrefHasPlayedBefore);
PlayerPrefs.DeleteKey(kReferenceImagesSeeded);
PlayerPrefs.DeleteKey(PanelManager.kPlayerPrefAdvancedMode);
AdvancedPanelLayouts.ClearPlayerPrefs();
PointerManager.ClearPlayerPrefs();
HasPlayedBefore = false;
}
// Cache this variable for the length of the play session. HasPlayedBefore will be updated,
// but m_FirstRunExperience should not.
m_FirstRunExperience = !HasPlayedBefore;
m_Switchboard = new Switchboard();
m_GroupManager = new GroupManager();
m_PolyAssetCatalog = GetComponent<PolyAssetCatalog>();
m_PolyAssetCatalog.Init();
m_BrushColorController = GetComponent<BrushColorController>();
// Tested on Windows. I hope they don't change the names of these preferences.
PlayerPrefs.DeleteKey("Screenmanager Is Fullscreen mode");
PlayerPrefs.DeleteKey("Screenmanager Resolution Height");
PlayerPrefs.DeleteKey("Screenmanager Resolution Width");
if (DevOptions.I.UseAutoProfiler) {
gameObject.AddComponent<AutoProfiler>();
}
m_Manifest = GetMergedManifest(consultUserConfig: true);
m_HttpServer = GetComponentInChildren<HttpServer>();
if (!Config.IsMobileHardware) {
HttpServer.AddHttpHandler("/load", HttpLoadSketchCallback);
}
m_AutosaveRestoreFileExists = File.Exists(AutosaveRestoreFilePath());
m_GoogleUserSettings = new GoogleUserSettings(m_GoogleIdentity);
m_DriveAccess = new DriveAccess(m_GoogleIdentity, m_GoogleUserSettings);
m_DriveSync = new DriveSync(m_DriveAccess, m_GoogleIdentity);
}
// TODO: should add OnDestroy to other scripts that create background tasks
void OnDestroy() {
if (!Config.IsMobileHardware) {
HttpServer.RemoveHttpHandler("/load");
}
if (m_DriveSync != null) {
m_DriveSync.UninitializeAsync().AsAsyncVoid();
}
if (m_DriveAccess != null) {
m_DriveAccess.UninitializeAsync().AsAsyncVoid();
}
}
// Called from HttpListener thread. Supported requests:
// /load?<SKETCH_PATH>
// Loads sketch given path on local filesystem. Any pending load is canceled.
// Response body: none
string HttpLoadSketchCallback(HttpListenerRequest request) {
var urlPath = request.Url.LocalPath;
var query = Uri.UnescapeDataString(request.Url.Query);
if (urlPath == "/load" && query.Length > 1) {
var filePath = query.Substring(1);
m_RequestedTiltFileQueue.Enqueue(filePath);
}
return "";
}
void Start() {
// Use of ControllerConsoleScript must wait until Start()
ControllerConsoleScript.m_Instance.AddNewLine(GetStartupString());
if (!VrSdk.IsHmdInitialized()) {
Debug.Log("VR HMD was not initialized on startup.");
StartupError = true;
CreateErrorDialog();
} else {
Debug.LogFormat("Sdk mode: {0} XRDevice.model: {1}",
App.Config.m_SdkMode, UnityEngine.XR.XRDevice.model);
}
m_TargetFrameRate = VrSdk.GetHmdTargetFrameRate();
if (VrSdk.GetHmdDof() == TiltBrush.VrSdk.DoF.None) {
Application.targetFrameRate = m_TargetFrameRate;
}
if (VrSdk.HasRoomBounds()) {
Vector3 extents = VrSdk.GetRoomExtents();
m_RoomRadius = Mathf.Min(Mathf.Abs(extents.x), Mathf.Abs(extents.z));
}
// Load the Usd Plugins
InitializeUsd();
foreach (string s in Config.m_SketchFiles) {
// Assume all relative paths are relative to the Sketches directory.
string sketch = s;
if (!System.IO.Path.IsPathRooted(sketch)) {
sketch = System.IO.Path.Combine(App.UserSketchPath(), sketch);
}
m_RequestedTiltFileQueue.Enqueue(sketch);
if (Config.m_SdkMode == SdkMode.Ods || Config.OfflineRender) {
// We only load one sketch for ODS rendering & offline rendering.
break;
}
}
if (Config.m_AutosaveRestoreEnabled && AutosaveRestoreFileExists) {
string lastAutosave = SaveLoadScript.m_Instance.MostRecentAutosaveFile();
if (lastAutosave != null) {
string newPath = SaveLoadScript.m_Instance.GenerateNewUntitledFilename(
UserSketchPath(), SaveLoadScript.TILT_SUFFIX);
if (newPath != null) {
File.Copy(lastAutosave, newPath);
m_ShowAutosaveHint = true;
}
}
AutosaveRestoreFileExists = false;
}
if (Config.m_SdkMode == SdkMode.Ods) {
m_OdsPivot = (GameObject)Instantiate(m_OdsPrefab);
OdsDriver driver = m_OdsPivot.GetComponent<OdsDriver>();
driver.FramesToCapture = Config.m_OdsNumFrames;
driver.m_fps = Config.m_OdsFps;
driver.TurnTableRotation = Config.m_OdsTurnTableDegrees;
driver.OutputFolder = Config.m_OdsOutputPath;
driver.OutputBasename = Config.m_OdsOutputPrefix;
if (!string.IsNullOrEmpty(App.Config.m_VideoPathToRender)) {
driver.CameraPath = App.Config.m_VideoPathToRender;
}
ODS.HybridCamera cam = driver.OdsCamera;
cam.CollapseIpd = Config.m_OdsCollapseIpd;
cam.imageWidth /= Config.m_OdsPreview ? 4 : 1;
Debug.LogFormat("Configuring ODS:{0}" +
"Frames: {1}{0}" +
"FPS: {8}{0}" +
"TurnTable: {2}{0}" +
"Output: {3}{0}" +
"Basename: {4}{0}" +
"QuickLoad: {5}{0}" +
"CollapseIPD: {6}{0}" +
"ImageWidth: {7}{0}",
System.Environment.NewLine,
driver.FramesToCapture,
driver.TurnTableRotation,
driver.OutputFolder,
driver.OutputBasename,
Config.m_QuickLoad,
cam.CollapseIpd,
cam.imageWidth,
driver.m_fps);
}
//these guys don't need to be alive just yet
PointerManager.m_Instance.EnablePointerStrokeGeneration(false);
Console.WriteLine("RenderODS: {0}, numFrames: {1}",
m_OdsPivot != null,
m_OdsPivot ? m_OdsPivot.GetComponent<OdsDriver>().FramesToCapture
: 0);
if (!AppAllowsCreation()) {
TutorialManager.m_Instance.IntroState = IntroTutorialState.InitializeForNoCreation;
} else {
TutorialManager.m_Instance.IntroState = IntroTutorialState.Done;
}
if (m_RequestedTiltFileQueue.Count == 0) {
TutorialManager.m_Instance.ActivateControllerTutorial(InputManager.ControllerName.Brush, false);
TutorialManager.m_Instance.ActivateControllerTutorial(InputManager.ControllerName.Wand, false);
}
ViewpointScript.m_Instance.Init();
QualityControls.m_Instance.Init();
bool bVR = VrSdk.GetHmdDof() != TiltBrush.VrSdk.DoF.None;
InputManager.m_Instance.AllowVrControllers = bVR;
PointerManager.m_Instance.UseSymmetryWidget(bVR);
switch (VrSdk.GetControllerDof()) {
case TiltBrush.VrSdk.DoF.Six:
// Vive, Rift + Touch
SketchControlsScript.m_Instance.ActiveControlsType =
SketchControlsScript.ControlsType.SixDofControllers;
break;
case TiltBrush.VrSdk.DoF.None:
SketchControlsScript.m_Instance.ActiveControlsType =
SketchControlsScript.ControlsType.ViewingOnly;
break;
case TiltBrush.VrSdk.DoF.Two:
// Monoscopic
SketchControlsScript.m_Instance.ActiveControlsType =
SketchControlsScript.ControlsType.KeyboardMouse;
break;
}
m_CurrentAppState = AppState.Standard;
m_DesiredAppState = AppState.LoadingBrushesAndLighting;
if (StartupError) {
m_DesiredAppState = AppState.Error;
}
m_SketchSurfacePanel = m_SketchSurface.GetComponent<SketchSurfacePanel>();
ViewpointScript.m_Instance.SetHeadMeshVisible(App.UserConfig.Flags.ShowHeadset);
ShowControllers = App.UserConfig.Flags.ShowControllers;
SwitchState();
#if USD_SUPPORTED && (UNITY_EDITOR || EXPERIMENTAL_ENABLED)
if (Config.IsExperimental && !string.IsNullOrEmpty(Config.m_IntroSketchUsdFilename)) {
var gobject = ImportUsd.ImportWithAnim(Config.m_IntroSketchUsdFilename);
gobject.transform.SetParent(App.Scene.transform, false);
}
#endif
if (Config.m_AutoProfile || m_UserConfig.Profiling.AutoProfile) {
StateChanged += AutoProfileOnStartAndQuit;
}
}
private void AutoProfileOnStartAndQuit(AppState oldState, AppState newState) {
if (newState == AppState.Standard) {
Invoke("AutoProfileAndQuit", Config.m_AutoProfileWaitTime);
StateChanged -= AutoProfileOnStartAndQuit;
}
}
private void AutoProfileAndQuit() {
SketchControlsScript.m_Instance.IssueGlobalCommand(
SketchControlsScript.GlobalCommands.DoAutoProfileAndQuit);
}
public void SetDesiredState(AppState rDesiredState) {
m_DesiredAppState = rDesiredState;
}
void Update() {
#if UNITY_EDITOR
// All changes to Scene transform must go through Coords.cs
if (m_SceneTransform.hasChanged) {
Debug.LogError("Detected unsanctioned change to Scene transform");
m_SceneTransform.hasChanged = false;
}
#endif
//look for state change
if (m_CurrentAppState != m_DesiredAppState) {
SwitchState();
}
if (InputManager.m_Instance.GetCommand(InputManager.SketchCommands.Activate)) {
//kinda heavy-handed, but whatevs
InitCursor();
}
// Wait for the environment transition to complete before capturing.
if (m_OdsPivot
&& !m_OdsPivot.activeInHierarchy
&& !SceneSettings.m_Instance.IsTransitioning
&& ((m_CurrentAppState == AppState.Loading && !Config.m_QuickLoad)
|| m_CurrentAppState == AppState.Standard)) {
try {
OdsDriver driver = m_OdsPivot.GetComponent<OdsDriver>();
// Load the secondary transform, if a second sketch was specified.
if (Config.m_SketchFiles.Length > 1) {
string sketch = Config.m_SketchFiles[1];
// Assume relative paths are relative to the sketches directory.
if (!System.IO.Path.IsPathRooted(sketch)) {
sketch = System.IO.Path.Combine(App.UserSketchPath(), sketch);
}
var head = TrTransform.identity;
var scene = TrTransform.identity;
if (SaveLoadScript.m_Instance.LoadTransformsForOds(new DiskSceneFileInfo(sketch),
ref head,
ref scene)) {
OdsHeadSecondary = head;
OdsSceneSecondary = scene;
} else {
Debug.LogErrorFormat("Failed to load secondary sketch for ODS: {0}", sketch);
}
}
if (driver.OutputBasename == null || driver.OutputBasename == "") {
driver.OutputBasename =
FileUtils.SanitizeFilename(SaveLoadScript.m_Instance.SceneFile.HumanName);
if (driver.OutputBasename == null || driver.OutputBasename == "") {
if (Config.m_SketchFiles.Length > 0) {
driver.OutputBasename = System.IO.Path.GetFileNameWithoutExtension(
Config.m_SketchFiles[0]);
} else {
driver.OutputBasename = "Untitled";
}
}
}
if (driver.OutputFolder == null || driver.OutputFolder == "") {
driver.OutputFolder = App.VrVideosPath();
FileUtils.InitializeDirectoryWithUserError(driver.OutputFolder);
}
InputManager.m_Instance.EnablePoseTracking(false);
driver.BeginRender();
} catch (System.Exception ex) {
Debug.LogException(ex);
Application.Quit();
Debug.Break();
}
}
m_PolyAssetCatalog.UpdateCatalog();
//update state
switch (m_CurrentAppState) {
case AppState.LoadingBrushesAndLighting: {
if (!BrushCatalog.m_Instance.IsLoading
&& !EnvironmentCatalog.m_Instance.IsLoading
&& !m_ShaderWarmup.activeInHierarchy) {
if (AppAllowsCreation()) {
BrushController.m_Instance.SetBrushToDefault();
BrushColor.SetColorToDefault();
} else {
PointerManager.m_Instance.SetBrushForAllPointers(BrushCatalog.m_Instance.DefaultBrush);
}
AudioManager.Enabled = true;
SceneSettings.m_Instance.SetDesiredPreset(EnvironmentCatalog.m_Instance.DefaultEnvironment);
bool skipStandardIntro = true;
if (HandleExternalTiltOpenRequest()) {
// tilt requested on command line was loaded
} else if (Config.m_FilePatternsToExport != null) {
m_DesiredAppState = AppState.Standard;
SketchControlsScript.m_Instance.IssueGlobalCommand(
SketchControlsScript.GlobalCommands.ExportListed);
} else if (Config.OfflineRender) {
m_DesiredAppState = AppState.Standard;
} else if (DemoManager.m_Instance.DemoModeEnabled) {
OnIntroComplete();
#if (UNITY_EDITOR || EXPERIMENTAL_ENABLED)
} else if (Config.IsExperimental) {
OnIntroComplete();
PanelManager.m_Instance.ReviveFloatingPanelsForStartup();
#endif
} else {
if (Config.m_SdkMode == SdkMode.Ods) {
// Skip the fade from black when we're rendering ODS.
m_DesiredAppState = AppState.Standard;
} else {
m_DesiredAppState = AppState.FadeFromBlack;
skipStandardIntro = false;
}
}
if (skipStandardIntro) {
DestroyIntroSketch();
ViewpointScript.m_Instance.FadeToScene(float.MaxValue);
}
}
break;
}
case AppState.FadeFromBlack: {
// On the Oculus platform, the Health and Safety warning may be visible, blocking the
// user's view. If this is the case, hold black until the warning is dismissed.
if (!VrSdk.IsAppFocusBlocked() || Config.m_SdkMode == SdkMode.Ods) {
m_AppStateCountdown -= Time.deltaTime;
}
if (m_AppStateCountdown <= 0.0f) {
PointerManager.m_Instance.EnablePointerStrokeGeneration(true);
m_AppStateCountdown = 0;
if (!HasPlayedBefore) {
m_DesiredAppState = AppState.FirstRunIntro;
} else {
m_DesiredAppState = AppState.Intro;
}
}
break;
}
case AppState.FirstRunIntro: {
if (UpdateIntroFadeIsFinished()) {
PointerManager.m_Instance.EnablePointerStrokeGeneration(true);
SaveLoadScript.m_Instance.NewAutosaveFile();
m_DesiredAppState = AppState.Standard;
}
break;
}
case AppState.Intro: {
if (UpdateIntroFadeIsFinished()) {
if (!Config.IsMobileHardware) {
InputManager.Brush.Behavior.BuzzAndGlow(1.0f, 7, .1f);
InputManager.Wand.Behavior.BuzzAndGlow(1.0f, 7, .1f);
AudioManager.m_Instance.PlayMagicControllerSound();
}
PanelManager.m_Instance.ShowIntroSketchbookPanels();
PointerManager.m_Instance.IndicateBrushSize = false;
PromoManager.m_Instance.RequestPromo(PromoType.InteractIntroPanel);
OnIntroComplete();
}
break;
}
case AppState.Loading: {
HandleExternalTiltOpenRequest();
SketchControlsScript.m_Instance.UpdateControlsForLoading();
if (WidgetManager.m_Instance.CreatingMediaWidgets) {
break;
}
//trigger our tutorial a little bit after we started loading so it doesn't show up immediately
if (!m_QuickLoadEatInput) {
float fPrevTutorialValue = m_QuickLoadHintCountdown;
m_QuickLoadHintCountdown -= Time.deltaTime;
if (fPrevTutorialValue > 0.0f && m_QuickLoadHintCountdown <= 0.0f) {
TutorialManager.m_Instance.EnableQuickLoadTutorial(true);
}
}
if (OverlayManager.m_Instance.CanDisplayQuickloadOverlay) {
// Watch for speed up button presses and keep on loadin'
// Don't allow for quickloading yet if we are fading out the overlay from loading media.
UpdateQuickLoadLogic();
}
if ((m_OdsPivot && Config.m_QuickLoad) ||
(Config.OfflineRender) || !string.IsNullOrEmpty(m_UserConfig.Profiling.SketchToLoad)) {
m_DesiredAppState = AppState.QuickLoad;
}
// Call ContinueDrawingFromMemory() unless we are rendering ODS, in which case we don't want
// to animate the strokes until the renderer has actually started.
bool bContinueDrawing = true;
if (Config.m_SdkMode != SdkMode.Ods || m_OdsPivot.GetComponent<OdsDriver>().IsRendering) {
bContinueDrawing = SketchMemoryScript.m_Instance.ContinueDrawingFromMemory();
}
if (!bContinueDrawing) {
FinishLoading();
InputManager.m_Instance.TriggerHapticsPulse(
InputManager.ControllerName.Brush, 4, 0.15f, 0.1f);
InputManager.m_Instance.TriggerHapticsPulse(
InputManager.ControllerName.Wand, 4, 0.15f, 0.1f);
}
break;
}
case AppState.QuickLoad: {
// Allow extra frames to complete fade to black.
// Required for OVR to position the overlay because it only does so once the transition
// is complete.
if (m_QuickloadStallFrames-- < 0) {
bool bContinueDrawing = SketchMemoryScript.m_Instance.ContinueDrawingFromMemory();
if (!bContinueDrawing) {
FinishLoading();
}
}
break;
}
case AppState.Uploading:
SketchControlsScript.m_Instance.UpdateControlsForUploading();
break;
case AppState.MemoryExceeded:
SketchControlsScript.m_Instance.UpdateControlsForMemoryExceeded();
break;
case AppState.Standard:
// Logic for fading out intro sketches.
if (m_IntroFadeTimer > 0 &&
!PanelManager.m_Instance.IntroSketchbookMode &&
!TutorialManager.m_Instance.TutorialActive()) {
if (UpdateIntroFadeIsFinished()) {
PanelManager.m_Instance.ReviveFloatingPanelsForStartup();
}
}
// If the app doesn't have focus, don't update.
if (VrSdk.IsAppFocusBlocked() && Config.m_SdkMode != SdkMode.Ods) {
break;
}
// Intro tutorial state machine.
TutorialManager.m_Instance.UpdateIntroTutorial();
// Continue edit-time playback, if any.
SketchMemoryScript.m_Instance.ContinueDrawingFromMemory();
if (PanelManager.m_Instance.SketchbookActiveIncludingTransitions() &&
PanelManager.m_Instance.IntroSketchbookMode) {
// Limit controls if the user hasn't exited from the sketchbook post intro.
SketchControlsScript.m_Instance.UpdateControlsPostIntro();
} else {
SketchControlsScript.m_Instance.UpdateControls();
}
// This should happen after SMS.ContinueDrawingFromMemory, so we're not loading and
// continuing in one frame.
HandleExternalTiltOpenRequest();
break;
case AppState.Reset:
SketchControlsScript.m_Instance.UpdateControls();
if (!PointerManager.m_Instance.IsMainPointerCreatingStroke() &&
!PointerManager.m_Instance.IsMainPointerProcessingLine()) {
StartReset();
}
break;
}
}
public void ExitIntroSketch() {
PanelManager.m_Instance.SetInIntroSketchbookMode(false);
PointerManager.m_Instance.IndicateBrushSize = true;
PointerManager.m_Instance.PointerColor = PointerManager.m_Instance.PointerColor;
PromoManager.m_Instance.RequestPromo(PromoType.BrushSize);
}
private void StartReset() {
// Switch to paint tool if not already there.
SketchSurfacePanel.m_Instance.EnableDefaultTool();
// Disable preview line.
PointerManager.m_Instance.AllowPointerPreviewLine(false);
// Switch to the default brush type and size.
BrushController.m_Instance.SetBrushToDefault();
// Disable audio reactive mode.
if (m_RequestingAudioReactiveMode) {
ToggleAudioReactiveModeRequest();
}
// Reset to the default brush color.
BrushColor.SetColorToDefault();
// Clear saved colors.
CustomColorPaletteStorage.m_Instance.ClearAllColors();
// Turn off straightedge
PointerManager.m_Instance.StraightEdgeModeEnabled = false;
// Turn off straightedge ruler.
if (PointerManager.m_Instance.StraightEdgeGuide.IsShowingMeter()) {
PointerManager.m_Instance.StraightEdgeGuide.FlipMeter();
}
// Close any panel menus that might be open (e.g. Sketchbook)
if (PanelManager.m_Instance.SketchbookActive()) {
PanelManager.m_Instance.ToggleSketchbookPanels();
} else if (PanelManager.m_Instance.SettingsActive()) {
PanelManager.m_Instance.ToggleSettingsPanels();
} else if (PanelManager.m_Instance.MemoryWarningActive()) {
PanelManager.m_Instance.ToggleMemoryWarningMode();
} else if (PanelManager.m_Instance.BrushLabActive()) {
PanelManager.m_Instance.ToggleBrushLabPanels();
}
// Hide all panels.
SketchControlsScript.m_Instance.RequestPanelsVisibility(false);
// Reset all panels.
SketchControlsScript.m_Instance.IssueGlobalCommand(
SketchControlsScript.GlobalCommands.ResetAllPanels);
// Rotate want panels to default orientation (color picker).
PanelManager.m_Instance.ResetWandPanelRotation();
// Close Twitch widget.
if (SketchControlsScript.m_Instance.IsCommandActive(SketchControlsScript.GlobalCommands.IRC)) {
SketchControlsScript.m_Instance.IssueGlobalCommand(SketchControlsScript.GlobalCommands.IRC);
}
// Close Youtube Chat widget.
if (SketchControlsScript.m_Instance.IsCommandActive(
SketchControlsScript.GlobalCommands.YouTubeChat)) {
SketchControlsScript.m_Instance.IssueGlobalCommand(
SketchControlsScript.GlobalCommands.YouTubeChat);
}
// Hide the pointer and reticle.
PointerManager.m_Instance.RequestPointerRendering(false);
SketchControlsScript.m_Instance.ForceShowUIReticle(false);
}
private void FinishReset() {
// Switch to the default environment.
SceneSettings.m_Instance.SetDesiredPreset(EnvironmentCatalog.m_Instance.DefaultEnvironment);
// Clear the sketch and reset the scene transform.
SketchControlsScript.m_Instance.NewSketch(fade: false);
// Disable mirror.
PointerManager.m_Instance.SetSymmetryMode(PointerManager.SymmetryMode.None);
// Reset mirror position.
PointerManager.m_Instance.ResetSymmetryToHome();
// Show the wand panels.
SketchControlsScript.m_Instance.RequestPanelsVisibility(true);
// Show the pointer.
PointerManager.m_Instance.RequestPointerRendering(true);
PointerManager.m_Instance.EnablePointerStrokeGeneration(true);
// Forget command history.
SketchMemoryScript.m_Instance.ClearMemory();
}
void FinishLoading() {
// Force progress to be full before exiting (for small scenes)
OverlayManager.m_Instance.UpdateProgress(1);
OverlayManager.m_Instance.HideOverlay();
//if we just released the button, kick a fade out
if (m_QuickLoadInputWasValid) {
App.VrSdk.PauseRendering(false);
App.VrSdk.FadeFromCompositor(0);
}
m_DesiredAppState = AppState.Standard;
if (VrSdk.GetControllerDof() == TiltBrush.VrSdk.DoF.Six) {
float holdDelay = (m_CurrentAppState == AppState.QuickLoad) ? 1.0f : 0.0f;
StartCoroutine(DelayedSketchLoadedCard(holdDelay));
} else {
OutputWindowScript.m_Instance.AddNewLine(
OutputWindowScript.LineType.Special, "Sketch Loaded!");
}
OnPlaybackComplete();
m_SketchSurfacePanel.EnableRenderer(true);
//turn off quick load tutorial
TutorialManager.m_Instance.EnableQuickLoadTutorial(false);
AudioManager.m_Instance.PlaySketchLoadedSound(
InputManager.m_Instance.GetControllerPosition(InputManager.ControllerName.Brush));
SketchControlsScript.m_Instance.RequestPanelsVisibility(true);
if (VideoRecorderUtils.ActiveVideoRecording == null) {
SketchSurfacePanel.m_Instance.EatToolsInput();
}
SketchSurfacePanel.m_Instance.RequestHideActiveTool(false);
SketchControlsScript.m_Instance.RestoreFloatingPanels();
PointerManager.m_Instance.RequestPointerRendering(
SketchSurfacePanel.m_Instance.ShouldShowPointer());
PointerManager.m_Instance.RestoreBrushInfo();
WidgetManager.m_Instance.LoadingState(false);
WidgetManager.m_Instance.WidgetsDormant = true;
SketchControlsScript.m_Instance.EatGrabInput();
SaveLoadScript.m_Instance.MarkAsAutosaveDone();
if (SaveLoadScript.m_Instance.SceneFile.InfoType == FileInfoType.Disk) {
PromoManager.m_Instance.RequestAdvancedPanelsPromo();
}
SketchMemoryScript.m_Instance.SanitizeMemoryList();
if (Config.OfflineRender) {
SketchControlsScript.m_Instance.IssueGlobalCommand(
SketchControlsScript.GlobalCommands.RenderCameraPath);
}
}
private IEnumerator<Timeslice> DelayedSketchLoadedCard(float delay) {
float stall = delay;
while (stall >= 0.0f) {
stall -= Time.deltaTime;
yield return null;
}
OutputWindowScript.m_Instance.CreateInfoCardAtController(
InputManager.ControllerName.Brush, "Sketch Loaded!");
}
void SwitchState() {
switch (m_CurrentAppState) {
case AppState.LoadingBrushesAndLighting:
if (VrSdk.GetControllerDof() == VrSdk.DoF.Two) {
// Sketch surface tool is not properly loaded because
// it is the default tool.
SketchSurfacePanel.m_Instance.ActiveTool.EnableTool(false);
SketchSurfacePanel.m_Instance.ActiveTool.EnableTool(true);
}
break;
case AppState.Reset:
// Demos should reset to the standard state only.
Debug.Assert(m_DesiredAppState == AppState.Standard);
FinishReset();
break;
case AppState.AutoProfiling:
case AppState.OfflineRendering:
InputManager.m_Instance.EnablePoseTracking(true);
break;
case AppState.MemoryExceeded:
SketchSurfacePanel.m_Instance.EnableDefaultTool();
PanelManager.m_Instance.ToggleMemoryWarningMode();
PointerManager.m_Instance.RequestPointerRendering(
SketchSurfacePanel.m_Instance.ShouldShowPointer());
break;
}
switch (m_DesiredAppState) {
case AppState.LoadingBrushesAndLighting:
BrushCatalog.m_Instance.BeginReload();
EnvironmentCatalog.m_Instance.BeginReload();
CreateIntroSketch();
break;
case AppState.FadeFromBlack:
ViewpointScript.m_Instance.FadeToScene(1.0f / m_FadeFromBlackDuration);
m_AppStateCountdown = m_FadeFromBlackDuration;
break;
case AppState.FirstRunIntro:
AudioManager.m_Instance.PlayFirstRunMusic(AudioManager.FirstRunMusic.IntroAmbient);
m_SketchSurfacePanel.EnableRenderer(false);
TutorialManager.m_Instance.IntroState = IntroTutorialState.ActivateBrush;
m_IntroFadeTimer = 0;
break;
case AppState.Intro:
AudioManager.m_Instance.PlayFirstRunMusic(AudioManager.FirstRunMusic.IntroAmbient);
m_SketchSurfacePanel.EnableRenderer(false);
m_IntroFadeTimer = 0;
break;
case AppState.Loading:
if (m_IntroFadeTimer > 0) {
AudioManager.m_Instance.SetMusicVolume(0.0f);
m_IntroFadeTimer = 0;
DestroyIntroSketch();
PanelManager.m_Instance.ReviveFloatingPanelsForStartup();
}
PointerManager.m_Instance.StoreBrushInfo();
m_QuickLoadHintCountdown = m_QuickLoadHintDelay;
m_QuickLoadEatInput = InputManager.m_Instance.GetCommand(InputManager.SketchCommands.Panic);
m_QuickLoadInputWasValid = false;
// Don't disable tools if we've got a valid load tool active.
bool bToolsAllowed = SketchSurfacePanel.m_Instance.ActiveTool.AvailableDuringLoading();
if (!bToolsAllowed) {
m_SketchSurfacePanel.EnableRenderer(false);
} else {
m_SketchSurfacePanel.RequestHideActiveTool(false);
}
if (!bToolsAllowed) {
SketchSurfacePanel.m_Instance.EnableDefaultTool();
}
PointerManager.m_Instance.RequestPointerRendering(false);
SketchControlsScript.m_Instance.RequestPanelsVisibility(false);
SketchControlsScript.m_Instance.ResetActivePanel();
PanelManager.m_Instance.HideAllPanels();
SketchControlsScript.m_Instance.ForceShowUIReticle(false);
PointerManager.m_Instance.SetSymmetryMode(PointerManager.SymmetryMode.None, false);
WidgetManager.m_Instance.LoadingState(true);
WidgetManager.m_Instance.StencilsDisabled = true;
break;
case AppState.QuickLoad:
SketchMemoryScript.m_Instance.QuickLoadDrawingMemory();
break;
case AppState.MemoryExceeded:
if (!PanelManager.m_Instance.MemoryWarningActive()) {
PanelManager.m_Instance.ToggleMemoryWarningMode();
}
SketchSurfacePanel.m_Instance.EnableSpecificTool(BaseTool.ToolType.EmptyTool);
AudioManager.m_Instance.PlayUploadCanceledSound(InputManager.Wand.Transform.position);
break;
case AppState.Standard:
PointerManager.m_Instance.DisablePointerPreviewLine();
// Refresh the tinting on the controllers
PointerManager.m_Instance.PointerColor = PointerManager.m_Instance.PointerColor;
if (m_ShowAutosaveHint) {
OutputWindowScript.m_Instance.CreateInfoCardAtController(InputManager.ControllerName.Wand,
"Abnormal program termination detected!\n" +
"The last autosave has been copied into your sketchbook.");
m_ShowAutosaveHint = false;
}
break;
case AppState.Reset:
PointerManager.m_Instance.EnablePointerStrokeGeneration(false);
PointerManager.m_Instance.AllowPointerPreviewLine(false);
PointerManager.m_Instance.EatLineEnabledInput();
PointerManager.m_Instance.EnableLine(false);
break;
case AppState.AutoProfiling:
case AppState.OfflineRendering:
InputManager.m_Instance.EnablePoseTracking(false);
break;
}
var oldState = m_CurrentAppState;
m_CurrentAppState = m_DesiredAppState;
if (StateChanged != null) {
StateChanged(oldState, m_CurrentAppState);
}
}
/// Load one requested sketch, if any, returning true if pending request was processed.
private bool HandleExternalTiltOpenRequest() {
// Early out if we're in the intro tutorial.
if (TutorialManager.m_Instance.TutorialActive() || m_RequestedTiltFileQueue.Count == 0) {
return false;
}
string path;
try {
path = (string)m_RequestedTiltFileQueue.Dequeue();
} catch (InvalidOperationException) {
return false;
}
Debug.LogFormat("Received external request to load {0}", path);
if (path.StartsWith(kProtocolHandlerPrefix)) {
return HandlePolyRequest(path);
}
// Copy to sketch folder in order to discourage the user from explicitly saving
// to gallery for future access, which would (by design) strip attribution.
// Crypto hash suffix is added to the filename for (deterministic) uniqueness.
try {
string dstFilename = Path.GetFileName(path);
if (Path.GetFullPath(Path.GetDirectoryName(path)) != Path.GetFullPath(UserSketchPath()) &&
SaveLoadScript.Md5Suffix(dstFilename) == null) {
dstFilename = SaveLoadScript.AddMd5Suffix(dstFilename,
SaveLoadScript.GetMd5(path));
}
string dstPath = Path.Combine(UserSketchPath(), dstFilename);
if (!File.Exists(dstPath)) {
File.Copy(path, dstPath);
}
SketchControlsScript.m_Instance.IssueGlobalCommand(
SketchControlsScript.GlobalCommands.LoadNamedFile, sParam: dstPath);
} catch (FileNotFoundException) {
OutputWindowScript.Error(String.Format("Couldn't open {0}", path));
return false;
}
return true;
}
private bool HandlePolyRequest(string request) {
string id = request.Substring(kProtocolHandlerPrefix.Length); // Strip prefix to get asset id
StartCoroutine(VrAssetService.m_Instance.LoadTiltFile(id));
return true;
}
public bool ShouldTintControllers() {
return m_DesiredAppState == AppState.Standard && !PanelManager.m_Instance.IntroSketchbookMode;
}
public bool IsInStateThatAllowsPainting() {
return !TutorialManager.m_Instance.TutorialActive() &&
CurrentState == AppState.Standard &&
!PanelManager.m_Instance.IntroSketchbookMode;
}
public bool IsInStateThatAllowsAnyGrabbing() {
return !TutorialManager.m_Instance.TutorialActive() &&
!PanelManager.m_Instance.IntroSketchbookMode &&
(CurrentState == AppState.Standard || CurrentState == AppState.Loading) &&
!SelectionManager.m_Instance.IsAnimatingTossFromGrabbingGroup;
}
public bool IsLoading() {
return CurrentState == AppState.Loading || CurrentState == AppState.QuickLoad;
}
void UpdateQuickLoadLogic() {
if (CurrentState == AppState.Loading && AppAllowsCreation()) {
//require the user to stop holding the trigger before pulling it again to speed load
if (m_QuickLoadEatInput) {
if (!InputManager.m_Instance.GetCommand(InputManager.SketchCommands.Panic)) {
m_QuickLoadEatInput = false;
}
} else {
if (InputManager.m_Instance.GetCommand(InputManager.SketchCommands.Panic) &&
!SketchControlsScript.m_Instance.IsUserInteractingWithAnyWidget() &&
!SketchControlsScript.m_Instance.IsUserGrabbingWorld() &&
(VideoRecorderUtils.ActiveVideoRecording == null) &&
(!VrSdk.IsAppFocusBlocked() || Config.m_SdkMode == SdkMode.Ods)) {
OverlayManager.m_Instance.SetOverlayFromType(OverlayType.LoadSketch);
//if we just pressed the button, kick a fade in
if (!m_QuickLoadInputWasValid) {
// b/69060780: This workaround is due to the ViewpointScript.Update() also messing
// with the overlay fade, and causing state conflicts in OVR.
if (!App.VrSdk.OverlayIsOVR || ViewpointScript.m_Instance.AllowsFading) {
App.VrSdk.FadeToCompositor(0);
} else {
ViewpointScript.m_Instance.SetOverlayToBlack();
}
App.VrSdk.PauseRendering(true);
InputManager.m_Instance.TriggerHaptics(InputManager.ControllerName.Wand, 0.05f);
}
m_QuickLoadInputWasValid = true;
if (m_CurrentAppState != AppState.QuickLoad) {
OverlayManager.m_Instance.SetOverlayTransitionRatio(1.0f);
m_QuickloadStallFrames = 1;
m_DesiredAppState = AppState.QuickLoad;
m_SketchSurfacePanel.EnableRenderer(false);
InputManager.m_Instance.TriggerHaptics(InputManager.ControllerName.Wand, 0.1f);
}
} else {
//if we just released the button, kick a fade out
if (m_QuickLoadInputWasValid) {
App.VrSdk.PauseRendering(false);
App.VrSdk.FadeFromCompositor(0);
}
m_QuickLoadInputWasValid = false;
}
}
}
}
void OnIntroComplete() {
SaveLoadScript.m_Instance.NewAutosaveFile();
PointerManager.m_Instance.EnablePointerStrokeGeneration(true);
SketchControlsScript.m_Instance.RequestPanelsVisibility(true);
// If the user chooses to skip the intro, assume they've done the tutorial before.
PlayerPrefs.SetInt(App.kPlayerPrefHasPlayedBefore, 1);
m_DesiredAppState = AppState.Standard;
}
// Updates the intro fade (both in and out) and returns true when finished.
// Has a special case for Mobile, so that the scene fades out as soon as it has faded in.
//
// For desktop:
// FFFFFFFFFFFFT FFFFFFFFFFFFFFFFFT
// ^ Start ^ Faded in ^ Standard Mode ^ Faded out
//
// For mobile:
// FFFFFFFFFFFFFFFFFFFFFFFFFFFT T
// ^ Start ^ Faded in ^ Faded out ^ Standard Mode
//
// (F = returns false, T = returns true)
bool UpdateIntroFadeIsFinished() {
if (m_IntroSketchRenderers == null) {
m_IntroFadeTimer = 0;
// This code path gets triggered when running on mobile. At this point the fade out has
// already happened, so we just return true so that the 'once-fadeout-has-finished' code gets
// triggered.
return true;
}
bool isMobile = Config.IsMobileHardware;
bool isFadingIn = m_IntroFadeTimer < 1f;
float fadeMax = isFadingIn ? 1f : 2f;
float fadeDuration;
if (isMobile) {
fadeDuration = isFadingIn
? m_IntroSketchMobileFadeInDuration
: m_IntroSketchMobileFadeOutDuration;
} else {
fadeDuration = isFadingIn ? m_IntroSketchFadeInDuration : m_IntroSketchFadeOutDuration;
}
m_IntroFadeTimer += Time.deltaTime / fadeDuration;
if (m_IntroFadeTimer > fadeMax) {
m_IntroFadeTimer = fadeMax;
}
for (int i = 0; i < m_IntroSketchRenderers.Length; ++i) {
m_IntroSketchRenderers[i].material.SetFloat("_IntroDissolve",
Mathf.SmoothStep(0, 1, Math.Abs(1 - m_IntroFadeTimer)));
}
if (m_IntroFadeTimer == fadeMax) {
if (isFadingIn) {
// With Mobile, we fade in then out, so the fade isn't complete at fade-in.
return !isMobile;
} else {
DestroyIntroSketch();
m_IntroSketchRenderers = null;
return true;
}
}
return false;
}
void InitCursor() {
if (StartupError) {
return;
}
if (VrSdk.GetHmdDof() == TiltBrush.VrSdk.DoF.None) {
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
}
public static T DeserializeObjectWithWarning<T>(string text, out string warning) {
// Try twice, once to catch "unknown key" warnings, once to actually get a result.
warning = null;
try {
return JsonConvert.DeserializeObject<T>(text, new JsonSerializerSettings {
MissingMemberHandling = MissingMemberHandling.Error
});
} catch (JsonSerializationException e) {
warning = e.Message;
return JsonConvert.DeserializeObject<T>(text);
}
}
void CreateDefaultConfig() {
// If we don't have a .cfg in our Tilt Brush directory, drop a default one.
string tiltBrushFolder = UserPath();
if (!Directory.Exists(tiltBrushFolder)) {
return;
}
string configPath = Path.Combine(tiltBrushFolder, kConfigFileName);
if (!File.Exists(configPath)) {
FileUtils.WriteTextFromResources(kDefaultConfigPath, configPath);
}
}
public void RefreshUserConfig() {
m_UserConfig = new UserConfig();
try {
string sConfigPath = App.ConfigPath();
if (!File.Exists(sConfigPath)) {
return;
}
string text;
try {
text = File.ReadAllText(sConfigPath, System.Text.Encoding.UTF8);
} catch (Exception e) {
// UnauthorizedAccessException, IOException
OutputWindowScript.Error($"Error reading {kConfigFileName}", e.Message);
return;
}
try {
string warning;
m_UserConfig = DeserializeObjectWithWarning<UserConfig>(text, out warning);
if (warning != null) {
OutputWindowScript.Error($"Warning reading {kConfigFileName}", warning);
}
} catch (Exception e) {
OutputWindowScript.Error($"Error reading {kConfigFileName}", e.Message);
return;
}
} finally {
// Apply any overrides sent through via the command line, even if reading from Tilt Brush.cfg
// goes horribly wrong.
Config.ApplyUserConfigOverrides(m_UserConfig);
}
}
public void CreateErrorDialog(string msg=null) {
GameObject dialog = Instantiate(m_ErrorDialog);
var textXf = dialog.transform.Find("Text");
var textMesh = textXf.GetComponent<TextMesh>();
if (msg == null) {
msg = "Failed to detect VR";
}
textMesh.text = string.Format(@" Tiltasaurus says...
{0}", msg);
}
static public bool AppAllowsCreation() {
// TODO: this feels like it should be an explicit part of Config,
// not something based on VR hardware...
return App.VrSdk.GetControllerDof() != TiltBrush.VrSdk.DoF.None;
}
static public string PlatformPath() {
if (!Application.isEditor && Application.platform == RuntimePlatform.OSXPlayer) {
return System.IO.Directory.GetParent(Application.dataPath).Parent.ToString();
} else if (Application.platform == RuntimePlatform.Android) {
return Application.persistentDataPath;
}
return System.IO.Directory.GetParent(Application.dataPath).ToString();
}
static public string SupportPath() {
return Path.Combine(PlatformPath(), "Support");
}
/// Returns a parent of UserPath; used to figure out how much path
/// is necessary to display to the user when giving feedback. We
/// assume this is the "boring" portion of the path that they can infer.
public static string DocumentsPath() {
switch (Application.platform) {
case RuntimePlatform.WindowsPlayer:
case RuntimePlatform.WindowsEditor:
case RuntimePlatform.OSXPlayer:
case RuntimePlatform.OSXEditor:
case RuntimePlatform.LinuxPlayer:
return System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
case RuntimePlatform.Android:
case RuntimePlatform.IPhonePlayer:
default:
return Application.persistentDataPath;
}
}
void InitUserPath() {
switch (Application.platform) {
case RuntimePlatform.WindowsPlayer:
case RuntimePlatform.WindowsEditor:
// user Documents folder
m_UserPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
// GetFolderPath() can fail, returning an empty string.
if (m_UserPath == "") {
// If that happens, try a bunch of other folders.
m_UserPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.MyDocuments);
if (m_UserPath == "") {
m_UserPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.DesktopDirectory);
}
}
break;
case RuntimePlatform.OSXPlayer:
case RuntimePlatform.OSXEditor:
case RuntimePlatform.LinuxPlayer:
// user Documents folder
m_UserPath = Path.Combine(System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal),
"Documents");
break;
case RuntimePlatform.Android:
//m_UserPath = "/sdcard/";
m_UserPath = Application.persistentDataPath;
m_OldUserPath = Application.persistentDataPath;
break;
case RuntimePlatform.IPhonePlayer:
default:
m_UserPath = Application.persistentDataPath;
break;
}
m_UserPath = Path.Combine(m_UserPath, App.kAppFolderName);
// In the case that we have changed the location of the user data, move the user data from the
// old location to the new one.
if (!string.IsNullOrEmpty(m_OldUserPath)) {
MoveUserDataFromOldLocation();
}
if (!Path.IsPathRooted(m_UserPath)) {
StartupError = true;
CreateErrorDialog("Failed to find Documents folder.\nIn Windows, try modifying your Controlled Folder Access settings.");
}
}
private void MoveUserDataFromOldLocation() {
m_OldUserPath = Path.Combine(m_OldUserPath, App.kAppFolderName);
if (!Directory.Exists(m_OldUserPath)) {
return;
}
if (Directory.Exists(m_UserPath)) {
return;
}
try {
Directory.Move(m_OldUserPath, m_UserPath);
// Recreate the old directory and put a message in there so a user used to looking in the old
// location can find out where to get their files.
Directory.CreateDirectory(m_OldUserPath);
string moveMessageFilename = Path.Combine(m_OldUserPath, kFileMoveFilename);
File.WriteAllText(moveMessageFilename, kFileMoveContents);
} catch (Exception ex) {
Debug.LogException(ex);
}
}
// Return path of root directory for storing user sketches, snapshots, etc.
public static string UserPath() {
return App.m_Instance.m_UserPath;
}
public static bool InitDirectoryAtPath(string path) {
if (Directory.Exists(path)) {
return true;
}
if (!FileUtils.InitializeDirectoryWithUserError(path)) {
return false;
}
return true;
}
public static string ShortenForDescriptionText(string desc) {
desc = desc.Split('\n')[0];
if (desc.Length > 33) {
desc = desc.Substring(0, 30) + "...";
}
return desc;
}
/// Creates the Media Library directory if it does not already exist.
/// Returns true if the directory already exists or if it is created successfully, false if the
/// directory could not be created.
public static bool InitMediaLibraryPath() {
string mediaLibraryPath = MediaLibraryPath();
if (!InitDirectoryAtPath(mediaLibraryPath)) { return false; }
string readmeFile = Path.Combine(mediaLibraryPath, Config.m_MediaLibraryReadme);
FileUtils.WriteTextFromResources(Config.m_MediaLibraryReadme,
Path.ChangeExtension(readmeFile, ".txt"));
return true;
}
/// Creates the Model Catalog directory and copies in the provided default models.
/// Returns true if the directory already exists or if it is created successfully, false if the
/// directory could not be created.
public static bool InitModelLibraryPath(string[] defaultModels) {
string modelsDirectory = ModelLibraryPath();
if (Directory.Exists(modelsDirectory)) { return true; }
if (!InitDirectoryAtPath(modelsDirectory)) { return false; }
foreach (string fileName in defaultModels) {
string[] path = fileName.Split(
new[] { '\\', '/' }, 3, StringSplitOptions.RemoveEmptyEntries);
string newModel = Path.Combine(modelsDirectory, path[1]);
if (!Directory.Exists(newModel)) {
Directory.CreateDirectory(newModel);
}
if (Path.GetExtension(fileName) == ".png" ||
Path.GetExtension(fileName) == ".jpeg" ||
Path.GetExtension(fileName) == ".jpg") {
FileUtils.WriteTextureFromResources(fileName, Path.Combine(newModel, path[2]));
} else {
FileUtils.WriteTextFromResources(fileName, Path.Combine(newModel, path[2]));
}
}
return true;
}
/// Creates the Reference Images directory and copies in the provided default images.
/// Returns true if the directory already exists or if it is created successfully, false if the
/// directory could not be created.
public static bool InitReferenceImagePath(string[] defaultImages) {
string path = ReferenceImagePath();
if (!Directory.Exists(path)) {
if (!FileUtils.InitializeDirectoryWithUserError(path)) {
return false;
}
}
// Poplulate the reference images folder exactly once.
int seeded = PlayerPrefs.GetInt(kReferenceImagesSeeded);
if (seeded == 0) {
foreach (string fileName in defaultImages) {
FileUtils.WriteTextureFromResources(fileName,
Path.Combine(path, Path.GetFileName(fileName)));
}
PlayerPrefs.SetInt(kReferenceImagesSeeded, 1);
}
return true;
}
public static bool InitVideoLibraryPath(string[] defaultVideos) {
string videosDirectory = VideoLibraryPath();
if (Directory.Exists(videosDirectory)) {
return true;
}
if (!InitDirectoryAtPath(videosDirectory)) {
return false;
}
foreach (var video in defaultVideos) {
string destFilename = Path.GetFileName(video);
FileUtils.WriteBytesFromResources(video, Path.Combine(videosDirectory, destFilename));
}
return true;
}
public static string MediaLibraryPath() {
return Path.Combine(UserPath(), "Media Library");
}
public static string ModelLibraryPath() {
return Path.Combine(MediaLibraryPath(), "Models");
}
public static string ReferenceImagePath() {
return Path.Combine(MediaLibraryPath(), "Images");
}
public static string VideoLibraryPath() {
return Path.Combine(MediaLibraryPath(), "Videos");
}
static public string UserSketchPath() {
return Path.Combine(UserPath(), "Sketches");
}
static public string AutosavePath() {
return Path.Combine(UserPath(), "Sketches/Autosave");
}
static public string ConfigPath() {
return Path.Combine(UserPath(), kConfigFileName);
}
static public string UserExportPath() {
return App.Config.m_ExportPath ?? Path.Combine(UserPath(), "Exports");
}
static public string AutosaveRestoreFilePath() {
return Path.Combine(UserPath(), "Sketches/Autosave/AutosaveRestore");
}
static public string SnapshotPath() {
return Path.Combine(UserPath(), "Snapshots");
}
static public string VideosPath() {
return Path.Combine(UserPath(), "Videos");
}
static public string VrVideosPath() {
return Path.Combine(UserPath(), "VRVideos");
}
void OnApplicationQuit() {
if (AppExit != null) {
AppExit();
}
AutosaveRestoreFileExists = false;
}
void OnPlaybackComplete() {
SaveLoadScript.m_Instance.SignalPlaybackCompletion();
if (SketchControlsScript.m_Instance.SketchPlaybackMode !=
SketchMemoryScript.PlaybackMode.Timestamps) {
// For non-timestamp playback mode, adjust current time to last stroke in drawing.
try {
this.CurrentSketchTime = SketchMemoryScript.m_Instance.GetApproximateLatestTimestamp();
} catch (InvalidOperationException) {
// Can happen as an edge case, eg if we try to load a file that doesn't exist.
this.CurrentSketchTime = 0;
}
}
}
public TiltBrushManifest GetMergedManifest(bool consultUserConfig) {
var manifest = m_Manifest;
#if (UNITY_EDITOR || EXPERIMENTAL_ENABLED)
if (Config.IsExperimental) {
// At build time, we don't want the user config to affect the build output.
if (consultUserConfig
&& m_UserConfig.Flags.ShowDangerousBrushes
&& m_ManifestExperimental != null) {
manifest = Instantiate(m_Manifest);
manifest.AppendFrom(m_ManifestExperimental);
}
}
#endif
return manifest;
}
public static bool InitializeUsd() {
if (!UsdUtils.InitializeUsd()) {
return false;
}
return true;
}
#if (UNITY_EDITOR || EXPERIMENTAL_ENABLED)
public bool IsBrushExperimental(BrushDescriptor brush) {
return m_ManifestExperimental.Brushes.Contains(brush);
}
#endif
DateTime GetLinkerTime(Assembly assembly, TimeZoneInfo target = null) {
#if !UNITY_ANDROID
var filePath = assembly.Location;
const int c_PeHeaderOffset = 60;
const int c_LinkerTimestampOffset = 8;
var buffer = new byte[2048];
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
stream.Read(buffer, 0, 2048);
var offset = BitConverter.ToInt32(buffer, c_PeHeaderOffset);
var secondsSince1970 = BitConverter.ToInt32(buffer, offset + c_LinkerTimestampOffset);
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var linkTimeUtc = epoch.AddSeconds(secondsSince1970);
return linkTimeUtc.ToLocalTime();
#else
return DateTime.Now;
#endif
}
// By executing the URL directly windows will open it without making the browser a child
// process of Tilt Brush. If this fails or throws an exception we fall back to Unity's
// OpenURL().
public static void OpenURL(string url) {
var isPolyUrl = (url.Contains("poly.google.com/") || url.Contains("vr.google.com"));
if (isPolyUrl && GoogleIdentity.LoggedIn) {
var email = GoogleIdentity.Profile.email;
url = $"https://accounts.google.com/AccountChooser?Email={email}&continue={url}";
}
#if UNITY_STANDALONE_WINDOWS
var startInfo = new System.Diagnostics.ProcessStartInfo(url);
startInfo.UseShellExecute = true;
try {
if (System.Diagnostics.Process.Start(startInfo) == null) {
Application.OpenURL(url);
}
} catch (Exception) {
Application.OpenURL(url);
}
#else
// Something about the url makes OpenURL() not work on OSX, so use a workaround
if (Application.platform == RuntimePlatform.OSXEditor ||
Application.platform == RuntimePlatform.OSXPlayer) {
System.Diagnostics.Process.Start(url);
} else {
Application.OpenURL(url);
}
#endif
}
/// This copies the support files from inside the Streaming Assets folder to the support folder.
/// This only happens on Android. The files have to be extracted directly from the .apk.
private static void CopySupportFiles() {
if (Application.platform != RuntimePlatform.Android) {
return;
}
if (!Directory.Exists(SupportPath())) {
Directory.CreateDirectory(SupportPath());
}
Func<string, int> GetIndexOfEnd = (s) => Application.streamingAssetsPath.IndexOf(s) + s.Length;
// Find the apk file
int apkIndex = GetIndexOfEnd("file://");
int fileIndex = Application.streamingAssetsPath.IndexOf("!/");
string apkFilename = Application.streamingAssetsPath.Substring(apkIndex, fileIndex - apkIndex);
const string supportBeginning = "assets/Support/";
try {
using (Stream zipFile = File.Open(apkFilename, FileMode.Open, FileAccess.Read)) {
ZipLibrary.ZipFile zip = new ZipLibrary.ZipFile(zipFile);
foreach (ZipLibrary.ZipEntry entry in zip) {
if (entry.IsFile && entry.Name.StartsWith(supportBeginning)) {
// Create the directory if needed.
string fullPath = Path.Combine(App.SupportPath(),
entry.Name.Substring(supportBeginning.Length));
string directory = Path.GetDirectoryName(fullPath);
if (!Directory.Exists(directory)) {
Directory.CreateDirectory(directory);
}
// Copy the data over to a file.
using (Stream entryStream = zip.GetInputStream(entry)) {
using (FileStream fileStream = File.Create(fullPath)) {
byte[] buffer = new byte[16 * 1024]; // Do it in 16k chunks
while (true) {
int size = entryStream.Read(buffer, 0, buffer.Length);
if (size > 0) {
fileStream.Write(buffer, 0, size);
} else {
break;
}
}
}
}
}
}
zip.Close();
}
} catch (Exception ex) {
Debug.LogException(ex);
}
}
} // class App
} // namespace TiltBrush
| 36.138693 | 127 | 0.680933 | [
"Apache-2.0"
] | blackalice/bilt-trush | Assets/Scripts/App.cs | 71,916 | 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>
//------------------------------------------------------------------------------
#pragma warning disable 1591
namespace Project03 {
/// <summary>
///Represents a strongly typed in-memory cache of data.
///</summary>
[global::System.Serializable()]
[global::System.ComponentModel.DesignerCategoryAttribute("code")]
[global::System.ComponentModel.ToolboxItem(true)]
[global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedDataSetSchema")]
[global::System.Xml.Serialization.XmlRootAttribute("ServicePartsDataSet")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.DataSet")]
public partial class ServicePartsDataSet : global::System.Data.DataSet {
private PartsTableDataTable tablePartsTable;
private ServiceTableDataTable tableServiceTable;
private global::System.Data.SchemaSerializationMode _schemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public ServicePartsDataSet() {
this.BeginInit();
this.InitClass();
global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged);
base.Tables.CollectionChanged += schemaChangedHandler;
base.Relations.CollectionChanged += schemaChangedHandler;
this.EndInit();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected ServicePartsDataSet(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) :
base(info, context, false) {
if ((this.IsBinarySerialized(info, context) == true)) {
this.InitVars(false);
global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler1 = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged);
this.Tables.CollectionChanged += schemaChangedHandler1;
this.Relations.CollectionChanged += schemaChangedHandler1;
return;
}
string strSchema = ((string)(info.GetValue("XmlSchema", typeof(string))));
if ((this.DetermineSchemaSerializationMode(info, context) == global::System.Data.SchemaSerializationMode.IncludeSchema)) {
global::System.Data.DataSet ds = new global::System.Data.DataSet();
ds.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema)));
if ((ds.Tables["PartsTable"] != null)) {
base.Tables.Add(new PartsTableDataTable(ds.Tables["PartsTable"]));
}
if ((ds.Tables["ServiceTable"] != null)) {
base.Tables.Add(new ServiceTableDataTable(ds.Tables["ServiceTable"]));
}
this.DataSetName = ds.DataSetName;
this.Prefix = ds.Prefix;
this.Namespace = ds.Namespace;
this.Locale = ds.Locale;
this.CaseSensitive = ds.CaseSensitive;
this.EnforceConstraints = ds.EnforceConstraints;
this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add);
this.InitVars();
}
else {
this.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema)));
}
this.GetSerializationData(info, context);
global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged);
base.Tables.CollectionChanged += schemaChangedHandler;
this.Relations.CollectionChanged += schemaChangedHandler;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Browsable(false)]
[global::System.ComponentModel.DesignerSerializationVisibility(global::System.ComponentModel.DesignerSerializationVisibility.Content)]
public PartsTableDataTable PartsTable {
get {
return this.tablePartsTable;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Browsable(false)]
[global::System.ComponentModel.DesignerSerializationVisibility(global::System.ComponentModel.DesignerSerializationVisibility.Content)]
public ServiceTableDataTable ServiceTable {
get {
return this.tableServiceTable;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.BrowsableAttribute(true)]
[global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Visible)]
public override global::System.Data.SchemaSerializationMode SchemaSerializationMode {
get {
return this._schemaSerializationMode;
}
set {
this._schemaSerializationMode = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public new global::System.Data.DataTableCollection Tables {
get {
return base.Tables;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public new global::System.Data.DataRelationCollection Relations {
get {
return base.Relations;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override void InitializeDerivedDataSet() {
this.BeginInit();
this.InitClass();
this.EndInit();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public override global::System.Data.DataSet Clone() {
ServicePartsDataSet cln = ((ServicePartsDataSet)(base.Clone()));
cln.InitVars();
cln.SchemaSerializationMode = this.SchemaSerializationMode;
return cln;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override bool ShouldSerializeTables() {
return false;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override bool ShouldSerializeRelations() {
return false;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override void ReadXmlSerializable(global::System.Xml.XmlReader reader) {
if ((this.DetermineSchemaSerializationMode(reader) == global::System.Data.SchemaSerializationMode.IncludeSchema)) {
this.Reset();
global::System.Data.DataSet ds = new global::System.Data.DataSet();
ds.ReadXml(reader);
if ((ds.Tables["PartsTable"] != null)) {
base.Tables.Add(new PartsTableDataTable(ds.Tables["PartsTable"]));
}
if ((ds.Tables["ServiceTable"] != null)) {
base.Tables.Add(new ServiceTableDataTable(ds.Tables["ServiceTable"]));
}
this.DataSetName = ds.DataSetName;
this.Prefix = ds.Prefix;
this.Namespace = ds.Namespace;
this.Locale = ds.Locale;
this.CaseSensitive = ds.CaseSensitive;
this.EnforceConstraints = ds.EnforceConstraints;
this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add);
this.InitVars();
}
else {
this.ReadXml(reader);
this.InitVars();
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override global::System.Xml.Schema.XmlSchema GetSchemaSerializable() {
global::System.IO.MemoryStream stream = new global::System.IO.MemoryStream();
this.WriteXmlSchema(new global::System.Xml.XmlTextWriter(stream, null));
stream.Position = 0;
return global::System.Xml.Schema.XmlSchema.Read(new global::System.Xml.XmlTextReader(stream), null);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
internal void InitVars() {
this.InitVars(true);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
internal void InitVars(bool initTable) {
this.tablePartsTable = ((PartsTableDataTable)(base.Tables["PartsTable"]));
if ((initTable == true)) {
if ((this.tablePartsTable != null)) {
this.tablePartsTable.InitVars();
}
}
this.tableServiceTable = ((ServiceTableDataTable)(base.Tables["ServiceTable"]));
if ((initTable == true)) {
if ((this.tableServiceTable != null)) {
this.tableServiceTable.InitVars();
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private void InitClass() {
this.DataSetName = "ServicePartsDataSet";
this.Prefix = "";
this.Namespace = "http://tempuri.org/ServicePartsDataSet.xsd";
this.EnforceConstraints = true;
this.SchemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema;
this.tablePartsTable = new PartsTableDataTable();
base.Tables.Add(this.tablePartsTable);
this.tableServiceTable = new ServiceTableDataTable();
base.Tables.Add(this.tableServiceTable);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private bool ShouldSerializePartsTable() {
return false;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private bool ShouldSerializeServiceTable() {
return false;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private void SchemaChanged(object sender, global::System.ComponentModel.CollectionChangeEventArgs e) {
if ((e.Action == global::System.ComponentModel.CollectionChangeAction.Remove)) {
this.InitVars();
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs) {
ServicePartsDataSet ds = new ServicePartsDataSet();
global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType();
global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence();
global::System.Xml.Schema.XmlSchemaAny any = new global::System.Xml.Schema.XmlSchemaAny();
any.Namespace = ds.Namespace;
sequence.Items.Add(any);
type.Particle = sequence;
global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
if (xs.Contains(dsSchema.TargetNamespace)) {
global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
try {
global::System.Xml.Schema.XmlSchema schema = null;
dsSchema.Write(s1);
for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) {
schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
s2.SetLength(0);
schema.Write(s2);
if ((s1.Length == s2.Length)) {
s1.Position = 0;
s2.Position = 0;
for (; ((s1.Position != s1.Length)
&& (s1.ReadByte() == s2.ReadByte())); ) {
;
}
if ((s1.Position == s1.Length)) {
return type;
}
}
}
}
finally {
if ((s1 != null)) {
s1.Close();
}
if ((s2 != null)) {
s2.Close();
}
}
}
xs.Add(dsSchema);
return type;
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public delegate void PartsTableRowChangeEventHandler(object sender, PartsTableRowChangeEvent e);
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public delegate void ServiceTableRowChangeEventHandler(object sender, ServiceTableRowChangeEvent e);
/// <summary>
///Represents the strongly named DataTable class.
///</summary>
[global::System.Serializable()]
[global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")]
public partial class PartsTableDataTable : global::System.Data.TypedTableBase<PartsTableRow> {
private global::System.Data.DataColumn columnPartNumber;
private global::System.Data.DataColumn columnPartName;
private global::System.Data.DataColumn columnPartPrice;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public PartsTableDataTable() {
this.TableName = "PartsTable";
this.BeginInit();
this.InitClass();
this.EndInit();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
internal PartsTableDataTable(global::System.Data.DataTable table) {
this.TableName = table.TableName;
if ((table.CaseSensitive != table.DataSet.CaseSensitive)) {
this.CaseSensitive = table.CaseSensitive;
}
if ((table.Locale.ToString() != table.DataSet.Locale.ToString())) {
this.Locale = table.Locale;
}
if ((table.Namespace != table.DataSet.Namespace)) {
this.Namespace = table.Namespace;
}
this.Prefix = table.Prefix;
this.MinimumCapacity = table.MinimumCapacity;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected PartsTableDataTable(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) :
base(info, context) {
this.InitVars();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public global::System.Data.DataColumn PartNumberColumn {
get {
return this.columnPartNumber;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public global::System.Data.DataColumn PartNameColumn {
get {
return this.columnPartName;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public global::System.Data.DataColumn PartPriceColumn {
get {
return this.columnPartPrice;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Browsable(false)]
public int Count {
get {
return this.Rows.Count;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public PartsTableRow this[int index] {
get {
return ((PartsTableRow)(this.Rows[index]));
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public event PartsTableRowChangeEventHandler PartsTableRowChanging;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public event PartsTableRowChangeEventHandler PartsTableRowChanged;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public event PartsTableRowChangeEventHandler PartsTableRowDeleting;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public event PartsTableRowChangeEventHandler PartsTableRowDeleted;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public void AddPartsTableRow(PartsTableRow row) {
this.Rows.Add(row);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public PartsTableRow AddPartsTableRow(int PartNumber, string PartName, decimal PartPrice) {
PartsTableRow rowPartsTableRow = ((PartsTableRow)(this.NewRow()));
object[] columnValuesArray = new object[] {
PartNumber,
PartName,
PartPrice};
rowPartsTableRow.ItemArray = columnValuesArray;
this.Rows.Add(rowPartsTableRow);
return rowPartsTableRow;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public PartsTableRow FindByPartNumber(int PartNumber) {
return ((PartsTableRow)(this.Rows.Find(new object[] {
PartNumber})));
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public override global::System.Data.DataTable Clone() {
PartsTableDataTable cln = ((PartsTableDataTable)(base.Clone()));
cln.InitVars();
return cln;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override global::System.Data.DataTable CreateInstance() {
return new PartsTableDataTable();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
internal void InitVars() {
this.columnPartNumber = base.Columns["PartNumber"];
this.columnPartName = base.Columns["PartName"];
this.columnPartPrice = base.Columns["PartPrice"];
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private void InitClass() {
this.columnPartNumber = new global::System.Data.DataColumn("PartNumber", typeof(int), null, global::System.Data.MappingType.Element);
base.Columns.Add(this.columnPartNumber);
this.columnPartName = new global::System.Data.DataColumn("PartName", typeof(string), null, global::System.Data.MappingType.Element);
base.Columns.Add(this.columnPartName);
this.columnPartPrice = new global::System.Data.DataColumn("PartPrice", typeof(decimal), null, global::System.Data.MappingType.Element);
base.Columns.Add(this.columnPartPrice);
this.Constraints.Add(new global::System.Data.UniqueConstraint("Constraint1", new global::System.Data.DataColumn[] {
this.columnPartNumber}, true));
this.columnPartNumber.AllowDBNull = false;
this.columnPartNumber.Unique = true;
this.columnPartName.MaxLength = 10;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public PartsTableRow NewPartsTableRow() {
return ((PartsTableRow)(this.NewRow()));
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override global::System.Data.DataRow NewRowFromBuilder(global::System.Data.DataRowBuilder builder) {
return new PartsTableRow(builder);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override global::System.Type GetRowType() {
return typeof(PartsTableRow);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override void OnRowChanged(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowChanged(e);
if ((this.PartsTableRowChanged != null)) {
this.PartsTableRowChanged(this, new PartsTableRowChangeEvent(((PartsTableRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override void OnRowChanging(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowChanging(e);
if ((this.PartsTableRowChanging != null)) {
this.PartsTableRowChanging(this, new PartsTableRowChangeEvent(((PartsTableRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override void OnRowDeleted(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowDeleted(e);
if ((this.PartsTableRowDeleted != null)) {
this.PartsTableRowDeleted(this, new PartsTableRowChangeEvent(((PartsTableRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override void OnRowDeleting(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowDeleting(e);
if ((this.PartsTableRowDeleting != null)) {
this.PartsTableRowDeleting(this, new PartsTableRowChangeEvent(((PartsTableRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public void RemovePartsTableRow(PartsTableRow row) {
this.Rows.Remove(row);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) {
global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType();
global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence();
ServicePartsDataSet ds = new ServicePartsDataSet();
global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny();
any1.Namespace = "http://www.w3.org/2001/XMLSchema";
any1.MinOccurs = new decimal(0);
any1.MaxOccurs = decimal.MaxValue;
any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
sequence.Items.Add(any1);
global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny();
any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1";
any2.MinOccurs = new decimal(1);
any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
sequence.Items.Add(any2);
global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute();
attribute1.Name = "namespace";
attribute1.FixedValue = ds.Namespace;
type.Attributes.Add(attribute1);
global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute();
attribute2.Name = "tableTypeName";
attribute2.FixedValue = "PartsTableDataTable";
type.Attributes.Add(attribute2);
type.Particle = sequence;
global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
if (xs.Contains(dsSchema.TargetNamespace)) {
global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
try {
global::System.Xml.Schema.XmlSchema schema = null;
dsSchema.Write(s1);
for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) {
schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
s2.SetLength(0);
schema.Write(s2);
if ((s1.Length == s2.Length)) {
s1.Position = 0;
s2.Position = 0;
for (; ((s1.Position != s1.Length)
&& (s1.ReadByte() == s2.ReadByte())); ) {
;
}
if ((s1.Position == s1.Length)) {
return type;
}
}
}
}
finally {
if ((s1 != null)) {
s1.Close();
}
if ((s2 != null)) {
s2.Close();
}
}
}
xs.Add(dsSchema);
return type;
}
}
/// <summary>
///Represents the strongly named DataTable class.
///</summary>
[global::System.Serializable()]
[global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")]
public partial class ServiceTableDataTable : global::System.Data.TypedTableBase<ServiceTableRow> {
private global::System.Data.DataColumn columnServiceID;
private global::System.Data.DataColumn columnServiceName;
private global::System.Data.DataColumn columnServiceCost;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public ServiceTableDataTable() {
this.TableName = "ServiceTable";
this.BeginInit();
this.InitClass();
this.EndInit();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
internal ServiceTableDataTable(global::System.Data.DataTable table) {
this.TableName = table.TableName;
if ((table.CaseSensitive != table.DataSet.CaseSensitive)) {
this.CaseSensitive = table.CaseSensitive;
}
if ((table.Locale.ToString() != table.DataSet.Locale.ToString())) {
this.Locale = table.Locale;
}
if ((table.Namespace != table.DataSet.Namespace)) {
this.Namespace = table.Namespace;
}
this.Prefix = table.Prefix;
this.MinimumCapacity = table.MinimumCapacity;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected ServiceTableDataTable(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) :
base(info, context) {
this.InitVars();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public global::System.Data.DataColumn ServiceIDColumn {
get {
return this.columnServiceID;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public global::System.Data.DataColumn ServiceNameColumn {
get {
return this.columnServiceName;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public global::System.Data.DataColumn ServiceCostColumn {
get {
return this.columnServiceCost;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Browsable(false)]
public int Count {
get {
return this.Rows.Count;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public ServiceTableRow this[int index] {
get {
return ((ServiceTableRow)(this.Rows[index]));
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public event ServiceTableRowChangeEventHandler ServiceTableRowChanging;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public event ServiceTableRowChangeEventHandler ServiceTableRowChanged;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public event ServiceTableRowChangeEventHandler ServiceTableRowDeleting;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public event ServiceTableRowChangeEventHandler ServiceTableRowDeleted;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public void AddServiceTableRow(ServiceTableRow row) {
this.Rows.Add(row);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public ServiceTableRow AddServiceTableRow(int ServiceID, string ServiceName, decimal ServiceCost) {
ServiceTableRow rowServiceTableRow = ((ServiceTableRow)(this.NewRow()));
object[] columnValuesArray = new object[] {
ServiceID,
ServiceName,
ServiceCost};
rowServiceTableRow.ItemArray = columnValuesArray;
this.Rows.Add(rowServiceTableRow);
return rowServiceTableRow;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public ServiceTableRow FindByServiceID(int ServiceID) {
return ((ServiceTableRow)(this.Rows.Find(new object[] {
ServiceID})));
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public override global::System.Data.DataTable Clone() {
ServiceTableDataTable cln = ((ServiceTableDataTable)(base.Clone()));
cln.InitVars();
return cln;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override global::System.Data.DataTable CreateInstance() {
return new ServiceTableDataTable();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
internal void InitVars() {
this.columnServiceID = base.Columns["ServiceID"];
this.columnServiceName = base.Columns["ServiceName"];
this.columnServiceCost = base.Columns["ServiceCost"];
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private void InitClass() {
this.columnServiceID = new global::System.Data.DataColumn("ServiceID", typeof(int), null, global::System.Data.MappingType.Element);
base.Columns.Add(this.columnServiceID);
this.columnServiceName = new global::System.Data.DataColumn("ServiceName", typeof(string), null, global::System.Data.MappingType.Element);
base.Columns.Add(this.columnServiceName);
this.columnServiceCost = new global::System.Data.DataColumn("ServiceCost", typeof(decimal), null, global::System.Data.MappingType.Element);
base.Columns.Add(this.columnServiceCost);
this.Constraints.Add(new global::System.Data.UniqueConstraint("Constraint1", new global::System.Data.DataColumn[] {
this.columnServiceID}, true));
this.columnServiceID.AllowDBNull = false;
this.columnServiceID.Unique = true;
this.columnServiceName.MaxLength = 10;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public ServiceTableRow NewServiceTableRow() {
return ((ServiceTableRow)(this.NewRow()));
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override global::System.Data.DataRow NewRowFromBuilder(global::System.Data.DataRowBuilder builder) {
return new ServiceTableRow(builder);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override global::System.Type GetRowType() {
return typeof(ServiceTableRow);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override void OnRowChanged(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowChanged(e);
if ((this.ServiceTableRowChanged != null)) {
this.ServiceTableRowChanged(this, new ServiceTableRowChangeEvent(((ServiceTableRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override void OnRowChanging(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowChanging(e);
if ((this.ServiceTableRowChanging != null)) {
this.ServiceTableRowChanging(this, new ServiceTableRowChangeEvent(((ServiceTableRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override void OnRowDeleted(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowDeleted(e);
if ((this.ServiceTableRowDeleted != null)) {
this.ServiceTableRowDeleted(this, new ServiceTableRowChangeEvent(((ServiceTableRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override void OnRowDeleting(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowDeleting(e);
if ((this.ServiceTableRowDeleting != null)) {
this.ServiceTableRowDeleting(this, new ServiceTableRowChangeEvent(((ServiceTableRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public void RemoveServiceTableRow(ServiceTableRow row) {
this.Rows.Remove(row);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) {
global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType();
global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence();
ServicePartsDataSet ds = new ServicePartsDataSet();
global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny();
any1.Namespace = "http://www.w3.org/2001/XMLSchema";
any1.MinOccurs = new decimal(0);
any1.MaxOccurs = decimal.MaxValue;
any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
sequence.Items.Add(any1);
global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny();
any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1";
any2.MinOccurs = new decimal(1);
any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
sequence.Items.Add(any2);
global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute();
attribute1.Name = "namespace";
attribute1.FixedValue = ds.Namespace;
type.Attributes.Add(attribute1);
global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute();
attribute2.Name = "tableTypeName";
attribute2.FixedValue = "ServiceTableDataTable";
type.Attributes.Add(attribute2);
type.Particle = sequence;
global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
if (xs.Contains(dsSchema.TargetNamespace)) {
global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
try {
global::System.Xml.Schema.XmlSchema schema = null;
dsSchema.Write(s1);
for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) {
schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
s2.SetLength(0);
schema.Write(s2);
if ((s1.Length == s2.Length)) {
s1.Position = 0;
s2.Position = 0;
for (; ((s1.Position != s1.Length)
&& (s1.ReadByte() == s2.ReadByte())); ) {
;
}
if ((s1.Position == s1.Length)) {
return type;
}
}
}
}
finally {
if ((s1 != null)) {
s1.Close();
}
if ((s2 != null)) {
s2.Close();
}
}
}
xs.Add(dsSchema);
return type;
}
}
/// <summary>
///Represents strongly named DataRow class.
///</summary>
public partial class PartsTableRow : global::System.Data.DataRow {
private PartsTableDataTable tablePartsTable;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
internal PartsTableRow(global::System.Data.DataRowBuilder rb) :
base(rb) {
this.tablePartsTable = ((PartsTableDataTable)(this.Table));
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public int PartNumber {
get {
return ((int)(this[this.tablePartsTable.PartNumberColumn]));
}
set {
this[this.tablePartsTable.PartNumberColumn] = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public string PartName {
get {
try {
return ((string)(this[this.tablePartsTable.PartNameColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("The value for column \'PartName\' in table \'PartsTable\' is DBNull.", e);
}
}
set {
this[this.tablePartsTable.PartNameColumn] = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public decimal PartPrice {
get {
try {
return ((decimal)(this[this.tablePartsTable.PartPriceColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("The value for column \'PartPrice\' in table \'PartsTable\' is DBNull.", e);
}
}
set {
this[this.tablePartsTable.PartPriceColumn] = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public bool IsPartNameNull() {
return this.IsNull(this.tablePartsTable.PartNameColumn);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public void SetPartNameNull() {
this[this.tablePartsTable.PartNameColumn] = global::System.Convert.DBNull;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public bool IsPartPriceNull() {
return this.IsNull(this.tablePartsTable.PartPriceColumn);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public void SetPartPriceNull() {
this[this.tablePartsTable.PartPriceColumn] = global::System.Convert.DBNull;
}
}
/// <summary>
///Represents strongly named DataRow class.
///</summary>
public partial class ServiceTableRow : global::System.Data.DataRow {
private ServiceTableDataTable tableServiceTable;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
internal ServiceTableRow(global::System.Data.DataRowBuilder rb) :
base(rb) {
this.tableServiceTable = ((ServiceTableDataTable)(this.Table));
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public int ServiceID {
get {
return ((int)(this[this.tableServiceTable.ServiceIDColumn]));
}
set {
this[this.tableServiceTable.ServiceIDColumn] = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public string ServiceName {
get {
try {
return ((string)(this[this.tableServiceTable.ServiceNameColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("The value for column \'ServiceName\' in table \'ServiceTable\' is DBNull.", e);
}
}
set {
this[this.tableServiceTable.ServiceNameColumn] = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public decimal ServiceCost {
get {
try {
return ((decimal)(this[this.tableServiceTable.ServiceCostColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("The value for column \'ServiceCost\' in table \'ServiceTable\' is DBNull.", e);
}
}
set {
this[this.tableServiceTable.ServiceCostColumn] = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public bool IsServiceNameNull() {
return this.IsNull(this.tableServiceTable.ServiceNameColumn);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public void SetServiceNameNull() {
this[this.tableServiceTable.ServiceNameColumn] = global::System.Convert.DBNull;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public bool IsServiceCostNull() {
return this.IsNull(this.tableServiceTable.ServiceCostColumn);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public void SetServiceCostNull() {
this[this.tableServiceTable.ServiceCostColumn] = global::System.Convert.DBNull;
}
}
/// <summary>
///Row event argument class
///</summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public class PartsTableRowChangeEvent : global::System.EventArgs {
private PartsTableRow eventRow;
private global::System.Data.DataRowAction eventAction;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public PartsTableRowChangeEvent(PartsTableRow row, global::System.Data.DataRowAction action) {
this.eventRow = row;
this.eventAction = action;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public PartsTableRow Row {
get {
return this.eventRow;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public global::System.Data.DataRowAction Action {
get {
return this.eventAction;
}
}
}
/// <summary>
///Row event argument class
///</summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public class ServiceTableRowChangeEvent : global::System.EventArgs {
private ServiceTableRow eventRow;
private global::System.Data.DataRowAction eventAction;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public ServiceTableRowChangeEvent(ServiceTableRow row, global::System.Data.DataRowAction action) {
this.eventRow = row;
this.eventAction = action;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public ServiceTableRow Row {
get {
return this.eventRow;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public global::System.Data.DataRowAction Action {
get {
return this.eventAction;
}
}
}
}
}
namespace Project03.ServicePartsDataSetTableAdapters {
/// <summary>
///Represents the connection and commands used to retrieve and save data.
///</summary>
[global::System.ComponentModel.DesignerCategoryAttribute("code")]
[global::System.ComponentModel.ToolboxItem(true)]
[global::System.ComponentModel.DataObjectAttribute(true)]
[global::System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterDesigner, Microsoft.VSDesigner" +
", Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
public partial class PartsTableTableAdapter : global::System.ComponentModel.Component {
private global::System.Data.SqlClient.SqlDataAdapter _adapter;
private global::System.Data.SqlClient.SqlConnection _connection;
private global::System.Data.SqlClient.SqlTransaction _transaction;
private global::System.Data.SqlClient.SqlCommand[] _commandCollection;
private bool _clearBeforeFill;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public PartsTableTableAdapter() {
this.ClearBeforeFill = true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected internal global::System.Data.SqlClient.SqlDataAdapter Adapter {
get {
if ((this._adapter == null)) {
this.InitAdapter();
}
return this._adapter;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
internal global::System.Data.SqlClient.SqlConnection Connection {
get {
if ((this._connection == null)) {
this.InitConnection();
}
return this._connection;
}
set {
this._connection = value;
if ((this.Adapter.InsertCommand != null)) {
this.Adapter.InsertCommand.Connection = value;
}
if ((this.Adapter.DeleteCommand != null)) {
this.Adapter.DeleteCommand.Connection = value;
}
if ((this.Adapter.UpdateCommand != null)) {
this.Adapter.UpdateCommand.Connection = value;
}
for (int i = 0; (i < this.CommandCollection.Length); i = (i + 1)) {
if ((this.CommandCollection[i] != null)) {
((global::System.Data.SqlClient.SqlCommand)(this.CommandCollection[i])).Connection = value;
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
internal global::System.Data.SqlClient.SqlTransaction Transaction {
get {
return this._transaction;
}
set {
this._transaction = value;
for (int i = 0; (i < this.CommandCollection.Length); i = (i + 1)) {
this.CommandCollection[i].Transaction = this._transaction;
}
if (((this.Adapter != null)
&& (this.Adapter.DeleteCommand != null))) {
this.Adapter.DeleteCommand.Transaction = this._transaction;
}
if (((this.Adapter != null)
&& (this.Adapter.InsertCommand != null))) {
this.Adapter.InsertCommand.Transaction = this._transaction;
}
if (((this.Adapter != null)
&& (this.Adapter.UpdateCommand != null))) {
this.Adapter.UpdateCommand.Transaction = this._transaction;
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected global::System.Data.SqlClient.SqlCommand[] CommandCollection {
get {
if ((this._commandCollection == null)) {
this.InitCommandCollection();
}
return this._commandCollection;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public bool ClearBeforeFill {
get {
return this._clearBeforeFill;
}
set {
this._clearBeforeFill = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private void InitAdapter() {
this._adapter = new global::System.Data.SqlClient.SqlDataAdapter();
global::System.Data.Common.DataTableMapping tableMapping = new global::System.Data.Common.DataTableMapping();
tableMapping.SourceTable = "Table";
tableMapping.DataSetTable = "PartsTable";
tableMapping.ColumnMappings.Add("PartNumber", "PartNumber");
tableMapping.ColumnMappings.Add("PartName", "PartName");
tableMapping.ColumnMappings.Add("PartPrice", "PartPrice");
this._adapter.TableMappings.Add(tableMapping);
this._adapter.DeleteCommand = new global::System.Data.SqlClient.SqlCommand();
this._adapter.DeleteCommand.Connection = this.Connection;
this._adapter.DeleteCommand.CommandText = @"DELETE FROM [dbo].[PartsTable] WHERE (([PartNumber] = @Original_PartNumber) AND ((@IsNull_PartName = 1 AND [PartName] IS NULL) OR ([PartName] = @Original_PartName)) AND ((@IsNull_PartPrice = 1 AND [PartPrice] IS NULL) OR ([PartPrice] = @Original_PartPrice)))";
this._adapter.DeleteCommand.CommandType = global::System.Data.CommandType.Text;
this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_PartNumber", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PartNumber", global::System.Data.DataRowVersion.Original, false, null, "", "", ""));
this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_PartName", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PartName", global::System.Data.DataRowVersion.Original, true, null, "", "", ""));
this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_PartName", global::System.Data.SqlDbType.NChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PartName", global::System.Data.DataRowVersion.Original, false, null, "", "", ""));
this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_PartPrice", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PartPrice", global::System.Data.DataRowVersion.Original, true, null, "", "", ""));
this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_PartPrice", global::System.Data.SqlDbType.Money, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PartPrice", global::System.Data.DataRowVersion.Original, false, null, "", "", ""));
this._adapter.InsertCommand = new global::System.Data.SqlClient.SqlCommand();
this._adapter.InsertCommand.Connection = this.Connection;
this._adapter.InsertCommand.CommandText = "INSERT INTO [dbo].[PartsTable] ([PartNumber], [PartName], [PartPrice]) VALUES (@P" +
"artNumber, @PartName, @PartPrice);\r\nSELECT PartNumber, PartName, PartPrice FROM " +
"PartsTable WHERE (PartNumber = @PartNumber)";
this._adapter.InsertCommand.CommandType = global::System.Data.CommandType.Text;
this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@PartNumber", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PartNumber", global::System.Data.DataRowVersion.Current, false, null, "", "", ""));
this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@PartName", global::System.Data.SqlDbType.NChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PartName", global::System.Data.DataRowVersion.Current, false, null, "", "", ""));
this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@PartPrice", global::System.Data.SqlDbType.Money, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PartPrice", global::System.Data.DataRowVersion.Current, false, null, "", "", ""));
this._adapter.UpdateCommand = new global::System.Data.SqlClient.SqlCommand();
this._adapter.UpdateCommand.Connection = this.Connection;
this._adapter.UpdateCommand.CommandText = @"UPDATE [dbo].[PartsTable] SET [PartNumber] = @PartNumber, [PartName] = @PartName, [PartPrice] = @PartPrice WHERE (([PartNumber] = @Original_PartNumber) AND ((@IsNull_PartName = 1 AND [PartName] IS NULL) OR ([PartName] = @Original_PartName)) AND ((@IsNull_PartPrice = 1 AND [PartPrice] IS NULL) OR ([PartPrice] = @Original_PartPrice)));
SELECT PartNumber, PartName, PartPrice FROM PartsTable WHERE (PartNumber = @PartNumber)";
this._adapter.UpdateCommand.CommandType = global::System.Data.CommandType.Text;
this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@PartNumber", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PartNumber", global::System.Data.DataRowVersion.Current, false, null, "", "", ""));
this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@PartName", global::System.Data.SqlDbType.NChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PartName", global::System.Data.DataRowVersion.Current, false, null, "", "", ""));
this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@PartPrice", global::System.Data.SqlDbType.Money, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PartPrice", global::System.Data.DataRowVersion.Current, false, null, "", "", ""));
this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_PartNumber", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PartNumber", global::System.Data.DataRowVersion.Original, false, null, "", "", ""));
this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_PartName", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PartName", global::System.Data.DataRowVersion.Original, true, null, "", "", ""));
this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_PartName", global::System.Data.SqlDbType.NChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PartName", global::System.Data.DataRowVersion.Original, false, null, "", "", ""));
this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_PartPrice", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PartPrice", global::System.Data.DataRowVersion.Original, true, null, "", "", ""));
this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_PartPrice", global::System.Data.SqlDbType.Money, 0, global::System.Data.ParameterDirection.Input, 0, 0, "PartPrice", global::System.Data.DataRowVersion.Original, false, null, "", "", ""));
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private void InitConnection() {
this._connection = new global::System.Data.SqlClient.SqlConnection();
this._connection.ConnectionString = global::Project03.Properties.Settings.Default.ServicePartsConnectionString;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private void InitCommandCollection() {
this._commandCollection = new global::System.Data.SqlClient.SqlCommand[1];
this._commandCollection[0] = new global::System.Data.SqlClient.SqlCommand();
this._commandCollection[0].Connection = this.Connection;
this._commandCollection[0].CommandText = "SELECT PartNumber, PartName, PartPrice FROM dbo.PartsTable";
this._commandCollection[0].CommandType = global::System.Data.CommandType.Text;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
[global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Fill, true)]
public virtual int Fill(ServicePartsDataSet.PartsTableDataTable dataTable) {
this.Adapter.SelectCommand = this.CommandCollection[0];
if ((this.ClearBeforeFill == true)) {
dataTable.Clear();
}
int returnValue = this.Adapter.Fill(dataTable);
return returnValue;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
[global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Select, true)]
public virtual ServicePartsDataSet.PartsTableDataTable GetData() {
this.Adapter.SelectCommand = this.CommandCollection[0];
ServicePartsDataSet.PartsTableDataTable dataTable = new ServicePartsDataSet.PartsTableDataTable();
this.Adapter.Fill(dataTable);
return dataTable;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
public virtual int Update(ServicePartsDataSet.PartsTableDataTable dataTable) {
return this.Adapter.Update(dataTable);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
public virtual int Update(ServicePartsDataSet dataSet) {
return this.Adapter.Update(dataSet, "PartsTable");
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
public virtual int Update(global::System.Data.DataRow dataRow) {
return this.Adapter.Update(new global::System.Data.DataRow[] {
dataRow});
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
public virtual int Update(global::System.Data.DataRow[] dataRows) {
return this.Adapter.Update(dataRows);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
[global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Delete, true)]
public virtual int Delete(int Original_PartNumber, string Original_PartName, global::System.Nullable<decimal> Original_PartPrice) {
this.Adapter.DeleteCommand.Parameters[0].Value = ((int)(Original_PartNumber));
if ((Original_PartName == null)) {
this.Adapter.DeleteCommand.Parameters[1].Value = ((object)(1));
this.Adapter.DeleteCommand.Parameters[2].Value = global::System.DBNull.Value;
}
else {
this.Adapter.DeleteCommand.Parameters[1].Value = ((object)(0));
this.Adapter.DeleteCommand.Parameters[2].Value = ((string)(Original_PartName));
}
if ((Original_PartPrice.HasValue == true)) {
this.Adapter.DeleteCommand.Parameters[3].Value = ((object)(0));
this.Adapter.DeleteCommand.Parameters[4].Value = ((decimal)(Original_PartPrice.Value));
}
else {
this.Adapter.DeleteCommand.Parameters[3].Value = ((object)(1));
this.Adapter.DeleteCommand.Parameters[4].Value = global::System.DBNull.Value;
}
global::System.Data.ConnectionState previousConnectionState = this.Adapter.DeleteCommand.Connection.State;
if (((this.Adapter.DeleteCommand.Connection.State & global::System.Data.ConnectionState.Open)
!= global::System.Data.ConnectionState.Open)) {
this.Adapter.DeleteCommand.Connection.Open();
}
try {
int returnValue = this.Adapter.DeleteCommand.ExecuteNonQuery();
return returnValue;
}
finally {
if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) {
this.Adapter.DeleteCommand.Connection.Close();
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
[global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Insert, true)]
public virtual int Insert(int PartNumber, string PartName, global::System.Nullable<decimal> PartPrice) {
this.Adapter.InsertCommand.Parameters[0].Value = ((int)(PartNumber));
if ((PartName == null)) {
this.Adapter.InsertCommand.Parameters[1].Value = global::System.DBNull.Value;
}
else {
this.Adapter.InsertCommand.Parameters[1].Value = ((string)(PartName));
}
if ((PartPrice.HasValue == true)) {
this.Adapter.InsertCommand.Parameters[2].Value = ((decimal)(PartPrice.Value));
}
else {
this.Adapter.InsertCommand.Parameters[2].Value = global::System.DBNull.Value;
}
global::System.Data.ConnectionState previousConnectionState = this.Adapter.InsertCommand.Connection.State;
if (((this.Adapter.InsertCommand.Connection.State & global::System.Data.ConnectionState.Open)
!= global::System.Data.ConnectionState.Open)) {
this.Adapter.InsertCommand.Connection.Open();
}
try {
int returnValue = this.Adapter.InsertCommand.ExecuteNonQuery();
return returnValue;
}
finally {
if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) {
this.Adapter.InsertCommand.Connection.Close();
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
[global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Update, true)]
public virtual int Update(int PartNumber, string PartName, global::System.Nullable<decimal> PartPrice, int Original_PartNumber, string Original_PartName, global::System.Nullable<decimal> Original_PartPrice) {
this.Adapter.UpdateCommand.Parameters[0].Value = ((int)(PartNumber));
if ((PartName == null)) {
this.Adapter.UpdateCommand.Parameters[1].Value = global::System.DBNull.Value;
}
else {
this.Adapter.UpdateCommand.Parameters[1].Value = ((string)(PartName));
}
if ((PartPrice.HasValue == true)) {
this.Adapter.UpdateCommand.Parameters[2].Value = ((decimal)(PartPrice.Value));
}
else {
this.Adapter.UpdateCommand.Parameters[2].Value = global::System.DBNull.Value;
}
this.Adapter.UpdateCommand.Parameters[3].Value = ((int)(Original_PartNumber));
if ((Original_PartName == null)) {
this.Adapter.UpdateCommand.Parameters[4].Value = ((object)(1));
this.Adapter.UpdateCommand.Parameters[5].Value = global::System.DBNull.Value;
}
else {
this.Adapter.UpdateCommand.Parameters[4].Value = ((object)(0));
this.Adapter.UpdateCommand.Parameters[5].Value = ((string)(Original_PartName));
}
if ((Original_PartPrice.HasValue == true)) {
this.Adapter.UpdateCommand.Parameters[6].Value = ((object)(0));
this.Adapter.UpdateCommand.Parameters[7].Value = ((decimal)(Original_PartPrice.Value));
}
else {
this.Adapter.UpdateCommand.Parameters[6].Value = ((object)(1));
this.Adapter.UpdateCommand.Parameters[7].Value = global::System.DBNull.Value;
}
global::System.Data.ConnectionState previousConnectionState = this.Adapter.UpdateCommand.Connection.State;
if (((this.Adapter.UpdateCommand.Connection.State & global::System.Data.ConnectionState.Open)
!= global::System.Data.ConnectionState.Open)) {
this.Adapter.UpdateCommand.Connection.Open();
}
try {
int returnValue = this.Adapter.UpdateCommand.ExecuteNonQuery();
return returnValue;
}
finally {
if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) {
this.Adapter.UpdateCommand.Connection.Close();
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
[global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Update, true)]
public virtual int Update(string PartName, global::System.Nullable<decimal> PartPrice, int Original_PartNumber, string Original_PartName, global::System.Nullable<decimal> Original_PartPrice) {
return this.Update(Original_PartNumber, PartName, PartPrice, Original_PartNumber, Original_PartName, Original_PartPrice);
}
}
/// <summary>
///Represents the connection and commands used to retrieve and save data.
///</summary>
[global::System.ComponentModel.DesignerCategoryAttribute("code")]
[global::System.ComponentModel.ToolboxItem(true)]
[global::System.ComponentModel.DataObjectAttribute(true)]
[global::System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterDesigner, Microsoft.VSDesigner" +
", Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
public partial class ServiceTableTableAdapter : global::System.ComponentModel.Component {
private global::System.Data.SqlClient.SqlDataAdapter _adapter;
private global::System.Data.SqlClient.SqlConnection _connection;
private global::System.Data.SqlClient.SqlTransaction _transaction;
private global::System.Data.SqlClient.SqlCommand[] _commandCollection;
private bool _clearBeforeFill;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public ServiceTableTableAdapter() {
this.ClearBeforeFill = true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected internal global::System.Data.SqlClient.SqlDataAdapter Adapter {
get {
if ((this._adapter == null)) {
this.InitAdapter();
}
return this._adapter;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
internal global::System.Data.SqlClient.SqlConnection Connection {
get {
if ((this._connection == null)) {
this.InitConnection();
}
return this._connection;
}
set {
this._connection = value;
if ((this.Adapter.InsertCommand != null)) {
this.Adapter.InsertCommand.Connection = value;
}
if ((this.Adapter.DeleteCommand != null)) {
this.Adapter.DeleteCommand.Connection = value;
}
if ((this.Adapter.UpdateCommand != null)) {
this.Adapter.UpdateCommand.Connection = value;
}
for (int i = 0; (i < this.CommandCollection.Length); i = (i + 1)) {
if ((this.CommandCollection[i] != null)) {
((global::System.Data.SqlClient.SqlCommand)(this.CommandCollection[i])).Connection = value;
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
internal global::System.Data.SqlClient.SqlTransaction Transaction {
get {
return this._transaction;
}
set {
this._transaction = value;
for (int i = 0; (i < this.CommandCollection.Length); i = (i + 1)) {
this.CommandCollection[i].Transaction = this._transaction;
}
if (((this.Adapter != null)
&& (this.Adapter.DeleteCommand != null))) {
this.Adapter.DeleteCommand.Transaction = this._transaction;
}
if (((this.Adapter != null)
&& (this.Adapter.InsertCommand != null))) {
this.Adapter.InsertCommand.Transaction = this._transaction;
}
if (((this.Adapter != null)
&& (this.Adapter.UpdateCommand != null))) {
this.Adapter.UpdateCommand.Transaction = this._transaction;
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected global::System.Data.SqlClient.SqlCommand[] CommandCollection {
get {
if ((this._commandCollection == null)) {
this.InitCommandCollection();
}
return this._commandCollection;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public bool ClearBeforeFill {
get {
return this._clearBeforeFill;
}
set {
this._clearBeforeFill = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private void InitAdapter() {
this._adapter = new global::System.Data.SqlClient.SqlDataAdapter();
global::System.Data.Common.DataTableMapping tableMapping = new global::System.Data.Common.DataTableMapping();
tableMapping.SourceTable = "Table";
tableMapping.DataSetTable = "ServiceTable";
tableMapping.ColumnMappings.Add("ServiceID", "ServiceID");
tableMapping.ColumnMappings.Add("ServiceName", "ServiceName");
tableMapping.ColumnMappings.Add("ServiceCost", "ServiceCost");
this._adapter.TableMappings.Add(tableMapping);
this._adapter.DeleteCommand = new global::System.Data.SqlClient.SqlCommand();
this._adapter.DeleteCommand.Connection = this.Connection;
this._adapter.DeleteCommand.CommandText = @"DELETE FROM [dbo].[ServiceTable] WHERE (([ServiceID] = @Original_ServiceID) AND ((@IsNull_ServiceName = 1 AND [ServiceName] IS NULL) OR ([ServiceName] = @Original_ServiceName)) AND ((@IsNull_ServiceCost = 1 AND [ServiceCost] IS NULL) OR ([ServiceCost] = @Original_ServiceCost)))";
this._adapter.DeleteCommand.CommandType = global::System.Data.CommandType.Text;
this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_ServiceID", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "ServiceID", global::System.Data.DataRowVersion.Original, false, null, "", "", ""));
this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_ServiceName", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "ServiceName", global::System.Data.DataRowVersion.Original, true, null, "", "", ""));
this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_ServiceName", global::System.Data.SqlDbType.NChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "ServiceName", global::System.Data.DataRowVersion.Original, false, null, "", "", ""));
this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_ServiceCost", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "ServiceCost", global::System.Data.DataRowVersion.Original, true, null, "", "", ""));
this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_ServiceCost", global::System.Data.SqlDbType.Money, 0, global::System.Data.ParameterDirection.Input, 0, 0, "ServiceCost", global::System.Data.DataRowVersion.Original, false, null, "", "", ""));
this._adapter.InsertCommand = new global::System.Data.SqlClient.SqlCommand();
this._adapter.InsertCommand.Connection = this.Connection;
this._adapter.InsertCommand.CommandText = "INSERT INTO [dbo].[ServiceTable] ([ServiceID], [ServiceName], [ServiceCost]) VALU" +
"ES (@ServiceID, @ServiceName, @ServiceCost);\r\nSELECT ServiceID, ServiceName, Ser" +
"viceCost FROM ServiceTable WHERE (ServiceID = @ServiceID)";
this._adapter.InsertCommand.CommandType = global::System.Data.CommandType.Text;
this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@ServiceID", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "ServiceID", global::System.Data.DataRowVersion.Current, false, null, "", "", ""));
this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@ServiceName", global::System.Data.SqlDbType.NChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "ServiceName", global::System.Data.DataRowVersion.Current, false, null, "", "", ""));
this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@ServiceCost", global::System.Data.SqlDbType.Money, 0, global::System.Data.ParameterDirection.Input, 0, 0, "ServiceCost", global::System.Data.DataRowVersion.Current, false, null, "", "", ""));
this._adapter.UpdateCommand = new global::System.Data.SqlClient.SqlCommand();
this._adapter.UpdateCommand.Connection = this.Connection;
this._adapter.UpdateCommand.CommandText = @"UPDATE [dbo].[ServiceTable] SET [ServiceID] = @ServiceID, [ServiceName] = @ServiceName, [ServiceCost] = @ServiceCost WHERE (([ServiceID] = @Original_ServiceID) AND ((@IsNull_ServiceName = 1 AND [ServiceName] IS NULL) OR ([ServiceName] = @Original_ServiceName)) AND ((@IsNull_ServiceCost = 1 AND [ServiceCost] IS NULL) OR ([ServiceCost] = @Original_ServiceCost)));
SELECT ServiceID, ServiceName, ServiceCost FROM ServiceTable WHERE (ServiceID = @ServiceID)";
this._adapter.UpdateCommand.CommandType = global::System.Data.CommandType.Text;
this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@ServiceID", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "ServiceID", global::System.Data.DataRowVersion.Current, false, null, "", "", ""));
this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@ServiceName", global::System.Data.SqlDbType.NChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "ServiceName", global::System.Data.DataRowVersion.Current, false, null, "", "", ""));
this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@ServiceCost", global::System.Data.SqlDbType.Money, 0, global::System.Data.ParameterDirection.Input, 0, 0, "ServiceCost", global::System.Data.DataRowVersion.Current, false, null, "", "", ""));
this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_ServiceID", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "ServiceID", global::System.Data.DataRowVersion.Original, false, null, "", "", ""));
this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_ServiceName", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "ServiceName", global::System.Data.DataRowVersion.Original, true, null, "", "", ""));
this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_ServiceName", global::System.Data.SqlDbType.NChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "ServiceName", global::System.Data.DataRowVersion.Original, false, null, "", "", ""));
this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_ServiceCost", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "ServiceCost", global::System.Data.DataRowVersion.Original, true, null, "", "", ""));
this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_ServiceCost", global::System.Data.SqlDbType.Money, 0, global::System.Data.ParameterDirection.Input, 0, 0, "ServiceCost", global::System.Data.DataRowVersion.Original, false, null, "", "", ""));
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private void InitConnection() {
this._connection = new global::System.Data.SqlClient.SqlConnection();
this._connection.ConnectionString = global::Project03.Properties.Settings.Default.ServicePartsConnectionString;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private void InitCommandCollection() {
this._commandCollection = new global::System.Data.SqlClient.SqlCommand[1];
this._commandCollection[0] = new global::System.Data.SqlClient.SqlCommand();
this._commandCollection[0].Connection = this.Connection;
this._commandCollection[0].CommandText = "SELECT ServiceID, ServiceName, ServiceCost FROM dbo.ServiceTable";
this._commandCollection[0].CommandType = global::System.Data.CommandType.Text;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
[global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Fill, true)]
public virtual int Fill(ServicePartsDataSet.ServiceTableDataTable dataTable) {
this.Adapter.SelectCommand = this.CommandCollection[0];
if ((this.ClearBeforeFill == true)) {
dataTable.Clear();
}
int returnValue = this.Adapter.Fill(dataTable);
return returnValue;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
[global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Select, true)]
public virtual ServicePartsDataSet.ServiceTableDataTable GetData() {
this.Adapter.SelectCommand = this.CommandCollection[0];
ServicePartsDataSet.ServiceTableDataTable dataTable = new ServicePartsDataSet.ServiceTableDataTable();
this.Adapter.Fill(dataTable);
return dataTable;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
public virtual int Update(ServicePartsDataSet.ServiceTableDataTable dataTable) {
return this.Adapter.Update(dataTable);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
public virtual int Update(ServicePartsDataSet dataSet) {
return this.Adapter.Update(dataSet, "ServiceTable");
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
public virtual int Update(global::System.Data.DataRow dataRow) {
return this.Adapter.Update(new global::System.Data.DataRow[] {
dataRow});
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
public virtual int Update(global::System.Data.DataRow[] dataRows) {
return this.Adapter.Update(dataRows);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
[global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Delete, true)]
public virtual int Delete(int Original_ServiceID, string Original_ServiceName, global::System.Nullable<decimal> Original_ServiceCost) {
this.Adapter.DeleteCommand.Parameters[0].Value = ((int)(Original_ServiceID));
if ((Original_ServiceName == null)) {
this.Adapter.DeleteCommand.Parameters[1].Value = ((object)(1));
this.Adapter.DeleteCommand.Parameters[2].Value = global::System.DBNull.Value;
}
else {
this.Adapter.DeleteCommand.Parameters[1].Value = ((object)(0));
this.Adapter.DeleteCommand.Parameters[2].Value = ((string)(Original_ServiceName));
}
if ((Original_ServiceCost.HasValue == true)) {
this.Adapter.DeleteCommand.Parameters[3].Value = ((object)(0));
this.Adapter.DeleteCommand.Parameters[4].Value = ((decimal)(Original_ServiceCost.Value));
}
else {
this.Adapter.DeleteCommand.Parameters[3].Value = ((object)(1));
this.Adapter.DeleteCommand.Parameters[4].Value = global::System.DBNull.Value;
}
global::System.Data.ConnectionState previousConnectionState = this.Adapter.DeleteCommand.Connection.State;
if (((this.Adapter.DeleteCommand.Connection.State & global::System.Data.ConnectionState.Open)
!= global::System.Data.ConnectionState.Open)) {
this.Adapter.DeleteCommand.Connection.Open();
}
try {
int returnValue = this.Adapter.DeleteCommand.ExecuteNonQuery();
return returnValue;
}
finally {
if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) {
this.Adapter.DeleteCommand.Connection.Close();
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
[global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Insert, true)]
public virtual int Insert(int ServiceID, string ServiceName, global::System.Nullable<decimal> ServiceCost) {
this.Adapter.InsertCommand.Parameters[0].Value = ((int)(ServiceID));
if ((ServiceName == null)) {
this.Adapter.InsertCommand.Parameters[1].Value = global::System.DBNull.Value;
}
else {
this.Adapter.InsertCommand.Parameters[1].Value = ((string)(ServiceName));
}
if ((ServiceCost.HasValue == true)) {
this.Adapter.InsertCommand.Parameters[2].Value = ((decimal)(ServiceCost.Value));
}
else {
this.Adapter.InsertCommand.Parameters[2].Value = global::System.DBNull.Value;
}
global::System.Data.ConnectionState previousConnectionState = this.Adapter.InsertCommand.Connection.State;
if (((this.Adapter.InsertCommand.Connection.State & global::System.Data.ConnectionState.Open)
!= global::System.Data.ConnectionState.Open)) {
this.Adapter.InsertCommand.Connection.Open();
}
try {
int returnValue = this.Adapter.InsertCommand.ExecuteNonQuery();
return returnValue;
}
finally {
if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) {
this.Adapter.InsertCommand.Connection.Close();
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
[global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Update, true)]
public virtual int Update(int ServiceID, string ServiceName, global::System.Nullable<decimal> ServiceCost, int Original_ServiceID, string Original_ServiceName, global::System.Nullable<decimal> Original_ServiceCost) {
this.Adapter.UpdateCommand.Parameters[0].Value = ((int)(ServiceID));
if ((ServiceName == null)) {
this.Adapter.UpdateCommand.Parameters[1].Value = global::System.DBNull.Value;
}
else {
this.Adapter.UpdateCommand.Parameters[1].Value = ((string)(ServiceName));
}
if ((ServiceCost.HasValue == true)) {
this.Adapter.UpdateCommand.Parameters[2].Value = ((decimal)(ServiceCost.Value));
}
else {
this.Adapter.UpdateCommand.Parameters[2].Value = global::System.DBNull.Value;
}
this.Adapter.UpdateCommand.Parameters[3].Value = ((int)(Original_ServiceID));
if ((Original_ServiceName == null)) {
this.Adapter.UpdateCommand.Parameters[4].Value = ((object)(1));
this.Adapter.UpdateCommand.Parameters[5].Value = global::System.DBNull.Value;
}
else {
this.Adapter.UpdateCommand.Parameters[4].Value = ((object)(0));
this.Adapter.UpdateCommand.Parameters[5].Value = ((string)(Original_ServiceName));
}
if ((Original_ServiceCost.HasValue == true)) {
this.Adapter.UpdateCommand.Parameters[6].Value = ((object)(0));
this.Adapter.UpdateCommand.Parameters[7].Value = ((decimal)(Original_ServiceCost.Value));
}
else {
this.Adapter.UpdateCommand.Parameters[6].Value = ((object)(1));
this.Adapter.UpdateCommand.Parameters[7].Value = global::System.DBNull.Value;
}
global::System.Data.ConnectionState previousConnectionState = this.Adapter.UpdateCommand.Connection.State;
if (((this.Adapter.UpdateCommand.Connection.State & global::System.Data.ConnectionState.Open)
!= global::System.Data.ConnectionState.Open)) {
this.Adapter.UpdateCommand.Connection.Open();
}
try {
int returnValue = this.Adapter.UpdateCommand.ExecuteNonQuery();
return returnValue;
}
finally {
if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) {
this.Adapter.UpdateCommand.Connection.Close();
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
[global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Update, true)]
public virtual int Update(string ServiceName, global::System.Nullable<decimal> ServiceCost, int Original_ServiceID, string Original_ServiceName, global::System.Nullable<decimal> Original_ServiceCost) {
return this.Update(Original_ServiceID, ServiceName, ServiceCost, Original_ServiceID, Original_ServiceName, Original_ServiceCost);
}
}
/// <summary>
///TableAdapterManager is used to coordinate TableAdapters in the dataset to enable Hierarchical Update scenarios
///</summary>
[global::System.ComponentModel.DesignerCategoryAttribute("code")]
[global::System.ComponentModel.ToolboxItem(true)]
[global::System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerDesigner, Microsoft.VSD" +
"esigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapterManager")]
public partial class TableAdapterManager : global::System.ComponentModel.Component {
private UpdateOrderOption _updateOrder;
private PartsTableTableAdapter _partsTableTableAdapter;
private ServiceTableTableAdapter _serviceTableTableAdapter;
private bool _backupDataSetBeforeUpdate;
private global::System.Data.IDbConnection _connection;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public UpdateOrderOption UpdateOrder {
get {
return this._updateOrder;
}
set {
this._updateOrder = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.EditorAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerPropertyEditor, Microso" +
"ft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3" +
"a", "System.Drawing.Design.UITypeEditor")]
public PartsTableTableAdapter PartsTableTableAdapter {
get {
return this._partsTableTableAdapter;
}
set {
this._partsTableTableAdapter = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.EditorAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerPropertyEditor, Microso" +
"ft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3" +
"a", "System.Drawing.Design.UITypeEditor")]
public ServiceTableTableAdapter ServiceTableTableAdapter {
get {
return this._serviceTableTableAdapter;
}
set {
this._serviceTableTableAdapter = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public bool BackupDataSetBeforeUpdate {
get {
return this._backupDataSetBeforeUpdate;
}
set {
this._backupDataSetBeforeUpdate = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Browsable(false)]
public global::System.Data.IDbConnection Connection {
get {
if ((this._connection != null)) {
return this._connection;
}
if (((this._partsTableTableAdapter != null)
&& (this._partsTableTableAdapter.Connection != null))) {
return this._partsTableTableAdapter.Connection;
}
if (((this._serviceTableTableAdapter != null)
&& (this._serviceTableTableAdapter.Connection != null))) {
return this._serviceTableTableAdapter.Connection;
}
return null;
}
set {
this._connection = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Browsable(false)]
public int TableAdapterInstanceCount {
get {
int count = 0;
if ((this._partsTableTableAdapter != null)) {
count = (count + 1);
}
if ((this._serviceTableTableAdapter != null)) {
count = (count + 1);
}
return count;
}
}
/// <summary>
///Update rows in top-down order.
///</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private int UpdateUpdatedRows(ServicePartsDataSet dataSet, global::System.Collections.Generic.List<global::System.Data.DataRow> allChangedRows, global::System.Collections.Generic.List<global::System.Data.DataRow> allAddedRows) {
int result = 0;
if ((this._partsTableTableAdapter != null)) {
global::System.Data.DataRow[] updatedRows = dataSet.PartsTable.Select(null, null, global::System.Data.DataViewRowState.ModifiedCurrent);
updatedRows = this.GetRealUpdatedRows(updatedRows, allAddedRows);
if (((updatedRows != null)
&& (0 < updatedRows.Length))) {
result = (result + this._partsTableTableAdapter.Update(updatedRows));
allChangedRows.AddRange(updatedRows);
}
}
if ((this._serviceTableTableAdapter != null)) {
global::System.Data.DataRow[] updatedRows = dataSet.ServiceTable.Select(null, null, global::System.Data.DataViewRowState.ModifiedCurrent);
updatedRows = this.GetRealUpdatedRows(updatedRows, allAddedRows);
if (((updatedRows != null)
&& (0 < updatedRows.Length))) {
result = (result + this._serviceTableTableAdapter.Update(updatedRows));
allChangedRows.AddRange(updatedRows);
}
}
return result;
}
/// <summary>
///Insert rows in top-down order.
///</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private int UpdateInsertedRows(ServicePartsDataSet dataSet, global::System.Collections.Generic.List<global::System.Data.DataRow> allAddedRows) {
int result = 0;
if ((this._partsTableTableAdapter != null)) {
global::System.Data.DataRow[] addedRows = dataSet.PartsTable.Select(null, null, global::System.Data.DataViewRowState.Added);
if (((addedRows != null)
&& (0 < addedRows.Length))) {
result = (result + this._partsTableTableAdapter.Update(addedRows));
allAddedRows.AddRange(addedRows);
}
}
if ((this._serviceTableTableAdapter != null)) {
global::System.Data.DataRow[] addedRows = dataSet.ServiceTable.Select(null, null, global::System.Data.DataViewRowState.Added);
if (((addedRows != null)
&& (0 < addedRows.Length))) {
result = (result + this._serviceTableTableAdapter.Update(addedRows));
allAddedRows.AddRange(addedRows);
}
}
return result;
}
/// <summary>
///Delete rows in bottom-up order.
///</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private int UpdateDeletedRows(ServicePartsDataSet dataSet, global::System.Collections.Generic.List<global::System.Data.DataRow> allChangedRows) {
int result = 0;
if ((this._serviceTableTableAdapter != null)) {
global::System.Data.DataRow[] deletedRows = dataSet.ServiceTable.Select(null, null, global::System.Data.DataViewRowState.Deleted);
if (((deletedRows != null)
&& (0 < deletedRows.Length))) {
result = (result + this._serviceTableTableAdapter.Update(deletedRows));
allChangedRows.AddRange(deletedRows);
}
}
if ((this._partsTableTableAdapter != null)) {
global::System.Data.DataRow[] deletedRows = dataSet.PartsTable.Select(null, null, global::System.Data.DataViewRowState.Deleted);
if (((deletedRows != null)
&& (0 < deletedRows.Length))) {
result = (result + this._partsTableTableAdapter.Update(deletedRows));
allChangedRows.AddRange(deletedRows);
}
}
return result;
}
/// <summary>
///Remove inserted rows that become updated rows after calling TableAdapter.Update(inserted rows) first
///</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private global::System.Data.DataRow[] GetRealUpdatedRows(global::System.Data.DataRow[] updatedRows, global::System.Collections.Generic.List<global::System.Data.DataRow> allAddedRows) {
if (((updatedRows == null)
|| (updatedRows.Length < 1))) {
return updatedRows;
}
if (((allAddedRows == null)
|| (allAddedRows.Count < 1))) {
return updatedRows;
}
global::System.Collections.Generic.List<global::System.Data.DataRow> realUpdatedRows = new global::System.Collections.Generic.List<global::System.Data.DataRow>();
for (int i = 0; (i < updatedRows.Length); i = (i + 1)) {
global::System.Data.DataRow row = updatedRows[i];
if ((allAddedRows.Contains(row) == false)) {
realUpdatedRows.Add(row);
}
}
return realUpdatedRows.ToArray();
}
/// <summary>
///Update all changes to the dataset.
///</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public virtual int UpdateAll(ServicePartsDataSet dataSet) {
if ((dataSet == null)) {
throw new global::System.ArgumentNullException("dataSet");
}
if ((dataSet.HasChanges() == false)) {
return 0;
}
if (((this._partsTableTableAdapter != null)
&& (this.MatchTableAdapterConnection(this._partsTableTableAdapter.Connection) == false))) {
throw new global::System.ArgumentException("All TableAdapters managed by a TableAdapterManager must use the same connection s" +
"tring.");
}
if (((this._serviceTableTableAdapter != null)
&& (this.MatchTableAdapterConnection(this._serviceTableTableAdapter.Connection) == false))) {
throw new global::System.ArgumentException("All TableAdapters managed by a TableAdapterManager must use the same connection s" +
"tring.");
}
global::System.Data.IDbConnection workConnection = this.Connection;
if ((workConnection == null)) {
throw new global::System.ApplicationException("TableAdapterManager contains no connection information. Set each TableAdapterMana" +
"ger TableAdapter property to a valid TableAdapter instance.");
}
bool workConnOpened = false;
if (((workConnection.State & global::System.Data.ConnectionState.Broken)
== global::System.Data.ConnectionState.Broken)) {
workConnection.Close();
}
if ((workConnection.State == global::System.Data.ConnectionState.Closed)) {
workConnection.Open();
workConnOpened = true;
}
global::System.Data.IDbTransaction workTransaction = workConnection.BeginTransaction();
if ((workTransaction == null)) {
throw new global::System.ApplicationException("The transaction cannot begin. The current data connection does not support transa" +
"ctions or the current state is not allowing the transaction to begin.");
}
global::System.Collections.Generic.List<global::System.Data.DataRow> allChangedRows = new global::System.Collections.Generic.List<global::System.Data.DataRow>();
global::System.Collections.Generic.List<global::System.Data.DataRow> allAddedRows = new global::System.Collections.Generic.List<global::System.Data.DataRow>();
global::System.Collections.Generic.List<global::System.Data.Common.DataAdapter> adaptersWithAcceptChangesDuringUpdate = new global::System.Collections.Generic.List<global::System.Data.Common.DataAdapter>();
global::System.Collections.Generic.Dictionary<object, global::System.Data.IDbConnection> revertConnections = new global::System.Collections.Generic.Dictionary<object, global::System.Data.IDbConnection>();
int result = 0;
global::System.Data.DataSet backupDataSet = null;
if (this.BackupDataSetBeforeUpdate) {
backupDataSet = new global::System.Data.DataSet();
backupDataSet.Merge(dataSet);
}
try {
// ---- Prepare for update -----------
//
if ((this._partsTableTableAdapter != null)) {
revertConnections.Add(this._partsTableTableAdapter, this._partsTableTableAdapter.Connection);
this._partsTableTableAdapter.Connection = ((global::System.Data.SqlClient.SqlConnection)(workConnection));
this._partsTableTableAdapter.Transaction = ((global::System.Data.SqlClient.SqlTransaction)(workTransaction));
if (this._partsTableTableAdapter.Adapter.AcceptChangesDuringUpdate) {
this._partsTableTableAdapter.Adapter.AcceptChangesDuringUpdate = false;
adaptersWithAcceptChangesDuringUpdate.Add(this._partsTableTableAdapter.Adapter);
}
}
if ((this._serviceTableTableAdapter != null)) {
revertConnections.Add(this._serviceTableTableAdapter, this._serviceTableTableAdapter.Connection);
this._serviceTableTableAdapter.Connection = ((global::System.Data.SqlClient.SqlConnection)(workConnection));
this._serviceTableTableAdapter.Transaction = ((global::System.Data.SqlClient.SqlTransaction)(workTransaction));
if (this._serviceTableTableAdapter.Adapter.AcceptChangesDuringUpdate) {
this._serviceTableTableAdapter.Adapter.AcceptChangesDuringUpdate = false;
adaptersWithAcceptChangesDuringUpdate.Add(this._serviceTableTableAdapter.Adapter);
}
}
//
//---- Perform updates -----------
//
if ((this.UpdateOrder == UpdateOrderOption.UpdateInsertDelete)) {
result = (result + this.UpdateUpdatedRows(dataSet, allChangedRows, allAddedRows));
result = (result + this.UpdateInsertedRows(dataSet, allAddedRows));
}
else {
result = (result + this.UpdateInsertedRows(dataSet, allAddedRows));
result = (result + this.UpdateUpdatedRows(dataSet, allChangedRows, allAddedRows));
}
result = (result + this.UpdateDeletedRows(dataSet, allChangedRows));
//
//---- Commit updates -----------
//
workTransaction.Commit();
if ((0 < allAddedRows.Count)) {
global::System.Data.DataRow[] rows = new System.Data.DataRow[allAddedRows.Count];
allAddedRows.CopyTo(rows);
for (int i = 0; (i < rows.Length); i = (i + 1)) {
global::System.Data.DataRow row = rows[i];
row.AcceptChanges();
}
}
if ((0 < allChangedRows.Count)) {
global::System.Data.DataRow[] rows = new System.Data.DataRow[allChangedRows.Count];
allChangedRows.CopyTo(rows);
for (int i = 0; (i < rows.Length); i = (i + 1)) {
global::System.Data.DataRow row = rows[i];
row.AcceptChanges();
}
}
}
catch (global::System.Exception ex) {
workTransaction.Rollback();
// ---- Restore the dataset -----------
if (this.BackupDataSetBeforeUpdate) {
global::System.Diagnostics.Debug.Assert((backupDataSet != null));
dataSet.Clear();
dataSet.Merge(backupDataSet);
}
else {
if ((0 < allAddedRows.Count)) {
global::System.Data.DataRow[] rows = new System.Data.DataRow[allAddedRows.Count];
allAddedRows.CopyTo(rows);
for (int i = 0; (i < rows.Length); i = (i + 1)) {
global::System.Data.DataRow row = rows[i];
row.AcceptChanges();
row.SetAdded();
}
}
}
throw ex;
}
finally {
if (workConnOpened) {
workConnection.Close();
}
if ((this._partsTableTableAdapter != null)) {
this._partsTableTableAdapter.Connection = ((global::System.Data.SqlClient.SqlConnection)(revertConnections[this._partsTableTableAdapter]));
this._partsTableTableAdapter.Transaction = null;
}
if ((this._serviceTableTableAdapter != null)) {
this._serviceTableTableAdapter.Connection = ((global::System.Data.SqlClient.SqlConnection)(revertConnections[this._serviceTableTableAdapter]));
this._serviceTableTableAdapter.Transaction = null;
}
if ((0 < adaptersWithAcceptChangesDuringUpdate.Count)) {
global::System.Data.Common.DataAdapter[] adapters = new System.Data.Common.DataAdapter[adaptersWithAcceptChangesDuringUpdate.Count];
adaptersWithAcceptChangesDuringUpdate.CopyTo(adapters);
for (int i = 0; (i < adapters.Length); i = (i + 1)) {
global::System.Data.Common.DataAdapter adapter = adapters[i];
adapter.AcceptChangesDuringUpdate = true;
}
}
}
return result;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected virtual void SortSelfReferenceRows(global::System.Data.DataRow[] rows, global::System.Data.DataRelation relation, bool childFirst) {
global::System.Array.Sort<global::System.Data.DataRow>(rows, new SelfReferenceComparer(relation, childFirst));
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected virtual bool MatchTableAdapterConnection(global::System.Data.IDbConnection inputConnection) {
if ((this._connection != null)) {
return true;
}
if (((this.Connection == null)
|| (inputConnection == null))) {
return true;
}
if (string.Equals(this.Connection.ConnectionString, inputConnection.ConnectionString, global::System.StringComparison.Ordinal)) {
return true;
}
return false;
}
/// <summary>
///Update Order Option
///</summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public enum UpdateOrderOption {
InsertUpdateDelete = 0,
UpdateInsertDelete = 1,
}
/// <summary>
///Used to sort self-referenced table's rows
///</summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private class SelfReferenceComparer : object, global::System.Collections.Generic.IComparer<global::System.Data.DataRow> {
private global::System.Data.DataRelation _relation;
private int _childFirst;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
internal SelfReferenceComparer(global::System.Data.DataRelation relation, bool childFirst) {
this._relation = relation;
if (childFirst) {
this._childFirst = -1;
}
else {
this._childFirst = 1;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private global::System.Data.DataRow GetRoot(global::System.Data.DataRow row, out int distance) {
global::System.Diagnostics.Debug.Assert((row != null));
global::System.Data.DataRow root = row;
distance = 0;
global::System.Collections.Generic.IDictionary<global::System.Data.DataRow, global::System.Data.DataRow> traversedRows = new global::System.Collections.Generic.Dictionary<global::System.Data.DataRow, global::System.Data.DataRow>();
traversedRows[row] = row;
global::System.Data.DataRow parent = row.GetParentRow(this._relation, global::System.Data.DataRowVersion.Default);
for (
; ((parent != null)
&& (traversedRows.ContainsKey(parent) == false));
) {
distance = (distance + 1);
root = parent;
traversedRows[parent] = parent;
parent = parent.GetParentRow(this._relation, global::System.Data.DataRowVersion.Default);
}
if ((distance == 0)) {
traversedRows.Clear();
traversedRows[row] = row;
parent = row.GetParentRow(this._relation, global::System.Data.DataRowVersion.Original);
for (
; ((parent != null)
&& (traversedRows.ContainsKey(parent) == false));
) {
distance = (distance + 1);
root = parent;
traversedRows[parent] = parent;
parent = parent.GetParentRow(this._relation, global::System.Data.DataRowVersion.Original);
}
}
return root;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public int Compare(global::System.Data.DataRow row1, global::System.Data.DataRow row2) {
if (object.ReferenceEquals(row1, row2)) {
return 0;
}
if ((row1 == null)) {
return -1;
}
if ((row2 == null)) {
return 1;
}
int distance1 = 0;
global::System.Data.DataRow root1 = this.GetRoot(row1, out distance1);
int distance2 = 0;
global::System.Data.DataRow root2 = this.GetRoot(row2, out distance2);
if (object.ReferenceEquals(root1, root2)) {
return (this._childFirst * distance1.CompareTo(distance2));
}
else {
global::System.Diagnostics.Debug.Assert(((root1.Table != null)
&& (root2.Table != null)));
if ((root1.Table.Rows.IndexOf(root1) < root2.Table.Rows.IndexOf(root2))) {
return -1;
}
else {
return 1;
}
}
}
}
}
}
#pragma warning restore 1591 | 60.354756 | 420 | 0.601258 | [
"MIT"
] | cljernigan/CProject03 | Project03/Project03/ServicePartsDataSet.Designer.cs | 140,870 | C# |
/* SCRIPT INSPECTOR 3
* version 3.0.29, May 2021
* Copyright © 2012-2021, Flipbook Games
*
* Unity's legendary editor for C#, UnityScript, Boo, Shaders, and text,
* now transformed into an advanced C# IDE!!!
*
* Follow me on http://twitter.com/FlipbookGames
* Like Flipbook Games on Facebook http://facebook.com/FlipbookGames
* Join discussion in Unity forums http://forum.unity3d.com/threads/138329
* Contact info@flipbookgames.com for feedback, bug reports, or suggestions.
* Visit http://flipbookgames.com/ for more info.
*/
namespace ScriptInspector
{
using UnityEditor;
using UnityEngine;
public class GoToLineWindow : EditorWindow
{
private string text;
private FGTextEditor editor;
public static GoToLineWindow Create(FGTextEditor editor)
{
var owner = EditorWindow.focusedWindow;
var wnd = EditorWindow.GetWindow<GoToLineWindow>(true);
wnd.editor = editor;
wnd.text = (editor.caretPosition.line + 1).ToString();
if (owner != null)
{
var center = owner.position.center;
wnd.position = new Rect((int)(center.x - 0.5f * 256f), (int)(center.y - 0.5f * 100f), 256f, 100f);
}
wnd.ShowAuxWindow();
return wnd;
}
private void OnEnable()
{
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5_0
title = "Go To Line";
#else
titleContent.text = "Go To Line";
#endif
minSize = new Vector2(265f, 100f);
maxSize = new Vector2(265f, 100f);
Repaint();
}
private void OnDisable()
{
editor.OwnerWindow.Focus();
}
private void OnGUI()
{
int lineToGoTo;
var validLineNumber = int.TryParse(text, out lineToGoTo) &&
lineToGoTo >= 1 && lineToGoTo <= editor.TextBuffer.lines.Count;
if (validLineNumber && Event.current.type == EventType.KeyDown && Event.current.character == '\n')
{
editor.SetCursorPosition(lineToGoTo - 1, 0);
Close();
editor.OwnerWindow.Focus();
return;
}
else if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape)
{
Close();
editor.OwnerWindow.Focus();
return;
}
GUILayout.BeginVertical();
GUILayout.Space(20f);
GUILayout.BeginHorizontal();
GUILayout.Space(10f);
GUI.SetNextControlName("text field");
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
EditorGUI.FocusTextInControl("text field");
#endif
text = EditorGUILayout.TextField(text);
GUI.FocusControl("text field");
GUILayout.Space(10f);
GUILayout.EndHorizontal();
GUILayout.Space(20f);
GUI.enabled = int.TryParse(text, out lineToGoTo) &&
lineToGoTo >= 1 && lineToGoTo <= editor.TextBuffer.lines.Count;
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("OK"))
{
editor.SetCursorPosition(lineToGoTo - 1, 0);
Close();
editor.OwnerWindow.Focus();
}
GUILayout.Space(6f);
GUI.enabled = true;
if (GUILayout.Button("Cancel"))
{
Close();
editor.OwnerWindow.Focus();
}
GUILayout.Space(10f);
GUILayout.EndHorizontal();
GUILayout.Space(10f);
GUILayout.EndVertical();
}
}
}
| 24.758065 | 117 | 0.689902 | [
"MIT"
] | DuLovell/Battle-Simulator | Assets/Imported Assets/Editor/ScriptInspector3/Scripts/GoToLineWindow.cs | 3,073 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Client.UI
{
public class SettlementData
{
public SettlementData()
{
}
#region 创造财富
/// <summary>
/// 大机会得分计算
/// </summary>
public int OpportunityScore
{
get
{
if (GameModel.GetInstance.isPlayNet == false)
{
var tmpNum = 0;
if (_bigOpportunitiesTotalNum > 0)
{
tmpNum = (int)(_bigOpportunitiesNum * (1 + 0.1f + _bigOpportunitiesNum / _bigOpportunitiesTotalNum));
}
return tmpNum;
}
return _opportunityscore;
}
set
{
_opportunityscore = value;
}
}
private int _opportunityscore = 0;
/// <summary>
/// 小机会得分计算
/// </summary>
public int smallChanceFixed
{
get
{
if(GameModel.GetInstance.isPlayNet==false)
{
var tmpNum = 0;
if (_smallOpportunitiesTotalNum > 0)
{
tmpNum = (int)(_smallOpportunitiesNum * (1 + 0.1f + _smallOpportunitiesNum / _smallOpportunitiesTotalNum));
}
return tmpNum;
}
return _smallchance;
}
set
{
_smallchance = value;
}
}
private int _smallchance = 0;
/// <summary>
/// 外圈结账日得分计算
/// </summary>
public int OutCheckScore
{
get
{
if (GameModel.GetInstance.isPlayNet == false)
{
return (int)(_settleOuterNum * 2.1f);
}
return _outercheckscore;
}
set
{
_outercheckscore = value;
}
}
private int _outercheckscore = 0;
/// <summary>
/// 卖出资产的积分
/// </summary>
public int SaleNumScore
{
get
{
if (GameModel.GetInstance.isPlayNet == false)
{
return (int)(_saleNums * 2.1f);
}
return _saleNumberScore;
}
set
{
_saleNumberScore = value;
}
}
private int _saleNumberScore;
#endregion
#region 管理财富
/// <summary>
/// 投资得分计算
/// </summary>
public int InvestmentScore
{
get
{
if (GameModel.GetInstance.isPlayNet == false)
{
var tmpNum = 0;
if (_investmentTotalNum > 0)
{
tmpNum = (int)(_investmentNum * (1 + 0.2f + _investmentNum / _investmentTotalNum));
}
return tmpNum;//
}
return _investmentScore;
}
set
{
_investmentScore = value;
}
}
private int _investmentScore;
/// <summary>
/// 购买保险的积分计算
/// </summary>
public int BuyCareScore
{
get
{
if (GameModel.GetInstance.isPlayNet == false)
{
return (int)(_buyCareNum * (2.2f));
}
return _buyCareScore;
}
set
{
_buyCareScore = value;
}
}
private int _buyCareScore = 0;
/// <summary>
/// 内圈结算积分
/// </summary>
public int InnerCheckScore
{
get
{
if (GameModel.GetInstance.isPlayNet == false)
{
return (int)(_settleInnerNum * 2.2f);
}
return _innerCheckScore;
}
set
{
_innerCheckScore = value;
}
}
private int _innerCheckScore = 0;
#endregion
#region 运用财富的数据
/// <summary>
/// 获取有钱有闲的得分情况
/// </summary>
public int RelaxScore
{
get
{
if (GameModel.GetInstance.isPlayNet == false)
{
var tmpNum = 0;
if (_richleisureTotalNum > 0)
{
tmpNum = (int)(_richleisureNum * (1 + 0.3f + _richleisureNum / _richleisureTotalNum));
}
return tmpNum;
}
return _relaxScore;
}
set
{
_relaxScore = value;
}
}
private int _relaxScore;
/// <summary>
/// 品质积分的得分情况
/// </summary>
public int QualityScore
{
get
{
if (GameModel.GetInstance.isPlayNet == false)
{
var tmpNum = 0;
if (_qualityTotalNum > 0)
{
tmpNum = (int)(_qualityNum * (1 + 0.3f + _qualityNum / _qualityTotalNum));
}
return tmpNum;
}
return _qualityScore;
}
set
{
_qualityScore = 0;
}
}
private int _qualityScore = 0;
/// <summary>
/// 慈善事业得分情况
/// </summary>
public int CharityScore
{
get
{
if (GameModel.GetInstance.isPlayNet == false)
{
var tmpNum = 0;
if (_charityTotalNum > 0)
{
tmpNum = (int)(_charityNum * (1 + 0.3f + _charityNum / _charityTotalNum));
}
return tmpNum;
}
return _charityScore;
}
set
{
_charityScore = value;
}
}
private int _charityScore;
#endregion
#region 超越财富
/// <summary>
/// 进修学习积分计算
/// </summary>
public int LearnScore
{
get
{
if (GameModel.GetInstance.isPlayNet == false)
{
int tmpNum = 0;
if (_learnTotalNum > 0)
{
tmpNum = (int)(_learnNum * (1 + 0.4f + _learnNum / _learnTotalNum));
}
return tmpNum;
}
return _learnScore;
}
set
{
_learnScore = value;
}
}
private int _learnScore = 0;
public int HealthScore
{
get
{
if (GameModel.GetInstance.isPlayNet == false)
{
int tmpNum = 0;
if (_healthTotalNum > 0)
{
tmpNum = (int)(_healthNum * (1 + 0.4f + _healthNum / _healthTotalNum));
}
return tmpNum;
}
return _healthScore;
}
set
{
_healthScore = value;
}
}
private int _healthScore=0;
/// <summary>
/// 失业分数计算
/// </summary>
public int UnemploymenyScore
{
get
{
if (GameModel.GetInstance.isPlayNet == false)
{
return (int)(_unemploymentNum * 2.4f);
}
return _unemployScore;
}
set
{
_unemployScore = value;
}
}
private int _unemployScore;
/// <summary>
/// 审计得分计算
/// </summary>
public int AuditScore
{
get
{
if (GameModel.GetInstance.isPlayNet == false)
{
int tmpNum = 0;
if (_auditTotalNum > 0)
{
tmpNum = (int)(_auditNum * (1 + 0.4f + _auditNum / _auditTotalNum));
}
return tmpNum;
}
return _auditScore;
}
set
{
_auditScore = value;
}
}
private int _auditScore = 0;
/// <summary>
/// 离婚得分计算
/// </summary>
public int DivorceScore
{
get
{
if(GameModel.GetInstance.isPlayNet==false)
{
int tmpNum = 0;
if (_divorceTotalNum > 0)
{
tmpNum = (int)(_divorceNum * (1 + 0.4f + _divorceNum / _divorceTotalNum));
}
return tmpNum;
}
return _divorceScore;
}
set
{
_divorceScore = value;
}
}
private int _divorceScore = 0;
/// <summary>
/// 金融风暴的得分计算
/// </summary>
public int LossMoneyScore
{
get
{
if (GameModel.GetInstance.isPlayNet == false)
{
int tmpNum = 0;
if (_moneyLossTotalNum > 0)
{
tmpNum = (int)(_moneyLoss * (1 + 0.4f + _moneyLoss / _moneyLossTotalNum));
}
return tmpNum;
}
return _lossMoneyScore;
}
set
{
_lossMoneyScore = value;
}
}
private int _lossMoneyScore = 0;
#endregion
/// <summary>
/// 总的得分数
/// </summary>
public int totoScore
{
get
{
if (GameModel.GetInstance.isPlayNet == false)
{
//超越财富
var eqIntegral = _charityNum * 1 + _childNum * 1 + _richleisureNum * 1 + _qualityNum * 1;
var spiritualIntegral = 20;
var adversityIntegral = _unemploymentNum * 1 + _auditNum * 1 + _divorceNum * 1;
var financialIntegral = _bigIntegral + _smallIntegral + _investmentIntegral + _settlementNum * 1;
int integral = eqIntegral * 20 + spiritualIntegral * 30 + adversityIntegral * 5 + financialIntegral * 40;
return integral;
}
return _totalScore;
}
set
{
_totalScore = value;
}
}
private int _totalScore = 0;
#region 游戏中遇到的次数
//运用财富
/// <summary>
/// 有钱有闲计数
/// </summary>
public int _richleisureNum = 0;
/// <summary>
/// The richleisure total number.遇到有钱有闲的总次数
/// </summary>
public int _richleisureTotalNum = 0;
/// <summary>
/// 品质生活计数
/// </summary>
public int _qualityNum = 0;
/// <summary>
/// The quality total number.品质生活的总次数
/// </summary>
public int _qualityTotalNum = 0;
/// <summary>
/// 生孩子计数
/// </summary>
public int _childNum;
/// <summary>
/// 慈善计数
/// </summary>
public int _charityNum;
/// <summary>
/// The charity total number. 慈善的总次数
/// </summary>
public float _charityTotalNum = 0;
//灵性指数
/// <summary>
/// 健康管理计数
/// </summary>
public int _healthNum;
/// <summary>
/// The health total number. 健康管理总的次数
/// </summary>
public float _healthTotalNum = 0;
/// <summary>
/// 学习进修计数
/// </summary>
public int _learnNum;
/// <summary>
/// The learn total number 进修学习总次数
/// </summary>
public float _learnTotalNum = 0;
//逆境指数
/// <summary>
///失业计数
/// </summary>
public int _unemploymentNum;
/// <summary>
///审计计数
/// </summary>
public int _auditNum;
/// <summary>
/// 遇到审计的总次数
/// </summary>
public float _auditTotalNum = 0;
/// <summary>
/// 离婚计数
/// </summary>
public int _divorceNum;
/// <summary>
/// The divorce total number.离婚的总次数
/// </summary>
public float _divorceTotalNum = 0;
/// <summary>
/// The money loss. 金融风暴次数
/// </summary>
public int _moneyLoss = 0;
/// <summary>
/// 左右遭遇金融风暴的次数
/// </summary>
public float _moneyLossTotalNum = 0;
//财商指数
/// <summary>
/// 大机会计数
/// </summary>
public int _bigOpportunitiesNum = 0;
/// <summary>
/// The big opportunities total number. 大机会总次数
/// </summary>
public float _bigOpportunitiesTotalNum = 0;
/// <summary>
/// 小机会计数
/// </summary>
public int _smallOpportunitiesNum;
/// <summary>
/// The small opportunities total number. 小机会总次数
/// </summary>
public float _smallOpportunitiesTotalNum = 0;
/// <summary>
/// 投资计数
/// </summary>
public int _investmentNum;
/// <summary>
/// The investment total number.投资总次数
/// </summary>
public float _investmentTotalNum = 0;
/// <summary>
/// 结算计数
/// </summary>
public int _settlementNum;
/// <summary>
/// The settle outer number. 外圈结账日数
/// </summary>
public int _settleOuterNum = 0;
/// <summary>
/// The settle inner number. 内圈结账日数
/// </summary>
public int _settleInnerNum = 0;
/// <summary>
/// The buy care number. 购买保险的次数
/// </summary>
public int _buyCareNum = 0;
/// <summary>
/// The sale nums. 成交的次数
/// </summary>
public int _saleNums = 0;
#endregion
/// <summary>
/// 管理财富
/// </summary>
//private int spiritualIntegral;
/// <summary>
/// 超越财富
/// </summary>
//private int adversityIntegral;
/// <summary>
/// 创造财富
/// </summary>
// private int financialIntegral;
/// <summary>
/// 运用财富
/// </summary>
// private int eqIntegral;
/// <summary>
/// 大机会积分
/// </summary>
public int _bigIntegral;
/// <summary>
/// 小机会积分
/// </summary>
public int _smallIntegral;
/// <summary>
/// 遇到风险的卡牌积分
/// </summary>
public int _riskIntegral;
/// <summary>
/// 外圈命运的积分
/// </summary>
public int _outerFateIntegral;
/// <summary>
/// 内圈有钱有闲积分
/// </summary>
public int _relaxIntegral;
/// <summary>
/// 投资积分
/// </summary>
public int _investmentIntegral;
/// <summary>
/// 品质生活的积分
/// </summary>
public int _qualityIntegral;
/// <summary>
/// 内圈命运卡牌积分
/// </summary>
public int _innerFateIntegral;
}
}
| 25.704718 | 132 | 0.379856 | [
"Apache-2.0"
] | rusmass/wealthland_client | arpg_prg/nativeclient_prg/Assets/Code/Client/PlayerInfo/SettlementData.cs | 17,708 | C# |
using Unity.Entities;
using Unity.Mathematics;
namespace Joystick
{
public struct CameraFollow : IComponentData
{
public Entity TargetToFollow;
public float2 DeadZone;
public float FollowSpeed;
}
}
| 18.153846 | 47 | 0.686441 | [
"MIT"
] | glauber-guimaraes/Run-Dino-Run | Assets/Samples/Project Tiny/0.15.3-preview/Joystick/Components/CameraFollow.cs | 238 | C# |
using FluentNHibernate.Mapping;
using QS.Test.TestDomain;
namespace QS.Test.TestDomainMapping.TestDomain
{
public class BusinessObjectTestEntityMap : ClassMap<BusinessObjectTestEntity>
{
public BusinessObjectTestEntityMap()
{
Id(x => x.Id);
}
}
}
| 18.642857 | 78 | 0.766284 | [
"Apache-2.0"
] | Art8m/QSProjects | QS.LibsTest/TestApp/HibernateMapping/BusinessObjectTestEntityMap.cs | 263 | C# |
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using amantini.davide._5h.PrimoEF;
namespace amantini.davide._5h.PrimoEF.Migrations
{
[DbContext(typeof(DbPersone))]
[Migration("20211015073036_InitialCreate")]
partial class InitialCreate
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "5.0.11");
modelBuilder.Entity("amantini.davide._5h.PrimoEF.Persona", b =>
{
b.Property<int>("PersonaID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Cognome")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<string>("Nome")
.HasColumnType("TEXT");
b.HasKey("PersonaID");
b.ToTable("Persone");
});
#pragma warning restore 612, 618
}
}
}
| 31.790698 | 76 | 0.554499 | [
"Apache-2.0"
] | DavideAmantini/PrimoEF | Migrations/20211015073036_InitialCreate.Designer.cs | 1,369 | C# |
using Playnite;
using Playnite.API;
using Playnite.App;
using Playnite.Common;
using Playnite.Common.System;
using Playnite.Database;
using Playnite.Metadata;
using Playnite.Plugins;
using Playnite.Scripting;
using Playnite.SDK;
using Playnite.SDK.Models;
using Playnite.SDK.Plugins;
using Playnite.Settings;
using PlayniteUI.Commands;
using PlayniteUI.Windows;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
namespace PlayniteUI.ViewModels
{
public class MainViewModel : ObservableObject, IDisposable
{
public static ILogger Logger = LogManager.GetLogger();
private static object gamesLock = new object();
protected bool ignoreCloseActions = false;
private readonly SynchronizationContext context;
public PlayniteAPI PlayniteApi { get; }
public ExtensionFactory Extensions { get; }
public IWindowFactory Window;
public IDialogsFactory Dialogs;
public IResourceProvider Resources;
public GameDatabase Database;
public GamesEditor GamesEditor;
public bool IsFullscreenView
{
get; protected set;
} = false;
private GameDetailsViewModel selectedGameDetails;
public GameDetailsViewModel SelectedGameDetails
{
get => selectedGameDetails;
set
{
selectedGameDetails = value;
OnPropertyChanged();
}
}
private GameViewEntry selectedGame;
public GameViewEntry SelectedGame
{
get => selectedGame;
set
{
if (value == selectedGame)
{
return;
}
SelectedGameDetails?.Dispose();
if (value == null)
{
SelectedGameDetails = null;
}
else
{
if (AppSettings.ViewSettings.GamesViewType == ViewType.List ||
(AppSettings.ViewSettings.GamesViewType == ViewType.Images && ShowGameSidebar))
{
SelectedGameDetails = new GameDetailsViewModel(value, AppSettings, GamesEditor, Dialogs, Resources);
}
else
{
SelectedGameDetails = null;
}
}
selectedGame = value;
OnPropertyChanged();
}
}
public IEnumerable<GameViewEntry> SelectedGames
{
get
{
if (selectedGamesBinder == null)
{
return null;
}
return selectedGamesBinder.Cast<GameViewEntry>();
}
}
private IList<object> selectedGamesBinder;
public IList<object> SelectedGamesBinder
{
get => selectedGamesBinder;
set
{
selectedGamesBinder = value;
OnPropertyChanged();
OnPropertyChanged(nameof(SelectedGames));
}
}
private GamesCollectionView gamesView;
public GamesCollectionView GamesView
{
get => gamesView;
set
{
gamesView = value;
OnPropertyChanged();
}
}
private List<ThirdPartyTool> thirdPartyTools;
public List<ThirdPartyTool> ThirdPartyTools
{
get => thirdPartyTools;
set
{
thirdPartyTools = value;
OnPropertyChanged();
}
}
private bool gameAdditionAllowed = true;
public bool GameAdditionAllowed
{
get => gameAdditionAllowed;
set
{
gameAdditionAllowed = value;
OnPropertyChanged();
}
}
private string progressStatus;
public string ProgressStatus
{
get => progressStatus;
set
{
progressStatus = value;
context.Post((a) => OnPropertyChanged(), null);
}
}
private double progressValue;
public double ProgressValue
{
get => progressValue;
set
{
progressValue = value;
context.Post((a) => OnPropertyChanged(), null);
}
}
private double progressTotal;
public double ProgressTotal
{
get => progressTotal;
set
{
progressTotal = value;
context.Post((a) => OnPropertyChanged(), null);
}
}
private bool progressVisible = false;
public bool ProgressVisible
{
get => progressVisible;
set
{
progressVisible = value;
context.Post((a) => OnPropertyChanged(), null);
}
}
private bool showGameSidebar = false;
public bool ShowGameSidebar
{
get => showGameSidebar;
set
{
if (value == true && SelectedGameDetails == null)
{
SelectedGameDetails = new GameDetailsViewModel(SelectedGame, AppSettings, GamesEditor, Dialogs, Resources);
}
showGameSidebar = value;
OnPropertyChanged();
}
}
private bool mainMenuOpened = false;
public bool MainMenuOpened
{
get => mainMenuOpened;
set
{
mainMenuOpened = value;
OnPropertyChanged();
}
}
private bool searchOpened = false;
public bool SearchOpened
{
get => searchOpened;
set
{
searchOpened = value;
OnPropertyChanged();
}
}
private Visibility visibility = Visibility.Visible;
public Visibility Visibility
{
get => visibility;
set
{
visibility = value;
OnPropertyChanged();
}
}
private WindowState windowState = WindowState.Normal;
public WindowState WindowState
{
get => windowState;
set
{
if (value == WindowState.Minimized && AppSettings.MinimizeToTray && AppSettings.EnableTray)
{
Visibility = Visibility.Hidden;
}
windowState = value;
OnPropertyChanged();
}
}
private PlayniteSettings appSettings;
public PlayniteSettings AppSettings
{
get => appSettings;
private set
{
appSettings = value;
OnPropertyChanged();
}
}
private DatabaseStats gamesStats;
public DatabaseStats GamesStats
{
get => gamesStats;
private set
{
gamesStats = value;
OnPropertyChanged();
}
}
public DatabaseFilter DatabaseFilters { get; set; }
#region General Commands
public RelayCommand<object> OpenFilterPanelCommand { get; private set; }
public RelayCommand<object> CloseFilterPanelCommand { get; private set; }
public RelayCommand<object> OpenMainMenuCommand { get; private set; }
public RelayCommand<object> CloseMainMenuCommand { get; private set; }
public RelayCommand<ThirdPartyTool> ThirdPartyToolOpenCommand { get; private set; }
public RelayCommand<object> UpdateGamesCommand { get; private set; }
public RelayCommand<object> OpenSteamFriendsCommand { get; private set; }
public RelayCommand<object> ReportIssueCommand { get; private set; }
public RelayCommand<object> ShutdownCommand { get; private set; }
public RelayCommand<object> ShowWindowCommand { get; private set; }
public RelayCommand<CancelEventArgs> WindowClosingCommand { get; private set; }
public RelayCommand<DragEventArgs> FileDroppedCommand { get; private set; }
public RelayCommand<object> OpenAboutCommand { get; private set; }
public RelayCommand<object> OpenPlatformsCommand { get; private set; }
public RelayCommand<object> OpenSettingsCommand { get; private set; }
public RelayCommand<object> AddCustomGameCommand { get; private set; }
public RelayCommand<object> AddInstalledGamesCommand { get; private set; }
public RelayCommand<object> AddEmulatedGamesCommand { get; private set; }
public RelayCommand<bool> OpenThemeTesterCommand { get; private set; }
public RelayCommand<object> OpenFullScreenCommand { get; private set; }
public RelayCommand<object> CancelProgressCommand { get; private set; }
public RelayCommand<object> ClearMessagesCommand { get; private set; }
public RelayCommand<object> DownloadMetadataCommand { get; private set; }
public RelayCommand<object> ClearFiltersCommand { get; private set; }
public RelayCommand<object> RemoveGameSelectionCommand { get; private set; }
public RelayCommand<ExtensionFunction> InvokeExtensionFunctionCommand { get; private set; }
public RelayCommand<object> ReloadScriptsCommand { get; private set; }
public RelayCommand<GameViewEntry> ShowGameSideBarCommand { get; private set; }
public RelayCommand<object> CloseGameSideBarCommand { get; private set; }
public RelayCommand<object> OpenSearchCommand { get; private set; }
public RelayCommand<object> ToggleFilterPanelCommand { get; private set; }
public RelayCommand<object> CheckForUpdateCommand { get; private set; }
public RelayCommand<ILibraryPlugin> UpdateLibraryCommand { get; private set; }
#endregion
#region Game Commands
public RelayCommand<Game> StartGameCommand { get; private set; }
public RelayCommand<Game> InstallGameCommand { get; private set; }
public RelayCommand<Game> UninstallGameCommand { get; private set; }
public RelayCommand<object> StartSelectedGameCommand { get; private set; }
public RelayCommand<object> EditSelectedGamesCommand { get; private set; }
public RelayCommand<object> RemoveSelectedGamesCommand { get; private set; }
public RelayCommand<Game> EditGameCommand { get; private set; }
public RelayCommand<IEnumerable<Game>> EditGamesCommand { get; private set; }
public RelayCommand<Game> OpenGameLocationCommand { get; private set; }
public RelayCommand<Game> CreateGameShortcutCommand { get; private set; }
public RelayCommand<Game> ToggleFavoritesCommand { get; private set; }
public RelayCommand<Game> ToggleVisibilityCommand { get; private set; }
public RelayCommand<IEnumerable<Game>> SetAsFavoritesCommand { get; private set; }
public RelayCommand<IEnumerable<Game>> RemoveAsFavoritesCommand { get; private set; }
public RelayCommand<IEnumerable<Game>> SetAsHiddensCommand { get; private set; }
public RelayCommand<IEnumerable<Game>> RemoveAsHiddensCommand { get; private set; }
public RelayCommand<Game> AssignGameCategoryCommand { get; private set; }
public RelayCommand<IEnumerable<Game>> AssignGamesCategoryCommand { get; private set; }
public RelayCommand<Game> RemoveGameCommand { get; private set; }
public RelayCommand<IEnumerable<Game>> RemoveGamesCommand { get; private set; }
#endregion
public MainViewModel(
GameDatabase database,
IWindowFactory window,
IDialogsFactory dialogs,
IResourceProvider resources,
PlayniteSettings settings,
GamesEditor gamesEditor,
PlayniteAPI playniteApi,
ExtensionFactory extensions)
{
context = SynchronizationContext.Current;
Window = window;
Dialogs = dialogs;
Resources = resources;
Database = database;
GamesEditor = gamesEditor;
AppSettings = settings;
PlayniteApi = playniteApi;
Extensions = extensions;
DatabaseFilters = new DatabaseFilter(database, extensions, AppSettings.FilterSettings);
try
{
ThirdPartyTools = ThirdPartyToolsList.GetTools(Extensions.LibraryPlugins?.Select(a => a.Value.Plugin));
}
catch (Exception e) when (!PlayniteEnvironment.ThrowAllErrors)
{
Logger.Error(e, "Failed to load third party tools.");
}
AppSettings.PropertyChanged += AppSettings_PropertyChanged;
AppSettings.FilterSettings.PropertyChanged += FilterSettings_PropertyChanged;
AppSettings.ViewSettings.PropertyChanged += ViewSettings_PropertyChanged;
GamesStats = new DatabaseStats(database);
InitializeCommands();
}
private void InitializeCommands()
{
OpenSearchCommand = new RelayCommand<object>((game) =>
{
SearchOpened = true;
}, new KeyGesture(Key.F, ModifierKeys.Control));
ToggleFilterPanelCommand = new RelayCommand<object>((game) =>
{
AppSettings.FilterPanelVisible = !AppSettings.FilterPanelVisible;
}, new KeyGesture(Key.G, ModifierKeys.Control));
OpenFilterPanelCommand = new RelayCommand<object>((game) =>
{
AppSettings.FilterPanelVisible = true;
});
CloseFilterPanelCommand = new RelayCommand<object>((game) =>
{
AppSettings.FilterPanelVisible = false;
});
OpenMainMenuCommand = new RelayCommand<object>((game) =>
{
MainMenuOpened = true;
});
CloseMainMenuCommand = new RelayCommand<object>((game) =>
{
MainMenuOpened = false;
});
ThirdPartyToolOpenCommand = new RelayCommand<ThirdPartyTool>((tool) =>
{
MainMenuOpened = false;
StartThirdPartyTool(tool);
});
UpdateGamesCommand = new RelayCommand<object>((a) =>
{
MainMenuOpened = false;
UpdateDatabase(true);
}, (a) => GameAdditionAllowed || !Database.IsOpen,
new KeyGesture(Key.F5));
OpenSteamFriendsCommand = new RelayCommand<object>((a) =>
{
OpenSteamFriends();
});
ReportIssueCommand = new RelayCommand<object>((a) =>
{
MainMenuOpened = false;
ReportIssue();
});
ShutdownCommand = new RelayCommand<object>((a) =>
{
MainMenuOpened = false;
if (GlobalTaskHandler.IsActive)
{
if (Dialogs.ShowMessage(
Resources.FindString("LOCBackgroundProgressCancelAskExit"),
Resources.FindString("LOCCrashClosePlaynite"),
MessageBoxButton.YesNo) != MessageBoxResult.Yes)
{
return;
}
}
ignoreCloseActions = true;
ShutdownApp();
}, new KeyGesture(Key.Q, ModifierKeys.Alt));
ShowWindowCommand = new RelayCommand<object>((a) =>
{
RestoreWindow();
});
WindowClosingCommand = new RelayCommand<CancelEventArgs>((args) =>
{
OnClosing(args);
});
FileDroppedCommand = new RelayCommand<DragEventArgs>((args) =>
{
OnFileDropped(args);
});
OpenAboutCommand = new RelayCommand<object>((a) =>
{
MainMenuOpened = false;
OpenAboutWindow(new AboutViewModel(AboutWindowFactory.Instance, Dialogs, Resources));
}, new KeyGesture(Key.F1));
OpenPlatformsCommand = new RelayCommand<object>((a) =>
{
MainMenuOpened = false;
ConfigurePlatforms(
new PlatformsViewModel(Database,
PlatformsWindowFactory.Instance,
Dialogs,
Resources));
}, (a) => Database.IsOpen,
new KeyGesture(Key.T, ModifierKeys.Control));
AddCustomGameCommand = new RelayCommand<object>((a) =>
{
MainMenuOpened = false;
AddCustomGame(GameEditWindowFactory.Instance);
}, (a) => Database.IsOpen,
new KeyGesture(Key.Insert));
AddInstalledGamesCommand = new RelayCommand<object>((a) =>
{
MainMenuOpened = false;
ImportInstalledGames(
new InstalledGamesViewModel(
InstalledGamesWindowFactory.Instance,
Dialogs), null);
}, (a) => Database.IsOpen);
AddEmulatedGamesCommand = new RelayCommand<object>((a) =>
{
MainMenuOpened = false;
ImportEmulatedGames(
new EmulatorImportViewModel(Database,
EmulatorImportViewModel.DialogType.GameImport,
EmulatorImportWindowFactory.Instance,
Dialogs,
Resources));
}, (a) => Database.IsOpen,
new KeyGesture(Key.E, ModifierKeys.Control));
OpenThemeTesterCommand = new RelayCommand<bool>((fullscreen) =>
{
var window = new ThemeTesterWindow();
window.SkinType = fullscreen ? ThemeTesterWindow.SourceType.Fullscreen : ThemeTesterWindow.SourceType.Normal;
window.Show();
}, new KeyGesture(Key.F8));
OpenFullScreenCommand = new RelayCommand<object>((a) =>
{
OpenFullScreen();
}, new KeyGesture(Key.F11));
CancelProgressCommand = new RelayCommand<object>((a) =>
{
CancelProgress();
}, (a) => !GlobalTaskHandler.CancelToken.IsCancellationRequested);
ClearMessagesCommand = new RelayCommand<object>((a) =>
{
ClearMessages();
}, (a) => PlayniteApi.Notifications.Count > 0);
DownloadMetadataCommand = new RelayCommand<object>((a) =>
{
MainMenuOpened = false;
DownloadMetadata(new MetadataDownloadViewModel(MetadataDownloadWindowFactory.Instance));
}, (a) => GameAdditionAllowed,
new KeyGesture(Key.D, ModifierKeys.Control));
ClearFiltersCommand = new RelayCommand<object>((a) =>
{
ClearFilters();
});
CheckForUpdateCommand = new RelayCommand<object>((a) =>
{
MainMenuOpened = false;
CheckForUpdate();
});
UpdateLibraryCommand = new RelayCommand<ILibraryPlugin>((a) =>
{
MainMenuOpened = false;
UpdateLibrary(a);
}, (a) => GameAdditionAllowed);
RemoveGameSelectionCommand = new RelayCommand<object>((a) =>
{
RemoveGameSelection();
});
InvokeExtensionFunctionCommand = new RelayCommand<ExtensionFunction>((f) =>
{
MainMenuOpened = false;
if (!Extensions.InvokeExtension(f, out var error))
{
Dialogs.ShowMessage(
Resources.FindString("LOCScriptExecutionError") + "\n\n" + error,
Resources.FindString("LOCScriptError"),
MessageBoxButton.OK, MessageBoxImage.Error);
}
});
ReloadScriptsCommand = new RelayCommand<object>((f) =>
{
MainMenuOpened = false;
Extensions.LoadScripts(PlayniteApi, AppSettings.DisabledPlugins);
}, new KeyGesture(Key.F12));
ShowGameSideBarCommand = new RelayCommand<GameViewEntry>((f) =>
{
SelectedGame = f;
ShowGameSidebar = true;
});
CloseGameSideBarCommand = new RelayCommand<object>((f) =>
{
ShowGameSidebar = false;
});
OpenSettingsCommand = new RelayCommand<object>((a) =>
{
MainMenuOpened = false;
OpenSettings(
new SettingsViewModel(Database,
AppSettings,
SettingsWindowFactory.Instance,
Dialogs,
Resources,
Extensions));
}, new KeyGesture(Key.F4));
StartGameCommand = new RelayCommand<Game>((game) =>
{
if (game != null)
{
GamesEditor.PlayGame(game);
}
else if (SelectedGame != null)
{
GamesEditor.PlayGame(SelectedGame.Game);
}
});
InstallGameCommand = new RelayCommand<Game>((game) =>
{
if (game != null)
{
GamesEditor.InstallGame(game);
}
else if (SelectedGame != null)
{
GamesEditor.InstallGame(SelectedGame.Game);
}
});
UninstallGameCommand = new RelayCommand<Game>((game) =>
{
if (game != null)
{
GamesEditor.UnInstallGame(game);
}
else if (SelectedGame != null)
{
GamesEditor.UnInstallGame(SelectedGame.Game);
}
});
EditSelectedGamesCommand = new RelayCommand<object>((a) =>
{
if (SelectedGames?.Count() > 1)
{
GamesEditor.EditGames(SelectedGames.Select(g => g.Game).ToList());
}
else
{
GamesEditor.EditGame(SelectedGame.Game);
}
},
(a) => SelectedGame != null,
new KeyGesture(Key.F3));
StartSelectedGameCommand = new RelayCommand<object>((a) =>
{
GamesEditor.PlayGame(SelectedGame.Game);
},
(a) => SelectedGames?.Count() == 1,
new KeyGesture(Key.Enter));
RemoveSelectedGamesCommand = new RelayCommand<object>((a) =>
{
if (SelectedGames?.Count() > 1)
{
GamesEditor.RemoveGames(SelectedGames.Select(g => g.Game).ToList());
}
else
{
GamesEditor.RemoveGame(SelectedGame.Game);
}
},
(a) => SelectedGame != null,
new KeyGesture(Key.Delete));
EditGameCommand = new RelayCommand<Game>((a) =>
{
if (GamesEditor.EditGame(a) == true)
{
SelectedGame = GamesView.Items.FirstOrDefault(g => g.Id == a.Id);
}
});
EditGamesCommand = new RelayCommand<IEnumerable<Game>>((a) =>
{
GamesEditor.EditGames(a.ToList());
});
OpenGameLocationCommand = new RelayCommand<Game>((a) =>
{
GamesEditor.OpenGameLocation(a);
});
CreateGameShortcutCommand = new RelayCommand<Game>((a) =>
{
GamesEditor.CreateShortcut(a);
});
ToggleFavoritesCommand = new RelayCommand<Game>((a) =>
{
GamesEditor.ToggleFavoriteGame(a);
});
ToggleVisibilityCommand = new RelayCommand<Game>((a) =>
{
GamesEditor.ToggleHideGame(a);
});
AssignGameCategoryCommand = new RelayCommand<Game>((a) =>
{
if (GamesEditor.SetGameCategories(a) == true)
{
SelectedGame = GamesView.Items.FirstOrDefault(g => g.Id == a.Id);
}
});
AssignGamesCategoryCommand = new RelayCommand<IEnumerable<Game>>((a) =>
{
GamesEditor.SetGamesCategories(a.ToList());
});
RemoveGameCommand = new RelayCommand<Game>((a) =>
{
GamesEditor.RemoveGame(a);
},
new KeyGesture(Key.Delete));
RemoveGamesCommand = new RelayCommand<IEnumerable<Game>>((a) =>
{
GamesEditor.RemoveGames(a.ToList());
},
new KeyGesture(Key.Delete));
SetAsFavoritesCommand = new RelayCommand<IEnumerable<Game>>((a) =>
{
GamesEditor.SetFavoriteGames(a.ToList(), true);
});
RemoveAsFavoritesCommand = new RelayCommand<IEnumerable<Game>>((a) =>
{
GamesEditor.SetFavoriteGames(a.ToList(), false);
});
SetAsHiddensCommand = new RelayCommand<IEnumerable<Game>>((a) =>
{
GamesEditor.SetHideGames(a.ToList(), true);
});
RemoveAsHiddensCommand = new RelayCommand<IEnumerable<Game>>((a) =>
{
GamesEditor.SetHideGames(a.ToList(), false);
});
}
private void ViewSettings_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(AppSettings.ViewSettings.GamesViewType) &&
AppSettings.ViewSettings.GamesViewType == ViewType.Images &&
ShowGameSidebar &&
SelectedGameDetails == null)
{
SelectedGameDetails = new GameDetailsViewModel(SelectedGame, AppSettings, GamesEditor, Dialogs, Resources);
}
}
private void FilterSettings_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName != nameof(AppSettings.FilterSettings.Active))
{
AppSettings.SaveSettings();
if (e.PropertyName != nameof(AppSettings.FilterSettings.Name) && e.PropertyName != nameof(AppSettings.FilterSettings.SearchActive))
{
AppSettings.FilterPanelVisible = true;
}
}
}
private void AppSettings_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(AppSettings.Language))
{
Localization.SetLanguage(AppSettings.Language);
}
AppSettings.SaveSettings();
}
public void StartThirdPartyTool(ThirdPartyTool tool)
{
try
{
tool.Start();
}
catch (Exception e) when (!PlayniteEnvironment.ThrowAllErrors)
{
Logger.Error(e, "Failed to start 3rd party tool.");
Dialogs.ShowErrorMessage(Resources.FindString("LOCAppStartupError") + "\n\n" + e.Message, Resources.FindString("LOCStartupError"));
}
}
public void RemoveGameSelection()
{
SelectedGame = null;
SelectedGamesBinder = null;
}
public void OpenSteamFriends()
{
try
{
ProcessStarter.StartUrl(@"steam://open/friends");
}
catch (Exception e) when (!PlayniteEnvironment.ThrowAllErrors)
{
Logger.Error(e, "Failed to open Steam friends.");
}
}
public void ReportIssue()
{
try
{
ProcessStarter.StartUrl(@"https://github.com/JosefNemec/Playnite/issues/new");
}
catch (Exception e) when (!PlayniteEnvironment.ThrowAllErrors)
{
Logger.Error(e, "Failed to open report issue url.");
}
}
public void ShutdownApp()
{
App.CurrentApp.Quit();
}
protected void InitializeView()
{
if (GameDatabase.GetMigrationRequired(AppSettings.DatabasePath))
{
var migrationProgress = new ProgressViewViewModel(new ProgressWindowFactory(),
() =>
{
if (AppSettings.DatabasePath.EndsWith(".db", StringComparison.OrdinalIgnoreCase))
{
var newDbPath = GameDatabase.GetMigratedDbPath(AppSettings.DatabasePath);
var newResolvedDbPath = GameDatabase.GetFullDbPath(newDbPath);
if (Directory.Exists(newResolvedDbPath))
{
newDbPath += "_db";
newResolvedDbPath += "_db";
}
if (!File.Exists(AppSettings.DatabasePath))
{
AppSettings.DatabasePath = newDbPath;
}
else
{
var dbSize = new FileInfo(AppSettings.DatabasePath).Length;
if (FileSystem.GetFreeSpace(newResolvedDbPath) < dbSize)
{
throw new NoDiskSpaceException(dbSize);
}
GameDatabase.MigrateDatabase(AppSettings.DatabasePath);
GameDatabase.MigrateToNewFormat(AppSettings.DatabasePath, newResolvedDbPath);
FileSystem.DeleteFile(AppSettings.DatabasePath);
AppSettings.DatabasePath = newDbPath;
}
}
else
{
// Do migration of new format when needed
}
}, Resources.FindString("LOCDBUpgradeProgress"));
if (migrationProgress.ActivateProgress() != true)
{
Logger.Error(migrationProgress.FailException, "Failed to migrate database to new version.");
var message = Resources.FindString("LOCDBUpgradeFail");
if (migrationProgress.FailException is NoDiskSpaceException exc)
{
message = string.Format(Resources.FindString("LOCDBUpgradeEmptySpaceFail"), Units.BytesToMegaBytes(exc.RequiredSpace));
}
Dialogs.ShowErrorMessage(message, "");
GameAdditionAllowed = false;
return;
}
}
var openProgress = new ProgressViewViewModel(new ProgressWindowFactory(),
() =>
{
if (!Database.IsOpen)
{
Database.SetDatabasePath(AppSettings.DatabasePath);
Database.OpenDatabase();
}
}, Resources.FindString("LOCOpeningDatabase"));
if (openProgress.ActivateProgress() != true)
{
Logger.Error(openProgress.FailException, "Failed to open library database.");
var message = Resources.FindString("LOCDatabaseOpenError") + $"\n{openProgress.FailException.Message}";
Dialogs.ShowErrorMessage(message, "");
GameAdditionAllowed = false;
return;
}
GamesView = new GamesCollectionView(Database, AppSettings, IsFullscreenView, Extensions);
BindingOperations.EnableCollectionSynchronization(GamesView.Items, gamesLock);
if (GamesView.CollectionView.Count > 0)
{
SelectGame((GamesView.CollectionView.GetItemAt(0) as GameViewEntry).Id);
}
else
{
SelectedGame = null;
}
try
{
GamesEditor.UpdateJumpList();
}
catch (Exception exc)
{
Logger.Error(exc, "Failed to set update JumpList data: ");
}
}
public async void UpdateDatabase(bool updateLibrary)
{
await UpdateDatabase(updateLibrary, true);
}
public async Task UpdateDatabase(bool updateLibrary, bool metaForNewGames)
{
if (!Database.IsOpen)
{
Logger.Error("Cannot load new games, database is not loaded.");
Dialogs.ShowErrorMessage(Resources.FindString("LOCDatabaseNotOpenedError"), Resources.FindString("LOCDatabaseErroTitle"));
return;
}
if (GlobalTaskHandler.ProgressTask != null && GlobalTaskHandler.ProgressTask.Status == TaskStatus.Running)
{
GlobalTaskHandler.CancelToken.Cancel();
await GlobalTaskHandler.ProgressTask;
}
GameAdditionAllowed = false;
try
{
if (!updateLibrary)
{
return;
}
GlobalTaskHandler.CancelToken = new CancellationTokenSource();
GlobalTaskHandler.ProgressTask = Task.Run(async () =>
{
var addedGames = new List<Game>();
ProgressVisible = true;
ProgressValue = 0;
ProgressTotal = 1;
foreach (var pluginId in Extensions.LibraryPlugins.Keys)
{
var plugin = Extensions.LibraryPlugins[pluginId];
Logger.Info($"Importing games from {plugin.Plugin.Name} plugin.");
ProgressStatus = string.Format(Resources.FindString("LOCProgressImportinGames"), plugin.Plugin.Name);
try
{
using (Database.BufferedUpdate())
{
addedGames.AddRange(GameLibrary.ImportGames(plugin.Plugin, Database, AppSettings.ForcePlayTimeSync));
}
RemoveMessage($"{plugin.Plugin.Id} - download");
}
catch (Exception e) when (!PlayniteEnvironment.ThrowAllErrors)
{
Logger.Error(e, $"Failed to import games from plugin: {plugin.Plugin.Name}");
AddMessage(new NotificationMessage(
$"{plugin.Plugin.Id} - download",
string.Format(Resources.FindString("LOCLibraryImportError"), plugin.Plugin.Name) + $"\n{e.Message}",
NotificationType.Error,
null));
}
}
ProgressStatus = Resources.FindString("LOCProgressLibImportFinish");
await Task.Delay(500);
if (addedGames.Any() && metaForNewGames && AppSettings.DownloadMetadataOnImport)
{
Logger.Info($"Downloading metadata for {addedGames.Count} new games.");
ProgressValue = 0;
ProgressTotal = addedGames.Count;
ProgressStatus = Resources.FindString("LOCProgressMetadata");
var metaSettings = new MetadataDownloaderSettings();
metaSettings.ConfigureFields(MetadataSource.StoreOverIGDB, true);
metaSettings.CoverImage.Source = MetadataSource.IGDBOverStore;
metaSettings.Name = new MetadataFieldSettings(true, MetadataSource.Store);
using (var downloader = new MetadataDownloader(Database, Extensions.LibraryPlugins.Select(a => a.Value.Plugin)))
{
downloader.DownloadMetadataGroupedAsync(addedGames, metaSettings,
(g, i, t) =>
{
ProgressValue = i + 1;
ProgressStatus = Resources.FindString("LOCProgressMetadata") + $" [{ProgressValue}/{ProgressTotal}]";
},
GlobalTaskHandler.CancelToken).Wait();
}
}
});
await GlobalTaskHandler.ProgressTask;
}
finally
{
GameAdditionAllowed = true;
ProgressVisible = false;
}
}
public async Task DownloadMetadata(MetadataDownloaderSettings settings, List<Game> games)
{
GameAdditionAllowed = false;
try
{
if (GlobalTaskHandler.ProgressTask != null && GlobalTaskHandler.ProgressTask.Status == TaskStatus.Running)
{
GlobalTaskHandler.CancelToken.Cancel();
await GlobalTaskHandler.ProgressTask;
}
GlobalTaskHandler.CancelToken = new CancellationTokenSource();
ProgressVisible = true;
ProgressValue = 0;
ProgressTotal = games.Count;
ProgressStatus = Resources.FindString("LOCProgressMetadata");
using (var downloader = new MetadataDownloader(Database, Extensions.LibraryPlugins.Select(a => a.Value.Plugin)))
{
GlobalTaskHandler.ProgressTask =
downloader.DownloadMetadataGroupedAsync(games, settings,
(g, i, t) =>
{
ProgressValue = i + 1;
ProgressStatus = Resources.FindString("LOCProgressMetadata") + $" [{ProgressValue}/{ProgressTotal}]";
},
GlobalTaskHandler.CancelToken);
await GlobalTaskHandler.ProgressTask;
}
}
finally
{
ProgressVisible = false;
GameAdditionAllowed = true;
}
}
public async Task DownloadMetadata(MetadataDownloaderSettings settings)
{
List<Game> games = null;
if (settings.GamesSource == MetadataGamesSource.Selected)
{
if (SelectedGames != null && SelectedGames.Count() > 0)
{
games = SelectedGames.Select(a => a.Game).Distinct().ToList();
}
else
{
return;
}
}
else if (settings.GamesSource == MetadataGamesSource.AllFromDB)
{
games = Database.Games.ToList();
}
else if (settings.GamesSource == MetadataGamesSource.Filtered)
{
games = GamesView.CollectionView.Cast<GameViewEntry>().Select(a => a.Game).Distinct().ToList();
}
await DownloadMetadata(settings, games);
}
public async void DownloadMetadata(MetadataDownloadViewModel model)
{
if (model.OpenView(MetadataDownloadViewModel.ViewMode.Manual) != true)
{
return;
}
await DownloadMetadata(model.Settings);
}
public void RestoreWindow()
{
Window.RestoreWindow();
}
public void AddCustomGame(IWindowFactory window)
{
var newGame = new Game()
{
Name = "New Game",
IsInstalled = true
};
Database.Games.Add(newGame);
if (GamesEditor.EditGame(newGame) == true)
{
var viewEntry = GamesView.Items.First(a => a.Game.GameId == newGame.GameId);
SelectedGame = viewEntry;
}
else
{
Database.Games.Remove(newGame);
}
}
public async void ImportInstalledGames(InstalledGamesViewModel model, string path)
{
if (model.OpenView(path) == true && model.Games?.Any() == true)
{
var addedGames = InstalledGamesViewModel.AddImportableGamesToDb(model.Games, Database);
if (AppSettings.DownloadMetadataOnImport)
{
if (!GlobalTaskHandler.IsActive)
{
var settings = new MetadataDownloaderSettings();
settings.ConfigureFields(MetadataSource.IGDB, true);
await DownloadMetadata(settings, addedGames);
}
else
{
Logger.Warn("Skipping metadata download for manually added games, some global task is already in progress.");
}
}
}
}
public async void ImportEmulatedGames(EmulatorImportViewModel model)
{
if (model.OpenView() == true && model.ImportedGames?.Any() == true)
{
if (AppSettings.DownloadMetadataOnImport)
{
if (!GlobalTaskHandler.IsActive)
{
var settings = new MetadataDownloaderSettings();
settings.ConfigureFields(MetadataSource.IGDB, true);
await DownloadMetadata(settings, model.ImportedGames);
}
else
{
Logger.Warn("Skipping metadata download for manually added emulated games, some global task is already in progress.");
}
}
}
}
public void OpenAboutWindow(AboutViewModel model)
{
model.OpenView();
}
public void OpenSettings(SettingsViewModel model)
{
var currentSkin = Themes.CurrentTheme;
var currentColor = Themes.CurrentColor;
if (model.OpenView() == true)
{
if (model.ProviderIntegrationChanged)
{
UpdateDatabase(true);
}
}
else
{
if (Themes.CurrentTheme != currentSkin || Themes.CurrentColor != currentColor)
{
Themes.ApplyTheme(currentSkin, currentColor);
}
}
}
public void ConfigurePlatforms(PlatformsViewModel model)
{
model.OpenView();
}
public void SelectGame(Guid id)
{
var viewEntry = GamesView.Items.FirstOrDefault(a => a.Game.Id == id);
SelectedGame = viewEntry;
}
protected virtual void OnClosing(CancelEventArgs args)
{
if (ignoreCloseActions)
{
return;
}
if (AppSettings.CloseToTray && AppSettings.EnableTray)
{
Visibility = Visibility.Hidden;
args.Cancel = true;
}
else
{
if (GlobalTaskHandler.IsActive)
{
if (Dialogs.ShowMessage(
Resources.FindString("LOCBackgroundProgressCancelAskExit"),
Resources.FindString("LOCCrashClosePlaynite"),
MessageBoxButton.YesNo) != MessageBoxResult.Yes)
{
args.Cancel = true;
return;
}
}
ShutdownApp();
}
}
private void OnFileDropped(DragEventArgs args)
{
if (args.Data.GetDataPresent(DataFormats.FileDrop))
{
var files = (string[])args.Data.GetData(DataFormats.FileDrop);
if (files.Count() == 1)
{
Window.BringToForeground();
var path = files[0];
if (File.Exists(path))
{
// Other file types to be added in #501
if (!(new List<string>() { ".exe", ".lnk" }).Contains(Path.GetExtension(path).ToLower()))
{
return;
}
var game = GameExtensions.GetGameFromExecutable(path);
var exePath = game.GetRawExecutablePath();
if (!string.IsNullOrEmpty(exePath))
{
var ico = IconExtension.ExtractIconFromExe(exePath, true);
if (ico != null)
{
var iconName = Guid.NewGuid().ToString() + ".png";
game.Icon = Database.AddFile(iconName, ico.ToByteArray(System.Drawing.Imaging.ImageFormat.Png), game.Id);
}
}
Database.Games.Add(game);
Database.AssignPcPlatform(game);
GamesEditor.EditGame(game);
SelectGame(game.Id);
}
else if (Directory.Exists(path))
{
var instModel = new InstalledGamesViewModel(
InstalledGamesWindowFactory.Instance,
Dialogs);
ImportInstalledGames(instModel, path);
}
}
}
}
public void AddMessage(NotificationMessage message)
{
PlayniteApi.Notifications.Add(message);
}
public void RemoveMessage(string id)
{
PlayniteApi.Notifications.Remove(id);
}
public void ClearMessages()
{
PlayniteApi.Notifications.RemoveAll();
}
public void CheckForUpdate()
{
try
{
var updater = new Updater(App.CurrentApp);
if (updater.IsUpdateAvailable)
{
var model = new UpdateViewModel(updater, UpdateWindowFactory.Instance, Resources, Dialogs);
model.OpenView();
}
else
{
Dialogs.ShowMessage(Resources.FindString("LOCUpdateNoNewUpdateMessage"), string.Empty);
}
}
catch (Exception e) when (!PlayniteEnvironment.ThrowAllErrors)
{
Logger.Error(e, "Failed to check for update.");
Dialogs.ShowErrorMessage(Resources.FindString("LOCUpdateCheckFailMessage"), Resources.FindString("LOCUpdateError"));
}
}
public async void UpdateLibrary(ILibraryPlugin library)
{
GameAdditionAllowed = false;
try
{
GlobalTaskHandler.CancelToken = new CancellationTokenSource();
GlobalTaskHandler.ProgressTask = Task.Run(async () =>
{
var addedGames = new List<Game>();
ProgressVisible = true;
ProgressValue = 0;
ProgressTotal = 1;
ProgressStatus = string.Format(Resources.FindString("LOCProgressImportinGames"), library.Name);
try
{
using (Database.BufferedUpdate())
{
addedGames.AddRange(GameLibrary.ImportGames(library, Database, AppSettings.ForcePlayTimeSync));
}
RemoveMessage($"{library.Id} - download");
}
catch (Exception e) when (!PlayniteEnvironment.ThrowAllErrors)
{
Logger.Error(e, $"Failed to import games from plugin: {library.Name}");
AddMessage(new NotificationMessage(
$"{library.Id} - download",
string.Format(Resources.FindString("LOCLibraryImportError"), library.Name) + $"\n{e.Message}",
NotificationType.Error,
null));
}
ProgressStatus = Resources.FindString("LOCProgressLibImportFinish");
await Task.Delay(500);
if (addedGames.Any() && AppSettings.DownloadMetadataOnImport)
{
Logger.Info($"Downloading metadata for {addedGames.Count} new games.");
ProgressValue = 0;
ProgressTotal = addedGames.Count;
ProgressStatus = Resources.FindString("LOCProgressMetadata");
var metaSettings = new MetadataDownloaderSettings();
metaSettings.ConfigureFields(MetadataSource.StoreOverIGDB, true);
metaSettings.CoverImage.Source = MetadataSource.IGDBOverStore;
metaSettings.Name = new MetadataFieldSettings(true, MetadataSource.Store);
using (var downloader = new MetadataDownloader(Database, Extensions.LibraryPlugins.Select(a => a.Value.Plugin)))
{
downloader.DownloadMetadataGroupedAsync(addedGames, metaSettings,
(g, i, t) =>
{
ProgressValue = i + 1;
ProgressStatus = Resources.FindString("LOCProgressMetadata") + $" [{ProgressValue}/{ProgressTotal}]";
},
GlobalTaskHandler.CancelToken).Wait();
}
}
});
await GlobalTaskHandler.ProgressTask;
}
finally
{
GameAdditionAllowed = true;
ProgressVisible = false;
}
}
public void OpenFullScreen()
{
if (GlobalTaskHandler.IsActive)
{
ProgressViewViewModel.ActivateProgress(() => GlobalTaskHandler.CancelAndWait(), Resources.FindString("LOCOpeningFullscreenModeMessage"));
}
CloseView();
App.CurrentApp.OpenFullscreenView(false);
}
public void OpenView()
{
Window.Show(this);
if (AppSettings.StartMinimized)
{
WindowState = WindowState.Minimized;
}
else
{
Window.BringToForeground();
}
InitializeView();
}
public virtual void CloseView()
{
ignoreCloseActions = true;
Window.Close();
ignoreCloseActions = false;
Dispose();
}
public async void CancelProgress()
{
await GlobalTaskHandler.CancelAndWaitAsync();
}
public virtual void ClearFilters()
{
AppSettings.FilterSettings.ClearFilters();
}
public virtual void Dispose()
{
GamesView?.Dispose();
GamesStats?.Dispose();
AppSettings.PropertyChanged -= AppSettings_PropertyChanged;
AppSettings.FilterSettings.PropertyChanged -= FilterSettings_PropertyChanged;
}
}
}
| 37.7902 | 154 | 0.495051 | [
"MIT"
] | BertVerbouw/Playnite | source/PlayniteUI/ViewModels/MainViewModel.cs | 54,760 | C# |
// Copyright © 2019, Silverlake Software LLC and Contributors (see NOTICES file)
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
namespace Mailboxes.Benchmarks
{
[MemoryDiagnoser]
public class CoreMailboxBenchmarks
{
static CoreMailboxBenchmarks()
{
SetDoneAction = _ => _done = true;
IsDoneFunc = () => _done;
}
[ParamsSource(nameof(MailboxTypeParams))]
public MailboxTypeParam MailboxType { get; set; }
public static IEnumerable<MailboxTypeParam> MailboxTypeParams()
{
yield return MailboxTypeParam.From<SimpleMailbox>();
yield return MailboxTypeParam.From<ConcurrentMailbox>();
yield return MailboxTypeParam.From<PriorityMailbox>();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
Mailbox CreateMailbox() => MailboxType.CreateMailbox();
[Benchmark]
public Mailbox Create() => CreateMailbox();
[Benchmark]
public Task<int> CreateAndOneCall()
{
return Test(CreateMailbox());
}
static async Task<int> Test(Mailbox mailbox)
{
await mailbox;
return 42;
}
static volatile bool _done;
static readonly SendOrPostCallback SetDoneAction;
static readonly Func<bool> IsDoneFunc;
[Benchmark]
public void CreateAndOneDirectCall()
{
var mailbox = CreateMailbox();
_done = false;
mailbox.Execute(SetDoneAction, null);
while (!_done)
Thread.SpinWait(1);
}
[Benchmark(OperationsPerInvoke = 1000)]
public Task<int> DirectIncrement()
{
var tcs = new TaskCompletionSource<int>();
var state = new IncrementState(CreateMailbox(), tcs);
Parallel.For(0, 1000, _ => state.DoDirectIncrement());
return tcs.Task;
}
[Benchmark(OperationsPerInvoke = 1000)]
public Task<int> AwaitIncrement()
{
var tcs = new TaskCompletionSource<int>();
var state = new IncrementState(CreateMailbox(), tcs);
Parallel.For(0, 1000, i => _ = state.DoAwaitIncrement());
return tcs.Task;
}
[Benchmark(OperationsPerInvoke = 1000)]
public Task<int[]> PairDirectIncrement()
{
var tcs1 = new TaskCompletionSource<int>();
var tcs2 = new TaskCompletionSource<int>();
var state1 = new IncrementState(CreateMailbox(), tcs1, 500);
var state2 = new IncrementState(CreateMailbox(), tcs2, 500);
Parallel.For(0, 1000, i =>
{
if (i % 2 == 0)
state1.DoDirectIncrement();
else
state2.DoDirectIncrement();
});
return Task.WhenAll(tcs1.Task, tcs2.Task);
}
[Benchmark(OperationsPerInvoke = 1000)]
public Task<int[]> PairAwaitIncrement()
{
var tcs1 = new TaskCompletionSource<int>();
var tcs2 = new TaskCompletionSource<int>();
var state1 = new IncrementState(CreateMailbox(), tcs1, 500);
var state2 = new IncrementState(CreateMailbox(), tcs2, 500);
Parallel.For(0, 1000, i =>
{
if (i % 2 == 0)
_ = state1.DoAwaitIncrement();
else
_ = state2.DoAwaitIncrement();
});
return Task.WhenAll(tcs1.Task, tcs2.Task);
}
public readonly struct MailboxTypeParam
{
readonly string _name;
readonly Func<Mailbox> _factory;
public MailboxTypeParam(string name, Func<Mailbox> factory)
{
_name = name;
_factory = factory;
}
public static MailboxTypeParam From<T>() where T : Mailbox, new() => new MailboxTypeParam(typeof(T).Name, () => new T());
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Mailbox CreateMailbox() => _factory();
public override string ToString() => _name;
}
class IncrementState
{
Mailbox _mailbox;
TaskCompletionSource<int> _tcs;
int _limit;
int _value;
SendOrPostCallback _incrementAction;
public IncrementState(Mailbox mailbox, TaskCompletionSource<int> tcs, int limit = 1000)
{
_mailbox = mailbox;
_tcs = tcs;
_limit = limit;
_incrementAction = o => ((IncrementState)o!).DoIncrement();
}
public void DoDirectIncrement()
{
_mailbox.Execute(_incrementAction, this);
}
void DoIncrement()
{
++_value;
if (_value == _limit)
{
_tcs.SetResult(_value);
}
}
public async Task DoAwaitIncrement()
{
await _mailbox;
++_value;
if (_value == _limit)
{
_tcs.SetResult(_value);
}
}
}
}
} | 29.704301 | 133 | 0.535566 | [
"Apache-2.0"
] | silverlakesoftware/mailboxes | source/Mailboxes.Benchmarks/CoreMailboxBenchmarks.cs | 5,528 | C# |
using HostLPass.Core.Domain;
using HostLPass.Core.Repository;
using HostLPass.Data.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HostLPass.Data.Repository
{
public class PaymentRepository : Repository<Payment>, IPaymentRepository
{
public PaymentRepository(IDatabaseFactory databaseFactory) : base(databaseFactory)
{
}
}
}
| 22.9 | 90 | 0.757642 | [
"MIT"
] | dangermin/HostelPass | HostLPass.Data/Repository/PaymentRepository.cs | 460 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml.Serialization;
using InTheHand.Net.Bluetooth;
namespace InTheHand.Net.Tests.Bluetooth.TestBluetoothEndPoint
{
[TestFixture]
public class IFormatterSztn : Serialization
{
protected override void DoTestRoundTrip(BluetoothEndPoint obj)
{
IFormatter szr = new BinaryFormatter();
Stream strm = new MemoryStream();
szr.Serialize(strm, obj);
//
strm.Position = 0;
BluetoothEndPoint back = (BluetoothEndPoint)szr.Deserialize(strm);
Assert.AreEqual(obj, back, "Equals");
Assert.AreEqual(obj.Address, back.Address, "Address");
Assert.AreEqual(obj.Address.ToString("C"), back.Address.ToString("C"), "Address.ToString(\"C\")");
Assert.AreEqual(obj.Service, back.Service, "Service");
Assert.AreEqual(obj.Port, back.Port, "Port");
}
[Test]
public void OneFormat()
{
BluetoothEndPoint obj = new BluetoothEndPoint(
BluetoothAddress.Parse("001122334455"), BluetoothService.SerialPort);
//
IFormatter szr = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
Stream strm = new MemoryStream();
szr.Serialize(strm, obj);
// SZ Format
const String NewLine = "\r\n";
String xmlData
= "<SOAP-ENV:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:clr=\"http://schemas.microsoft.com/soap/encoding/clr/1.0\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" + NewLine
+ "<SOAP-ENV:Body>" + NewLine
+ "<a1:BluetoothEndPoint id=\"ref-1\" xmlns:a1=\"http://schemas.microsoft.com/clr/nsassem/InTheHand.Net/[A-F-N]\">" + NewLine
+ "<m_id href=\"#ref-3\"/>" + NewLine
+ "<m_service>" + NewLine
+ "<_a>4353</_a>" + NewLine
+ "<_b>0</_b>" + NewLine
+ "<_c>4096</_c>" + NewLine
+ "<_d>128</_d>" + NewLine
+ "<_e>0</_e>" + NewLine
+ "<_f>0</_f>" + NewLine
+ "<_g>128</_g>" + NewLine
+ "<_h>95</_h>" + NewLine
+ "<_i>155</_i>" + NewLine
+ "<_j>52</_j>" + NewLine
+ "<_k>251</_k>" + NewLine
+ "</m_service>" + NewLine
+ "<m_port>-1</m_port>" + NewLine
+ "</a1:BluetoothEndPoint>" + NewLine
+ "<a1:BluetoothAddress id=\"ref-3\" xmlns:a1=\"http://schemas.microsoft.com/clr/nsassem/InTheHand.Net/[A-F-N]\">" + NewLine
+ "<dataString id=\"ref-4\">001122334455</dataString>" + NewLine
+ "</a1:BluetoothAddress>" + NewLine
+ "</SOAP-ENV:Body>" + NewLine
+ "</SOAP-ENV:Envelope>" + NewLine
;
strm.Position = 0;
String result = new StreamReader(strm).ReadToEnd();
string expected = InTheHand.Net.Tests.Bluetooth.TestBluetoothAddress.IFormatterSztn
.InsertAssemblyFullNameEscaped(xmlData);
Assert.AreEqual(expected, result, "Equals");
}
}//class
[TestFixture]
public class XmlSztn : Serialization
{
protected override void DoTestRoundTrip(BluetoothEndPoint obj)
{
XmlSerializer szr = new XmlSerializer(obj.GetType());
StringWriter wtr = new StringWriter();
szr.Serialize(wtr, obj);
//
StringReader rdr = new StringReader(wtr.ToString());
BluetoothEndPoint back = (BluetoothEndPoint)szr.Deserialize(rdr);
Assert.AreEqual(obj, back, "Equals");
Assert.AreEqual(obj.Address, back.Address, "Address");
Assert.AreEqual(obj.Address.ToString("C"), back.Address.ToString("C"), "Address.ToString(\"C\")");
Assert.AreEqual(obj.Service, back.Service, "Service");
Assert.AreEqual(obj.Port, back.Port, "Port");
}
[Test]
public void OneFormat()
{
BluetoothEndPoint obj = new BluetoothEndPoint(
BluetoothAddress.Parse("001122334455"), BluetoothService.SerialPort);
//
XmlSerializer szr = new XmlSerializer(obj.GetType());
StringWriter wtr = new StringWriter();
szr.Serialize(wtr, obj);
// SZ Format
const String NewLine = "\r\n";
const String XmlHeader = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" + NewLine;
String xmlData
= XmlHeader
+ "<BluetoothEndPoint xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" + NewLine
+ " <Address>001122334455</Address>" + NewLine
+ " <Service>00001101-0000-1000-8000-00805f9b34fb</Service>" + NewLine
+ " <Port>-1</Port>" + NewLine
+ "</BluetoothEndPoint>"
;
Assert.AreEqual(xmlData, wtr.ToString(), "Equals");
}
}//class
public abstract class Serialization
{
protected abstract void DoTestRoundTrip(BluetoothEndPoint addr);
[Test]
public void One()
{
DoTestRoundTrip(new BluetoothEndPoint(
BluetoothAddress.Parse("001122334455"), BluetoothService.SerialPort));
}
[Test]
public void Two()
{
DoTestRoundTrip(new BluetoothEndPoint(
BluetoothAddress.Parse("FFEEDDCCBBAA"),
new Guid("{3906B199-5B79-4326-B18E-B065B211C14E}")));
}
[Test]
public void None()
{
DoTestRoundTrip(new BluetoothEndPoint(BluetoothAddress.None, BluetoothService.Empty));
}
}//class
}
| 42.09396 | 408 | 0.564573 | [
"MIT"
] | 3wayHimself/32feet | ITH.Net.Personal.FX2.Tests/BtEndPointSerialization.cs | 6,272 | C# |
// -------------------------------------------------------
// Copyright (c) Coalition of the Good-Hearted Engineers
// FREE TO USE FOR THE WORLD
// -------------------------------------------------------
using Microsoft.AspNetCore.Mvc;
using RESTFulSense.Controllers;
namespace Jubilant.Core.Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class HomeController : RESTFulController
{
[HttpGet]
public ActionResult<string> Get() =>
Ok("Hello Mario, the princess is in another catle.");
}
}
| 28 | 65 | 0.535714 | [
"MIT"
] | iCloudBMX/Jubilant.Core | Jubilant.Core.Api/Controllers/HomeController.cs | 562 | C# |
using System;
namespace Reddit.Inputs
{
[Serializable]
public class ListingInput : BaseInput
{
/// <summary>
/// fullname of a thing
/// </summary>
public string after { get; set; }
/// <summary>
/// fullname of a thing
/// </summary>
public string before { get; set; }
/// <summary>
/// the maximum number of items desired
/// </summary>
public int limit { get; set; }
/// <summary>
/// a positive integer
/// </summary>
public int count { get; set; }
/// <summary>
/// Populate a new listing input.
/// </summary>
/// <param name="after">fullname of a thing</param>
/// <param name="before">fullname of a thing</param>
/// <param name="limit">the maximum number of items desired (default: 25)</param>
/// <param name="count">a positive integer (default: 0)</param>
public ListingInput(string after = "", string before = "", int limit = 25, int count = 0)
{
this.after = after;
this.before = before;
this.limit = limit;
this.count = count;
}
}
}
| 27.840909 | 97 | 0.510204 | [
"MIT"
] | DanClowry/Reddit.NET | src/Reddit.NET/Inputs/ListingInput.cs | 1,227 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace CodingChallengeWeek3
{
class Tasks
{
}
}
| 11.666667 | 33 | 0.671429 | [
"MIT"
] | 042020-dotnet-uta/michaelHall-repo0 | CodingChallengeWeek3/Tasks.cs | 142 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using EventStore.Client;
using M5x.Config;
using M5x.DEC.Schema.Extensions;
using M5x.EventStore.Interfaces;
using M5x.Serilog;
using M5x.Testing;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Xunit.Abstractions;
namespace M5x.EventStore.Tests;
public static class Inject
{
public static IServiceCollection AddEsSubscriber(this IServiceCollection services)
{
return services
.AddSingleton(p
=> new PersistentSubscriptionSettings(false, StreamPosition.Start))
.AddConsoleLogger()
.AddDECEsClients()
.AddHostedService<EsConsumer>();
}
}
public class EsPersistentSubscriptionClientTests : IoCTestsBase
{
private IEsPersistentSubscriptionsClient _clt;
private IEsEmitter _emitter;
private Uuid _eventId;
private IHostExecutor _host;
public EsPersistentSubscriptionClientTests(ITestOutputHelper output,
IoCTestContainer container) : base(output,
container)
{
}
protected override void Initialize()
{
_clt = Container.GetRequiredService<IEsPersistentSubscriptionsClient>();
_host = Container.GetRequiredService<IHostExecutor>();
_emitter = Container.GetRequiredService<IEsEmitter>();
}
[Fact]
public void Needs_Emitter()
{
Assert.NotNull(_emitter);
}
[Fact]
public void Needs_Client()
{
Assert.NotNull(_clt);
}
[Fact]
public void Needs_Host()
{
Assert.NotNull(_host);
}
[Fact]
public async Task Should_AnEmittedFactShouldAppear()
{
try
{
await _host.StartAsync();
var times = 200;
var j = 0;
do
{
// var events = new[] { TestData.EventData(Guid.NewGuid()) };
// var res = await _emitter.EmitAsync(TestConstants.Id, events);
// Assert.NotNull(res);
Thread.Sleep(100);
j++;
} while (j < 200);
}
catch (Exception e)
{
Output.WriteLine(e.InnerAndOuter());
throw;
}
finally
{
await _host.StopAsync();
}
}
protected override void SetTestEnvironment()
{
DotEnv.FromEmbedded();
}
protected override void InjectDependencies(IServiceCollection services)
{
services
.AddTransient(p => Output)
.AddTransient<IEsEmitter, EsEmitter>()
.AddSingleton(p
=> new PersistentSubscriptionSettings(false, StreamPosition.Start))
.AddConsoleLogger()
.AddDECEsClients()
.AddHostedService<EsProducer>()
.AddHostedService<EsConsumer>();
}
[Fact]
public void Needs_FakeEventData()
{
var events = TestData.EventData(Guid.NewGuid());
Assert.NotNull(events);
}
[Fact]
public void Needs_EventId()
{
_eventId = Uuid.Parse(TestConstants.Guid.ToString());
Assert.NotNull(_eventId);
}
} | 24.527132 | 86 | 0.606827 | [
"MIT"
] | rgfaber/m5x-sdk | tests/M5x.EventStore.Tests/EsPersistentSubscriptionClientTests.cs | 3,164 | C# |
using System;
using System.Data.SqlClient;
namespace DBExecuteReader
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Server=.; Database=SoftUni; Integrated Security=true";
using(var connection = new SqlConnection(connectionString))
{
connection.Open();
var commandQuery = "SELECT FirstName, LastName FROM Employees WHERE FirstName LIKE 'N%'";
var command = new SqlCommand(commandQuery, connection);
var reader = command.ExecuteReader();
while (reader.Read())
{
string firstName = (string)reader["FirstName"];
string lastName = (string)reader["LastName"];
Console.WriteLine(firstName + " " + lastName);
}
}
}
}
}
| 31.1 | 106 | 0.5209 | [
"MIT"
] | Katsarov/EF-Core | 01.ADO.NET/ADONET1/DBExecuteReader/Program.cs | 935 | C# |
/* Copyright (c) 2018 ExT (V.Sigalkin) */
using UnityEngine;
using extOSC.Core.Events;
namespace extOSC.Components.Events
{
[AddComponentMenu("extOSC/Components/Receiver/Float Event")]
public class OSCReceiverEventFloat : OSCReceiverEvent<OSCEventFloat>
{
#region Protected Methods
protected override void Invoke(OSCMessage message)
{
float value;
if (message.ToFloat(out value))
{
if (onReceive != null)
onReceive.Invoke(value);
}
}
#endregion
}
} | 22.037037 | 72 | 0.586555 | [
"MIT"
] | TheBricktop/extOSC | Assets/extOSC/Scripts/Compontents/Events/OSCReceiverEventFloat.cs | 597 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace uSync.BackOffice.Controllers
{
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class SyncActionResult
{
public SyncActionResult() { }
public SyncActionResult(IEnumerable<uSyncAction> actions)
{
this.Actions = actions;
}
public IEnumerable<uSyncAction> Actions { get; set; }
}
}
| 22.904762 | 70 | 0.68815 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | JohanPlate/uSync | uSync.BackOffice/Controllers/ViewModels/SyncActionResult.cs | 483 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.