text stringlengths 13 6.01M |
|---|
using System.ComponentModel.DataAnnotations.Schema;
namespace GradConnect.Models
{
public class Reference
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }
public string Email { get; set; }
//Navigational property
[InverseProperty("CV")]
public int CvId { get; set; }
public virtual CV Cv { get; set; }
}
} |
namespace iSukces.Code.Interfaces
{
public partial class Auto
{
public enum LazyMemberType
{
Auto, Property, Method
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Welic.Dominio.Models.Client.Map;
using Welic.Dominio.Patterns.Pattern.Ef6;
namespace Welic.Dominio.Models.Estacionamento.Map
{
public class VeiculosMap : Entity
{
public int IdVeiculo { get; set; }
public int Tipo { get; set; }
public string Marca { get; set; }
public string Modelo { get; set; }
public string Cor { get; set; }
public string Placa { get; set; }
public int IdPessoa { get; set; }
public string Chassi { get; set; }
public string CNH { get; set; }
public string Categoria { get; set; }
public DateTime ExpedicaoCnh { get; set; }
public DateTime VencimentoCnh { get; set; }
[ForeignKey("IdPessoa")]
public PessoaMap PessoaMap { get; set; }
public ICollection<SolicitacoesVagasLiberadasMap> SolicitacoesVagasLiberadas { get; set; }
}
}
|
namespace ParseUrl
{
using System;
using System.Text.RegularExpressions;
public class Startup
{
public static void Main(string[] args)
{
var input = Console.ReadLine();
Console.WriteLine(Execute(input));
}
private static string Execute(string input)
{
var regex = new Regex(@"^(?<protocol>\w+)(:\/\/)(?<server>[\w.]+)\/(?<resource>[\w\/-]+)$");
var match = regex.Match(input);
if (match.Length != 0)
{
var protocol = match.Groups["protocol"].Value;
var server = match.Groups["server"].Value;
var resource = match.Groups["resource"].Value;
return $"Protocol = {protocol}\nServer = {server}\nResources = {resource}";
}
else
{
return "Invalid URL";
}
}
}
}
|
namespace VRTK.Prefabs.CameraRig.SimulatedCameraRig
{
using UnityEngine;
using UnityEngine.XR;
using Malimbe.MemberChangeMethod;
using Malimbe.XmlDocumentationAttribute;
using Malimbe.PropertySerializationAttribute;
using Zinnia.Data.Attribute;
using Zinnia.Data.Operation.Mutation;
using VRTK.Prefabs.CameraRig.TrackedAlias;
/// <summary>
/// The public interface into the SimulatedCameraRig Prefab.
/// </summary>
public class SimulatorFacade : MonoBehaviour
{
#region Simulator Settings
/// <summary>
/// The optional Tracked Alias prefab, must be provided if one is used in the scene.
/// </summary>
[Serialized]
[field: Header("Simulator Settings"), DocumentedByXml]
public TrackedAliasFacade TrackedAlias { get; set; }
/// <summary>
/// Determines whether to disable the XRSettings.
/// </summary>
[Serialized]
[field: DocumentedByXml]
public bool DisableXRSettings { get; set; } = true;
/// <summary>
/// The frame rate to simulate with fixedDeltaTime.
/// </summary>
[Serialized]
[field: DocumentedByXml]
public float SimulatedFrameRate { get; set; } = 90f;
#endregion
#region Reference Settings
/// <summary>
/// The linked TransformPositionMutator.
/// </summary>
[Serialized]
[field: Header("Reference Settings"), DocumentedByXml, Restricted]
public TransformPositionMutator PlayAreaPosition { get; protected set; }
/// <summary>
/// The linked TransformPropertyResetter.
/// </summary>
[Serialized]
[field: DocumentedByXml, Restricted]
public TransformPropertyResetter PlayAreaResetter { get; protected set; }
#endregion
/// <summary>
/// The original configuration of XRSettings.
/// </summary>
protected bool originalXRSettings;
/// <summary>
/// The original configuration of FixedDeltaTime.
/// </summary>
protected float originalFixedDeltaTime;
protected virtual void OnEnable()
{
originalXRSettings = XRSettings.enabled;
originalFixedDeltaTime = Time.fixedDeltaTime;
ConfigureTrackedAlias();
ConfigureXRSettings(DisableXRSettings);
}
protected virtual void OnDisable()
{
ConfigureXRSettings(false);
Time.fixedDeltaTime = originalFixedDeltaTime;
}
/// <summary>
/// Configures the provided <see cref="TrackedAlias"/> onto the simulator CameraRig.
/// </summary>
protected virtual void ConfigureTrackedAlias()
{
if (TrackedAlias == null)
{
return;
}
GameObject playAreaObject = TrackedAlias.PlayAreaAlias.gameObject;
PlayAreaPosition.Target = PlayAreaPosition != null ? playAreaObject : null;
PlayAreaResetter.Source = PlayAreaResetter != null ? playAreaObject : null;
}
/// <summary>
/// Configures the XRSettings.
/// </summary>
/// <param name="state">The new value for the setting.</param>
protected virtual void ConfigureXRSettings(bool state)
{
if (state)
{
originalXRSettings = XRSettings.enabled;
XRSettings.enabled = false;
}
else
{
XRSettings.enabled = originalXRSettings;
}
}
/// <summary>
/// Configures the simulated frame rate.
/// </summary>
protected virtual void ConfigureSimulatedFrameRate()
{
Time.fixedDeltaTime = Time.timeScale / SimulatedFrameRate;
}
/// <summary>
/// Called after <see cref="TrackedAlias"/> has been changed.
/// </summary>
[CalledAfterChangeOf(nameof(TrackedAlias))]
protected virtual void OnAfterTrackedAliasChange()
{
ConfigureTrackedAlias();
}
/// <summary>
/// Called after <see cref="DisableXRSettings"/> has been changed.
/// </summary>
[CalledAfterChangeOf(nameof(DisableXRSettings))]
protected virtual void OnAfterDisableXRSettingsChange()
{
ConfigureXRSettings(DisableXRSettings);
}
/// <summary>
/// Called after <see cref="SimulatedFrameRate"/> has been changed.
/// </summary>
[CalledAfterChangeOf(nameof(SimulatedFrameRate))]
protected virtual void OnAfterSimulatedFrameRateChange()
{
ConfigureSimulatedFrameRate();
}
}
} |
using gView.Framework.Data;
using gView.Framework.Geometry;
using gView.Framework.IO;
using gView.Framework.system;
using gView.Framework.Web;
using gView.GraphicsEngine.Abstraction;
using gView.Interoperability.OGC.Dataset.WFS;
using gView.Interoperability.OGC.SLD;
using gView.MapServer;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace gView.Interoperability.OGC.Dataset.WMS
{
public class WMSClass : IWebServiceClass
{
private static IFormatProvider _nhi = System.Globalization.CultureInfo.InvariantCulture.NumberFormat;
private static object lockThis = new object();
private string _name;
private WMSDataset _dataset;
private List<IWebServiceTheme> _themes = new List<IWebServiceTheme>();
private IBitmap _legend = null;
private GeorefBitmap _image = null;
private IEnvelope _envelope;
private GetCapabilities _getCapabilities;
private GetMap _getMap;
private GetFeatureInfo _getFeatureInfo;
private DescribeLayer _describeLayer;
private GetLegendGraphic _getLegendGraphic;
private GetStyles _getStyles;
private WMSExceptions _exceptions;
private SRS _srs;
private UserDefinedSymbolization _userDefinedSymbolization;
private bool _use_SLD_BODY = true;
private ISpatialReference _sRef = null;
private List<IWebServiceTheme> _clonedThemes = null;
public WMSClass(WMSDataset dataset)
{
_dataset = dataset;
if (_dataset != null)
{
_name = _dataset._name;
}
}
internal void Init(string CapabilitiesString, WFSDataset wfsDataset)
{
try
{
_themes = new List<IWebServiceTheme>();
XmlDocument doc = new XmlDocument();
doc.LoadXml(CapabilitiesString);
XmlNode CapabilitiesNode = doc.SelectSingleNode("WMT_MS_Capabilities/Capability");
_getCapabilities = new GetCapabilities(CapabilitiesNode.SelectSingleNode("Request/GetCapabilities"));
_getMap = new GetMap(CapabilitiesNode.SelectSingleNode("Request/GetMap"));
_getFeatureInfo = new GetFeatureInfo(CapabilitiesNode.SelectSingleNode("Request/GetFeatureInfo"));
_describeLayer = new DescribeLayer(CapabilitiesNode.SelectSingleNode("Request/DescribeLayer"));
_getLegendGraphic = new GetLegendGraphic(CapabilitiesNode.SelectSingleNode("Request/GetLegendGraphic"));
_getStyles = new GetStyles(CapabilitiesNode.SelectSingleNode("Request/GetStyles"));
_exceptions = new WMSExceptions(CapabilitiesNode.SelectSingleNode("Exception"));
_userDefinedSymbolization = new UserDefinedSymbolization(CapabilitiesNode.SelectSingleNode("UserDefinedSymbolization"));
XmlNode service = CapabilitiesNode.SelectSingleNode("Layer");
XmlNode title = service.SelectSingleNode("Title");
if (title != null)
{
_name = title.InnerText;
}
_srs = new SRS(service);
this.SRSCode = _srs.Srs[_srs.SRSIndex];
foreach (XmlNode layer in service.SelectNodes("Layer"))
{
string name = "", Title = "";
XmlNode nameNode = layer.SelectSingleNode("Name");
XmlNode titleNode = layer.SelectSingleNode("Title");
if (nameNode == null)
{
continue;
}
name = Title = nameNode.InnerText;
if (titleNode != null)
{
Title = titleNode.InnerText;
}
XmlNodeList styles = layer.SelectNodes("Style");
WFSFeatureClass wfsFc = null;
if (wfsDataset != null)
{
IDatasetElement wfsElement = wfsDataset[name];
if (wfsElement != null && wfsElement.Class is WFSFeatureClass)
{
wfsFc = wfsElement.Class as WFSFeatureClass;
}
}
if (styles.Count == 0)
{
IClass wClass = null;
if (wfsFc != null)
{
wClass = wfsFc;
}
else if (layer.Attributes["queryable"] != null && layer.Attributes["queryable"].Value == "1")
{
wClass = new WMSQueryableThemeClass(_dataset, name, String.Empty, layer, _getFeatureInfo, _srs, _exceptions);
}
else
{
wClass = new WMSThemeClass(_dataset, name, String.Empty, layer);
}
IWebServiceTheme theme;
if (wClass is WFSFeatureClass)
{
theme = new WebServiceTheme2(
wClass, Title, name, true, this);
}
else
{
theme = new WebServiceTheme(
wClass, Title, name, true, this
);
}
_themes.Add(theme);
}
else
{
foreach (XmlNode style in styles)
{
string sName = "", sTitle = "";
XmlNode sNameNode = style.SelectSingleNode("Name");
XmlNode sTitleNode = style.SelectSingleNode("Title");
if (sNameNode == null)
{
continue;
}
sName = sTitle = sNameNode.InnerText;
if (sTitleNode != null)
{
sTitle = sTitleNode.InnerText;
}
IClass wClass = null;
if (wfsFc is WFSFeatureClass)
{
wClass = wfsFc;
((WFSFeatureClass)wClass).Style = sName;
}
else if (layer.Attributes["queryable"] != null && layer.Attributes["queryable"].Value == "1")
{
wClass = new WMSQueryableThemeClass(_dataset, name, sName, layer, _getFeatureInfo, _srs, _exceptions);
}
else
{
wClass = new WMSThemeClass(_dataset, name, sName, layer);
}
IWebServiceTheme theme;
if (wClass is WFSFeatureClass)
{
theme = new WebServiceTheme2(
wClass, Title + " (Style=" + sTitle + ")", name, true, this);
}
else
{
theme = new WebServiceTheme(
wClass, Title + " (Style=" + sTitle + ")", name, true, this
);
}
_themes.Add(theme);
}
}
}
doc = null;
}
catch (Exception ex)
{
string errMsg = ex.Message;
}
}
public string[] SRSCodes
{
get
{
if (_srs == null)
{
return null;
}
string[] codes = new string[_srs.Srs.Count];
int i = 0;
foreach (string code in _srs.Srs)
{
codes[i++] = code;
}
return codes;
}
}
public string SRSCode
{
get
{
if (_srs == null || _srs.Srs == null || _srs.Srs.Count <= _srs.SRSIndex)
{
return null;
}
return _srs.Srs[_srs.SRSIndex];
}
set
{
if (_srs == null || value == null)
{
return;
}
for (int i = 0; i < _srs.Srs.Count; i++)
{
if (_srs.Srs[i].ToLower() == value.ToLower())
{
_srs.SRSIndex = i;
break;
}
}
_sRef = gView.Framework.Geometry.SpatialReference.FromID(_srs.Srs[_srs.SRSIndex]);
if (_srs.LatLonBoundingBox != null)
{
_envelope = GeometricTransformerFactory.Transform2D(
_srs.LatLonBoundingBox,
gView.Framework.Geometry.SpatialReference.FromID("EPSG:4326"),
_sRef).Envelope;
}
}
}
public string[] FeatureInfoFormats
{
get
{
if (_getFeatureInfo == null || _getFeatureInfo.Formats == null)
{
return null;
}
string[] formats = new string[_getFeatureInfo.Formats.Count];
int i = 0;
foreach (string format in _getFeatureInfo.Formats)
{
formats[i++] = format;
}
return formats;
}
}
public string FeatureInfoFormat
{
get
{
if (_getFeatureInfo == null || _getFeatureInfo.Formats == null ||
_getFeatureInfo.Formats.Count <= _getFeatureInfo.FormatIndex)
{
return null;
}
return _getFeatureInfo.Formats[_getFeatureInfo.FormatIndex];
}
set
{
if (_getFeatureInfo == null || _getFeatureInfo.Formats == null)
{
return;
}
for (int i = 0; i < _getFeatureInfo.Formats.Count; i++)
{
if (_getFeatureInfo.Formats[i].ToLower() == value.ToLower())
{
_getFeatureInfo.FormatIndex = i;
break;
}
}
}
}
public string[] GetMapFormats
{
get
{
if (_getMap == null || _getMap.Formats == null)
{
return null;
}
string[] formats = new string[_getMap.Formats.Count];
int i = 0;
foreach (string format in _getMap.Formats)
{
formats[i++] = format;
}
return formats;
}
}
public string GetMapFormat
{
get
{
if (_getMap == null || _getMap.Formats == null)
{
return null;
}
return _getMap.Formats[_getMap.FormatIndex];
}
set
{
if (_getMap == null || _getMap.Formats == null)
{
return;
}
for (int i = 0; i < _getMap.Formats.Count; i++)
{
if (_getMap.Formats[i].ToLower() == value.ToLower())
{
_getMap.FormatIndex = i;
break;
}
}
}
}
public bool SupportSLD
{
get
{
if (_userDefinedSymbolization == null)
{
return false;
}
return _userDefinedSymbolization.SupportSLD;
}
}
public bool UseSLD_BODY
{
get { return _use_SLD_BODY; }
set { _use_SLD_BODY = false; }
}
#region IWebServiceClass Member
public event AfterMapRequestEventHandler AfterMapRequest = null;
async public Task<bool> MapRequest(gView.Framework.Carto.IDisplay display)
{
if (_srs == null)
{
return false;
}
if (!_dataset.IsOpened)
{
if (!await _dataset.Open())
{
return false;
}
}
List<IWebServiceTheme> themes = Themes;
if (themes == null)
{
return false;
}
#region Check for visible Layers
bool visFound = false;
foreach (IWebServiceTheme theme in themes)
{
if (!theme.Visible)
{
continue;
}
if (theme.MinimumScale > 1 && theme.MinimumScale > display.mapScale)
{
continue;
}
if (theme.MaximumScale > 1 && theme.MaximumScale < display.mapScale)
{
continue;
}
visFound = true;
break;
}
if (!visFound)
{
if (_image != null)
{
_image.Dispose();
_image = null;
}
return true;
}
#endregion Check for visible Layers
int iWidth = display.iWidth;
int iHeight = display.iHeight;
IEnvelope displayEnv = display.Envelope;
if (display.SpatialReference != null && !display.SpatialReference.Equals(this.SpatialReference))
{
displayEnv = GeometricTransformerFactory.Transform2D(displayEnv, display.SpatialReference, this.SpatialReference).Envelope;
iHeight = (int)((displayEnv.Height / displayEnv.Width) * iWidth);
}
StyledLayerDescriptorWriter sldWriter = null;
StringBuilder request = new StringBuilder("VERSION=1.1.1&REQUEST=GetMap");
StringBuilder layers = new StringBuilder(), styles = new StringBuilder();
foreach (IWebServiceTheme theme in themes)
{
if (!theme.Visible || theme.Locked ||
(!(theme.Class is WMSThemeClass) &&
!(theme.Class is WFSFeatureClass)))
{
continue;
}
if (layers.Length > 0)
{
layers.Append(",");
styles.Append(",");
}
layers.Append(theme.Class.Name);
if (theme.Class is IWMSStyle)
{
styles.Append(((IWMSStyle)theme.Class).Style);
}
if (theme.FeatureRenderer != null &&
_userDefinedSymbolization.SupportSLD &&
_userDefinedSymbolization.UserStyle)
{
SLDRenderer sldRenderer = null;
if (theme.FeatureRenderer is SLDRenderer)
{
sldRenderer = (SLDRenderer)theme.FeatureRenderer;
}
else
{
//if (theme.FilterQuery is ISpatialFilter)
//{
// IGeometry pGeometry = GeometricTransformer.Transform2D(
// ((ISpatialFilter)theme.FilterQuery).Geometry,
// display.SpatialReference,
// this.SpatialReference);
// IGeometry oGeometry = ((ISpatialFilter)theme.FilterQuery).Geometry;
// ((ISpatialFilter)theme.FilterQuery).Geometry = pGeometry;
// sldRenderer = new SLDRenderer(theme);
// ((ISpatialFilter)theme.FilterQuery).Geometry = oGeometry;
//}
//else
{
sldRenderer = await SLDRenderer.CreateAync(theme);
if (display.SpatialReference != null)
{
sldRenderer.SetDefaultSrsName(display.SpatialReference.Name);
}
}
}
if (sldWriter == null)
{
sldWriter = new StyledLayerDescriptorWriter();
}
sldWriter.WriteNamedLayer(theme.Class.Name, sldRenderer);
}
}
request.Append("&LAYERS=" + layers.ToString());
if (sldWriter != null)
{
string sld = sldWriter.ToLineString();
if (!_use_SLD_BODY && !string.IsNullOrEmpty(MapServerConfig.DefaultOutputPath))
{
string sldFilename = "style_" + Guid.NewGuid().ToString("N") + ".sld";
StreamWriter sw = new StreamWriter(MapServerConfig.DefaultOutputPath + @"/" + sldFilename);
sw.WriteLine(sldWriter.ToString());
sw.Close();
request.Append("&SLD=" + MapServerConfig.DefaultOutputUrl + "/" + sldFilename);
}
else
{
request.Append("&SLD_BODY=" + sld.Replace("#", "%23"));
}
}
else
{
request.Append("&STYLES=" + styles.ToString());
}
if (_exceptions != null && _exceptions.Formats.Count > 0)
{
request.Append("&EXCEPTIONS=" + _exceptions.Formats[0]);
}
request.Append("&SRS=" + _srs.Srs[_srs.SRSIndex]);
request.Append("&WIDTH=" + iWidth);
request.Append("&HEIGHT=" + iHeight);
request.Append("&FORMAT=" + _getMap.Formats[_getMap.FormatIndex]);
request.Append("&BBOX=" +
displayEnv.minx.ToString(_nhi) + "," +
displayEnv.miny.ToString(_nhi) + "," +
displayEnv.maxx.ToString(_nhi) + "," +
displayEnv.maxy.ToString(_nhi));
//request.Append("&BGCOLOR=FFFFFF");
request.Append("&TRANSPARENT=TRUE");
if (_image != null)
{
_image.Dispose();
_image = null;
}
IBitmap bitmap = null;
//if (_getMap.Post_OnlineResource != String.Empty && sldWriter != null)
//{
// //bm = WebFunctions.DownloadImage(WMSDataset.Append2Url(_getMap.Post_OnlineResource, request.ToString() + "&SLD="),
// // UTF8Encoding.UTF8.GetBytes(sldWriter.ToString()));
// bm = WebFunctions.DownloadImage(_getMap.Post_OnlineResource,
// UTF8Encoding.UTF8.GetBytes(request.ToString()));
//}
//else
{
#if(DEBUG)
gView.Framework.system.Logger.LogDebug("Start WMS DownloadImage");
#endif
string url = WMSDataset.Append2Url(_getMap.Get_OnlineResource, request.ToString());
try
{
bitmap = WebFunctions.DownloadImage(url,
ConfigTextStream.ExtractValue(_dataset._connectionString, "usr"),
ConfigTextStream.ExtractValue(_dataset._connectionString, "pwd"));
}
catch (Exception ex)
{
await WMSClass.ErrorLogAsync(display.Map as IServiceRequestContext, "MapRequest", url, ex);
return false;
}
#if(DEBUG)
gView.Framework.system.Logger.LogDebug("WMS DownloadImage Finished");
#endif
}
if (bitmap != null)
{
_image = new GeorefBitmap(bitmap);
_image.Envelope = displayEnv;
_image.SpatialReference = this.SpatialReference;
if (AfterMapRequest != null)
{
AfterMapRequest(this, display, _image);
}
}
return _image != null;
}
public Task<bool> LegendRequest(gView.Framework.Carto.IDisplay display)
{
return Task.FromResult(false);
}
public GeorefBitmap Image
{
get { return _image; }
}
public IBitmap Legend
{
get { return _legend; }
}
public gView.Framework.Geometry.IEnvelope Envelope
{
get
{
IEnvelope ret = null;
if (_srs != null &&
_srs.SRSIndex >= 0 && _srs.SRSIndex < _srs.Srs.Count)
{
ret = _srs.Envelope(_srs.Srs[_srs.SRSIndex]);
}
if (ret == null)
{
ret = new Envelope(-180, -90, 180, 90);
}
return ret;
}
}
public gView.Framework.Geometry.ISpatialReference SpatialReference
{
get
{
return _sRef;
}
set
{
if (value == null)
{
return;
}
for (int i = 0; i < _srs.Srs.Count; i++)
{
if (_srs.Srs[i].ToLower() == value.Name.ToLower())
{
_srs.SRSIndex = i;
_sRef = value;
break;
}
}
}
}
public List<IWebServiceTheme> Themes
{
get
{
if (_clonedThemes != null)
{
return _clonedThemes;
}
return _themes;
}
}
#endregion IWebServiceClass Member
#region IClass Member
public string Name
{
get { return _name; }
}
public string Aliasname
{
get { return _name; }
}
public IDataset Dataset
{
get { return _dataset; }
}
#endregion IClass Member
#region IClone Member
public object Clone()
{
WMSClass clone = new WMSClass(_dataset);
clone._clonedThemes = new List<IWebServiceTheme>();
foreach (IWebServiceTheme theme in Themes)
{
if (theme == null || theme.Class == null)
{
continue;
}
WebServiceTheme clonedTheme = new WebServiceTheme(
theme.Class, theme.Title, theme.LayerID, theme.Visible, clone);
clonedTheme.ID = theme.ID;
clone._clonedThemes.Add(clonedTheme);
}
clone._exceptions = this._exceptions;
clone._srs = (SRS)this._srs.Clone();
clone._sRef = this._sRef;
clone._envelope = this._envelope;
clone._getCapabilities = this._getCapabilities;
clone._getFeatureInfo = this._getFeatureInfo;
clone._getMap = this._getMap;
clone._userDefinedSymbolization = this._userDefinedSymbolization;
clone.AfterMapRequest = AfterMapRequest;
return clone;
}
#endregion IClone Member
#region HelperClasses
internal class GetRequest
{
public string Get_OnlineResource = "";
public string Post_OnlineResource = "";
public List<string> Formats = new List<string>();
public GetRequest(XmlNode node)
{
if (node == null)
{
return;
}
XmlNode onlineResource = node.SelectSingleNode("DCPType/HTTP/Get/OnlineResource");
if (onlineResource != null && onlineResource.Attributes["xlink:href"] != null)
{
Get_OnlineResource = onlineResource.Attributes["xlink:href"].Value;
}
onlineResource = node.SelectSingleNode("DCPType/HTTP/Post/OnlineResource");
if (onlineResource != null && onlineResource.Attributes["xlink:href"] != null)
{
Post_OnlineResource = onlineResource.Attributes["xlink:href"].Value;
}
foreach (XmlNode format in node.SelectNodes("Format"))
{
Formats.Add(format.InnerText);
}
}
}
internal class GetCapabilities : GetRequest
{
public GetCapabilities(XmlNode node)
: base(node)
{
}
}
internal class GetMap : GetRequest
{
public int FormatIndex = -1;
public GetMap(XmlNode node)
: base(node)
{
for (int i = 0; i < Formats.Count; i++)
{
switch (Formats[i].ToLower())
{
case "image/png":
FormatIndex = i;
break;
case "image/jpg":
case "image/jpeg":
if (FormatIndex == -1)
{
FormatIndex = i;
}
break;
}
}
if (FormatIndex == -1)
{
FormatIndex = 0;
}
}
}
internal class GetFeatureInfo : GetRequest
{
public int FormatIndex = -1;
public GetFeatureInfo(XmlNode node)
: base(node)
{
for (int i = 0; i < Formats.Count; i++)
{
switch (Formats[i].ToLower())
{
case "text/xml":
FormatIndex = i;
break;
case "text/html":
if (FormatIndex == -1)
{
FormatIndex = i;
}
break;
}
}
if (FormatIndex == -1)
{
FormatIndex = 0;
}
}
}
internal class DescribeLayer : GetRequest
{
public int FormatIndex = -1;
public DescribeLayer(XmlNode node)
: base(node)
{
if (FormatIndex == -1 && Formats.Count > 0)
{
FormatIndex = 0;
}
}
}
internal class GetLegendGraphic : GetRequest
{
public int FormatIndex = -1;
public GetLegendGraphic(XmlNode node)
: base(node)
{
if (FormatIndex == -1 && Formats.Count > 0)
{
FormatIndex = 0;
}
}
}
internal class GetStyles : GetRequest
{
public int FormatIndex = -1;
public GetStyles(XmlNode node)
: base(node)
{
if (FormatIndex == -1 && Formats.Count > 0)
{
FormatIndex = 0;
}
}
}
internal class WMSExceptions
{
public List<string> Formats = new List<string>();
public WMSExceptions(XmlNode node)
{
foreach (XmlNode format in node.SelectNodes("Format"))
{
Formats.Add(format.InnerText);
}
}
}
internal class SRS : IClone
{
public int SRSIndex = -1;
public List<string> Srs = new List<string>();
public IEnvelope LatLonBoundingBox = null;
private Dictionary<string, IEnvelope> _boundaryBoxes = new Dictionary<string, IEnvelope>();
private SRS()
{
}
public SRS(XmlNode node)
: this(node, null, String.Empty)
{
}
public SRS(XmlNode node, XmlNamespaceManager ns, string nsName)
{
if (node == null)
{
return;
}
if (nsName != String.Empty)
{
nsName += ":";
}
foreach (XmlNode srs in node.SelectNodes(nsName + "SRS", ns))
{
// Manche schreiben den SRS code in eine Zeile mit Leerzeichen
foreach (string srscode in srs.InnerText.Split(' '))
{
Srs.Add(srscode);
if (srscode.ToUpper() != "EPSG:4326" && SRSIndex == -1 &&
srscode.ToLower().StartsWith("EPSG:"))
{
SRSIndex = Srs.Count - 1;
}
}
}
if (Srs.Count == 0)
{
Srs.Add("EPSG:4326"); // WGS84 immer verwenden, wenn nix anders vorgegeben wird...
}
if (SRSIndex == -1)
{
SRSIndex = 0;
}
foreach (XmlNode box in node.SelectNodes(nsName + "BoundingBox[@SRS]", ns))
{
if (box.Attributes["minx"] == null ||
box.Attributes["miny"] == null ||
box.Attributes["maxx"] == null ||
box.Attributes["maxy"] == null)
{
continue;
}
IEnvelope env = new Envelope(
double.Parse(box.Attributes["minx"].Value, _nhi),
double.Parse(box.Attributes["miny"].Value, _nhi),
double.Parse(box.Attributes["maxx"].Value, _nhi),
double.Parse(box.Attributes["maxy"].Value, _nhi));
_boundaryBoxes.Add(box.Attributes["SRS"].Value.ToUpper(), env);
}
XmlNode latlonbox = node.SelectSingleNode(nsName + "LatLonBoundingBox", ns);
if (latlonbox != null &&
latlonbox.Attributes["minx"] != null &&
latlonbox.Attributes["miny"] != null &&
latlonbox.Attributes["maxx"] != null &&
latlonbox.Attributes["maxy"] != null)
{
LatLonBoundingBox = new Envelope(
double.Parse(latlonbox.Attributes["minx"].Value, _nhi),
double.Parse(latlonbox.Attributes["miny"].Value, _nhi),
double.Parse(latlonbox.Attributes["maxx"].Value, _nhi),
double.Parse(latlonbox.Attributes["maxy"].Value, _nhi));
}
}
public IEnvelope Envelope(string srs)
{
IEnvelope env = null;
_boundaryBoxes.TryGetValue(srs.ToUpper(), out env);
if (env == null && LatLonBoundingBox != null)
{
// Projezieren
ISpatialReference sRef = gView.Framework.Geometry.SpatialReference.FromID(srs);
ISpatialReference epsg_4326 = gView.Framework.Geometry.SpatialReference.FromID("epsg:4326");
IGeometry geom = GeometricTransformerFactory.Transform2D(LatLonBoundingBox, epsg_4326, sRef);
if (geom != null)
{
env = geom.Envelope;
}
}
return (env != null) ? env : new Envelope(-180, -90, 180, 90);
}
#region IClone Member
public object Clone()
{
SRS clone = new SRS();
clone.SRSIndex = this.SRSIndex;
clone.Srs = this.Srs;
clone.LatLonBoundingBox = this.LatLonBoundingBox;
clone._boundaryBoxes = this._boundaryBoxes;
return clone;
}
#endregion IClone Member
}
internal class UserDefinedSymbolization
{
public bool SupportSLD = false;
public bool UserLayer = false;
public bool UserStyle = false;
public bool RemoteWFS = false;
public UserDefinedSymbolization(XmlNode node)
{
if (node == null)
{
return;
}
if (node.Attributes["SupportSLD"] != null)
{
SupportSLD = node.Attributes["SupportSLD"].Value == "1";
}
if (node.Attributes["UserLayer"] != null)
{
UserLayer = node.Attributes["UserLayer"].Value == "1";
}
if (node.Attributes["UserStyle"] != null)
{
UserStyle = node.Attributes["UserStyle"].Value == "1";
}
if (node.Attributes["RemoteWFS"] != null)
{
RemoteWFS = node.Attributes["RemoteWFS"].Value == "1";
}
}
}
#endregion HelperClasses
async public static Task LogAsync(IServiceRequestContext context, string header, string server, string service, string axl)
{
if (context == null ||
context.MapServer == null ||
context.MapServer.LoggingEnabled(loggingMethod.request_detail_pro) == false)
{
return;
}
StringBuilder sb = new StringBuilder();
sb.Append("\n");
sb.Append(header);
sb.Append("\n");
sb.Append("Server: " + server + " Service: " + service);
sb.Append("\n");
sb.Append(axl);
await context.MapServer.LogAsync(context, "gView.Interoperability.ArcXML", loggingMethod.request_detail_pro, sb.ToString());
}
async public static Task Log(IServiceRequestContext context, string header, string server, string service, StringBuilder axl)
{
if (context == null ||
context.MapServer == null ||
context.MapServer.LoggingEnabled(loggingMethod.request_detail_pro) == false)
{
return;
}
await LogAsync(context, header, server, service, axl.ToString());
}
async public static Task ErrorLogAsync(IServiceRequestContext context, string header, string url, Exception ex)
{
if (context == null ||
context.MapServer == null ||
context.MapServer.LoggingEnabled(loggingMethod.error) == false)
{
return;
}
StringBuilder msg = new StringBuilder();
if (ex != null)
{
msg.Append(ex.Message + "\n");
Exception inner = ex;
while ((inner = inner.InnerException) != null)
{
msg.Append(inner.Message + "\n");
}
}
await context.MapServer.LogAsync(context, header + ": " + url, loggingMethod.error,
msg.ToString() +
ex.Source + "\n" +
ex.StackTrace + "\n");
}
/*
#region IMetadata Member
public void ReadMetadata(IPersistStream stream)
{
XmlStreamOption getmap = stream.Load("GetMapFormat") as XmlStreamOption;
if (getmap != null)
this.GetMapFormat = getmap.Value.ToString();
XmlStreamOption getfeatures = stream.Load("GetFeatureInfoFormat") as XmlStreamOption;
if (getfeatures != null)
this.FeatureInfoFormat = getfeatures.Value.ToString();
XmlStreamOption srscodes = stream.Load("EPSGCodes") as XmlStreamOption;
if (srscodes != null)
this.SRSCode = srscodes.Value.ToString();
}
public void WriteMetadata(IPersistStream stream)
{
XmlStreamOption<string> getmap = new XmlStreamOption<string>(this.GetMapFormats, this.GetMapFormat);
getmap.DisplayName = "GetMap Request Format";
getmap.Description = "The GetMap Image Format";
stream.Save("GetMapFormat", getmap);
XmlStreamOption<string> getfeatures = new XmlStreamOption<string>(this.FeatureInfoFormats, this.FeatureInfoFormat);
getfeatures.DisplayName = "GetFeatureInfo Request Format";
getfeatures.Description = "The FeatureInfo Request Format";
stream.Save("GetFeatureInfoFormat", getfeatures);
XmlStreamOption<string> srscodes = new XmlStreamOption<string>(this.SRSCodes, this.SRSCode);
stream.Save("EPSGCodes", srscodes);
}
#endregion IMetadata Member
* */
}
} |
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
using static Terraria.ModLoader.ModContent;
namespace ReducedGrinding.NPCs
{
[AutoloadHead]
public class LootMerchant : ModNPC
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Loot Merchant");
}
public override void SetDefaults()
{
npc.townNPC = true;
npc.friendly = true;
npc.width = 22; //His hitbox, the visual width/height is affected by frame count below.
npc.height = 42;
npc.aiStyle = 7;
npc.damage = 10;
npc.defense = 15;
npc.lifeMax = 250;
npc.HitSound = SoundID.NPCHit1;
npc.DeathSound = SoundID.NPCDeath1;
npc.knockBackResist = 0.5f;
Main.npcFrameCount[npc.type] = 26;
animationType = NPCID.Merchant;
}
public override bool CanTownNPCSpawn(int numTownNPCs, int money)
{
if (GetInstance<IOtherCustomNPCsConfig>().LootMerchant)
return true;
else
return false;
}
public override string TownNPCName()
{ //NPC names
switch (Main.rand.Next(27))
{
case 0:
return "Dalton";
case 1:
return "Hall";
case 2:
return "Zack";
case 3:
return "Lewin";
case 4:
return "Kenton";
case 5:
return "James";
case 6:
return "Kameron";
case 7:
return "Reggie";
case 8:
return "Murphy";
case 9:
return "Harlan";
case 10:
return "Manny";
case 11:
return "Raine";
case 12:
return "Buddy";
case 13:
return "Carleton";
case 14:
return "Gale";
case 15:
return "Wilson";
case 16:
return "Darien";
case 17:
return "Cedric";
case 18:
return "Walt";
case 19:
return "Jensen";
case 20:
return "Thorley";
case 21:
return "Desmond";
case 22:
return "Rylan";
case 23:
return "Doug";
case 24:
return "Ralf";
case 25:
return "Oakley";
default:
return "Dudley";
}
}
public override string GetChat()
{
switch (Main.rand.Next(4))
{
case 0:
return "I like to collect loot from monsters and a little mining, want to buy any?";
case 1:
return "If you're looking for loot, you've come to the right place.";
case 2:
return "Looking for loot?";
default:
return "You could kill some mobs for their loot, or you could buy them from me.";
}
}
public override void SetChatButtons(ref string button, ref string button2)
{
button = "Shop";
}
public override void OnChatButtonClicked(bool firstButton, ref bool shop)
{
if (firstButton)
{
shop = true;
}
}
public override void SetupShop(Chest shop, ref int nextSlot)
{
int gameProgress = 0;
if (NPC.downedSlimeKing)
gameProgress = 1;
if (NPC.downedBoss1)
gameProgress = 2;
if (NPC.downedBoss2)
gameProgress = 3;
if (NPC.downedBoss3)
gameProgress = 4;
if (Main.hardMode)
gameProgress = 5;
if (NPC.downedPlantBoss)
gameProgress = 6;
if (NPC.downedGolemBoss)
gameProgress = 7;
shop.item[nextSlot].SetDefaults(ItemID.Gel);
nextSlot++;
if (WorldGen.goldBar == ItemID.GoldBar)
shop.item[nextSlot].SetDefaults(ItemID.GoldOre);
else
shop.item[nextSlot].SetDefaults(ItemID.PlatinumOre);
nextSlot++;
shop.item[nextSlot].SetDefaults(ItemID.Ruby);
nextSlot++;
if (gameProgress > 0)
{
shop.item[nextSlot].SetDefaults(ItemID.Lens);
nextSlot++;
}
if (gameProgress > 1)
{
if (WorldGen.crimson)
{
shop.item[nextSlot].SetDefaults(ItemID.ViciousPowder);
nextSlot++;
shop.item[nextSlot].SetDefaults(ItemID.Vertebrae);
nextSlot++;
}
else
{
shop.item[nextSlot].SetDefaults(ItemID.VilePowder);
nextSlot++;
shop.item[nextSlot].SetDefaults(ItemID.RottenChunk);
nextSlot++;
}
}
if (gameProgress > 2)
{
{
shop.item[nextSlot].SetDefaults(ItemID.BottledHoney);
nextSlot++;
shop.item[nextSlot].SetDefaults(ItemID.Stinger);
nextSlot++;
}
}
if (gameProgress > 3)
{
{
//While all other summon material is sold right before the next boss, this is sold after Skeletron, because it has no use until then.
shop.item[nextSlot].SetDefaults(ItemID.ClothierVoodooDoll);
nextSlot++;
shop.item[nextSlot].SetDefaults(ItemID.GuideVoodooDoll);
nextSlot++;
}
}
if (gameProgress > 4)
{
{
shop.item[nextSlot].SetDefaults(WorldGen.ironBar);
nextSlot++;
shop.item[nextSlot].SetDefaults(ItemID.SoulofLight);
nextSlot++;
shop.item[nextSlot].SetDefaults(ItemID.SoulofNight);
nextSlot++;
shop.item[nextSlot].SetDefaults(ItemID.Bone);
nextSlot++;
}
}
if (gameProgress > 5)
{
{
shop.item[nextSlot].SetDefaults(ItemID.LihzahrdPowerCell);
nextSlot++;
}
}
if (gameProgress > 6)
{
{
shop.item[nextSlot].SetDefaults(ItemID.TruffleWorm);
nextSlot++;
}
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemBattleMenuButton : MonoBehaviour
{
//Facilitates interaction with mouse cursor on items instantiated in item menu in battle
public Item itemToUse;
/// <summary>
/// Used by battle state machine to perform using an item
/// </summary>
public void UseItem()
{
GameObject.Find("BattleManager").GetComponent<BattleStateMachine>().SetChosenItem(itemToUse);
}
}
|
using Sales.Models;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace Sales.Services
{
public class SupplyOfferServices
{
public void AddSupplyOffer(SupplyOffer supplyOffer)
{
using (SalesDB db = new SalesDB())
{
db.SuppliesOffers.Add(supplyOffer);
db.SaveChanges();
}
}
public void UpdateSupplyOffer(SupplyOffer supplyOffer)
{
using (SalesDB db = new SalesDB())
{
db.Entry(supplyOffer).State = EntityState.Modified;
db.SaveChanges();
}
}
public void DeleteSupplyOffer(SupplyOffer supplyOffer)
{
using (SalesDB db = new SalesDB())
{
db.SuppliesOffers.Attach(supplyOffer);
db.SuppliesOffers.Remove(supplyOffer);
db.SaveChanges();
}
}
public int GetLastSupplyOfferID()
{
using (SalesDB db = new SalesDB())
{
return db.SuppliesOffers.AsEnumerable().LastOrDefault().ID;
}
}
public int GetSuppliesOffersNumer(string key)
{
using (SalesDB db = new SalesDB())
{
return db.SuppliesOffers.Include(i => i.Client).Where(w => (w.ID.ToString() + w.Client.Name).Contains(key)).Count();
}
}
public SupplyOffer GetSupplyOffer(int id)
{
using (SalesDB db = new SalesDB())
{
return db.SuppliesOffers.Include(i => i.Client).SingleOrDefault(s => s.ID == id);
}
}
public List<SupplyOffer> SearchSuppliesOffers(string key, int page)
{
using (SalesDB db = new SalesDB())
{
return db.SuppliesOffers.Include(i => i.Client).Where(w => (w.ID.ToString() + w.Client.Name).Contains(key)).OrderByDescending(o => o.Date).Skip((page - 1) * 17).Take(17).ToList();
}
}
}
}
|
using System;
namespace PGNtoFEN {
class Program {
static void Main(string[] args) {
Console.WriteLine("Convert PGN to FEN!");
repl();
Console.WriteLine("Goodnight.");
}
private static void repl() {
Console.WriteLine("Paste PGN string here or type exit:");
var pgn = Console.ReadLine();
if (pgn == "exit") {
return;
}
var converter = new Converter();
var result = converter.Convert(pgn);
Console.WriteLine(result);
repl();
}
}
}
|
using gView.Framework.Data;
using gView.Framework.FDB;
using gView.Framework.system;
using System;
using System.Linq;
using System.Windows.Forms;
namespace gView.Framework.UI.Controls
{
public partial class AdditionalFieldsControl : UserControl
{
public AdditionalFieldsControl()
{
InitializeComponent();
PlugInManager compMan = new PlugInManager();
var autoFields = compMan.GetPlugins(Plugins.Type.IAutoField);
if (autoFields != null)
{
tablePanel.RowCount = autoFields.Count();
//tablePanel.Height = autoFields.Count() * 25;
tablePanel.Resize += new EventHandler(tablePanel_Resize);
int row = 0;
foreach (var compType in autoFields)
{
IAutoField aField = compMan.CreateInstance<IAutoField>(compType);
if (aField == null)
{
continue;
}
TextBox box = new TextBox();
AutoFieldCheckBox checkBox = new AutoFieldCheckBox(aField, box);
box.Text = aField.AutoFieldPrimayName;
tablePanel.Controls.Add(checkBox, 0, row);
tablePanel.Controls.Add(box, 1, row++);
}
}
}
void tablePanel_Resize(object sender, EventArgs e)
{
foreach (Control control in tablePanel.Controls)
{
if (control is CheckBox)
{
control.Width = tablePanel.Width - 120;
}
if (control is TextBox)
{
control.Width = 120;
}
}
}
public FieldCollection AdditionalFields
{
get
{
FieldCollection fields = new FieldCollection();
foreach (Control control in tablePanel.Controls)
{
if (control is AutoFieldCheckBox && ((AutoFieldCheckBox)control).Checked)
{
fields.Add(((AutoFieldCheckBox)control).AutoField);
}
}
return fields;
}
}
}
internal class AutoFieldCheckBox : CheckBox
{
private IAutoField _field;
private TextBox _nameBox;
public AutoFieldCheckBox(IAutoField field, TextBox nameBox)
{
if (field == null || nameBox == null)
{
return;
}
_field = field;
_nameBox = nameBox;
this.Text = _field.AutoFieldName;
if (_field.AutoFieldDescription != String.Empty)
{
this.Text += (": " + _field.AutoFieldDescription);
}
_nameBox.TextChanged += new EventHandler(nameBox_TextChanged);
}
void nameBox_TextChanged(object sender, EventArgs e)
{
if (_field is Field)
{
((Field)_field).name = _nameBox.Text;
}
}
public IAutoField AutoField
{
get { return _field; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using OPCAutomation;
using IRAP.OPC.Entity;
using IRAP.OPC.Entity.IRAPServer;
using IRAP.OPC.Library;
namespace IRAP.BL.OPCGateway
{
public class TKepServerListener
{
/// <summary>
/// KepServer
/// </summary>
private OPCServer kepServer = new OPCServer();
private OPCGroups kepGroups = null;
private OPCGroup kepGroup = null;
private OPCItems kepItems = null;
private OPCItem kepItem = null;
private List<TIRAPOPCTagItem> tags = new List<TIRAPOPCTagItem>();
private string ipKepServer = "";
private string nameKepServer = "";
/// <summary>
/// 当前是否已经连接到 KepServer
/// </summary>
private bool kepServerConnected = false;
private int transactionID = 1;
//private TKepServerWriter writter = new TKepServerWriter();
public TKepServerListener()
{
kepServer.ServerShutDown += new DIOPCServerEvent_ServerShutDownEventHandler(KepServer_ServerShutDown);
}
~TKepServerListener()
{
#if DEBUG
Debug.WriteLine(
string.Format(
"关闭远程服务器[{0}][{1}]的连接",
nameKepServer,
ipKepServer));
#endif
if (kepGroup != null)
{
kepGroup.DataChange -= new DIOPCGroupEvent_DataChangeEventHandler(KepGroup_DataChange);
}
if (kepServer != null)
{
kepServer.Disconnect();
kepServer = null;
}
}
/// <summary>
/// KepServer 的 IP 地址
/// </summary>
public string KepServerIP { get { return ipKepServer; } }
/// <summary>
/// KepServer 的服务器名称
/// </summary>
public string KepServerName { get { return nameKepServer; } }
private void KepServer_ServerShutDown(string Reason)
{
kepServerConnected = false;
Debug.WriteLine(
string.Format(
"远程服务器[{0}][{1}]断开连接,可能已经关机了。",
nameKepServer,
ipKepServer));
}
/// <summary>
/// 每当项数据有变化时执行的事件
/// </summary>
/// <param name="transactionID"></param>
/// <param name="numItems"></param>
/// <param name="clientHandles"></param>
/// <param name="itemValues"></param>
/// <param name="qualities"></param>
/// <param name="timeStamp"></param>
private void KepGroup_DataChange(
int transactionID,
int numItems,
ref Array clientHandles,
ref Array itemValues,
ref Array qualities,
ref Array timeStamp)
{
for (int i = 1; i <= numItems; i++)
{
try
{
string strValue = "";
int idxTagName = -1;
idxTagName = int.Parse(clientHandles.GetValue(i).ToString()) - 1;
if (idxTagName >= 0 && idxTagName < tags.Count)
{
if (itemValues.GetValue(i) != null)
strValue = itemValues.GetValue(i).ToString();
TIRAPOPCTagValueItem item = new TIRAPOPCTagValueItem()
{
KepServerAddress = ipKepServer,
KepServerName = nameKepServer,
TagName = tags[idxTagName].TagName,
Value = strValue,
Quality = qualities.GetValue(i).ToString(),
TimeStamp = timeStamp.GetValue(i).ToString(),
ReceiveTime = DateTime.Now,
};
//Console.WriteLine(
// string.Format(
// "[{0}]收到消息事件:TagName[{1}],Value[{2}],TimeStamp[{3}]",
// DateTime.Now.ToString("HH:mm:ss.fff"),
// item.TagName, item.Value, item.TimeStamp));
// 将收到的消息放入待处理消息队列中
//TIRAPOPCTagValueItemQueue.Instance.Add(item);
//Debug.WriteLine(
// string.Format(
// "入队:TagName[{0}],Value[{1}],Quality[{2}],TimeStamp[{3}],共[{4}]条消息",
// item.TagName, item.Value, item.Quality, item.TimeStamp,
// TIRAPOPCTagValueItemQueue.Instance.QueueItemCount));
// 直接生成消息处理线程处理收到的消息
TOPCTagValueThread settleThread = new TOPCTagValueThread(item);
Thread thread = new Thread(new ThreadStart(settleThread.Start));
thread.Start();
}
}
catch (Exception error)
{
//Debug.WriteLine(string.Format("入队时出错:[{0}]", error.Message));
Debug.WriteLine(string.Format("处理时出错:[{0}]", error.Message));
}
}
}
private void KepGroup_AsyncWriteComplete(
int transactionID,
int numItems,
ref Array clientHandles,
ref Array errors)
{
string outputStr = "";
for (int i = 1; i <= numItems; i++)
{
outputStr +=
string.Format(
"[{0}]Trans:[{1}] CH:[{2}] Errors:[{3}]",
DateTime.Now.ToString("HH:mm:ss.fff"),
transactionID,
clientHandles.GetValue(i).ToString(),
errors.GetValue(i).ToString());
}
Console.WriteLine(outputStr);
}
public bool Init(string ipKepServer, string nameKepServer)
{
if (kepServerConnected)
kepServer.Disconnect();
this.ipKepServer = ipKepServer;
this.nameKepServer = nameKepServer;
Debug.WriteLine(
string.Format(
"连接远程服务器[{0}][{1}]......",
nameKepServer,
ipKepServer));
try
{
kepServer.Connect(nameKepServer, ipKepServer);
Debug.WriteLine("远程服务器连接成功");
}
catch (Exception error)
{
kepServerConnected = false;
Debug.WriteLine(
string.Format(
"连接远程服务器[{0}]出现错误:[{1}]",
ipKepServer,
error.Message));
return false;
}
// 连接了远程服务器后,枚举中该服务器中所有的节点
OPCBrowser browser = kepServer.CreateBrowser();
browser.ShowBranches();
browser.ShowLeafs(true);
foreach (object tag in browser)
{
string tagName = tag.ToString();
if (!tagName.Contains("._"))
tags.Add(
new TIRAPOPCTagItem()
{
TagName = tagName,
});
}
// 建立数据变化的侦听
kepGroups = kepServer.OPCGroups;
kepGroups.RemoveAll();
kepGroup = kepGroups.Add("OPCLISTENERGROUP");
kepGroups.DefaultGroupIsActive = true;
kepGroups.DefaultGroupDeadband = 0;
kepGroup.UpdateRate = 250;
kepGroup.IsActive = true;
kepGroup.IsSubscribed = true;
kepGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(KepGroup_DataChange);
kepGroup.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(KepGroup_AsyncWriteComplete);
kepItems = kepGroup.OPCItems;
for (int i = 0; i < tags.Count; i++)
{
//if (!tags[i].TagName.Contains("DATA_READY"))
//{
tags[i].ServerHandle = kepItems.AddItem(tags[i].TagName, i + 1).ServerHandle;
TIRAPOPCTag tag =
TIRAPOPCDevices.Instance.FindOPCTagItem(
string.Format(
"{0}.{1}",
nameKepServer,
tags[i].TagName));
if (tag != null)
{
tag.ServerHandle = tags[i].ServerHandle;
tag.WriteTagValueMethod = WriteTagValue;
Debug.WriteLine(
string.Format(
"TagName:[{0}], ServerHandle:[{1}]",
tag.TagName,
tag.ServerHandle));
}
//}
}
//writter.Init(ipKepServer, nameKepServer);
return true;
}
public void WriteTagValue(string TagName, string TagValue)
{
foreach (TIRAPOPCTagItem tagItem in tags)
{
if (tagItem.TagName == TagName)
{
OPCItem item = kepItems.GetOPCItem(tagItem.ServerHandle);
if (item != null)
{
item.Write(TagValue);
}
break;
}
}
}
public void WriteTagValue(
int tagServerHandle,
string tagValue,
out int errCode,
out string errText)
{
errCode = 0;
errText = "写入完成";
OPCItem item = kepItems.GetOPCItem(tagServerHandle);
if (item != null)
try
{
//item.Write(tagValue);
int[] temp = new int[2] { 0, item.ServerHandle };
Array serverHandles = (Array)temp;
object[] valueTemp = new object[2] { "", tagValue };
Array values = (Array)valueTemp;
Array error;
int cancelID;
kepGroup.AsyncWrite(
1,
ref serverHandles,
ref values,
out error,
transactionID++,
out cancelID);
}
catch (Exception error)
{
errCode = -1;
errText = string.Format("写入时发生错误:{0}", error.Message);
}
else
{
errCode = -2;
errText = "没有找到需要写入的 Tag";
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace St.EgDay3.M2.Ex0.AddedForLinq
{
class Program
{
public class Foo
{
// ADDED: Automatic properties
public string AutoProperty1 { get; set; }
public string AutoProperty2 { get; set; }
}
static void Main(string[] args)
{
// ADDED: type inference
var i = 1;
// BECAUSE: we can't specify a projected anonymous classes type
// ADDED: anonymous classes
var f = new { Prop1 = "A", Prop2 = "B" };
// BECAUSE: we need to project types
// ADDED: Collection initializers
var list = new List<Foo>()
{
new Foo() { AutoProperty1 = "1", AutoProperty2 = "2"},
new Foo() { AutoProperty1 = "3", AutoProperty2 = "4"}
};
// ADDED: lambda functions
Func<double, double> lf = x => x*x;
// BECAUSE: we need to initialized collections from projections
// ADDED: Projection
// this also uses anonymous classes, autoprop, collection intializer, type inference
// and lambda functions, extension methods (.Select)
var projected = list.Select(e => new {AutoProp = int.Parse(e.AutoProperty1)});
Console.WriteLine(projected.FirstOrDefault().AutoProp.GetType());
// ADDED: expression trees
// projected is treated underneat as an exp tree
}
}
}
|
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace RSS.WebApi.DTOs
{
public class IdentityUserDTO
{
public IdentityUser User { get; set; }
public IList<Claim> Claims { get; set; }
public IList<string> Roles { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
using UnityEditor;
/* A tool for creating sprite sheet animations quickly and easily
* @author Mike Dobson
*/
public class CreateAnimations : EditorWindow {
public static Object selectedObject;
int numAnimations;
string controllerName;
string[] animationNames = new string[100];
float[] clipFrameRate = new float[100];
float[] clipTimeBetween = new float[100];
int[] startFrames = new int[100];
int[] endFrames = new int[100];
bool[] pingPong = new bool[100];
bool[] loop = new bool[100];
[MenuItem("Project Tools/2D Animations")]
public static void Init()
{
selectedObject = Selection.activeObject;
if (selectedObject == null)
return;
CreateAnimations window = (CreateAnimations)EditorWindow.GetWindow(typeof(CreateAnimations));
window.Show();
}
void OnGUI()
{
if (selectedObject != null)
{
//Displays the object name that the animations are being created from
EditorGUILayout.LabelField("Animations for " + selectedObject.name);
//Seperator
EditorGUILayout.Separator();
//Get the name of the controller for the animations
controllerName = EditorGUILayout.TextField("Controller Name", controllerName);
//Get the number of animations
numAnimations = EditorGUILayout.IntField("How Many Animations?", numAnimations);
//Loop through each animation
for (int i = 0; i < numAnimations; i++)
{
//Determine the name of the animation
animationNames[i] = EditorGUILayout.TextField("Animation Name", animationNames[i]);
//Start a section where the following items will be displayed horozontally instead of vertically
EditorGUILayout.BeginHorizontal();
//Determine the start frame of the animation
startFrames[i] = EditorGUILayout.IntField("Start Frame", startFrames[i]);
//Determine the end frame of the animation
endFrames[i] = EditorGUILayout.IntField("End Frame", endFrames[i]);
//End the section where the previous items are displayed horozontally instead of vertically
EditorGUILayout.EndHorizontal();
//Start a section where the items will be displayed horozontally instead of vertically
EditorGUILayout.BeginHorizontal();
//Determine the frame rate of the animation
clipFrameRate[i] = EditorGUILayout.FloatField("Frame Rate", clipFrameRate[i]);
//Determine the space between each keyframe
clipTimeBetween[i] = EditorGUILayout.FloatField("Frame Spacing", clipTimeBetween[i]);
//End the section where the previous items are displayed horozontally instead of vertically
EditorGUILayout.EndHorizontal();
//Start a section where the items will be displayed horozontally instead of vertically
EditorGUILayout.BeginHorizontal();
//Create a checkbox to determine if this animation should loop
loop[i] = EditorGUILayout.Toggle("Loop", loop[i]);
//Create a checkbox to determine if this animation should pingpong
pingPong[i] = EditorGUILayout.Toggle("Ping Pong", pingPong[i]);
//End the section where items are displayed horozontally instead of vertically
EditorGUILayout.EndHorizontal();
//Seperator
EditorGUILayout.Separator();
}
//Create a button with the label Create
if (GUILayout.Button("Create"))
{
//if the button has been pressed
UnityEditor.Animations.AnimatorController controller =
UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath(("Assets/" + controllerName + ".controller"));
for (int i = 0; i < numAnimations; i++)
{
//Create animation clip
AnimationClip tempClip = CreateClip(selectedObject, animationNames[i], startFrames[i], endFrames[i], clipFrameRate[i], clipTimeBetween[i], pingPong[i]);
if (loop[i])
{
//set the loop on the clip to true
AnimationClipSettings settings = AnimationUtility.GetAnimationClipSettings(tempClip);
settings.loopTime = true;
settings.loopBlend = true;
AnimationUtility.SetAnimationClipSettings(tempClip, settings);
}
controller.AddMotion(tempClip);
}
}
}
}
public AnimationClip CreateClip(Object obj, string clipName, int startFrame, int endFrame, float frameRate, float timeBetween, bool pingPong)
{
//Get the path to the object
string path = AssetDatabase.GetAssetPath(obj);
//Extract the sprites at the path
Object[] sprites = AssetDatabase.LoadAllAssetsAtPath(path);
//Determine how many frames and the length of each frame
int frameCount = endFrame - startFrame + 1;
float frameLength = 1f / timeBetween;
//create the new empty animation clip
AnimationClip clip = new AnimationClip();
//set the framerate of the clip
clip.frameRate = frameRate;
//create the new empty curve binding
EditorCurveBinding curveBinding = new EditorCurveBinding();
//assign it to change the sprite renderer
curveBinding.type = typeof(SpriteRenderer);
//assign it to alter the sprite of the sprite renderer
curveBinding.propertyName = "m_Sprite";
//Create a container for all the keyframes
ObjectReferenceKeyframe[] keyFrames;
//Determine how many frames there will be if we are or are not pingponging
if(!pingPong)
{
keyFrames = new ObjectReferenceKeyframe[frameCount + 1];
}
else
{
keyFrames = new ObjectReferenceKeyframe[frameCount * 2 + 1];
}
//track what frame number we are on
int frameNumber = 0;
//loop from start to end, incrementing frameNumber as we go
for (int i = startFrame; i < endFrame + 1; i++, frameNumber++)
{
//create an empty keyframe
ObjectReferenceKeyframe tempKeyFrame = new ObjectReferenceKeyframe();
//Assign i a time to appear in the animation
tempKeyFrame.time = frameNumber * frameLength;
//assign it a sprite
tempKeyFrame.value = sprites[i];
//Place it into the container fro all the keyframes
keyFrames[frameNumber] = tempKeyFrame;
}
if(pingPong)
{
//create the keyframes starting at the end and going backwards
//continue to keep track of the frame number
for(int i = endFrame; i>= startFrame; i--, frameNumber++)
{
ObjectReferenceKeyframe tempkeyframe = new ObjectReferenceKeyframe();
tempkeyframe.time = frameNumber * frameLength;
tempkeyframe.value = sprites[i];
keyFrames[frameNumber] = tempkeyframe;
}
}
//Create the last sprite to stop it from switching to the first frame from the last immediately
ObjectReferenceKeyframe lastSprite = new ObjectReferenceKeyframe();
lastSprite.time = frameNumber * frameLength;
lastSprite.value = sprites[startFrame];
keyFrames[frameNumber] = lastSprite;
//assign the name to the clip
clip.name = clipName;
//apply the curve
AnimationUtility.SetObjectReferenceCurve(clip, curveBinding, keyFrames);
//create the clip
AssetDatabase.CreateAsset(clip, ("Assets/" + clipName + ".anim"));
//return the clip
return clip;
}
}
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using WebSim.Domain.Orders;
namespace WebSim.Persistence.Orders
{
public class OrderConfiguration : IEntityTypeConfiguration<Order>
{
const string priceDecimalType = "decimal(18,2)";
public void Configure(EntityTypeBuilder<Order> builder)
{
builder.Property(o => o.Comments).HasMaxLength(500);
builder.ToTable("Orders");
builder.Property(p => p.Discount).HasColumnType(priceDecimalType);
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
namespace SocketServer {
public class Server {
private TcpListener Listener { get; set; }
public Thread ListenThread { get; private set; }
private List<TcpClient> Clients { get; set; }
private bool Stop { get; set; }
private Action<string> Print { get; set; }
private Dispatcher Disp { get; set; }
public List<User> Users { get; private set; }
// TODO: Make a garbage collector over Clients, so that every none active client is removed from the server imidiatly
public Server(Action<string> print, Dispatcher dispatcher) {
Listener = new TcpListener(IPAddress.Any, 8060);
ListenThread = new Thread(ListenForClients);
Clients = new List<TcpClient>();
Print = print;
Disp = dispatcher;
Users = new List<User>();
}
public void StartServer() {
Stop = false;
Print("Server is starting");
ListenThread.Start();
}
public void Terminate() {
Listener.Stop();
Stop = true;
Clients.ForEach(x => x.Close());
Print("Done");
}
private void ListenForClients() {
Listener.Start();
while (!Stop) {
try {
var client = Listener.AcceptTcpClient();
var clientThread = new Thread(HandleClientComm);
clientThread.Start(client);
if (!Clients.Contains(client)) {
Clients.Add(client);
}
} catch (SocketException) { }
}
}
private void HandleClientComm(object client) {
using(var tcpClient = (TcpClient)client)
using(var ns = tcpClient.GetStream())
using (var sw = new StreamWriter(ns)) {
var message = new byte[4096];
while (true) {
var bytesRead = 0;
try {
bytesRead = ns.Read(message, 0, 4096);
} catch {
break;
}
if (bytesRead == 0) {
break;
}
var address = tcpClient.Client.RemoteEndPoint;
var encoder = new UTF8Encoding();
var m = encoder.GetString(message, 0, bytesRead).Split('\n')[0];
Disp.Invoke(() => Print("(from client: " + address + ") => " + m));
var s = encoder.GetString(message, 0, bytesRead);
if (!ns.CanWrite) continue;
sw.WriteLine(s);
sw.Flush();
}
if (!tcpClient.Connected && Clients.Contains(tcpClient)) {
Clients.Remove(tcpClient);
}
}
}
}
} |
using SciVacancies.Domain.Enums;
using System;
using NPoco;
namespace SciVacancies.ReadModel.Core
{
[TableName("res_notifications")]
[PrimaryKey("guid", AutoIncrement = false)]
public class ResearcherNotification : BaseEntity
{
public string title { get; set; }
public Guid vacancy_guid { get; set; }
public Guid researcher_guid { get; set; }
public NotificationStatus status { get; set; }
public DateTime creation_date { get; set; }
public DateTime? update_date { get; set; }
}
}
|
using System;
using Microsoft.AspNetCore.Mvc;
using NetFive.Services;
namespace NetFive.Controllers
{
[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{
private readonly IUsersService usersService;
public UsersController(IUsersService usersService)
{
this.usersService = usersService;
}
[HttpGet("{id}")]
public IActionResult GetUser(Guid id)
{
return this.Ok(this.usersService.Get(id));
}
}
} |
using FluentMigrator;
namespace Profiling2.Migrations.Seeds
{
[Migration(201301230939)]
public class PRF_seeds : Migration
{
public override void Down()
{
Delete.FromTable("PRF_AdminAuditType").AllRows();
Delete.FromTable("PRF_ActionTakenType").AllRows();
Delete.FromTable("PRF_PersonResponsibilityType").AllRows();
Delete.FromTable("PRF_PersonRelationshipType").AllRows();
Delete.FromTable("PRF_OrganizationResponsibilityType").AllRows();
Delete.FromTable("PRF_OrganizationRelationshipType").AllRows();
Delete.FromTable("PRF_UnitHierarchyType").AllRows();
Delete.FromTable("PRF_Reliability").AllRows();
Delete.FromTable("PRF_ProfileStatus").AllRows();
Delete.FromTable("PRF_AdminSuggestionFeaturePersonResponsibility").AllRows();
Delete.FromTable("PRF_EventRelationshipType").AllRows();
}
public override void Up()
{
//Execute.EmbeddedScript("201301230939_PRF_seeds.sql");
Insert.IntoTable("PRF_AdminAuditType").Row(new { AdminAuditTypeName = "INSERT" });
Insert.IntoTable("PRF_AdminAuditType").Row(new { AdminAuditTypeName = "UPDATE" });
Insert.IntoTable("PRF_AdminAuditType").Row(new { AdminAuditTypeName = "DELETE" });
Insert.IntoTable("PRF_ActionTakenType").Row(new
{
ActionTakenTypeName = "ordered arrest of alleged perpetrator(s)",
Notes = "Subject ordered arrest of alleged perpetrator(s). Object not identified."
});
Insert.IntoTable("PRF_ActionTakenType").Row(new
{
ActionTakenTypeName = "ordered arrest of",
Notes = "Subject ordered arrest of object."
});
Insert.IntoTable("PRF_ActionTakenType").Row(new
{
ActionTakenTypeName = "arrested the alleged perpetrator(s)",
Notes = "Subject arrested the alleged perpetrator(s). Object not identified."
});
Insert.IntoTable("PRF_ActionTakenType").Row(new
{
ActionTakenTypeName = "arrested",
Notes = "Subject arrested object."
});
Insert.IntoTable("PRF_ActionTakenType").Row(new
{
ActionTakenTypeName = "Alleged perpetrator(s) arrested",
Notes = "Alleged perpetrator(s) arrested. Subject and object not identified."
});
Insert.IntoTable("PRF_ActionTakenType").Row(new
{
ActionTakenTypeName = "arrested by",
Notes = "Subject arrested by object."
});
Insert.IntoTable("PRF_ActionTakenType").Row(new
{
ActionTakenTypeName = "Investigation opened",
Notes = "Investigation opened. Subject and object not identified."
});
Insert.IntoTable("PRF_ActionTakenType").Row(new
{
ActionTakenTypeName = "Alleged perpetrator(s) transferred to military prosecutor's office",
Notes = "Alleged perpetrator(s) transferred to military prosecutor's office. Subject and object not identified."
});
Insert.IntoTable("PRF_ActionTakenType").Row(new
{
ActionTakenTypeName = "transferred to military prosecutor's office",
Notes = "Subject transferred to military prosecutor''s office. Object not identified."
});
Insert.IntoTable("PRF_ActionTakenType").Row(new
{
ActionTakenTypeName = "sentenced",
Notes = "Subject sentenced. Object not identified."
});
Insert.IntoTable("PRF_ActionTakenType").Row(new
{
ActionTakenTypeName = "Perpetrator(s) sentenced",
Notes = "Perpetrator(s) sentenced. Subject and object not identified."
});
Insert.IntoTable("PRF_ActionTakenType").Row(new
{
ActionTakenTypeName = "Other",
Notes = "An action taken type that is not captured with the standardized list."
});
Insert.IntoTable("PRF_ActionTakenType").Row(new { ActionTakenTypeName = "Complaint lodged" });
Insert.IntoTable("PRF_ActionTakenType").Row(new { ActionTakenTypeName = "released the victim(s)" });
Insert.IntoTable("PRF_ActionTakenType").Row(new { ActionTakenTypeName = "was arrested" });
Insert.IntoTable("PRF_ActionTakenType").Row(new { ActionTakenTypeName = "released the alleged perpetrator(s)" });
Insert.IntoTable("PRF_ActionTakenType").Row(new { ActionTakenTypeName = "interfered in the legal process" });
Insert.IntoTable("PRF_ActionTakenType").Row(new { ActionTakenTypeName = "was released" });
Insert.IntoTable("PRF_ActionTakenType").Row(new { ActionTakenTypeName = "was acquitted " });
Insert.IntoTable("PRF_ActionTakenType").Row(new { ActionTakenTypeName = "Alleged perpetrator(s) acquitted " });
Insert.IntoTable("PRF_ActionTakenType").Row(new { ActionTakenTypeName = "Victim(s) released" });
Insert.IntoTable("PRF_ActionTakenType").Row(new { ActionTakenTypeName = "Minor was demobilized" });
Insert.IntoTable("PRF_PersonResponsibilityType").Row(new { PersonResponsibilityTypeName = "Command" });
Insert.IntoTable("PRF_PersonResponsibilityType").Row(new { PersonResponsibilityTypeName = "Direct" });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new
{
PersonRelationshipTypeName = "has direct family links with",
Notes = "ascendents, descendents, brothers, sisters",
IsCommutative = 1
});
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is schoolmates with", IsCommutative = 1 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is business partner with", IsCommutative = 1 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is a superior to", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is a mentor to", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "fought with", IsCommutative = 1 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is a friend of", IsCommutative = 1 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is a political associate of", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "has family connections with", IsCommutative = 1 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "belongs to the same clan as", IsCommutative = 1 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "has ethnic ties with", IsCommutative = 1 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is a subordinate of", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "acted together with", IsCommutative = 1 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "could be the same person known as", IsCommutative = 1 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is the deputy of", IsCommutative = 1 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is the bodyguard of", IsCommutative = 1 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new
{
PersonRelationshipTypeName = "fought in the same group as",
Notes = "when no information on hierarchy is available and individuals are not related to specific events",
IsCommutative = 1
});
Insert.IntoTable("PRF_PersonRelationshipType").Row(new
{
PersonRelationshipTypeName = "belonged to the same group as ",
Notes = "when no information on hierarchy is available ; individuals are not related to specific events ; no information on their participation to fightings",
IsCommutative = 1
});
Insert.IntoTable("PRF_PersonRelationshipType").Row(new
{
PersonRelationshipTypeName = "is NOT the same person as",
Notes = "Two different persons not to be confused",
IsCommutative = 1
});
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "often works with", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is the same person as", IsCommutative = 1 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is a potential rival of", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "replaced", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is PROBABLY NOT the same person as", IsCommutative = 1 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is in conflict with", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "has contacts with", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "has no real authority on", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "provided weapons and ammunition to", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "fought against", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is suspected to be close to", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "was a political associate", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is from the same village as", IsCommutative = 1 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "went to the same school as", IsCommutative = 1 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "provided financial/material support to", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is close to", IsCommutative = 1 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is PROBABLY the same person as", IsCommutative = 1 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "looks like same person", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "AKA", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is the young brother of", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is a colleague of", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "alias", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "was a superior to", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "was a subordinate to", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "was replaced by", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "worked with", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "could be the same person as", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is a superior", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "swapped command posts with", IsCommutative = 1 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is allegedly enjoying the protection of", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "allegedly protects", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "was the deputy of", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "aided", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "was the bodyguard of", IsCommutative = 0 });
Insert.IntoTable("PRF_PersonRelationshipType").Row(new { PersonRelationshipTypeName = "is a subordinate", IsCommutative = 0 });
Insert.IntoTable("PRF_OrganizationResponsibilityType").Row(new { OrganizationResponsibilityTypeName = "Command", Notes = "There was no known plan to commit the HRV according to the information available." });
Insert.IntoTable("PRF_OrganizationResponsibilityType").Row(new { OrganizationResponsibilityTypeName = "Operational" });
Insert.IntoTable("PRF_OrganizationResponsibilityType").Row(new { OrganizationResponsibilityTypeName = "Material Participant" });
Insert.IntoTable("PRF_OrganizationResponsibilityType").Row(new { OrganizationResponsibilityTypeName = "Main organization involved in the HRV" });
Insert.IntoTable("PRF_OrganizationResponsibilityType").Row(new { OrganizationResponsibilityTypeName = "Supporting Organization" });
Insert.IntoTable("PRF_OrganizationRelationshipType").Row(new { OrganizationRelationshipTypeName = "evolved from" });
Insert.IntoTable("PRF_OrganizationRelationshipType").Row(new { OrganizationRelationshipTypeName = "partnered with" });
Insert.IntoTable("PRF_OrganizationRelationshipType").Row(new { OrganizationRelationshipTypeName = "is superior to" });
Insert.IntoTable("PRF_OrganizationRelationshipType").Row(new { OrganizationRelationshipTypeName = "fought against" });
Insert.IntoTable("PRF_OrganizationRelationshipType").Row(new { OrganizationRelationshipTypeName = "sub group of" });
Insert.IntoTable("PRF_OrganizationRelationshipType").Row(new { OrganizationRelationshipTypeName = "is a commander" });
Insert.IntoTable("PRF_UnitHierarchyType").Row(new { UnitHierarchyTypeName = "DSRSG" });
Insert.IntoTable("PRF_UnitHierarchyType").Row(new { UnitHierarchyTypeName = "Force" });
Insert.IntoTable("PRF_UnitHierarchyType").Row(new { UnitHierarchyTypeName = "Hierarchy" });
Insert.IntoTable("PRF_UnitHierarchyType").Row(new { UnitHierarchyTypeName = "Operation" });
Insert.IntoTable("PRF_UnitHierarchyType").Row(new { UnitHierarchyTypeName = "Unknown" });
Insert.IntoTable("PRF_Reliability").Row(new { ReliabilityName = "High" });
Insert.IntoTable("PRF_Reliability").Row(new { ReliabilityName = "Moderate" });
Insert.IntoTable("PRF_Reliability").Row(new { ReliabilityName = "Low" });
Insert.IntoTable("PRF_ProfileStatus").Row(new { ProfileStatusName = "Rough outline", Notes = "For profiles with a name, and very rough career and/or human rights information" });
Insert.IntoTable("PRF_ProfileStatus").Row(new { ProfileStatusName = "In progress", Notes = "For more developed profiles, with a solid amount of career and human rights information." });
Insert.IntoTable("PRF_ProfileStatus").Row(new { ProfileStatusName = "Complete", Notes = "For profiles which are comprehensive, given the available information, and complete as of the last update." });
Insert.IntoTable("PRF_ProfileStatus").Row(new { ProfileStatusName = "FARDC 2007 List", Notes = "Imported following the integration of DSRSG's list of 2007 FARDC integrated soldiers of all ranks. No profiles." });
// referenced by ID number in Entity class
Insert.IntoTable("PRF_AdminSuggestionFeaturePersonResponsibility").Row(new { Feature = "Profiled person has a relationship with a person bearing responsibility for suggested event.", CurrentWeight = 10, Archive = 1, Notes = "Constrained by dates." });
Insert.IntoTable("PRF_AdminSuggestionFeaturePersonResponsibility").Row(new { Feature = "Profiled person bears responsibility to an event related to suggested event.", CurrentWeight = 8 });
Insert.IntoTable("PRF_AdminSuggestionFeaturePersonResponsibility").Row(new { Feature = "Profiled person's last name appears in suggested event's narrative.", CurrentWeight = 7, Notes = "Each word separated by a space is checked individually." });
Insert.IntoTable("PRF_AdminSuggestionFeaturePersonResponsibility").Row(new { Feature = "Profiled person's first name appears in suggested event's narrative.", CurrentWeight = 2, Notes = "Each word separated by a space is checked individually." });
Insert.IntoTable("PRF_AdminSuggestionFeaturePersonResponsibility").Row(new { Feature = "Profiled person shares a source with suggested event.", CurrentWeight = 5 });
Insert.IntoTable("PRF_AdminSuggestionFeaturePersonResponsibility").Row(new { Feature = "Profiled person's alias appears in suggested event's narrative.", CurrentWeight = 4, Notes = "Each word separated by a space is checked individually." });
Insert.IntoTable("PRF_AdminSuggestionFeaturePersonResponsibility").Row(new { Feature = "Profiled person has a career in the location or territory of the suggested event.", CurrentWeight = 3, Notes = "Constained by dates." });
Insert.IntoTable("PRF_AdminSuggestionFeaturePersonResponsibility").Row(new { Feature = "Profiled person has a career in an organization bearing responsibility for suggested event.", CurrentWeight = 2, Notes = "Constrained by dates." });
Insert.IntoTable("PRF_AdminSuggestionFeaturePersonResponsibility").Row(new { Feature = "Profiled person bears responsibility for an event occurring in the same location or territory as suggested event.", CurrentWeight = 1 });
Insert.IntoTable("PRF_AdminSuggestionFeaturePersonResponsibility").Row(new { Feature = "Profiled person is part of an \"is superior to\" relationship with a person bearing responsibility for suggested event.", CurrentWeight = 10, Notes = "Constrained by dates." });
Insert.IntoTable("PRF_AdminSuggestionFeaturePersonResponsibility").Row(new { Feature = "Profiled person is part of an \"is a subordinate of\" relationship with a person bearing responsibility for suggested event.", CurrentWeight = 10, Notes = "Constrained by dates." });
Insert.IntoTable("PRF_AdminSuggestionFeaturePersonResponsibility").Row(new { Feature = "Profiled person is part of an \"is the deputy of\" relationship with a person bearing responsibility for suggested event.", CurrentWeight = 10, Notes = "Constrained by dates." });
Insert.IntoTable("PRF_AdminSuggestionFeaturePersonResponsibility").Row(new { Feature = "Profiled person is part of an \"provided weapons and ammunition to\" relationship with a person bearing responsibility for suggested event.", CurrentWeight = 7, Notes = "Constrained by dates." });
Insert.IntoTable("PRF_AdminSuggestionFeaturePersonResponsibility").Row(new { Feature = "Profiled person is part of an \"fought with\" relationship with a person bearing responsibility for suggested event.", CurrentWeight = 7, Notes = "Constrained by dates." });
Insert.IntoTable("PRF_AdminSuggestionFeaturePersonResponsibility").Row(new { Feature = "Profiled person is part of an \"acted together with\" relationship with a person bearing responsibility for suggested event.", CurrentWeight = 7, Notes = "Constrained by dates." });
Insert.IntoTable("PRF_AdminSuggestionFeaturePersonResponsibility").Row(new { Feature = "Profiled person is part of an \"is the bodyguard of\" relationship with a person bearing responsibility for suggested event.", CurrentWeight = 7, Notes = "Constrained by dates." });
Insert.IntoTable("PRF_AdminSuggestionFeaturePersonResponsibility").Row(new { Feature = "Profiled person is part of an \"fought in same group as\" relationship with a person bearing responsibility for suggested event.", CurrentWeight = 3, Notes = "Constrained by dates." });
Insert.IntoTable("PRF_AdminSuggestionFeaturePersonResponsibility").Row(new { Feature = "Profiled person is part of an \"belonged to the same group as\" relationship with a person bearing responsibility for suggested event.", CurrentWeight = 3, Notes = "Constrained by dates." });
Insert.IntoTable("PRF_AdminSuggestionFeaturePersonResponsibility").Row(new { Feature = "Profiled person has a career a unit bearing responsibility for suggested event.", CurrentWeight = 5, Notes = "Constrained by dates." });
Insert.IntoTable("PRF_EventRelationshipType").Row(new { EventRelationshipTypeName = "is a reprisal for" });
Insert.IntoTable("PRF_EventRelationshipType").Row(new { EventRelationshipTypeName = "is in response to" });
Insert.IntoTable("PRF_EventRelationshipType").Row(new { EventRelationshipTypeName = "occurred simultaneously" });
Insert.IntoTable("PRF_EventRelationshipType").Row(new { EventRelationshipTypeName = "are related" });
}
}
}
|
using MikeGrayCodes.BuildingBlocks.Application.Behaviors;
using MikeGrayCodes.Ordering.Application.Application.Commands;
using MikeGrayCodes.Ordering.Domain.Entities.Orders;
using System.Threading;
using System.Threading.Tasks;
namespace MikeGrayCodes.Ordering.Application.Commands.CancelOrder
{
public class CancelOrderExistsHandler : IExistsHandler<CancelOrderCommand>
{
private readonly IOrderRepository orderRepository;
public CancelOrderExistsHandler(IOrderRepository orderRepository)
{
this.orderRepository = orderRepository;
}
public async Task<bool> Evaluate(CancelOrderCommand request, CancellationToken cancellationToken = default)
{
var orderToUpdate = await orderRepository.GetAsync(request.OrderNumber);
return orderToUpdate != null;
}
}
}
|
using Cs_IssPrefeitura.Dominio.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace Cs_IssPrefeitura.Dominio.Interfaces.Servicos
{
public interface IServicoAtoIss: IServicoBase<AtoIss>
{
AtoIss CalcularValoresAtoIss(AtoIss atoCalcular);
List<AtoIss> LerArquivoXml(string caminho);
List<string> CarregarListaAtribuicoes();
List<string> CarregarListaTipoAtos();
List<AtoIss> ListarAtosPorPeriodo(DateTime inicio, DateTime fim);
List<AtoIss> VerificarRegistrosExistentesPorData(DateTime data);
List<AtoIss> ConsultaDetalhada(string tipoConsulta, string dados);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2.WrongOrder
{
class UnOrder
{
//not working properly
// arr[2] always must be input
// arr[1] = previous input
// arr[0] = pre-previous input
static byte input;
static void Main()
{
while (true)
{
byte counter = 0;
byte[] arr = new byte[4];
for (int index = 1; index < arr.Length ; index++)
{
input = byte.Parse(Console.ReadLine());
arr[index - 1] = input;
if (arr[index] == arr[2])
{
arr[2] = 0; // or = input
//arr[index] = arr[index - 1];
}
Console.Write(arr[0] + " " + arr[1] + " " + arr[2]);
Console.WriteLine();
if ( arr[1] > arr[0] && arr[1] > arr[2])
{
counter++;
}
}
if (input == 0 || input > 200)
{
Console.WriteLine(counter + "+");
break;
}
}
}
}
}
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Linq;
using System.Threading.Tasks;
using CollectionsWorkAngular.Constants;
using CollectionsWorkAngular.Data.Comments;
using CollectionsWorkAngular.Data.Persons;
using CollectionsWorkAngular.Data.Users;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace CollectionsWorkAngular.Data
{
/// <summary>
/// Класс, который предостовляет методы для пополнения базы данных данными в случае если их там нет
/// </summary>
public class DbSeeder
{
#region Приватные поля
private ApplicationDbContext DbContext;
private RoleManager<IdentityRole> RoleManager;
private UserManager<ApplicationUser> UserManager;
#endregion
#region Конструктор
public DbSeeder(ApplicationDbContext dbContext, RoleManager<IdentityRole> roleManager,
UserManager<ApplicationUser> userManager)
{
DbContext = dbContext;
this.RoleManager = roleManager;
this.UserManager = userManager;
}
#endregion
#region Публичные методы
public async Task SeedAsync()
{
// Проверяем, создана ли база данных. Если нет, то данный метод создаст базу, если база существует то ничего не произойдёт
//TODO Если базы нет, то данный метод создаст базу, но не будет использовать миграции!!! То есть база не будет готова к дальнейшим обновлениям моделей
//Необходимо заменить данный метод на Migrate(), чтобы убедиться, что база создана с помощью миграций Entity Framework
//Автор(Sanctis) ничего не сказал об этом, поэтому, не нарушая последовательность книги я оставлю это место для дальнейшего редактирования
DbContext.Database.EnsureCreated();
// Создаём пользователей(ApplicationUser) и добавляем их в базу, если их там нет
if (await DbContext.Users.CountAsync() == 0) await CreateUsersAsync();
// Создаём людей(Person) и комментарии к каждому из них, и добавляем их в базу, если их там нет
if (await DbContext.People.CountAsync() == 0) CreatePeople();
}
#endregion
#region Seed Methods
private async Task CreateUsersAsync()
{
// локальные переменные
DateTime createdDate = new DateTime(2016, 03, 01, 12, 30, 00);
DateTime lastModifiedDate = DateTime.Now;
string role_Administrators = "Administrators";
string role_Registered = "Registered";
//Создаём роли, если их нет в базе
if (!await RoleManager.RoleExistsAsync(role_Administrators))
await RoleManager.CreateAsync(new IdentityRole(role_Administrators));
if (!await RoleManager.RoleExistsAsync(role_Registered))
await RoleManager.CreateAsync(new IdentityRole(role_Registered));
// Создаём админа(ApplicationUser), если его нет в базе
var user_Admin = new ApplicationUser()
{
UserName = "Admin",
Email = "admin@opengamelist.com",
CreatedDate = createdDate,
LastModifiedDate = lastModifiedDate
};
//Добавляем пользователя "Admin" в базу данных и назначаем ему роль "Administrator"
if (await UserManager.FindByIdAsync(user_Admin.Id) == null)
{
await UserManager.CreateAsync(user_Admin, "Pass4Admin");
await UserManager.AddToRoleAsync(user_Admin, role_Administrators);
//Снимаем блокировку(Lockout) и Email подтверждение
user_Admin.EmailConfirmed = true;
user_Admin.LockoutEnabled = false;
}
#if DEBUG
// Создаём еще пару пользователей, в случае если их нет в базе
var user_Ryan = new ApplicationUser()
{
UserName = "Ryan",
Email = "ryan@opengamelist.com",
CreatedDate = createdDate,
LastModifiedDate = lastModifiedDate,
EmailConfirmed = true,
LockoutEnabled = false
};
var user_Solice = new ApplicationUser()
{
UserName = "Solice",
Email = "solice@opengamelist.com",
CreatedDate = createdDate,
LastModifiedDate = lastModifiedDate,
EmailConfirmed = true,
LockoutEnabled = false
};
var user_Vodan = new ApplicationUser()
{
UserName = "Vodan",
Email = "vodan@opengamelist.com",
CreatedDate = createdDate,
LastModifiedDate = lastModifiedDate,
EmailConfirmed = true,
LockoutEnabled = false
};
if (await UserManager.FindByIdAsync(user_Ryan.Id) == null)
{
await UserManager.CreateAsync(user_Ryan, "Pass4Ryan");
await UserManager.AddToRoleAsync(user_Ryan, role_Registered);
user_Ryan.EmailConfirmed = true;
user_Ryan.LockoutEnabled = false;
}
if (await UserManager.FindByIdAsync(user_Solice.Id) == null)
{
await UserManager.CreateAsync(user_Solice, "Pass4Solice");
await UserManager.AddToRoleAsync(user_Solice, role_Registered);
user_Solice.EmailConfirmed = true;
user_Solice.LockoutEnabled = false;
}
if (await UserManager.FindByIdAsync(user_Vodan.Id) == null)
{
await UserManager.CreateAsync(user_Vodan, "Pass4Vodan");
await UserManager.AddToRoleAsync(user_Vodan, role_Registered);
user_Vodan.EmailConfirmed = true;
user_Vodan.LockoutEnabled = false;
}
#endif
//сохраняем изменения, сделанные в контексте
await DbContext.SaveChangesAsync();
}
private void CreatePeople()
{
DateTime createdDate = new DateTime(2016, 03, 01, 12, 30, 00);
var authorId = DbContext.Users.Where(u => u.UserName == "Admin").FirstOrDefault().Id;
EntityEntry<Person> e1 = DbContext.People.Add(new Person()
{
FirstName = "Василий",
LastName = "Пупкин",
About = "Люблю программировать",
Age = 55,
CreatedDate = DateTime.Today,
UserId = authorId,
Gender = Gender.Male,
LastModifiedDate = DateTime.Today,
ViewCount = 10
});
EntityEntry<Person> e2 = DbContext.People.Add(new Person()
{
FirstName = "Иван",
LastName = "Петров",
About = "Люблю рисовать",
Age = 20,
CreatedDate = DateTime.Today,
UserId = authorId,
Gender = Gender.Male,
LastModifiedDate = DateTime.Today,
ViewCount = 7
});
EntityEntry<Person> e3 = DbContext.People.Add(new Person()
{
FirstName = "Сергей",
LastName = "Иванов",
About = "Люблю петь",
Age = 16,
CreatedDate = DateTime.Today,
UserId = authorId,
Gender = Gender.Male,
LastModifiedDate = DateTime.Today,
ViewCount = 15
});
EntityEntry<Person> e4 = DbContext.People.Add(new Person()
{
FirstName = "Маша",
LastName = "Зайцева",
About = "Обожаю готовить",
Age = 25,
CreatedDate = DateTime.Today,
UserId = authorId,
Gender = Gender.Female,
LastModifiedDate = DateTime.Today,
ViewCount = 150
});
if (DbContext.Comments.Count() == 0)
{
//добавляем каждому пёрсону по 10 комментариев
int numComments = 10;
for (int i = 1; i <= numComments; i++) DbContext.Comments.Add(GetSampleComment(i, e1.Entity.Id, authorId, createdDate.AddDays(i)));
for (int i = 1; i <= numComments; i++) DbContext.Comments.Add(GetSampleComment(i, e2.Entity.Id, authorId, createdDate.AddDays(i)));
for (int i = 1; i <= numComments; i++) DbContext.Comments.Add(GetSampleComment(i, e3.Entity.Id, authorId, createdDate.AddDays(i)));
for (int i = 1; i <= numComments; i++) DbContext.Comments.Add(GetSampleComment(i, e4.Entity.Id, authorId, createdDate.AddDays(i)));
}
DbContext.SaveChanges();
}
#endregion Seed Methods
#region Helpers
//Вспомогательный метод для генерации фейковых комментариев
private Comment GetSampleComment(int n, int PersonId, string authorId, DateTime createdDate)
{
return new Comment()
{
PersonId = PersonId,
UserId = authorId,
ParentId = null,
Text = String.Format("Sample comment #{0} for the Person #{1}", n, PersonId),
CreatedDate = createdDate,
LastModifiedDate = createdDate
};
}
#endregion
}
} |
//
// ProviderBase.cs
//
// Author:
// nofanto ibrahim <nofanto.ibrahim@gmail.com>
//
// Copyright (c) 2011 sejalan
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Specialized;
namespace Sejalan.Framework.Provider
{
/// <summary>
/// Base class for framework's provider.
/// </summary>
public class ProviderBase
{
// Fields
private string _Description;
private bool _Initialized;
private string _name;
private NameValueCollection _Parameters;
/// <summary>
/// Gets the parameters.
/// </summary>
/// <value>The parameters.</value>
public virtual NameValueCollection Parameters
{
get { return _Parameters; }
}
/// <summary>
/// Initializes a new instance of the <see cref="ProviderBase"/> class.
/// </summary>
protected ProviderBase()
{
}
/// <summary>
/// Initializes the specified name.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="config">The config.</param>
public virtual void Initialize(string name, NameValueCollection config)
{
lock (this)
{
if (this._Initialized)
{
throw new InvalidOperationException("ProviderAlreadyInitialized");
}
this._Initialized = true;
}
if (name == null)
{
throw new ArgumentNullException("name");
}
if (name.Length == 0)
{
throw new ArgumentException("ConfigProviderNameNullEmpty");
}
this._name = name;
if (config != null)
{
this._Description = config["description"];
config.Remove("description");
}
this._Parameters = config;
}
/// <summary>
/// Gets the description.
/// </summary>
/// <value>The description.</value>
public virtual string Description
{
get
{
if (!string.IsNullOrEmpty(this._Description))
{
return this._Description;
}
return this.Name;
}
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public virtual string Name
{
get
{
return this._name;
}
}
}
}
|
namespace CodingMilitia.PlayBall.WebFrontend.BackForFront.Web.Features.Auth
{
public class AuthInfoModel
{
public string Name { get; set; }
}
} |
//using System;
//using System.CodeDom;
//using OpenQA.Selenium;
//using OpenQA.Selenium.Support.UI;
//using Kliiko.Ui.Tests.Environment;
//using System.Threading;
//using TechTalk.SpecFlow;
//using Kliiko.Ui.Tests.Selenium;
//using System.Globalization;
//namespace Kliiko.Ui.Tests.WebPages.Blocks
//{
// class SurveyPage : WebPage
// {
// private static readonly By LABEL_SURVEY = By.XPath("//*[@id='survey-content']//*[@class='text-center']");
// private static readonly By BUTTON_CREATE_NEW = By.XPath("//*[@id='survey-content']//*[@class='btn btn-addNewElement btn-green']");
// private static readonly By CONTAINER_SURVEY = By.XPath("//*[@id='survey-content']//*[@class='background-green']");
// private static readonly By LABEL_MANAGE_SURVEY = By.XPath("//*[@id='manageForm']");
// private static readonly By BUTTON_BACK = By.XPath("(//*[@id='manageForm']//*[@class='btn btn-addNewElement btn-green'])[1]");
// private static readonly By PANEL_INTRODUCTION = By.XPath("//*[@id='panel-introduction']");
// private static readonly By BUTTON_QUESTION_ONE_PLUS = By.XPath("(//*[@name='answers']//*[@src='/icons/add_new_list_blue.png'])[1]");
// private static readonly By BUTTON_QUESTION_TWO_PLUS = By.XPath("(//*[@name='answers']//*[@src='/icons/add_new_list_blue.png'])[2]");
// #region [Introduction]
// private static readonly By INTRODUCTION_INPUT_NAME = By.XPath("//*[@id='panel-introduction']//*[@id='surveyName']");
// private static readonly By INTRODUCTION_INPUT_DESCRIPTION = By.XPath("//*[@id='panel-introduction']//*[@id='description']");
// private static readonly By INTRODUCTION_VALIDATION_NAME = By.XPath("(//*[@ng-repeat='error in sc.validationErrors'])[3]");
// #endregion
// #region [Question 1]
// private static readonly By PANEL_QUESTION_ONE = By.XPath("//*[@id='manageForm']//*[@id='panel-0']");
// private static readonly By QUESTION_ONE_INPUT_NAME = By.XPath("//*[@id='panel-0']//*[@name='name']");
// private static readonly By QUESTION_ONE_INPUT_QUESTION = By.XPath("//*[@id='panel-0']//*[@name='question']");
// private static readonly By QUESTION_ONE_INPUT_ANSWER_ONE = By.XPath("//*[@id='panel-0']//*[@id='answer-0-0']");
// private static readonly By QUESTION_ONE_INPUT_ANSWER_TWO = By.XPath("//*[@id='panel-0']//*[@id='answer-0-1']");
// private static readonly By QUESTION_ONE_INPUT_ANSWER_THREE = By.XPath("//*[@id='panel-0']//*[@id='answer-0-2']");
// private static readonly By QUESTION_ONE_BUTTON_ENABLE = By.XPath("//*[@id='panel-0']//*[@ng-click='sc.changeQuestions(question, object.order)']");
// private static readonly By QUESTION_ONE_VALDIATION_NAME = By.XPath("(//*[@ng-repeat='error in sc.validationErrors'])[9]");
// private static readonly By QUESTION_ONE_VALIDATION_ANSWER_ONE =By.XPath("(//*[@ng-repeat='error in sc.validationErrors'])[15]");
// private static readonly By QUESTION_ONE_VALIDATION_ANSWER_TWO = By.XPath("(//*[@ng-repeat='error in sc.validationErrors'])[18]");
// #endregion
// #region [Question 2]
// private static readonly By PANEL_QUESTION_TWO = By.XPath("//*[@id='manageForm']//*[@id='panel-1']");
// private static readonly By QUESTION_TWO_INPUT_NAME = By.XPath("//*[@id='panel-1']//*[@id='questionName-1']");
// private static readonly By QUESTION_TWO_INPUT_QUESTION = By.XPath("//*[@id='panel-1']//*[@name='question']");
// private static readonly By QUESTION_TWO_INPUT_ANSWER_ONE = By.XPath("//*[@id='panel-1']//*[@id='answer-1-0']");
// private static readonly By QUESTION_TWO_INPUT_ANSWER_TWO = By.XPath("//*[@id='panel-1']//*[@id='answer-1-1']");
// private static readonly By QUESTION_TWO_INPUT_ANSWER_THREE = By.XPath("//*[@id='panel-1']//*[@id='answer-1-2']");
// private static readonly By QUESTION_TWO_BUTTON_ENABLE = By.XPath("//*[@id='panel-1']//*[@ng-click='sc.changeQuestions(question, object.order)']");
// private static readonly By QUESTION_TWO_VALIDATION_NAME = By.XPath("(//*[@ng-repeat='error in sc.validationErrors'])[21]");
// private static readonly By QUESTION_TWO_VALIDATION_ANSWER_ONE =By.XPath("(//*[@ng-repeat='error in sc.validationErrors'])[27]");
// private static readonly By QUESTION_TWO_VALIDATION_ANSWER_TWO = By.XPath("(//*[@ng-repeat='error in sc.validationErrors'])[30]");
// #endregion
// #region [Question 3]
// private static readonly By PANEL_QUESTION_THREE = By.XPath("");
// #endregion
// #region [LikeDislke]
// private static readonly By PANEL_LIKE_DISLIKE = By.XPath("(//*[@id='panel-3']//*[@class='ng-scope'])[1]");
// private static readonly By LIKE_DISLIKE_INPUT_NAME = By.XPath("//*[@id='panel-3']//*[@id='questionName-3']");
// private static readonly By LIKE_DISLIKE_INPUT_QUESTION = By.XPath("//*[@id='panel-3']//*[@name='question']");
// private static readonly By LIKE_DISLIKE_INPUT_ANSWER_ONE = By.XPath("//*[@id='panel-3']//*[@id='answer-3-0']");
// private static readonly By LIKE_DISLIKE_INPUT_ANSWER_TWO = By.XPath("//*[@id='panel-3']//*[@id='answer-3-1']");
// private static readonly By LIKE_DISLIKE_BUTTON_ENABLE = By.XPath("//*[@id='panel-3']//*[@ng-click='sc.changeQuestions(question, object.order)']");
// private static readonly By LIKE_DISLIKE_VALIDATION_NAME = By.XPath("(//*[@ng-repeat='error in sc.validationErrors'])[39]");
// private static readonly By LIKE_DISLIKE_VALIDATION_ANSWER_ONE = By.XPath("(//*[@ng-repeat='error in sc.validationErrors'])[48]");
// private static readonly By LIKE_DISLIKE_VALIDATION_ANSWER_TWO = By.XPath("(//*[@ng-repeat='error in sc.validationErrors'])[51]");
// #endregion
// #region [Importance]
// private static readonly By PANEL_IMPORTANCE = By.XPath("//*[@id='panel-4']//*[@class='panel-title']");
// private static readonly By IMPORTANCE_INPUT_NAME = By.XPath("//*[@id='panel-4']//*[@id='questionName-4']");
// private static readonly By IMPORTANCE_INPUT_QUESTION = By.XPath("//*[@id='panel-4']//*[@name='question']");
// private static readonly By IMPORTANCE_ANSWER_ONE = By.XPath("//*[@id='panel-4']//*[@id='answer-4-0']");
// private static readonly By IMPORTANCE_ANSWER_TWO = By.XPath("//*[@id='panel-4']//*[@id='answer-4-1']");
// private static readonly By IMPORTANCE_BUTTON_ENABLE = By.XPath("//*[@id='panel-4']//*[@ng-click='sc.changeQuestions(question, object.order)']");
// private static readonly By IMPORTANCE_VALIDATION_NAME = By.XPath("(//*[@ng-repeat='error in sc.validationErrors'])[54]");
// private static readonly By IMPORTANCE_VALIDATION_ANSWER_ONE = By.XPath("(//*[@ng-repeat='error in sc.validationErrors'])[63]");
// private static readonly By IMPORTANCE_VALIDATION_ANSWER_TWO = By.XPath("(//*[@ng-repeat='error in sc.validationErrors'])[66]");
// #endregion
// #region [Most Important]
// private static readonly By PANEL_MOST_IMPORTANT = By.XPath("//*[@id='panel-5']//*[@class='panel-title']");
// private static readonly By MOST_IMPORTANT_INPUT_NAME = By.XPath("//*[@id='panel-5']//*[@id='questionName-5']");
// private static readonly By MOST_IMPORTANT_INPUT_QUESTION = By.XPath("//*[@id='panel-5']//*[@name='question']");
// private static readonly By MOST_IMPORTANT_QUESTION_ONE = By.XPath("//*[@id='panel-5']//*[@id='answer-5-0']");
// private static readonly By MOST_IMPORTANT_QUESTION_TWO = By.XPath("//*[@id='panel-5']//*[@id='answer-5-0']");
// private static readonly By MOST_IMPORTANT_BUTTON_ENABLE = By.XPath("//*[@id='panel-5']//*[@ng-click='sc.changeQuestions(question, object.order)']");
// private static readonly By MOST_IMPORTANT_VALIDATION_NAME = By.XPath("(//*[@ng-repeat='error in sc.validationErrors'])[69]");
// private static readonly By MOST_IMPORTANCE_VALIDATION_ANSWER_ONE = By.XPath("(//*[@ng-repeat='error in sc.validationErrors'])[75]");
// private static readonly By MOST_IMPORTANCE_VALIDATION_ANSWER_TWO = By.XPath("(//*[@ng-repeat='error in sc.validationErrors'])[78]");
// #endregion
// #region [Interest]
// private static readonly By PANEL_INTEREST =By.XPath("//*[@id='panel-6']");
// private static readonly By INTEREST_QUESTION = By.XPath("//*[@id='panel-6']//*[@name='question']");
// private static readonly By INETEREST_ANSWER = By.XPath("//*[@id='panel-6']//*[@id='answer-6-0']");
// private static readonly By INTEREST_BUTTON_SUBMIT = By.XPath("//*[@id='panel-6']//*[@ng-click='sc.changeQuestions(question, object.order)']");
// private static readonly By INTEREST_VALDIATION_NAME = By.XPath("(//*[@ng-repeat='error in sc.validationErrors'])[84]");
// #endregion
// #region [Prize Draw]
// private static readonly By PANEL_PRIZE_DRAW = By.XPath("//*[@name='7']");
// private static readonly By PRIZE_DRAW_INPUT_QUESTION = By.XPath("//*[@name='7']//*[@name='question']");
// private static readonly By PRIZE_DRAW_INPUT_ANSWER = By.XPath("//*[@name='7']//*[@id='answer-7-0']");
// private static readonly By PRIZE_DRAW_BUTTON_SUBMIT = By.XPath("//*[@name='7']//*[@ng-click='sc.changeQuestions(question, object.order)']");
// private static readonly By PRIZE_DRAW_VALIDATION_NAME = By.XPath("(//*[@ng-repeat='error in sc.validationErrors'])[90]");
// #endregion
// #region [Contact Details]
// private static readonly By PANEL_CONTACT_DETAILS = By.XPath("//*[@name='8']");
// private static readonly By CONTACT_DETAILS_INPUT_QUESTION = By.XPath("//*[@name='8']//*[@name='question']");
// private static readonly By CONTACT_DETAILS_INPUT_ANSWER = By.XPath("//*[@name='8']//*[@id='answer-8-0']");
// private static readonly By CONTACT_DETAILS_INPUT_FIRST_NAME = By.XPath("//*[@name='8']//*[@id='First Name']");
// private static readonly By CONTACT_DETAILS_INPUT_LAST_NAME = By.XPath("//*[@name='8']//*[@id='Last Name']");
// private static readonly By CONTACT_DETAILS_DROP_DOWN_AGE = By.XPath("//*[@name='answers']//*[@id='Gender']");
// private static readonly By CONTACT_DETAILS_INPUT_AGE = By.XPath("//*[@name='answers']//*[@id='Age']");
// private static readonly By CONTACT_DETAILS_INPUT_EMAIL = By.XPath("//*[@name='answers']//*[@id='Email']");
// private static readonly By CONTACT_DETAILS_INPUT_MOBILE = By.XPath("//*[@name='answers']//*[@id='Mobile']");
// private static readonly By CONTACT_DETAILS_INPUT_LANDLINE = By.XPath("//*[@name='answers']//*[@id='Landline Number']");
// private static readonly By CONTACT_DETAILS_INPUT_POSTAL_ADDRESS = By.XPath("//*[@name='answers']//*[@id='Postal Address']");
// private static readonly By CONTACT_DETAILS_INPUT_CITY = By.XPath("[@id='City']");
// private static readonly By CONTACT_DETAILS_INPUT_STATE = By.XPath("//*[@name='answers']//*[@id='State']");
// private static readonly By CONTACT_DETAILS_INPUT_POSTAL_CODE = By.XPath("//*[@name='answers']//*[@id='Postcode']");
// private static readonly By CONTACT_DETAILS_INPUT_COUNTRY = By.XPath("//*[@name='answers']//*[@id='Country']");
// private static readonly By CONTACT_DETAILS_INPUT_COMPANY_NAME = By.XPath("[@id='Company Name']");
// private static readonly By CONTACT_DETAILS_BUTTON_LANDLINE = By.XPath("(//*[@ng-if='object.contact']//*[@role='button'])[1]");
// private static readonly By CONTACT_DETAILS_BUTTON_POSTAL_ADDRESS = By.XPath("(//*[@ng-if='object.contact']//*[@role='button'])[2]");
// private static readonly By CONTACT_DETAILS_BUTTON_CITY = By.XPath("(//*[@ng-if='object.contact']//*[@role='button'])[3]");
// private static readonly By CONTACT_DETAILS_BUTTON_STATE = By.XPath("(//*[@ng-if='object.contact']//*[@role='button'])[4]");
// private static readonly By CONTACT_DETAILS_BUTTON_POSTAL_CODE = By.XPath("(//*[@ng-if='object.contact']//*[@role='button'])[5]");
// private static readonly By CONTACT_DETAILS_BUTTON_COUNTRY = By.XPath("(//*[@ng-if='object.contact']//*[@role='button'])[6]");
// private static readonly By CONTACT_DETAILS_BUTTON_COMPANY_NAME = By.XPath("(//*[@ng-if='object.contact']//*[@role='button'])[7]");
// private static readonly By CONTACT_DETAILS_BUTTON_ENABLE = By.XPath("//*[@id='panel-8']//*[@ng-click='sc.changeQuestions(question, object.order)']");
// private static readonly By CONTACT_DETAILS_VALDIATION_ANSWER = By.XPath("(//*[@ng-repeat='error in sc.validationErrors'])[96]");
// #endregion
// #region [Thanks]
// private static readonly By PANEL_THANKS = By.XPath("//*[@id='manageForm']//*[@id='panel-thanks']");
// private static readonly By INPUT_THANKS =By.XPath("//*[@id='panel-thanks']//*[@name='thanks']");
// private static readonly By BUTTON_PREVIEW = By.XPath("//*[@id='manageForm']//*[@data-target='#previewModal']");
// private static readonly By BUTTON_FINISH = By.XPath("//*[@id='manageForm']//*[@ng-click='sc.finishManage()']");
// #endregion
// #region [Enable Contact Details Fields]
// public static void EnableLandlineNumber()
// {
// Web.Click(CONTACT_DETAILS_BUTTON_LANDLINE);
// }
// public static void EnablePostalAddress()
// {
// Web.Click(CONTACT_DETAILS_BUTTON_POSTAL_ADDRESS);
// }
// public static void EnableCity()
// {
// Web.Click(CONTACT_DETAILS_BUTTON_CITY);
// }
// public static void EnableState()
// {
// Web.Click(CONTACT_DETAILS_BUTTON_STATE);
// }
// public static void EnablePostcode()
// {
// Web.Click(CONTACT_DETAILS_BUTTON_POSTAL_CODE);
// }
// public static void EnableCountry()
// {
// Web.Click(CONTACT_DETAILS_BUTTON_COUNTRY);
// }
// public static void EnableCompanyName()
// {
// Web.Click(CONTACT_DETAILS_BUTTON_COMPANY_NAME);
// }
// #endregion
// #region [Enter fields]
// public static void FillIntroduction(object data)
// {
// string name = WebApplication.GetFieldDataFromDynamicClass(data, "Name");
// string introduction = WebApplication.GetFieldDataFromDynamicClass(data, "Introduction");
// Web.TypeNewText(INTRODUCTION_INPUT_NAME, name);
// Web.TypeNewText(INTRODUCTION_INPUT_DESCRIPTION, introduction);
// }
// public static void FillQuestionOne(object data)
// {
// string name = WebApplication.GetFieldDataFromDynamicClass(data, "Name");
// string question = WebApplication.GetFieldDataFromDynamicClass(data, "Question");
// string answerOne = WebApplication.GetFieldDataFromDynamicClass(data, "Answer1");
// string answerTwo = WebApplication.GetFieldDataFromDynamicClass(data, "Answer2");
// string answerThree = WebApplication.GetFieldDataFromDynamicClass(data, "Answer3");
// Web.TypeNewText(QUESTION_ONE_INPUT_NAME, name);
// Web.TypeNewText(QUESTION_ONE_INPUT_QUESTION, question);
// Web.TypeNewText(QUESTION_ONE_INPUT_ANSWER_ONE, answerOne);
// Web.TypeNewText(QUESTION_ONE_INPUT_ANSWER_TWO, answerTwo);
// if(Web.IsElementPresent(QUESTION_ONE_INPUT_ANSWER_THREE)) { Web.TypeNewText(QUESTION_ONE_INPUT_ANSWER_THREE, answerThree); }
// bool result = Web.IsElementPresent(QUESTION_ONE_INPUT_ANSWER_THREE);
// }
// public static void FillQuestionTwo(object data)
// {
// string name = WebApplication.GetFieldDataFromDynamicClass(data, "Name");
// string question = WebApplication.GetFieldDataFromDynamicClass(data, "Question");
// string answerOne = WebApplication.GetFieldDataFromDynamicClass(data, "Answer1");
// string answerTwo = WebApplication.GetFieldDataFromDynamicClass(data, "Answer2");
// string answerThree = WebApplication.GetFieldDataFromDynamicClass(data, "Answer3");
// Web.TypeNewText(QUESTION_TWO_INPUT_NAME, name);
// Web.TypeNewText(QUESTION_TWO_INPUT_QUESTION, question);
// Web.TypeNewText(QUESTION_TWO_INPUT_ANSWER_ONE, answerOne);
// Web.TypeNewText(QUESTION_TWO_INPUT_ANSWER_TWO, answerTwo);
// if (Web.IsElementDisplayed(QUESTION_TWO_INPUT_ANSWER_THREE)) { Web.TypeNewText(QUESTION_TWO_INPUT_ANSWER_THREE, answerThree); }
// }
// public static void FillLikeDislike(object data)
// {
// string name = WebApplication.GetFieldDataFromDynamicClass(data, "Name");
// string question = WebApplication.GetFieldDataFromDynamicClass(data, "Question");
// string answerOne = WebApplication.GetFieldDataFromDynamicClass(data, "Answer1");
// string answerTwo = WebApplication.GetFieldDataFromDynamicClass(data, "Answer2");
// Web.TypeNewText(LIKE_DISLIKE_INPUT_NAME, name);
// Web.TypeNewText(LIKE_DISLIKE_INPUT_QUESTION, question);
// Web.TypeNewText(LIKE_DISLIKE_INPUT_ANSWER_ONE, answerOne);
// Web.TypeNewText(LIKE_DISLIKE_INPUT_ANSWER_TWO, answerTwo);
// }
// public static void FillImportance(object data)
// {
// string name = WebApplication.GetFieldDataFromDynamicClass(data, "Name");
// string question = WebApplication.GetFieldDataFromDynamicClass(data, "Question");
// string answerOne = WebApplication.GetFieldDataFromDynamicClass(data, "Answer1");
// string answerTwo = WebApplication.GetFieldDataFromDynamicClass(data, "Answer2");
// Web.TypeNewText(IMPORTANCE_INPUT_NAME, name);
// Web.TypeNewText(IMPORTANCE_INPUT_QUESTION, question);
// Web.TypeNewText(IMPORTANCE_ANSWER_ONE, answerOne);
// Web.TypeNewText(IMPORTANCE_ANSWER_TWO, answerTwo);
// }
// public static void FillMostImportant(object data)
// {
// string name = WebApplication.GetFieldDataFromDynamicClass(data, "Name");
// string question = WebApplication.GetFieldDataFromDynamicClass(data, "Question");
// string answerOne = WebApplication.GetFieldDataFromDynamicClass(data, "Answer1");
// string answerTwo = WebApplication.GetFieldDataFromDynamicClass(data, "Answer2");
// Web.TypeNewText(MOST_IMPORTANT_INPUT_NAME, name);
// Web.TypeNewText(MOST_IMPORTANT_INPUT_QUESTION, question);
// Web.TypeNewText(MOST_IMPORTANT_QUESTION_ONE, answerOne);
// Web.TypeNewText(MOST_IMPORTANT_QUESTION_TWO, answerTwo);
// }
// public static void FillContactDetails(object data)
// {
// string question = WebApplication.GetFieldDataFromDynamicClass(data, "Question");
// string firstName = WebApplication.GetFieldDataFromDynamicClass(data, "FirstName");
// string lastName = WebApplication.GetFieldDataFromDynamicClass(data, "LastName");
// string gender = WebApplication.GetFieldDataFromDynamicClass(data, "Gender");
// string age = WebApplication.GetFieldDataFromDynamicClass(data, "Age");
// string email = WebApplication.GetFieldDataFromDynamicClass(data, "Email");
// string mobile = WebApplication.GetFieldDataFromDynamicClass(data, "Mobile");
// Web.TypeNewText(CONTACT_DETAILS_INPUT_QUESTION, question);
// Web.TypeNewText(CONTACT_DETAILS_INPUT_FIRST_NAME, firstName);
// Web.TypeNewText(CONTACT_DETAILS_INPUT_LAST_NAME, lastName);
// Web.SelectByValue(CONTACT_DETAILS_DROP_DOWN_AGE, gender);
// Web.TypeNewText(CONTACT_DETAILS_INPUT_AGE,age);
// Web.TypeNewText(CONTACT_DETAILS_INPUT_EMAIL,email);
// Web.TypeNewText(CONTACT_DETAILS_INPUT_MOBILE, mobile);
// }
// public static void FillThanks(object data)
// {
// string thanks = WebApplication.GetFieldDataFromDynamicClass(data, "Thanks");
// string answer = WebApplication.GetFieldDataFromDynamicClass(data, "Answer");
// Web.TypeNewText(CONTACT_DETAILS_INPUT_ANSWER, answer);
// Web.TypeNewText(INPUT_THANKS, thanks);
// }
// #endregion
// #region [Common Navigation]
// public static void ClickCreteNew()
// {
// Web.Click(BUTTON_CREATE_NEW);
// }
// public static void ClickFinish()
// {
// Web.Click(BUTTON_FINISH);
// }
// #endregion
// #region [Expect Web Elements]
// public static void ExpectWebElements()
// {
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(LABEL_SURVEY));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(BUTTON_CREATE_NEW));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(CONTAINER_SURVEY));
// }
// public static void ExpectWebElementsCreateNew()
// {
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(LABEL_SURVEY));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(BUTTON_CREATE_NEW));
// // Web.WaitUntil(ExpectedConditions.ElementIsVisible(CONTAINER_SURVEY));
// }
// public static void ExpectWebElementsSurveyCreate()
// {
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(PANEL_INTRODUCTION));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(PANEL_QUESTION_ONE));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(PANEL_QUESTION_TWO));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(PANEL_LIKE_DISLIKE));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(PANEL_IMPORTANCE));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(PANEL_MOST_IMPORTANT));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(PANEL_INTEREST));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(PANEL_PRIZE_DRAW));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(PANEL_CONTACT_DETAILS));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(PANEL_THANKS));
// }
// public static void ExpectIntroductionValidation()
// {
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(INTRODUCTION_VALIDATION_NAME));
// }
// public static void ExpectQuestionOneValidation()
// {
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(QUESTION_ONE_VALDIATION_NAME));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(QUESTION_ONE_VALIDATION_ANSWER_ONE));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(QUESTION_ONE_VALIDATION_ANSWER_TWO));
// }
// public static void ExpectQuestionTwoValidation()
// {
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(QUESTION_TWO_VALIDATION_NAME));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(QUESTION_TWO_VALIDATION_ANSWER_ONE));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(QUESTION_TWO_VALIDATION_ANSWER_TWO));
// }
// public static void ExpectLikeDislikeValidation()
// {
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(LIKE_DISLIKE_VALIDATION_NAME));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(LIKE_DISLIKE_VALIDATION_ANSWER_ONE));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(LIKE_DISLIKE_VALIDATION_ANSWER_TWO));
// }
// public static void ExpectImportanceValidation()
// {
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(IMPORTANCE_VALIDATION_NAME));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(IMPORTANCE_VALIDATION_ANSWER_ONE));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(IMPORTANCE_VALIDATION_ANSWER_TWO));
// }
// public static void ExpectMostImportantValidation()
// {
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(MOST_IMPORTANT_VALIDATION_NAME));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(MOST_IMPORTANCE_VALIDATION_ANSWER_ONE));
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(MOST_IMPORTANCE_VALIDATION_ANSWER_TWO));
// }
// public static void ExpectContactDetailsValidation()
// {
// Web.WaitUntil(ExpectedConditions.ElementIsVisible(CONTACT_DETAILS_VALDIATION_ANSWER));
// }
// #endregion
// #region [Enable Blocks]
// public static void EnableQuestionOneBlock()
// {
// Web.Click(QUESTION_ONE_BUTTON_ENABLE);
// }
// public static void EnableQUestionTwoBlock()
// {
// Web.Click(QUESTION_TWO_BUTTON_ENABLE);
// }
// public static void EnableLikeDislikeBlock()
// {
// Web.Click(LIKE_DISLIKE_BUTTON_ENABLE);
// }
// public static void EnableImportanceBlock()
// {
// Web.Click(IMPORTANCE_BUTTON_ENABLE);
// }
// public static void EnableMostImportantBlock()
// {
// Web.Click(MOST_IMPORTANT_BUTTON_ENABLE);
// }
// public static void EnableInterestBlock()
// {
// Web.Click(INTEREST_BUTTON_SUBMIT);
// }
// public static void EnablePrizeDrawBlock()
// {
// Web.Click(PRIZE_DRAW_BUTTON_SUBMIT);
// }
// public static void EnableContactDetailsBlock()
// {
// Web.Click(CONTACT_DETAILS_BUTTON_ENABLE);
// }
// public static void EnableBlockByName(string name)
// {
// switch (name)
// {
// case "Question One":
// EnableQuestionOneBlock();
// break;
// case "Question Two":
// EnableQUestionTwoBlock();
// break;
// case "Like-Dislike":
// EnableLikeDislikeBlock();
// break;
// case "Importance":
// EnableImportanceBlock();
// break;
// case "Most Important":
// EnableMostImportantBlock();
// break;
// case "Interest":
// EnableInterestBlock();
// break;
// case "Prize Draw":
// EnablePrizeDrawBlock();
// break;
// case "Contact Details":
// EnableContactDetailsBlock();
// break;
// }
// }
// #endregion
// public static void AddQuestions(int block)
// {
// switch (block)
// {
// case 1:
// Web.Click(BUTTON_QUESTION_ONE_PLUS);
// break;
// case 2:
// Web.Click(BUTTON_QUESTION_TWO_PLUS);
// break;
// }
// }
// public static void EnableSectionByName(string section)
// {
// switch (section)
// {
// case "Like Dislike":
// Web.Click(PANEL_LIKE_DISLIKE);
// break;
// case "Importance":
// Web.Click(PANEL_IMPORTANCE);
// break;
// case "Most Important":
// Web.Click(PANEL_MOST_IMPORTANT);
// break;
// }
// }
// public static void CheckValidation(string panel)
// {
// switch (panel)
// {
// case "introduction":
// ExpectIntroductionValidation();
// break;
// case "Question One":
// ExpectQuestionOneValidation();
// break;
// case "Question Two":
// ExpectQuestionTwoValidation();
// break;
// case "Like Dislike":
// ExpectLikeDislikeValidation();
// break;
// case "Importance":
// ExpectImportanceValidation();
// break;
// case "Most Important":
// ExpectImportanceValidation();
// break;
// case "Contact Details":
// ExpectImportanceValidation();
// break;
// }
// }
// }
//}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Structures
{
struct StrExc06
{
private int First;
private int Second;
public StrExc06(int a,int b)
{
First = a;
Second = b;
}
public static StrExc06 operator +(StrExc06 A, StrExc06 B)
{
StrExc06 C = new StrExc06();
C.First = A.First + B.First;
C.Second = A.Second + B.Second;
return C;
}
public static StrExc06 operator *(StrExc06 A, StrExc06 B)
{
StrExc06 C = new StrExc06();
C.First = A.First * B.First;
C.Second = A.Second * B.Second;
return C;
}
public static StrExc06 operator -(StrExc06 A, StrExc06 B)
{
StrExc06 C = new StrExc06();
C.First = A.First - B.First;
C.Second = A.Second - B.Second;
return C;
}
public static int operator ~(StrExc06 A)
{
return Math.Max(A.First, A.Second);
}
public static int operator !(StrExc06 A)
{
return Math.Min(A.First, A.Second);
}
}
class Exc06
{
public static void MainExc06()
{
StrExc06 Astr = new StrExc06(4, 2);
StrExc06 Bstr = new StrExc06(5, 9);
StrExc06 Cstr = Astr + Bstr;
Cstr = Astr * Bstr;
Cstr = Astr - Bstr;
int min = !Astr;
int max = ~Cstr;
min = !Bstr;
max = ~Bstr;
}
}
}
|
using ChipmunkSharp;
using CocosSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChipmunkExample
{
class jointsLayer : ChipmunkDemoLayer
{
cpVect boxOffset;
private void label(string p)
{
CCLabelTtf tmp = GetDefaultFontTtf(p);
tmp.Position = boxOffset.ToCCPoint();
tmp.Scale = 0.5f;
tmp.Position = new CCPoint(tmp.PositionX + 70, tmp.PositionY + 100);
AddChild(tmp);
}
private cpBody addLever(cpVect pos)
{
var mass = 1;
var a = new cpVect(0, 15);
var b = new cpVect(0, -15);
var body = space.AddBody(new cpBody(mass, cp.MomentForSegment(mass, a, b, 0.0f)));
body.SetPosition(cpVect.cpvadd(pos, cpVect.cpvadd(boxOffset, new cpVect(0, -15))));
var shape = space.AddShape(new cpSegmentShape(body, a, b, 5));
shape.SetElasticity(0);
shape.SetFriction(0.7f);
return body;
}
private cpBody addBar(cpVect pos)
{
var mass = 2;
var a = new cpVect(0, 30);
var b = new cpVect(0, -30);
var body = space.AddBody(new cpBody(mass, cp.MomentForSegment(mass, a, b, 0.0f)));
body.SetPosition(cpVect.cpvadd(pos, boxOffset));
var shape = space.AddShape(new cpSegmentShape(body, a, b, 5));
shape.SetElasticity(0);
shape.SetFriction(0.7f);
shape.SetFilter(new cpShapeFilter(1, cp.ALL_CATEGORIES, cp.ALL_CATEGORIES));
return body;
}
public cpBody addBall(cpVect pos)
{
var radius = 15;
var mass = 1;
var body = space.AddBody(new cpBody(mass, cp.MomentForCircle(mass, 0, radius, new cpVect(0, 0))));
body.SetPosition(cpVect.cpvadd(pos, boxOffset));
var shape = space.AddShape(new cpCircleShape(body, radius, new cpVect(0, 0)));
shape.SetElasticity(0);
shape.SetFriction(0.7f);
shape.SetFilter(new cpShapeFilter(1, cp.ALL_CATEGORIES, cp.ALL_CATEGORIES));
return body;
}
public cpBody addWheel(cpVect pos)
{
var radius = 15;
var mass = 1;
var body = space.AddBody(new cpBody(mass, cp.MomentForCircle(mass, 0, radius, new cpVect(0, 0))));
body.SetPosition(cpVect.cpvadd(pos, boxOffset));
var shape = space.AddShape(new cpCircleShape(body, radius, new cpVect(0, 0)));
shape.SetElasticity(0);
shape.SetFriction(0.7f);
//shape.group = 1; // use a group to keep the car parts from colliding
shape.SetFilter(new cpShapeFilter(1, cp.ALL_CATEGORIES, cp.ALL_CATEGORIES));
return body;
}
public cpBody addChassis(cpVect pos)
{
var mass = 5;
var width = 80;
var height = 30;
var body = space.AddBody(new cpBody(mass, cp.MomentForBox(mass, width, height)));
body.SetPosition(cpVect.cpvadd(pos, boxOffset));
var shape = space.AddShape(cpPolyShape.BoxShape(body, width, height, 0.0f));
shape.SetElasticity(0);
shape.SetFriction(0.7f);
//shape.group = 1; // use a group to keep the car parts from colliding
shape.SetFilter(new cpShapeFilter(1, cp.ALL_CATEGORIES, cp.ALL_CATEGORIES));
return body;
}
public override void Update(float dt)
{
base.Update(dt);
space.Step(dt);
}
protected override void Draw()
{
base.Draw();
}
public override void OnEnter()
{
base.OnEnter();
Position = new CCPoint(100, 100);
space.SetIterations(10);
space.SetGravity(new cpVect(0, -100));
space.SetSleepTimeThreshold(0.5f);
cpBody staticBody = space.GetStaticBody();// staticBody;
cpShape shape;
for (var y = 480; y >= 0; y -= 120)
{
shape = space.AddShape(new cpSegmentShape(staticBody, new cpVect(0, y), new cpVect(640, y), 0));
shape.SetElasticity(1);
shape.SetFriction(1);
shape.SetFilter(NOT_GRABBABLE_FILTER);
}
for (var x = 0; x <= 640; x += 160)
{
shape = space.AddShape(new cpSegmentShape(staticBody, new cpVect(x, 0), new cpVect(x, 480), 0));
shape.SetElasticity(1);
shape.SetFriction(1);
shape.SetFilter(NOT_GRABBABLE_FILTER);
}
cpBody body1, body2;
var posA = new cpVect(50, 60);
var posB = new cpVect(110, 60);
var POS_A = new Func<cpVect>(() => { return cpVect.cpvadd(boxOffset, posA); });
var POS_B = new Func<cpVect>(() => { return cpVect.cpvadd(boxOffset, posB); });
// Keeps the anchor points the same distance apart from when the joint was created.
boxOffset = new cpVect(0, 0);
label("Pin Joint");
body1 = addBall(posA);
body2 = addBall(posB);
body2.SetAngle((float)Math.PI);
space.AddConstraint(new cpPinJoint(body1, body2, new cpVect(15, 0), new cpVect(15, 0)));
// Slide Joints - Like pin joints but with a min/max distance.
// Can be used for a cheap approximation of a rope.
boxOffset = new cpVect(160, 0);
label("Slide Joint");
body1 = addBall(posA);
body2 = addBall(posB);
body2.SetAngle((float)Math.PI);
space.AddConstraint(new cpSlideJoint(body1, body2, new cpVect(15, 0), new cpVect(15, 0), 20, 40));
// Pivot Joints - Holds the two anchor points together. Like a swivel.
boxOffset = new cpVect(320, 0);
label("Pivot Joint");
body1 = addBall(posA);
body2 = addBall(posB);
body2.SetAngle((float)Math.PI);
// Alternately, specify two anchor points using cp.PivotJoint(a, b, anch1, anch2)
space.AddConstraint(new cpPivotJoint(body1, body2, cpVect.cpvadd(boxOffset, new cpVect(80, 60))));
// Groove Joints - Like a pivot joint, but one of the anchors is a line segment that the pivot can slide in
boxOffset = new cpVect(480, 0);
label("Groove Joint");
body1 = addBall(posA);
body2 = addBall(posB);
space.AddConstraint(new cpGrooveJoint(body1, body2, new cpVect(30, 30), new cpVect(30, -30), new cpVect(-30, 0)));
// Damped Springs
boxOffset = new cpVect(0, 120);
label("Damped Spring");
body1 = addBall(posA);
body2 = addBall(posB);
body2.SetAngle((float)Math.PI);
space.AddConstraint(new cpDampedSpring(body1, body2, new cpVect(15, 0), new cpVect(15, 0), 20, 5, 0.3f));
// Damped Rotary Springs
boxOffset = new cpVect(160, 120);
label("Damped Rotary Spring");
body1 = addBar(posA);
body2 = addBar(posB);
// Add some pin joints to hold the circles in place.
space.AddConstraint(new cpPivotJoint(body1, staticBody, POS_A()));
space.AddConstraint(new cpPivotJoint(body2, staticBody, POS_B()));
space.AddConstraint(new cpDampedRotarySpring(body1, body2, 0, 3000, 60));
// Rotary Limit Joint
boxOffset = new cpVect(320, 120);
label("Rotary Limit Joint");
body1 = addLever(posA);
body2 = addLever(posB);
// Add some pin joints to hold the circles in place.
space.AddConstraint(new cpPivotJoint(body1, staticBody, POS_A()));
space.AddConstraint(new cpPivotJoint(body2, staticBody, POS_B()));
// Hold their rotation within 90 degrees of each other.
space.AddConstraint(new cpRotaryLimitJoint(body1, body2, -(float)Math.PI / 2, (float)Math.PI / 2));
// Ratchet Joint - A rotary ratchet, like a socket wrench
boxOffset = new cpVect(480, 120);
label("Ratchet Joint");
body1 = addLever(posA);
body2 = addLever(posB);
// Add some pin joints to hold the circles in place.
space.AddConstraint(new cpPivotJoint(body1, staticBody, POS_A()));
space.AddConstraint(new cpPivotJoint(body2, staticBody, POS_B()));
// Ratchet every 90 degrees
space.AddConstraint(new cpRatchetJoint(body1, body2, 0, (float)Math.PI / 2f));
// Gear Joint - Maintain a specific angular velocity ratio
boxOffset = new cpVect(0, 240);
label("Gear Joint");
body1 = addBar(posA);
body2 = addBar(posB);
// Add some pin joints to hold the circles in place.
space.AddConstraint(new cpPivotJoint(body1, staticBody, POS_A()));
space.AddConstraint(new cpPivotJoint(body2, staticBody, POS_B()));
// Force one to sping 2x as fast as the other
space.AddConstraint(new cpGearJoint(body1, body2, 0, 2));
// Simple Motor - Maintain a specific angular relative velocity
boxOffset = new cpVect(160, 240);
label("Simple Motor");
body1 = addBar(posA);
body2 = addBar(posB);
// Add some pin joints to hold the circles in place.
space.AddConstraint(new cpPivotJoint(body1, staticBody, POS_A()));
space.AddConstraint(new cpPivotJoint(body2, staticBody, POS_B()));
// Make them spin at 1/2 revolution per second in relation to each other.
space.AddConstraint(new cpSimpleMotor(body1, body2, (float)Math.PI));
// Make a car with some nice soft suspension
boxOffset = new cpVect(320, 240);
var wheel1 = addWheel(posA);
var wheel2 = addWheel(posB);
var chassis = addChassis(new cpVect(80, 100));
space.AddConstraint(new cpGrooveJoint(chassis, wheel1, new cpVect(-30, -10), new cpVect(-30, -40), new cpVect(0, 0)));
space.AddConstraint(new cpGrooveJoint(chassis, wheel2, new cpVect(30, -10), new cpVect(30, -40), new cpVect(0, 0)));
space.AddConstraint(new cpDampedSpring(chassis, wheel1, new cpVect(-30, 0), new cpVect(0, 0), 50, 20, 10));
space.AddConstraint(new cpDampedSpring(chassis, wheel2, new cpVect(30, 0), new cpVect(0, 0), 50, 20, 10));
Schedule();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace PlanMGMT.Converter
{
public class IsExpendAllContentConverter : System.Windows.Data.IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(value==null)
{
return "";
}
if((bool)value)
{
return "点击全部折叠";
}
else
{
return "点击全部展开";
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
using Microsoft.Xna.Framework;
namespace OpenOracle.Old
{
public abstract class Actor
{
protected Actor() {}
protected Actor(SpriteSheetBaseOld spriteSheet)
{
SpriteSheet = spriteSheet;
}
public int MovementSpeed { get; set; } = 1;
public Point Origin { get; set; }
public Point ScreenPosition { get; private set; }
public Point ScreenTile => new Point(
ScreenPosition.X / SpriteSheet.SpriteWidth,
ScreenPosition.Y / SpriteSheet.SpriteHeight);
public SpriteSheetBaseOld SpriteSheet { get; set; }
public virtual Point BottomLeft => new Point(
ScreenPosition.X,
ScreenPosition.Y + SpriteSheet.SpriteHeight);
public virtual Point BottomRight => new Point(
ScreenPosition.X + SpriteSheet.SpriteWidth,
ScreenPosition.Y + SpriteSheet.SpriteHeight);
public virtual Point Center => new Point(
ScreenPosition.X + SpriteSheet.SpriteWidth / 2,
ScreenPosition.Y + SpriteSheet.SpriteHeight / 2);
public virtual Point TopLeft => ScreenPosition;
public virtual Point TopRight => new Point(
ScreenPosition.X + SpriteSheet.SpriteWidth,
ScreenPosition.Y);
public void MoveDown()
{
MoveDown(MovementSpeed);
}
public void MoveDown(int speed)
{
ScreenPosition = new Point(ScreenPosition.X, ScreenPosition.Y + speed);
}
public void MoveLeft()
{
MoveLeft(MovementSpeed);
}
public void MoveLeft(int speed)
{
ScreenPosition = new Point(ScreenPosition.X - speed, ScreenPosition.Y);
}
public void MoveRight()
{
MoveRight(MovementSpeed);
}
public void MoveRight(int speed)
{
ScreenPosition = new Point(ScreenPosition.X + speed, ScreenPosition.Y);
}
public void MoveToScreenPosition(int x, int y)
{
ScreenPosition = new Point(x, y);
}
public void MoveUp()
{
MoveUp(MovementSpeed);
}
public void MoveUp(int speed)
{
ScreenPosition = new Point(ScreenPosition.X, ScreenPosition.Y - speed);
}
}
}
|
using Plugin.Media;
using Plugin.Media.Abstractions;
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Xamarin.Forms;
using Newtonsoft.Json.Linq;
using System.Linq;
using Plugin.Geolocator;
using berry.Model;
using Newtonsoft.Json;
namespace berry
{
public partial class CustomVision : ContentPage
{
public CustomVision()
{
InitializeComponent();
}
private async void loadCamera(object sender, EventArgs e)
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("No Camera", ":( No camera available.", "OK");
return;
}
MediaFile file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
Name = $"{DateTime.UtcNow}.jpg",
Directory = "Sample",
PhotoSize = PhotoSize.Medium
});
if (file == null)
return;
image.Source = ImageSource.FromStream(() =>
{
return file.GetStream();
});
await postLocationAsync();
await MakePredictionRequest(file);
}
async Task postLocationAsync()
{
var gps = CrossGeolocator.Current;
gps.DesiredAccuracy = 50;
var position = await gps.GetPositionAsync(TimeSpan.FromMilliseconds(10000));
NotStrawberryModel location_gps = new NotStrawberryModel()
{
Longitude = (float)position.Longitude,
Latitude = (float)position.Latitude
};
await AzureManager.AzureManagerInstance.PostStrawberryInformation(location_gps);
}
static byte[] GetImageAsByteArray(MediaFile name)
{
var len = name.GetStream();
BinaryReader binaryReader = new BinaryReader(len);
return binaryReader.ReadBytes((int)len.Length);
}
async Task MakePredictionRequest(MediaFile name)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Prediction-Key", "ce5fd674a76843fbadde6a1694ebef61");
string url = "https://southcentralus.api.cognitive.microsoft.com/customvision/v1.0/Prediction/475c9df6-b10f-4260-af91-ce586d59e054/image?iterationId=67001aa1-7497-44fb-987a-fc9850c4acc0";
HttpResponseMessage r;
byte[] byteData = GetImageAsByteArray(name);
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
r = await client.PostAsync(url, content);
if (r.IsSuccessStatusCode)
{
var responseString = await r.Content.ReadAsStringAsync();
EvaluationModel responseModel = JsonConvert.DeserializeObject<EvaluationModel>(responseString);
double max = responseModel.Predictions.Max(m => m.Probability);
TagLabel.Text = (max >= 0.5) ? "Yes, it's a Strawberry\n" : "Nope, this is not a Strawberry\n";
JObject rss = JObject.Parse(responseString);
var Probability = from p in rss["Predictions"] select (string)p["Probability"];
var Tag = from p in rss["Predictions"] select (string)p["Tag"];
foreach (var x in Tag)
{
TagLabel.Text += x + ": \n";
}
foreach (var x in Probability)
{
PredictionLabel.Text += "\n" + x;
}
}
name.Dispose();
}
}
}
} |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
using ReactMusicStore.Core.Utilities.Common;
namespace ReactMusicStore.Core.Utilities.Extensions
{
public static class LinqExtensions
{
public static PropertyInfo ExtractPropertyInfo(this LambdaExpression propertyAccessor)
{
return propertyAccessor.ExtractMemberInfo() as PropertyInfo;
}
public static FieldInfo ExtractFieldInfo(this LambdaExpression propertyAccessor)
{
return propertyAccessor.ExtractMemberInfo() as FieldInfo;
}
[SuppressMessage("ReSharper", "CanBeReplacedWithTryCastAndCheckForNull")]
public static MemberInfo ExtractMemberInfo(this LambdaExpression propertyAccessor)
{
Guard.NotNull(propertyAccessor, nameof(propertyAccessor));
MemberInfo info;
try
{
MemberExpression operand;
// o => o.PropertyOrField
LambdaExpression expression = propertyAccessor;
if (expression.Body is UnaryExpression)
{
// If the property is not an Object, then the member access expression will be wrapped in a conversion expression
// (object)o.PropertyOrField
UnaryExpression body = (UnaryExpression)expression.Body;
// o.PropertyOrField
operand = (MemberExpression)body.Operand;
}
else
{
// o.PropertyOrField
operand = (MemberExpression)expression.Body;
}
// Member
MemberInfo member = operand.Member;
info = member;
}
catch (Exception e)
{
throw new ArgumentException("The property or field accessor expression is not in the expected format 'o => o.PropertyOrField'.", e);
}
return info;
}
}
} |
using System;
using System.Windows.Forms;
namespace Phenix.Services.Host.Core
{
/// <summary>
/// 标记已升级
/// </summary>
internal partial class MarkUpgradedDialog : Phenix.Core.Windows.DialogForm
{
private MarkUpgradedDialog()
{
InitializeComponent();
}
#region 工厂
/// <summary>
/// 执行
/// </summary>
public static bool Execute()
{
using (MarkUpgradedDialog dialog = new MarkUpgradedDialog())
{
if (!String.IsNullOrEmpty(ServiceManager.UpgradeReason))
dialog.Reason = ServiceManager.UpgradeReason;
if (dialog.ShowDialog() == DialogResult.OK)
{
ServiceManager.MarkUpgraded(dialog.Reason);
return true;
}
return false;
}
}
#endregion
#region 属性
private string Reason
{
get { return this.upgradeReasonRichTextBox.Text; }
set { this.upgradeReasonRichTextBox.Text = value; }
}
#endregion
}
}
|
using ProjekatZdravoKorporacija.View;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace ProjekatZdravoKorporacija
{
/// <summary>
/// Interaction logic for OKMessageBox.xaml
/// </summary>
public partial class OKMessageBox : Window
{
private Object typeOfParent;
private int errorCode;
public OKMessageBox(Object obj, int code)
{
InitializeComponent();
typeOfParent = obj;
errorCode = code;
}
private void closeBtn_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void okBtn_Click(object sender, RoutedEventArgs e)
{
this.Close();
foreach (Window window in Application.Current.Windows)
{
if (window.GetType() == typeof(MainWindow))
{
if (typeOfParent.GetType() == typeof(EditPatient))
{
if (this.errorCode == 1 || this.errorCode == 2)
{
this.Close(); //doslo je do greske
}
else if (this.errorCode == 3)
{
(window as MainWindow).Main.Content = new PatientView(); //uspjesna izmjena informacija o pacijentu
}
}
else if (typeOfParent.GetType() == typeof(Registration))
{
if (this.errorCode == 1 || this.errorCode == 2)
{
this.Close(); //doslo je do greske
}
else if (this.errorCode == 3)
{
(window as MainWindow).Main.Content = new PatientView(); //uspjesna registracija pacijenta
}
}
else if (typeOfParent.GetType() == typeof(ChangePassword))
{
if (this.errorCode == 1 || this.errorCode == 2)
{
this.Close(); //doslo je do greske
}
else if(this.errorCode == 3)
{
(window as MainWindow).Main.Content = new EditProfile(); //uspjesna promjena lozinke
}
}
else if (typeOfParent.GetType() == typeof(EditProfile))
{
if (this.errorCode == 1 || this.errorCode == 2)
{
this.Close(); //doslo je do greske
}
else if (this.errorCode == 3)
{
(window as MainWindow).Main.Content = new Home(); //uspjesna izmjena informacija na profilu
}
}
else if (typeOfParent.GetType() == typeof(LogIn))
{
if (this.errorCode == 1 || this.errorCode == 2 || this.errorCode == 3)
{
this.Close(); //doslo je do greske prilikom prijave na sistem
}
}
else if (typeOfParent.GetType() == typeof(ScheduleExamination))
{
if (this.errorCode == 1 || this.errorCode == 2 || this.errorCode == 3 || this.errorCode == 4)
{
this.Close(); //doslo je do greske
}
else if (this.errorCode == 0)
{
(window as MainWindow).Main.Content = new ExaminationViewByDoctor(""); //uspjesna izmjena informacija na profilu
}
}
}
}
}
}
}
|
using System;
using System.Threading.Tasks;
namespace CC.Mobile.Services
{
public interface IConfigLoader<T>{
Task<T> LoadConfig();
T LoadConfigSync();
}
}
|
using System.Collections.Generic;
using System.IO;
namespace NBatch.Main.Readers.FileReader.Services
{
sealed class FileService : IFileService
{
private readonly string _resourceUrl;
public FileService(string resourceUrl)
{
_resourceUrl = resourceUrl;
}
public IEnumerable<string> ReadLines(long startIndex, int chunkSize)
{
int rowCounter = -1;
int chunkCounter = 0;
using (StreamReader reader = File.OpenText(_resourceUrl))
{
string input;
while ((input = reader.ReadLine()) != null)
{
if (LineAlreadyProcessed(startIndex, ref rowCounter))
continue;
if (HasReachedChunkSize(chunkSize, ref chunkCounter))
break;
yield return input;
}
}
}
private static bool HasReachedChunkSize(int chunkSize, ref int chunkCounter)
{
return ++chunkCounter > chunkSize;
}
private static bool LineAlreadyProcessed(long startIndex, ref int rowCounter)
{
return ++rowCounter < startIndex;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace demoPoC.Models
{
public class Consist
{
/*
* <BusVersion i:nil="true"/>
<GPRSIpAddress>10.149.234.74</GPRSIpAddress>
<IpAddress/>
<Name>187010</Name>
<NrOfCars>1</NrOfCars>
<SoldTime>2017-06-14T20:40:00</SoldTime>
<StateId>0</StateId>
<VehiclePos>0</VehiclePos>
*/
public string GPRSIpAddress { get; set; }
public int ConsistName { get; set; }
public int NrOfCars { get; set; }
public string SoldTime { get; set; }
public int StateId { get; set; }
public int VehiclePos { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using SpaceOpDeath.Utils;
namespace SpaceOpDeath
{
class Program
{
static void Main( string[] args )
{
string appName = ConfigurationManager.AppSettings["AppName"];
Console.WriteLine( appName );
Console.WriteLine( "Réalisé par Curtis Pelissier\n-----------------------------\n" );
try
{
GameEvent ge = GameEvent.gameEvent;
ge.StartGame();
}
catch ( SpaceOpDeathException e )
{
Console.WriteLine( "Une erreur est survenue : " + e.Message );
}
catch ( Exception e )
{
Console.WriteLine( "Une erreur est survenue : le jeu ne peut continuer son exécution." );
Console.WriteLine( e.Message );
}
Console.ReadLine();
}
}
}
|
using Fingo.Auth.Domain.Infrastructure.Interfaces;
using Fingo.Auth.Domain.Users.Interfaces;
namespace Fingo.Auth.Domain.Users.Factories.Interfaces
{
public interface IAddImportedUsersFactory : IActionFactory
{
IAddImportedUsers Create();
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tulpep.NotificationWindow;
using CapaDatos;
namespace CapaUsuario.Cobros
{
public partial class FrmRegistracionMonetaria : Form
{
public FrmRegistracionMonetaria()
{
InitializeComponent();
ListarRegistraciones();
ListarConfirmaciones();
}
private void FrmRegistracionMonetaria_Load(object sender, EventArgs e)
{
WindowState = FormWindowState.Maximized;
}
private void ListarConfirmaciones()
{
DgvConfirmaciones.DataSource = ExecuteQuery.SelectAll(404);
}
private void ListarRegistraciones()
{
DgvListadoRegistraciones.DataSource = ExecuteQuery.SelectAll(401);
}
private void CrearRegistracionButton_Click(object sender, EventArgs e)
{
if (DgvConfirmaciones.Rows.Count == 0)
{
MessageBox.Show("No hay confirmaciones de cobro", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var rta = MessageBox.Show("¿Está seguro de crear una registración por la confirmación seleccionada?",
"Confrimación", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
if (rta == DialogResult.No) return;
var codConfirmacion = (int)DgvConfirmaciones.SelectedRows[0].Cells[0].Value;
var fechaRegistracion = DateTime.Now;
// InsertRegistracion(codConfirmacion, fechaRegistracion);
// En la cuenta corriente del cliente, en el campo << DEBE >> pasará a restársele el valor de << IMPORTE RECIBIDO >>
// mientras que en el campo << SALDO >> de la cuenta bancaria cuyo registro se accederá a través de
// << COD.CUENTA BANCARIA >> se le sumará el campo << IMPORTE RECIBIDO >>
object[] parameters =
{
codConfirmacion,
fechaRegistracion.ToShortDateString()
};
ExecuteQuery.InsertInto(41, parameters);
if (MessageException.message == "")
{
ExecuteQuery.UpdateOne(40, codConfirmacion, "relleno");
if (MessageException.message == "")
{
int codCuenta = (int)DgvConfirmaciones.SelectedRows[0].Cells[1].Value;
ExecuteQuery.UpdateOne(41, codConfirmacion, codCuenta);
if (MessageException.message == "")
{
var popup1 = new PopupNotifier()
{
Image = Properties.Resources.sql_success1,
TitleText = "Mensaje",
ContentText = "La registración ha sido insertada con exito",
ContentFont = new Font("Segoe UI Bold", 11F),
TitleFont = new Font("Segoe UI Bold", 10F),
ImagePadding = new Padding(10)
};
popup1.Popup();
ListarConfirmaciones();
ListarRegistraciones();
}
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
ListarRegistraciones();
}
else
{
int codigo = 0;
if (Int32.TryParse(textBox1.Text, out codigo))
{
ExecuteQuery.SelectOne(502, codigo);
}
}
}
}
}
|
using System;
using Android.Runtime;
using Object = Java.Lang.Object;
namespace RU.Tinkoff.Acquiring.Sdk
{
public partial class Money
{
public unsafe int CompareTo(Object p0)
{
//return Long.ValueOf(n_GetCoins).CompareTo((o as Money).n_GetCoins);
if (id_compareTo_Lru_tinkoff_acquiring_sdk_Money_ == IntPtr.Zero)
id_compareTo_Lru_tinkoff_acquiring_sdk_Money_ = JNIEnv.GetMethodID(class_ref, "compareTo", "(Lru/tinkoff/acquiring/sdk/Money;)I");
try
{
JValue* __args = stackalloc JValue[1];
__args[0] = new JValue(p0);
int __ret;
if (((object)this).GetType() == ThresholdType)
__ret = JNIEnv.CallIntMethod(((global::Java.Lang.Object)this).Handle, id_compareTo_Lru_tinkoff_acquiring_sdk_Money_, __args);
else
__ret = JNIEnv.CallNonvirtualIntMethod(((global::Java.Lang.Object)this).Handle, ThresholdClass, JNIEnv.GetMethodID(ThresholdClass, "compareTo", "(Lru/tinkoff/acquiring/sdk/Money;)I"), __args);
return __ret;
}
finally
{
}
}
}
}
|
using Microsoft.AspNetCore.Mvc.Rendering;
using Models.Common;
using System;
using System.Collections.Generic;
using System.Text;
namespace Models.ViewModels
{
public class PurchaseOrderStatusViewModel
{
// hidden
public string ApplicationUserId { get; set; }
public string Id { get; set; }
public string Code { get; set; }
public string Status { get; set; }
public List<string> NewStatus = new List<string>();
public string Budget { get; set; }
public string DateRaised { get; set; }
public string DateFullfilled { get; set; }
public string DateRequired { get; set; }
public string Note { get; set; }
public string ToDetail { get; set; }
public string DeliverToDetail { get; set; }
public string InvoiceToDetail { get; set; }
public string Price { get; set; }
public string Tax { get; set; }
public string Total { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[Header("Player_Properties")]
private Rigidbody2D _rigidbody;
private SwipeController _swipecontroller;
private PlayerCollision _playercollision;
private Animator playerAnimator;
public UiController _uicontroller;
public float sideSpeed;
public float jumpSpeed;
public Vector3 sizeOfPlayer;
private bool shieldActive;
private void Start()
{
#region //Setting component to refrences
_rigidbody = GetComponent<Rigidbody2D>();
_swipecontroller = GetComponent<SwipeController>();
_playercollision = GetComponent<PlayerCollision>();
playerAnimator = GetComponent<Animator>();
#endregion
}
private void Update()
{
#region //Setting the shield active based on player input
if(_uicontroller.buttonActivated)
{
shieldActive = true;
}
if(!_uicontroller.buttonActivated)
{
shieldActive = false;
}
#endregion
#region //Checks whether the shield is active or not, at all stages while running
if (shieldActive)
{
if (playerAnimator.GetBool("Jump") == false)
{
playerAnimator.SetBool("Run", false);
}
}
if (!shieldActive)
{
if (playerAnimator.GetBool("Jump") == false)
{
playerAnimator.SetBool("Run", true);
}
}
#endregion
#region //Checks whether shield was activated in mid-air
if (playerAnimator.GetBool("Jump") == true)
{
if(shieldActive)
{
playerAnimator.SetBool("Mid_Jump_Shield", true);
}
}
#endregion
#region //Setting velocity zero after touching either boundary
if (_rigidbody.velocity.y >= 0 && _playercollision.RightBoundaryTouch == true)
{
_rigidbody.velocity = Vector3.zero;
if (shieldActive)
{
playerAnimator.SetBool("Mid_Jump_Shield", false);
playerAnimator.SetBool("Jump", false);
}
if (!shieldActive)
{
playerAnimator.SetBool("Jump", false);
playerAnimator.SetBool("Mid_Jump_Shield", false);
}
}
if (_rigidbody.velocity.y >= 0 && _playercollision.LeftBoundaryTouch == true)
{
_rigidbody.velocity = Vector3.zero;
if (shieldActive)
{
playerAnimator.SetBool("Mid_Jump_Shield", false);
playerAnimator.SetBool("Jump", false);
}
else
{
playerAnimator.SetBool("Jump", false);
playerAnimator.SetBool("Mid_Jump_Shield", false);
}
}
#endregion //Setting velocity zero after touching either boundary
}
private void FixedUpdate()
{
#region //Sets velocity and jump and animation
if (_swipecontroller.swipeLeft)
{
_swipecontroller.swipeLeft = false;
this.gameObject.transform.localScale = new Vector3(sizeOfPlayer.x, sizeOfPlayer.y, sizeOfPlayer.z);
_playercollision.RightBoundaryTouch = false;
//_rigidbody.velocity = new Vector2(-sideSpeed, jumpSpeed);
//just a test
_rigidbody.AddForce(new Vector2(-sideSpeed, jumpSpeed));
if (shieldActive)
{
shieldActive = false;
playerAnimator.SetBool("Jump", true);
playerAnimator.SetBool("Run", true);
}
if (!shieldActive)
{
playerAnimator.SetBool("Jump", true);
playerAnimator.SetBool("Run", true);
}
}
if (_swipecontroller.swipeRight)
{
_swipecontroller.swipeRight = false;
this.gameObject.transform.localScale = new Vector3(sizeOfPlayer.x, -sizeOfPlayer.y, sizeOfPlayer.z);
_playercollision.LeftBoundaryTouch = false;
//_rigidbody.velocity = new Vector2(sideSpeed, jumpSpeed);
//just a test
_rigidbody.AddForce(new Vector2(sideSpeed, jumpSpeed));
if (shieldActive)
{
shieldActive = false;
playerAnimator.SetBool("Jump", true);
playerAnimator.SetBool("Run", true);
}
if (!shieldActive)
{
playerAnimator.SetBool("Jump", true);
playerAnimator.SetBool("Run", true);
}
}
#endregion
}
}
|
using System.Reflection;
[assembly: AssemblyTitle("DiRT")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DiRT")]
[assembly: AssemblyCopyright("© 2014-2020 Davorin Učakar, Ryan Bray, Andrew Cummings")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.10.0.0")]
[assembly: AssemblyFileVersion("1.10.0.0")]
|
using System;
using System.Collections.Generic;
using System.Linq;
using ILogging;
using ServiceDeskSVC.DataAccess.Models;
namespace ServiceDeskSVC.DataAccess.Repositories
{
public class AssetManagerSoftwareRepository:IAssetManagerSoftwareRepository
{
private readonly ServiceDeskContext _context;
private readonly ILogger _logger;
public AssetManagerSoftwareRepository(ServiceDeskContext context, ILogger logger)
{
_context = context;
_logger = logger;
}
public List<AssetManager_Software> GetAllSoftwareAssets()
{
List<AssetManager_Software> allSoftwareAssets = _context.AssetManager_Software.ToList();
return allSoftwareAssets;
}
public AssetManager_Software GetSoftwareAssetByID(int id)
{
AssetManager_Software software = _context.AssetManager_Software.FirstOrDefault(x => x.SoftwareAssetNumber == id);
return software;
}
public bool DeleteSoftwareAsset(int id)
{
bool result = false;
try
{
var assetToDelete = _context.AssetManager_Software.FirstOrDefault(s => s.SoftwareAssetNumber == id);
_context.AssetManager_Software.Remove(assetToDelete);
_context.SaveChanges();
result = true;
_logger.Info("Software Asset with assset number " + id + " was deleted.");
}
catch(Exception ex)
{
_logger.Error(ex);
}
return result;
}
public int CreateSoftwareAsset(AssetManager_Software softwareAsset)
{
softwareAsset.SoftwareAssetNumber = GetNextSoftwareAssetNumber();
_context.AssetManager_Software.Add(softwareAsset);
_context.SaveChanges();
return softwareAsset.Id;
}
public int EditSoftwareAsset(int id, AssetManager_Software softwareAsset)
{
try
{
var oldSoftwareAsset = GetSoftwareAssetByID(id);
if(oldSoftwareAsset != null)
{
oldSoftwareAsset.AccountingReqNumber = softwareAsset.AccountingReqNumber;
oldSoftwareAsset.AssociatedCompanyId = softwareAsset.AssociatedCompanyId;
oldSoftwareAsset.DateOfPurchase = softwareAsset.DateOfPurchase;
oldSoftwareAsset.EndOfSupportDate = softwareAsset.EndOfSupportDate;
oldSoftwareAsset.LicenseCount = softwareAsset.LicenseCount;
oldSoftwareAsset.LicensingInfo = softwareAsset.LicensingInfo;
oldSoftwareAsset.ModifiedById = softwareAsset.ModifiedById;
oldSoftwareAsset.ModifiedDate = softwareAsset.ModifiedDate;
oldSoftwareAsset.Name = softwareAsset.Name;
oldSoftwareAsset.Notes = softwareAsset.Notes;
oldSoftwareAsset.ProductOwnerId = softwareAsset.ProductOwnerId;
oldSoftwareAsset.ProductUsersId = softwareAsset.ProductUsersId;
oldSoftwareAsset.PublisherId = softwareAsset.PublisherId;
oldSoftwareAsset.SoftwareTypeId = softwareAsset.SoftwareTypeId;
oldSoftwareAsset.SupportingCompanyId = softwareAsset.SupportingCompanyId;
}
_context.SaveChanges();
_logger.Info("Software Asset with asset number" + id + " was updated.");
return softwareAsset.Id;
}
catch(Exception ex)
{
_logger.Error(ex);
return 0;
}
}
private int GetNextSoftwareAssetNumber()
{
var asset = _context.AssetManager_Software.OrderByDescending(t => t.SoftwareAssetNumber).FirstOrDefault();
if(asset != null)
{
return asset.SoftwareAssetNumber + 1;
}
else
{
return 1;
}
}
}
}
|
using System;
using System.Drawing;
using TY.SPIMS.Client.Helper;
using TY.SPIMS.Controllers;
using TY.SPIMS.Entities;
using TY.SPIMS.POCOs;
using TY.SPIMS.Utilities;
using TY.SPIMS.Controllers.Interfaces;
namespace TY.SPIMS.Client.Brands
{
public partial class AddBrandForm : InputDetailsForm
{
private readonly IBrandController brandController;
public int BrandId { get; set; }
public bool FromAddItem { get; set; }
public event BrandUpdatedEventHandler BrandUpdated;
protected virtual void OnBrandUpdated(EventArgs e)
{
BrandUpdatedEventHandler handler = BrandUpdated;
if (handler != null)
{
handler(this, e);
}
}
public AddBrandForm()
{
this.brandController = IOC.Container.GetInstance<BrandController>();
InitializeComponent();
}
#region Load
private void AddBrandForm_Load(object sender, EventArgs e)
{
if (BrandId != 0)
LoadBrandDetails();
}
public void LoadBrandDetails()
{
if (BrandId != 0)
{
Brand b = this.brandController.FetchBrandById(BrandId);
IdTextbox.Text = b.Id.ToString();
BrandTextbox.Text = b.BrandName;
}
else
ClearForm();
}
#endregion
#region Save
private void SaveButton_Click(object sender, EventArgs e)
{
SaveBrand();
}
private void SaveBrand()
{
if (string.IsNullOrWhiteSpace(BrandTextbox.Text))
{
ClientHelper.ShowRequiredMessage("Brand name");
return;
}
if (hasDuplicate)
{
ClientHelper.ShowDuplicateMessage("Brand name");
return;
}
if (IdTextbox.Text == "0")
{
this.brandController.InsertBrand(
new BrandColumnModel()
{
BrandName = BrandTextbox.Text.Trim(),
IsDeleted = false
});
ClientHelper.ShowSuccessMessage("Brand added successfully.");
}
else
{
this.brandController.UpdateBrand(
new BrandColumnModel()
{
Id = BrandId,
BrandName = BrandTextbox.Text.Trim(),
IsDeleted = false
});
ClientHelper.ShowSuccessMessage("Brand updated successfully.");
}
if (BrandUpdated != null)
BrandUpdated(new object(), new EventArgs());
ClearForm();
if (FromAddItem)
this.Close();
}
#endregion
#region Clear
private void ClearForm()
{
if (BrandId == 0)
{
IdTextbox.Text = "0";
BrandTextbox.Clear();
}
else
{
IdTextbox.Text = BrandId.ToString();
LoadBrandDetails();
}
}
#endregion
#region Duplicate
private bool hasDuplicate = false;
private void BrandTextbox_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(BrandTextbox.Text))
hasDuplicate = DuplicateChecker.CodeHasDuplicate(CodeType.Brand, BrandTextbox.Text.Trim(), BrandId);
if (hasDuplicate)
BrandTextbox.ForeColor = Color.Red;
else
BrandTextbox.ForeColor = Color.Black;
}
#endregion
}
public delegate void BrandUpdatedEventHandler(object sender, EventArgs e);
} |
using ChristmasPictureRater.Models;
namespace ChristmasPictureRater.Dtos
{
public class DrawingDto
{
public DrawingDto(int id, string image, Categories category, string artistsName, int likes)
{
Id = id;
Image = image;
Category = category;
ArtistsName = artistsName;
Likes = likes;
}
public DrawingDto(Drawing drawing) : this(drawing.Id, drawing.Image, drawing.Category, drawing.ArtistsName,
drawing.Likes)
{
}
public int Id { get; }
public string Image { get; }
public Categories Category { get; }
public string ArtistsName { get; }
public int Likes { get; }
}
public class RateDrawingsDto
{
public RateDrawingsDto(DrawingDto drawing1, DrawingDto drawing2)
{
Drawing1 = drawing1;
Drawing2 = drawing2;
}
public DrawingDto Drawing1 { get; }
public DrawingDto Drawing2 { get; }
}
} |
using UnityEngine;
using UnityAtoms.BaseAtoms;
using UnityAtoms.MonoHooks;
namespace UnityAtoms.MonoHooks
{
/// <summary>
/// Variable Instancer of type `CollisionGameObject`. Inherits from `AtomVariableInstancer<CollisionGameObjectVariable, CollisionGameObjectPair, CollisionGameObject, CollisionGameObjectEvent, CollisionGameObjectPairEvent, CollisionGameObjectCollisionGameObjectFunction>`.
/// </summary>
[EditorIcon("atom-icon-hotpink")]
[AddComponentMenu("Unity Atoms/Variable Instancers/CollisionGameObject Variable Instancer")]
public class CollisionGameObjectVariableInstancer : AtomVariableInstancer<
CollisionGameObjectVariable,
CollisionGameObjectPair,
CollisionGameObject,
CollisionGameObjectEvent,
CollisionGameObjectPairEvent,
CollisionGameObjectCollisionGameObjectFunction>
{ }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler_Logic.Problems {
public class Problem293 : ProblemBase {
private List<double> _primes = new List<double>();
private double[] _powers;
private HashSet<double> _admissables = new HashSet<double>();
private HashSet<double> _fortunates = new HashSet<double>();
private Dictionary<double, bool> _primesFound = new Dictionary<double, bool>();
public override string ProblemName {
get { return "293: Pseudo-Fortunate Numbers"; }
}
public override string GetAnswer() {
double max = 1000000000;
FindPrimes(max);
FindAdmissableNumbers(max, 0, 1);
return FindFortunates().ToString();
}
private void FindPrimes(double max) {
List<double> primes = new List<double>();
primes.Add(2);
primes.Add(3);
primes.Add(5);
primes.Add(7);
primes.Add(11);
primes.Add(13);
primes.Add(17);
primes.Add(19);
primes.Add(23);
double total = 1;
foreach (double prime in primes) {
total *= prime;
if (total <= max) {
_primes.Add(prime);
} else {
break;
}
}
_powers = new double[_primes.Count];
_powers[0] = 1;
}
private void FindAdmissableNumbers(double max, int powerIndex, double currentNum) {
do {
double nextPower = Math.Pow(_primes[powerIndex], _powers[powerIndex]);
currentNum *= nextPower;
if (currentNum > max) {
break;
}
if (powerIndex == _powers.Count() - 1) {
_admissables.Add(currentNum);
} else {
FindAdmissableNumbers(max, powerIndex + 1, currentNum);
}
currentNum /= nextPower;
if (powerIndex == 0) {
_powers[powerIndex]++;
} else if (_powers[powerIndex - 1] > 0) {
_powers[powerIndex]++;
} else {
break;
}
} while (true);
_powers[powerIndex] = 0;
}
private double FindFortunates() {
double sum = 0;
foreach (double admissable in _admissables) {
double num = admissable + 3;
while (!IsPrime(num)) {
num += 1;
}
double fortunate = num - admissable;
if (!_fortunates.Contains(fortunate)) {
sum += fortunate;
_fortunates.Add(fortunate);
}
}
return sum;
}
private bool IsPrime(double num) {
if (_primesFound.ContainsKey(num)) {
return _primesFound[num];
} else {
double max = Math.Sqrt(num);
for (ulong factor = 2; factor <= max; factor++) {
if (num % factor == 0) {
_primesFound.Add(num, false);
return false;
}
}
_primesFound.Add(num, true);
return true;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
namespace DMS.Admin
{
public partial class AdminDefault : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet dsGlobalList = Getdata();
grdGlobalList.DataSource = dsGlobalList;
grdGlobalList.DataBind();
}
}
private DataSet Getdata()
{
List<Transaction> trans = new List<Transaction>();
trans.Add(new Transaction { Key = "@UserId", value = Context.User.Identity.Name });
DataSet ds = Transaction.SqlSelTransaction("spGetFileContent", trans);
DataView dv = ds.Tables[0].DefaultView;
ds.Tables.Clear();
ds.Tables.Add(dv.Table);
return ds;
}
protected void imgDel_Click(object sender, ImageClickEventArgs e)
{
string ContentId = ((ImageButton)sender).CommandArgument.ToString();
List<Transaction> trans = new List<Transaction>();
trans.Add(new Transaction { Key = "@ContentId", value = ContentId });
bool res = Transaction.SqlInUpDelTransaction("spDelFileContent", trans);
Response.Redirect(Request.RawUrl);
}
protected void imgDownload_Click(object sender, ImageClickEventArgs e)
{
string ContentId = ((ImageButton)sender).CommandArgument.ToString();
List<Transaction> trans = new List<Transaction>();
trans.Add(new Transaction { Key = "@ContentId", value = ContentId });
DataSet ds = Transaction.SqlSelTransaction("spGetFileContent", trans);
string ContentPath = ds.Tables[0].Rows[0]["ContentPath"].ToString();
string ContentName = ds.Tables[0].Rows[0]["ContentName"].ToString();
//WebClient webClient = new WebClient();
//webClient.DownloadFile(ContentPath, @"d:\"+ContentName+".pdf");
try
{
string path = (ContentPath); //get physical file path from server
string name = Path.GetFileName(path); //get file name
string ext = Path.GetExtension(path); //get file extension
string type = "";
// set known types based on file extension
if (ext != null)
{
switch (ext.ToLower())
{
case ".htm":
case ".html":
type = "text/HTML";
break;
case ".txt":
type = "text/plain";
break;
case ".GIF":
type = "image/GIF";
break;
case ".pdf":
type = "Application/pdf";
break;
case ".doc":
case ".rtf":
type = "Application/msword";
break;
}
}
Response.AppendHeader("content-disposition", "attachment; filename=" + ContentName + "." + ext);
if (type != "")
Response.ContentType = type;
Response.WriteFile(path);
Response.End(); //give POP to user for file downlaod
}
catch (Exception ex)
{
}
}
protected void grdGlobalList_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdGlobalList.PageIndex = e.NewPageIndex;
DataSet ds = Getdata();
grdGlobalList.DataSource = ds;
grdGlobalList.DataBind();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EBS.Query.DTO;
namespace EBS.Query
{
public interface ICategoryQuery
{
IEnumerable<CategoryTreeNode> GetCategoryTree();
}
}
|
// Decompiled with JetBrains decompiler
// Type: Tpi_Watcher.Form1
// Assembly: Tpi Watcher, Version=1.2.0.0, Culture=neutral, PublicKeyToken=null
// MVID: A91036F6-4ADD-407B-9987-2D811322E7F8
// Assembly location: C:\PixelPos\TPI Watcher\Tpi Watcher.exe
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Net.Sockets;
using System.Security;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace Tpi_Watcher
{
public class Form1 : Form
{
private string TPixelLogFilePath = "C:\\PixelPos\\TPixelClient\\Log\\TPixel.log";
private string TpiMonitorLogFilePath = "C:\\PixelPos\\TPixelClient\\Log\\TpiWatcher.log";
private string TpiMonitorLogFileDirectory = "C:\\PixelPos\\TPixelClient\\Log\\";
private List<int> CmdWindowIds = new List<int>();
private bool EnableLogging;
private IContainer components;
private NotifyIcon notifyIcon1;
private System.Windows.Forms.Timer timer1;
private Process ProTPixel;
private Process ProPixelPos;
private ContextMenuStrip contextMenuStrip1;
private ToolStripMenuItem Exit;
private ToolStripMenuItem ShowLogFile;
private ToolStripMenuItem showMonitorLogToolStripMenuItem;
public Form1()
{
this.InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
if (this.EnableLogging)
{
this.showMonitorLogToolStripMenuItem.Visible = true;
this.ProTPixel.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
}
else
{
this.showMonitorLogToolStripMenuItem.Visible = false;
this.ProTPixel.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
}
this.WriteToLogIfEnabled("Waiting for PixelPos to Load....");
this.timer1.Enabled = true;
this.contextMenuStrip1.Visible = false;
this.notifyIcon1.ShowBalloonTip(3000, "Info", "Waiting for PixelPos to Load....", ToolTipIcon.Info);
}
private void Form1_VisibleChanged(object sender, EventArgs e)
{
this.Visible = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (this.CheckIfProcessStarted("PixelPointPos"))
{
this.WriteToLogIfEnabled("PixelPos loaded");
if (this.CheckIfProcessStarted("Java"))
return;
this.WriteToLogIfEnabled("Java process not running, attempting to start.....");
this.StartTpi();
}
else
{
if (this.CmdWindowIds.Count <= 0)
return;
this.WriteToLogIfEnabled("PixelPos is not running, Cleaning up open windows...");
this.StopAllTpiProcesses();
}
}
private void StopAllTpiProcesses()
{
Process[] processesByName1 = Process.GetProcessesByName("java");
Process[] processesByName2 = Process.GetProcessesByName("Cmd");
if (processesByName1.Length == 0)
return;
int num1 = 0;
int num2 = 0;
this.WriteToLogIfEnabled("Attemping to Kill " + processesByName1.Length.ToString() + " Instance(s) of Java");
foreach (Process process in processesByName1)
{
process.Kill();
++num1;
this.WriteToLogIfEnabled("Killed " + (object) num1 + " Instance(s) of java");
}
this.WriteToLogIfEnabled("Attemping to Kill " + processesByName2.Length.ToString() + " Instance(s) of Cmd");
foreach (Process process in processesByName2)
{
if (this.CmdWindowIds.Contains(process.Id))
{
process.Kill();
++num2;
this.WriteToLogIfEnabled("Killed " + (object) num2 + " Instance(s) of cmd");
this.CmdWindowIds.Remove(process.Id);
}
}
}
private void WriteToLogIfEnabled(string message)
{
if (!this.EnableLogging)
return;
try
{
if (!Directory.Exists(this.TpiMonitorLogFileDirectory))
{
Directory.CreateDirectory(this.TpiMonitorLogFileDirectory);
this.WriteToLogIfEnabled("Tpi Monitor logging directory didn't exist so created");
}
File.AppendAllText(this.TpiMonitorLogFilePath, string.Concat(new object[4]
{
(object) DateTime.Now,
(object) ": ",
(object) message,
(object) Environment.NewLine
}));
}
catch (Exception ex)
{
}
}
private void StartTpi()
{
this.WriteToLogIfEnabled("Stopping all open winodws before start attempt...");
this.StopAllTpiProcesses();
try
{
this.WriteToLogIfEnabled("Attempting to start Tpi....");
this.ProTPixel.Start();
this.WriteToLogIfEnabled("Tpi Started");
this.CmdWindowIds.Add(this.ProTPixel.Id);
this.WriteToLogIfEnabled("Window Is is " + this.CmdWindowIds.ToString());
this.notifyIcon1.ShowBalloonTip(3000, "Info", "TPI Loaded", ToolTipIcon.Info);
this.WriteToLogIfEnabled("Waiting 10 seconds for Pos to Load");
Thread.Sleep(10000);
}
catch (Exception ex)
{
this.notifyIcon1.ShowBalloonTip(3000, "Error", "Can't Find the TPi Run.bat file ", ToolTipIcon.Error);
this.WriteToLogIfEnabled("Can't Find the TPi Run.bat file " + ex.Message);
}
}
private bool CheckIfPortIsOpen()
{
TcpClient tcpClient = new TcpClient();
bool flag = false;
try
{
tcpClient.Connect("127.0.0.1", 5656);
if (this.EnableLogging)
{
this.WriteToLogIfEnabled("Port 5656 is Open ");
flag = true;
}
}
catch (Exception ex)
{
if (this.EnableLogging)
{
this.WriteToLogIfEnabled("Port 5656 is Closed " + ex.Message);
flag = false;
}
}
return flag;
}
private bool CheckIfProcessStarted(string program)
{
return Process.GetProcessesByName(program).Length != 0;
}
private void ShowLogFile_Click(object sender, EventArgs e)
{
Process.Start("Notepad.exe", this.TPixelLogFilePath);
}
private void ProTPixel_Exited(object sender, EventArgs e)
{
this.notifyIcon1.ShowBalloonTip(3000, "Info", "TPI has closed", ToolTipIcon.Info);
this.WriteToLogIfEnabled("TPixelClient has exited");
}
private void Exit_Click(object sender, EventArgs e)
{
this.Close();
}
private void showMonitorLogToolStripMenuItem_Click(object sender, EventArgs e)
{
Process.Start("Notepad.exe", this.TpiMonitorLogFilePath);
}
protected override void Dispose(bool disposing)
{
if (disposing && this.components != null)
this.components.Dispose();
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.components = (IContainer) new Container();
ComponentResourceManager componentResourceManager = new ComponentResourceManager(typeof (Form1));
this.notifyIcon1 = new NotifyIcon(this.components);
this.contextMenuStrip1 = new ContextMenuStrip(this.components);
this.showMonitorLogToolStripMenuItem = new ToolStripMenuItem();
this.ShowLogFile = new ToolStripMenuItem();
this.Exit = new ToolStripMenuItem();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.ProTPixel = new Process();
this.ProPixelPos = new Process();
this.contextMenuStrip1.SuspendLayout();
this.SuspendLayout();
this.notifyIcon1.ContextMenuStrip = this.contextMenuStrip1;
this.notifyIcon1.Icon = (Icon) componentResourceManager.GetObject("notifyIcon1.Icon");
this.notifyIcon1.Text = "TPixel Watcher";
this.notifyIcon1.Visible = true;
this.contextMenuStrip1.Items.AddRange(new ToolStripItem[3]
{
(ToolStripItem) this.showMonitorLogToolStripMenuItem,
(ToolStripItem) this.ShowLogFile,
(ToolStripItem) this.Exit
});
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.ShowImageMargin = false;
this.contextMenuStrip1.Size = new Size(148, 92);
this.showMonitorLogToolStripMenuItem.Name = "showMonitorLogToolStripMenuItem";
this.showMonitorLogToolStripMenuItem.Size = new Size(147, 22);
this.showMonitorLogToolStripMenuItem.Text = "Show Monitor Log";
this.showMonitorLogToolStripMenuItem.Click += new EventHandler(this.showMonitorLogToolStripMenuItem_Click);
this.ShowLogFile.Name = "ShowLogFile";
this.ShowLogFile.Size = new Size(147, 22);
this.ShowLogFile.Text = "Show TPI Log";
this.ShowLogFile.Click += new EventHandler(this.ShowLogFile_Click);
this.Exit.Name = "Exit";
this.Exit.Size = new Size(147, 22);
this.Exit.Text = "Exit";
this.Exit.Click += new EventHandler(this.Exit_Click);
this.timer1.Interval = 5000;
this.timer1.Tick += new EventHandler(this.timer1_Tick);
this.ProTPixel.EnableRaisingEvents = true;
this.ProTPixel.StartInfo.Arguments = "/K C:\\pixelpos\\tpixelclient\\run.bat";
this.ProTPixel.StartInfo.Domain = "";
this.ProTPixel.StartInfo.FileName = "cmd.exe";
this.ProTPixel.StartInfo.LoadUserProfile = false;
this.ProTPixel.StartInfo.Password = (SecureString) null;
this.ProTPixel.StartInfo.StandardErrorEncoding = (Encoding) null;
this.ProTPixel.StartInfo.StandardOutputEncoding = (Encoding) null;
this.ProTPixel.StartInfo.UserName = "";
this.ProTPixel.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
this.ProTPixel.StartInfo.WorkingDirectory = "C:\\PixelPos\\TPixelClient\\";
this.ProTPixel.SynchronizingObject = (ISynchronizeInvoke) this;
this.ProTPixel.Exited += new EventHandler(this.ProTPixel_Exited);
this.ProPixelPos.EnableRaisingEvents = true;
this.ProPixelPos.StartInfo.Domain = "";
this.ProPixelPos.StartInfo.FileName = "C:\\Program Files\\PixelPoint\\Pixel SQL Station Install\\POSStationExec.exe";
this.ProPixelPos.StartInfo.LoadUserProfile = false;
this.ProPixelPos.StartInfo.Password = (SecureString) null;
this.ProPixelPos.StartInfo.StandardErrorEncoding = (Encoding) null;
this.ProPixelPos.StartInfo.StandardOutputEncoding = (Encoding) null;
this.ProPixelPos.StartInfo.UserName = "";
this.ProPixelPos.StartInfo.WorkingDirectory = "C:\\Program Files\\PixelPoint\\Pixel SQL Station Install\\";
this.ProPixelPos.SynchronizingObject = (ISynchronizeInvoke) this;
this.AutoScaleDimensions = new SizeF(6f, 13f);
this.AutoScaleMode = AutoScaleMode.Font;
this.ClientSize = new Size(284, 261);
this.Name = "Form1";
this.Text = "TPixel Watcher";
this.Load += new EventHandler(this.Form1_Load);
this.VisibleChanged += new EventHandler(this.Form1_VisibleChanged);
this.contextMenuStrip1.ResumeLayout(false);
this.ResumeLayout(false);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.Application.Dtos;
namespace TestAbp.WebApi.Controllers
{
public class PeopleController : BaseController
{
private readonly IPeopleService _peopleService;
public PeopleController(IPeopleService peopleService)
{
_peopleService = peopleService;
}
[HttpPost("PageListAsync")]
public async Task<PagedResultDto<PeopleDto>> PageListAsync([FromBody]PagedAndSortedResultRequestDto input)
{
return await _peopleService.PageListAsync(input);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Questions : MonoBehaviour
{
[SerializeField]
private Text _textQuestion;
public Score Score;
public VideoManage _Video;
private GazeInteraction _Gaze;
private AdvisersManager _advise;
[SerializeField]
private ShowEndStats _showEnd;
public GameObject AnswerButtons;
private Text HintText;
private int AddScore = 20;
public string[] QuestionStrings;
public bool[] AnswersBooleans;
public string[] Hints;
public float[] TimeTillQuestion;
[SerializeField]
private int CurrentQuestion = 0;
private bool CurrentRightAnswer;
void Awake()
{
HintText = GameObject.FindGameObjectWithTag("HintText").GetComponent<Text>();
_advise = GetComponent<AdvisersManager>();
_Gaze = GameObject.Find("Camera").GetComponent<GazeInteraction>();
Score = GameObject.Find("Game_Manager").GetComponent<Score>();
_showEnd = _Gaze.gameObject.GetComponent<ShowEndStats>();
StartCoroutine(ShowQuestion());
_advise.ShowHint(false);
AnswerButtons.SetActive(false);
}
void GetQuestion()
{
_textQuestion.text = QuestionStrings[CurrentQuestion];
CurrentRightAnswer = AnswersBooleans[CurrentQuestion];
}
public void Waar()
{
if (!_advise.usedAdviser)
{
if (CurrentRightAnswer)
{
Score.AnimateCounter(AddScore);
}
}
AnswerButtons.SetActive(false);
_Gaze.SetActive(false);
_Video.PlayOrResume();
StartCoroutine(ShowQuestion());
_advise.usedAdviser = false;
_advise.ShowHint(false);
}
public void NietWaar()
{
if (!_advise.usedAdviser)
{
if (!CurrentRightAnswer)
{
Score.AnimateCounter(AddScore);
}
}
AnswerButtons.SetActive(false);
_Gaze.SetActive(false);
_Video.PlayOrResume();
StartCoroutine(ShowQuestion());
_advise.usedAdviser = false;
_advise.ShowHint(false);
}
IEnumerator ShowQuestion()
{
if (CurrentQuestion <= QuestionStrings.Length-1)
{
yield return new WaitForSeconds(TimeTillQuestion[CurrentQuestion]);
AnswerButtons.SetActive(true);
GetQuestion();
_Video.Pause();
if (_advise._adviserLeft == 0)
{
_advise.ActiveAdviseur(false);
}
else
{
_advise.ActiveAdviseur(true);
}
CurrentQuestion++;
}
else if(CurrentQuestion == QuestionStrings.Length)
{
_Video.Pause();
yield return new WaitForSeconds(5);
_showEnd.ActiveStats();
}
}
public void SetHInt()
{
HintText.text = Hints[CurrentQuestion-1];
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CCF.DB;
namespace ManageDomain.DAL
{
public class WatchLogDal
{
public List<Models.WatchLog.TimeWatch> GetListLogs(CCF.DB.DbConn dbconn, DateTime date, string projectname, int logtype,
DateTime? begintime, DateTime? endtime, string title, long? groupid, long? innergroupid, int ordertype, int usetimemin, int usetimemax, int pno, int pagesize, out int totalcount)
{
string wherecon = "";
string ordercon = " order by createtime desc ";
if (ordertype == 1)
{
ordercon = " order by elapsed desc,createtime desc ";
}
wherecon += " and logtype=@logtype ";
if (!string.IsNullOrEmpty(projectname))
{
wherecon += " and projectname=@projectname ";
}
if (begintime != null)
{
wherecon += " and createtime>=@begintime ";
}
if (endtime != null)
{
wherecon += " and createtime<=@endtime ";
}
if (!string.IsNullOrEmpty(title))
{
wherecon += " and title like concat('%',@title,'%') ";
}
if (groupid != null)
{
wherecon += " and groupid=@groupid ";
}
if (innergroupid != null)
{
wherecon += " and innergroupid=@innergroupid ";
}
if (usetimemin > 0)
{
wherecon += " and elapsed>=@usetimemin ";
}
if (usetimemax > 0)
{
wherecon += " and elapsed<=@usetimemax ";
}
string tablename = "timewatch" + date.ToString("yyyyMMdd");
string sql = string.Format("select * from {0} where 1=1 {1} {2} limit @startindex,@pagesize;", tablename, wherecon, ordercon);
string countsql = string.Format("select count(1) from {0} where 1=1 {1} {2};", tablename, wherecon, ordercon);
var para = new
{
logtype = logtype,
projectname = projectname ?? "",
begintime = begintime,
endtime = endtime,
title = title ?? "",
groupid = groupid,
innergroupid = innergroupid,
startindex = (pno - 1) * pagesize,
pagesize = pagesize,
usetimemin = usetimemin / 1000m,
usetimemax = usetimemax / 1000m
};
var data = dbconn.Query<Models.WatchLog.TimeWatch>(sql, para);
foreach (var a in data)
{
a.CreateTime = a.CreateTime.AddMilliseconds(a.CreateTimeMs);
}
totalcount = dbconn.ExecuteScalar<int>(countsql, para);
return data;
}
public Tuple<DateTime?, DateTime?> GetTableRange(CCF.DB.DbConn dbconn)
{
string sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='" + dbconn.GetBaseConnection().Database + "' " +
" and TABLE_NAME like 'timewatch________' order by TABLE_NAME asc limit 1;";
System.Data.DataTable tb = dbconn.SqlToDataTable(sql, null);
DateTime? begindate = null;
if (tb.Rows.Count > 0)
{
string t = tb.Rows[0][0].ToString();
begindate = DateTime.Parse(string.Format("{0}-{1}-{2}", t.Substring(9, 4), t.Substring(13, 2), t.Substring(15, 2)));
}
sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='" + dbconn.GetBaseConnection().Database + "' " +
" and TABLE_NAME like 'timewatch________' order by TABLE_NAME desc limit 1;";
tb = dbconn.SqlToDataTable(sql, null);
DateTime? enddate = null;
if (tb.Rows.Count > 0)
{
string t = tb.Rows[0][0].ToString();
enddate = DateTime.Parse(string.Format("{0}-{1}-{2}", t.Substring(9, 4), t.Substring(13, 2), t.Substring(15, 2)));
}
return new Tuple<DateTime?, DateTime?>(begindate, enddate);
}
public bool IsOkDate(CCF.DB.DbConn dbconn, DateTime date)
{
string sql = "SELECT count(1) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='" + dbconn.GetBaseConnection().Database + "' " +
" and TABLE_NAME=@tablename limit 1;";
int count = dbconn.ExecuteScalar<int>(sql, new { tablename = "timewatch" + date.ToString("yyyyMMdd") });
return count > 0;
}
public Models.WatchLog.TimeWatch GetDetail(CCF.DB.DbConn dbconn, DateTime date, int id)
{
string sql = string.Format("select * from timewatch{0} where id=@id;", date.ToString("yyyyMMdd"));
var para = new
{
id = id
};
var data = dbconn.Query<Models.WatchLog.TimeWatch>(sql, para);
foreach (var a in data)
{
a.CreateTime = a.CreateTime.AddMilliseconds(a.CreateTimeMs);
}
return data.FirstOrDefault();
}
public List<Models.WatchLog.TimeWatch> GetTimeLineList(CCF.DB.DbConn dbconn, DateTime date, long innergroupid)
{
string sql = string.Format("select * from timewatch{0} where innergroupid=@innergroupid limit 500;", date.ToString("yyyyMMdd"));
var para = new
{
innergroupid = innergroupid
};
var data = dbconn.Query<Models.WatchLog.TimeWatch>(sql, para);
if (data.Count > 0)
{
if (data.FirstOrDefault().CreateTime.Hour < 1 && data.FirstOrDefault().CreateTime.Minute < 10)
{
if (IsOkDate(dbconn, date.AddDays(-1)))
{
sql = string.Format("select * from timewatch{0} where innergroupid=@innergroupid limit 500;", date.AddDays(-1).ToString("yyyyMMdd"));
data.AddRange(dbconn.Query<Models.WatchLog.TimeWatch>(sql, para));
}
}
if (data.FirstOrDefault().CreateTime.Hour > 22 && data.FirstOrDefault().CreateTime.Minute > 50)
{
if (IsOkDate(dbconn, date.AddDays(1)))
{
sql = string.Format("select * from timewatch{0} where innergroupid=@innergroupid limit 500;", date.AddDays(1).ToString("yyyyMMdd"));
data.AddRange(dbconn.Query<Models.WatchLog.TimeWatch>(sql, para));
}
}
}
foreach (var a in data)
{
a.CreateTime = a.CreateTime.AddMilliseconds(a.CreateTimeMs);
}
return data;
}
}
}
|
using System;
namespace src.SmartSchool.WebAPI.V1.Dtos
{
/// <summary>
///Versão 1: classe responsável pela difinição de propriedade de registros da entidade Aluno.
/// </summary>
public class AlunoPatchDto
{
public int Id { get; set; }
public string Nome { get; set; }
public string Sobrenome { get; set; }
public string Telefone { get; set; }
public bool Ativo { get; set; }
}
}
|
using System.Reflection;
using System.Linq;
namespace ModelTransformationComponent
{
/// <summary>
/// Конкретная фабрика системных конструкций
/// <para/>
/// Наследует <see cref="AbstractRuleFactory"/>
/// </summary>
class SystemRuleFactory : AbstractRuleFactory
{
/// <summary>
/// Создание системной конструкции
/// </summary>
/// <param name="text">Текстовое описание конструкции</param>
/// <param name="charcnt">Количество символов, использованных для создания</param>
/// <returns>Системная конструкция</returns>
public override Rule CreateRule(string text, out int charcnt)
{
SystemTrieSingleton systemTrieSingleton = SystemTrieSingleton.getInstance();
var result = systemTrieSingleton.Search(text, out charcnt, out string Suggestion);
if (result != null)
return result;
else
{
if (Suggestion.Length > 0)
throw new SyntaxError(Suggestion, text);
throw new SyntaxError("system rule", text);
}
}
}
} |
namespace PaymentService.Domain.Entities
{
using System;
using MicroservicesPOC.Shared.Domain;
public abstract class AccountingEntry : Entity<Guid>
{
public AccountingEntry() { }
public AccountingEntry(PolicyAccount policyAccount, DateTimeOffset creationDate, DateTimeOffset effectiveDate, decimal amount)
{
this.PolicyAccount = policyAccount;
this.CreationDate = creationDate;
this.EffectiveDate = effectiveDate;
this.Amount = amount;
}
public PolicyAccount PolicyAccount { get; protected set; }
public DateTimeOffset CreationDate { get; protected set; }
public DateTimeOffset EffectiveDate { get; protected set; }
public decimal Amount { get; protected set; }
public abstract decimal Apply(decimal state);
public bool IsEffectiveOn(DateTimeOffset theDate) => this.EffectiveDate <= theDate;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Player : MonoBehaviour {
#region main variables
public Sprite playerSymbol;
#endregion
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace WitsmlExplorer.Api.Extensions
{
public static class CollectionExtensions
{
public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> data, int chunkSize)
{
if (chunkSize < 1)
throw new ArgumentException($"{nameof(chunkSize)} cannot be less than 1");
return data
.Select((x, i) => new { Index = i, Value = x })
.GroupBy(x => x.Index / chunkSize)
.Select(x => x.Select(v => v.Value));
}
}
}
|
using System;
using UnityEngine;
using UnityEngine.EventSystems;
namespace LuaFramework
{
public class LuaEventListener : EventTrigger
{
public delegate void VoidDelegate(GameObject go, float x, float y);
public LuaEventListener.VoidDelegate onClick;
public LuaEventListener.VoidDelegate onDown;
public LuaEventListener.VoidDelegate onEnter;
public LuaEventListener.VoidDelegate onExit;
public LuaEventListener.VoidDelegate onUp;
public LuaEventListener.VoidDelegate onSelect;
public LuaEventListener.VoidDelegate onUpdateSelect;
public LuaEventListener.VoidDelegate onDrag;
public LuaEventListener.VoidDelegate onDragBegin;
public LuaEventListener.VoidDelegate onDragEnd;
public LuaEventListener.VoidDelegate onDrop;
public int pre_event_type = -1;
public int curr_event_type = 0;
public static LuaEventListener Get(GameObject go)
{
LuaEventListener listener = go.GetComponent<LuaEventListener>();
if (listener == null)
{
listener = go.AddComponent<LuaEventListener>();
}
return listener;
}
public override void OnPointerClick(PointerEventData eventData)
{
if (this.onClick != null)
{
this.pre_event_type = this.curr_event_type;
this.curr_event_type = 1;
this.onClick(base.gameObject, eventData.position.x, eventData.position.y);
}
}
public override void OnPointerDown(PointerEventData eventData)
{
if (this.onDown != null)
{
this.pre_event_type = this.curr_event_type;
this.curr_event_type = 2;
this.onDown(base.gameObject, eventData.position.x, eventData.position.y);
}
}
public override void OnPointerEnter(PointerEventData eventData)
{
if (this.onEnter != null)
{
this.pre_event_type = this.curr_event_type;
this.curr_event_type = 3;
this.onEnter(base.gameObject, eventData.position.x, eventData.position.y);
}
}
public override void OnPointerExit(PointerEventData eventData)
{
if (this.onExit != null)
{
this.pre_event_type = this.curr_event_type;
this.curr_event_type = 4;
this.onExit(base.gameObject, eventData.position.x, eventData.position.y);
}
}
public override void OnPointerUp(PointerEventData eventData)
{
if (this.onUp != null)
{
this.pre_event_type = this.curr_event_type;
this.curr_event_type = 5;
this.onUp(base.gameObject, eventData.position.x, eventData.position.y);
}
}
public override void OnDrag(PointerEventData eventData)
{
if (this.onDrag != null)
{
this.pre_event_type = this.curr_event_type;
this.curr_event_type = 8;
this.onDrag(base.gameObject, eventData.position.x, eventData.position.y);
}
}
public override void OnBeginDrag(PointerEventData eventData)
{
if (this.onDragBegin != null)
{
this.pre_event_type = this.curr_event_type;
this.curr_event_type = 9;
this.onDragBegin(base.gameObject, eventData.position.x, eventData.position.y);
}
}
public override void OnEndDrag(PointerEventData eventData)
{
if (this.onDragEnd != null)
{
this.pre_event_type = this.curr_event_type;
this.curr_event_type = 10;
this.onDragEnd(base.gameObject, eventData.position.x, eventData.position.y);
}
}
public override void OnDrop(PointerEventData eventData)
{
if (this.onDrop != null)
{
this.pre_event_type = this.curr_event_type;
this.curr_event_type = 10;
this.onDrop(base.gameObject, eventData.position.x, eventData.position.y);
}
}
}
}
|
using System;
using System.Collections.Generic;
using Fingo.Auth.AuthServer.Client.Exceptions;
using Fingo.Auth.AuthServer.Client.Services.Implementation;
using Fingo.Auth.AuthServer.Client.Services.Interfaces;
using Fingo.Auth.Domain.Models.UserModels;
using Fingo.Auth.JsonWrapper;
using Moq;
using Xunit;
namespace Fingo.Auth.AuthServer.Client.Tests.Services.Implementation
{
public class RemoteAccountServiceTest
{
[Fact]
public void CreateNewUserInProjectShouldReturnServerConnectionException()
{
// arrange
var postServiceMock = new Mock<IPostService>();
postServiceMock.Setup(
serv => serv.SendAndGetAnswer(It.IsAny<string>() , It.IsAny<Dictionary<string , string>>()))
.Throws(new Exception());
IRemoteAccountService remoteAccountService = new RemoteAccountService(postServiceMock.Object);
// act & assert
Assert.Throws<ServerConnectionException>(
() => remoteAccountService.CreateNewUserInProject(new UserModel()));
}
[Fact]
public void CreateNewUserInProjectShouldReturnServerNotValidAnswerException()
{
// arrange
var postServiceMock = new Mock<IPostService>();
postServiceMock.Setup(
serv => serv.SendAndGetAnswer(It.IsAny<string>() , It.IsAny<Dictionary<string , string>>()))
.Returns("actually not a valid answer");
IRemoteAccountService remoteAccountService = new RemoteAccountService(postServiceMock.Object);
// act & assert
Assert.Throws<ServerNotValidAnswerException>(
() => remoteAccountService.CreateNewUserInProject(new UserModel()));
}
[Fact]
public void CreateNewUserInProjectShouldSucceed()
{
// arrange
var postServiceMock = new Mock<IPostService>();
postServiceMock.Setup(
serv => serv.SendAndGetAnswer(It.IsAny<string>() , It.IsAny<Dictionary<string , string>>()))
.Returns(new JsonObject {Result = JsonValues.UserCreatedInProject}.ToJson());
IRemoteAccountService remoteAccountService = new RemoteAccountService(postServiceMock.Object);
// act & assert
remoteAccountService.CreateNewUserInProject(new UserModel());
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace FoodGallery.Models
{
public class RestaurentReview
{
public int Id { get; set; }
[Range(1,5)]
[Required]
public double Rating { get; set; }
public string Comment { get; set; }
[DisplayFormat(NullDisplayText = "Aonymous")]
public string Reviewer { get; set; }
public int RestaurentID { get; set; }
}
} |
using SFA.DAS.Authorization.ModelBinding;
namespace SFA.DAS.ProviderCommitments.Web.Models.Apprentice
{
public class SentRequest : IAuthorizationContextModel
{
public string ApprenticeshipHashedId { get; set; }
}
}
|
namespace Content.Server.Radar;
[RegisterComponent]
public sealed class RadarConsoleComponent : Component
{
[ViewVariables(VVAccess.ReadWrite)]
[DataField("range")]
public float Range = 512f;
}
|
using System;
using social_network;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System.Collections.Generic;
//Use Visual Studio's Test Explorer to run all tests
//to open the test explorer panel in visual studio:
//Test(top bar) > Windows > Test Explorer
namespace social_network_test
{
[TestClass]
public class social_network_test
{
[TestMethod]
public void TestAll()
{
TestSaveThenLoadFile();
TestClearAllData();
TestRegisterNewUser();
TestAuthenticate();
TestComposePost();
TestViewPost();
TestViewAllUsers();
TestSendViewRespondFriendRequest();
}
[TestMethod]
public void TestSaveThenLoadFile()
{
Person testUser = new Person
{
Username = "testUser",
Password = "testPass",
FirstName = "David",
LastName = "Munn",
Wall = new List<Post>(),
Friends = new List<string>(),
FriendRequestsReceived = new List<string>(),
FriendRequestsSent = new List<string>()
};
social_network.System.RegisteredUsers.Add(testUser);
social_network.System.SaveToFile();
social_network.System.RegisteredUsers = null;
social_network.System.LoadFromFile();
Assert.AreEqual(testUser.Username, social_network.System.RegisteredUsers[0].Username);
Assert.AreEqual(testUser.Password, social_network.System.RegisteredUsers[0].Password);
social_network.System.ClearAllData();
}
[TestMethod]
public void TestClearAllData()
{
string path = "../../../social_network/data";
if (!File.Exists(path + "test.txt"))
{ File.Create(path + "test.txt"); }
string[] directoryBefore = Directory.GetFiles(path);
social_network.System.ClearAllData();
string[] directoryAfter = Directory.GetFiles(path);
Assert.AreNotEqual(directoryBefore, directoryAfter);
}
[TestMethod]
public void TestRegisterNewUser()
{
social_network.System.RegisterNewUser("cs350user", "cs350pass", "firstname", "lastname");
Assert.AreEqual("cs350user", social_network.System.RegisteredUsers[0].Username);
social_network.System.ClearAllData();
}
[TestMethod]
public void TestAuthenticate()
{
User ClientUser = new User(null);
social_network.System.RegisterNewUser("cs350user", "cs350pass", "firstname", "lastname");
ClientUser.Authenticate("cs350user", "cs350pass");
Assert.AreEqual("cs350user", ClientUser.Self.Username);
social_network.System.ClearAllData();
}
[TestMethod]
public void TestComposePost()
{
User ClientUser = new User(null);
social_network.System.RegisterNewUser("cs350user", "cs350pass", "firstname", "lastname");
ClientUser.Authenticate("cs350user", "cs350pass");
ClientUser.ComposePost("subject line here.", "body content here.");
Assert.AreEqual("subject line here.", ClientUser.Self.Wall[0].Subject);
social_network.System.ClearAllData();
}
[TestMethod]
public void TestViewPost()
{
User ClientUser = new User(null);
social_network.System.RegisterNewUser("cs350user", "cs350pass", "firstname", "lastname");
social_network.System.RegisterNewUser("notfriend", "notfriend", "not", "friend");
//users can view their own posts.
ClientUser.Authenticate("notfriend", "notfriend");
ClientUser.ComposePost("subject line here.", "body content here.");
//might fail on the off chance that the current minute advances betweem when the original test post
//made above and the following testpost's time is set below.
string testPost = String.Format("by: notfriend\nat: {0}, {1}\nsubject: subject line here.\nmessage: body content here.",
DateTime.Now.ToShortTimeString(), DateTime.Now.ToShortDateString());
Assert.AreEqual(testPost, ClientUser.ViewPost(ClientUser.Self.Wall[0]));
//users see error message if they try to look at the wall of someone who is not their friend.
ClientUser.Authenticate("cs350user", "cs350pass");
Assert.AreEqual("Access not allowed. You must be friends with this user to see their wall.",
ClientUser.ViewPost(social_network.System.RegisteredUsers[1].Wall[0]));
social_network.System.ClearAllData();
}
[TestMethod]
public void TestViewAllUsers()
{
User ClientUser = new User(null);
social_network.System.RegisterNewUser("cs350user", "cs350pass", "firstname", "lastname");
social_network.System.RegisterNewUser("friend", "friend", "friendy", "friend");
ClientUser.Authenticate("cs350user", "cs350pass");
ClientUser.ViewAllUsers();
social_network.System.ClearAllData();
}
[TestMethod]
public void TestSendViewRespondFriendRequest()
{
User ClientUser = new User(null);
social_network.System.RegisterNewUser("cs350user", "cs350pass", "firstname", "lastname");
social_network.System.RegisterNewUser("friend", "friend", "friendy", "friend");
ClientUser.Authenticate("cs350user", "cs350pass");
ClientUser.SendFriendRequest(social_network.System.RegisteredUsers[1]);
Assert.AreEqual("Friend requests you have sent: \nfriend, friendy, friend\n", ClientUser.ViewSentFriendRequests());
ClientUser.Authenticate("friend", "friend");
Assert.AreEqual("Friend requests sent to you: \ncs350user, firstname, lastname\n", ClientUser.ViewReceivedFriendRequests());
ClientUser.RespondToFriendRequest(true, social_network.System.RegisteredUsers[0]);
Assert.AreEqual("Friend List: \ncs350user, firstname, lastname\n", ClientUser.ViewFriends());
social_network.System.ClearAllData();
}
}
}
|
using System.IO;
namespace Decima.HZD
{
[RTTI.Serializable(0x8E09340D7626AFAE)]
public class DataBufferResource : BaseResource, RTTI.IExtraBinaryDataCallback
{
public HwBuffer Buffer;
public void DeserializeExtraData(BinaryReader reader)
{
uint bufferElementCount = reader.ReadUInt32();
if (bufferElementCount > 0)
{
uint isStreaming = reader.ReadUInt32();
uint flags = reader.ReadUInt32();
var format = (EDataBufferFormat)reader.ReadUInt32();
uint bufferStride = reader.ReadUInt32();
if (isStreaming != 0 && isStreaming != 1)
throw new InvalidDataException("Must be true or false");
if (format != EDataBufferFormat.Structured)
bufferStride = HwBuffer.GetStrideForFormat(format);
Buffer = HwBuffer.FromData(reader, format, isStreaming != 0, bufferStride, bufferElementCount);
}
}
}
} |
namespace MySurveys.Services
{
using System.Linq;
using Contracts;
using Data.Repository;
using Models;
using Web.Infrastructure.IdBinder;
public class SurveyService : ISurveyService
{
private IRepository<Survey> surveys;
private IRepository<Question> questions;
private IRepository<PossibleAnswer> possibleAnswers;
private IIdentifierProvider identifierProvider;
public SurveyService(IRepository<Survey> surveys, IRepository<Question> questions, IIdentifierProvider identifierProvider, IRepository<PossibleAnswer> possibleAnswers)
{
this.surveys = surveys;
this.questions = questions;
this.possibleAnswers = possibleAnswers;
this.identifierProvider = identifierProvider;
}
public IQueryable<Survey> GetAll()
{
return this.surveys
.All()
.OrderByDescending(s => s.Responses.Count);
}
public IQueryable<Survey> GetAllPublic()
{
return this.surveys
.All()
.Where(s => s.IsPublic == true)
.OrderByDescending(s => s.Responses.Count);
}
public Survey GetById(int id)
{
return this.surveys.GetById(id);
}
public Survey GetById(string id)
{
var idAsInt = this.identifierProvider.DecodeId(id);
return this.surveys.GetById(idAsInt);
}
public Survey Update(Survey survey)
{
this.surveys.Update(survey);
this.surveys.SaveChanges();
return survey;
}
public void Delete(object id)
{
var survey = this.surveys.GetById(id);
this.surveys.Delete(id);
foreach (var quest in survey.Questions)
{
var question = this.questions.GetById(quest.Id);
this.questions.Delete(quest.Id);
foreach (var amswer in question.PossibleAnswers)
{
this.possibleAnswers.Delete(amswer.Id);
}
}
this.possibleAnswers.SaveChanges();
this.questions.SaveChanges();
this.surveys.SaveChanges();
}
public IQueryable<Survey> GetMostPopular(int numberOfSurveys)
{
return this.surveys
.All()
.OrderByDescending(x => x.Responses.Count)
.Take(numberOfSurveys);
}
public Survey Add(Survey survey)
{
this.surveys.Add(survey);
this.surveys.SaveChanges();
return survey;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.UI;
using UnityEngine.UI.Extensions;
public class TaskManager : MonoBehaviour
{
public static TaskManager instance;
private void Awake ()
{
if (instance == null)
instance = this;
else if (instance != this)
{
Destroy ( this.gameObject );
return;
}
}
public Task activeTask { get; protected set; }
public List<Task> tasks { get; protected set; } = new List<Task> ();
[SerializeField] private float timePerTask = 30.0f;
private float currentTime = 0.0f;
[SerializeField] private TextMeshProUGUI taskNameText;
[SerializeField] private TextMeshProUGUI timeLeftText;
[SerializeField] private TextMeshProUGUI progressDarkText;
[SerializeField] private TextMeshProUGUI progressLightText;
[SerializeField] private Image fillImage;
[SerializeField] private float fillImageDamp;
private float fillImageTarget;
[Space]
[SerializeField] private AreaCollider truckAreaCollider;
[SerializeField] private UILineRenderer lr;
private bool displayAreaNavigation = false;
private Vector3 targetPosition = new Vector3 ();
private TrashSpawner spawner;
NavMeshPath path;
MiniMap mm;
private void Start ()
{
TickSystem.Tick += Tick;
path = new NavMeshPath ();
mm = FindObjectOfType<MiniMap> ();
CreateTasks ();
AssignInitialTask ();
truckAreaCollider.OnAreaChanged += OnTruckAreaChanged;
InvokeRepeating ( nameof ( CheckAreaNavigation ), 0.25f, 0.25f );
}
private void Update ()
{
MonitorTime ();
UpdateActiveTask ();
fillImage.fillAmount = Mathf.Lerp ( fillImage.fillAmount, fillImageTarget, fillImageDamp * Time.deltaTime );
}
private void Tick()
{
if (TickSystem.Equals ( 10 ))
{
if (activeTask != null && activeTask.isActive)
{
timeLeftText.text = currentTime.ToString ( "0" ) + " secs\nleft";
}
}
}
private void CreateTasks ()
{
tasks.Add ( new Task01 () );
tasks.Add ( new Task02 () );
tasks.Add ( new Task03 () );
tasks.Add ( new Task04 () );
tasks.Add ( new Task05 () );
tasks.Add ( new Task06 () );
tasks.Add ( new Task07 () );
tasks.Add ( new Task08 () );
tasks.Add ( new Task09 () );
tasks.Add ( new Task10 () );
}
public void AddTime ()
{
currentTime = activeTask.timeAllowed / 2.0f;
PopupCanvas.instance.DisplayGreen ( (activeTask.timeAllowed / 2.0f).ToString () + " seconds added" );
}
private void AssignInitialTask (Task previousTask = null)
{
tasks = Shuffle ( tasks );
if (previousTask != null)
{
if (tasks[0] == previousTask)
{
tasks.RemoveAt ( 0 );
tasks.Add ( previousTask );
}
}
else
{
Task task = tasks.FirstOrDefault ( x => x.taskName == "Collect 5 trash" );
tasks.Remove ( task );
tasks.Insert ( 0, task );
}
AssignTask ( tasks[0] );
}
private void AssignTask (Task task)
{
activeTask = task;
currentTime = activeTask.timeAllowed;
taskNameText.text = activeTask.taskName;
timeLeftText.text = currentTime.ToString ( "0" ) + " secs\nleft";
UpdateProgressText ();
activeTask.Begin ();
activeTask.OnTaskUpdated += OnTaskUpdated;
activeTask.OnTaskComplete += OnTaskComplete;
if (string.IsNullOrEmpty ( activeTask.requiredArea ))
{
displayAreaNavigation = false;
lr.Points = new Vector2[0];
}
else
{
if (truckAreaCollider.currentArea != null)
{
OnTruckAreaChanged ( truckAreaCollider.currentArea );
}
}
}
[NaughtyAttributes.Button]
private void UpdateProgressText ()
{
progressLightText.text = activeTask.GetProgressString ();
progressDarkText.text = activeTask.GetProgressString ();
fillImageTarget = activeTask.GetProgressPercentage ();
}
private void MonitorTime ()
{
if (activeTask != null && activeTask.isActive && currentTime > 0)
{
currentTime -= Time.deltaTime;
if (currentTime < 0.0f)
{
QuestionCanvas.instance.ShowQuestion ();
currentTime = 0.0f;
}
timeLeftText.text = currentTime.ToString ( "0" ) + " secs\nleft";
}
}
private void UpdateActiveTask ()
{
if (activeTask != null && activeTask.isActive)
{
activeTask.Update ();
}
}
private void OnTaskUpdated(Task task)
{
if (task != activeTask) return;
UpdateProgressText ();
}
private void OnTaskComplete (Task task)
{
if (task != activeTask) return;
activeTask.OnTaskUpdated -= OnTaskUpdated;
activeTask.OnTaskComplete -= OnTaskComplete;
if (tasks.IndexOf ( task ) < tasks.Count - 1)
{
AssignTask ( tasks[tasks.IndexOf ( task ) + 1] );
}
else
{
AssignInitialTask ( task );
}
PopupCanvas.instance.DisplayGreen ( "Task Complete" );
}
public void FailTask ()
{
if (activeTask == null) return;
Task task = activeTask;
activeTask.OnTaskUpdated -= OnTaskUpdated;
activeTask.OnTaskComplete -= OnTaskComplete;
if (tasks.IndexOf ( task ) < tasks.Count - 1)
{
AssignTask ( tasks[tasks.IndexOf ( task ) + 1] );
}
else
{
AssignInitialTask ( task );
}
PopupCanvas.instance.DisplayRed ( "Task Failed" );
Debug.Log ( "Task failed" );
}
public List<T> Shuffle<T> (List<T> list)
{
System.Random rng = new System.Random ();
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next ( n + 1 );
T value = list[k];
list[k] = list[n];
list[n] = value;
}
return list;
}
private void OnTruckAreaChanged(Area newArea)
{
if (activeTask != null )
{
if (activeTask.isActive)
{
if (!string.IsNullOrEmpty ( activeTask.requiredArea ))
{
if(newArea.AreaName != activeTask.requiredArea)
{
if (spawner == null) spawner = FindObjectOfType<TrashSpawner> ();
targetPosition = spawner.SpawnData.FirstOrDefault ( x => x.area.AreaName == activeTask.requiredArea ).area.gameObject.transform.GetChild ( 0 ).position;
displayAreaNavigation = true;
return;
}
}
}
}
displayAreaNavigation = false;
lr.Points = new Vector2[0];
}
private void CheckAreaNavigation ()
{
if (!displayAreaNavigation) return;
if (NavMesh.CalculatePath ( truckAreaCollider.transform.position, targetPosition, NavMesh.AllAreas, path ))
{
Vector2[] mmPoints = new Vector2[path.corners.Length];
for (int i = 0; i < path.corners.Length; i++)
{
path.corners[i] += Vector3.up * 0.01f;
mmPoints[i] = mm.GetPositionOnMiniMap ( path.corners[i], false, false );
}
lr.Points = mmPoints;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.Extensions.Logging;
using OrchardCore.DisplayManagement.Notify;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Results.AllowSync;
using DFC.ServiceTaxonomy.GraphSync.Helpers;
using DFC.ServiceTaxonomy.GraphSync.Services;
using DFC.ServiceTaxonomy.GraphSync.Services.Interface;
using DFC.ServiceTaxonomy.Slack;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Metadata;
namespace DFC.ServiceTaxonomy.GraphSync.Notifications
{
//todo:
// the oc code stores the notification message in a cookie(!)
// which means when the message gets too long (e.g. contains a long exception stack), the page breaks because you can only have ~4k's worth of cookies to a domain
// i've looked into replacing the OC notification filter with our own, but haven't found a way to do that
//the only options i can think of are...
// a) include a script in the notification message which calls back using ajax to get the contents (we'd have to store the message in a cache to provide it)
// b) implement a new separate notifications system (borrowing heavily from the current oc implementation)
// c) just replace the NotifyFilter, but there doesn't seem to be an easy way to do that
// in the meantime, we try and limit the notification message length (e.g. don't show the exception call stack)
public class GraphSyncNotifier : IGraphSyncNotifier
{
private readonly INodeContentItemLookup _nodeContentItemLookup;
private readonly IContentDefinitionManager _contentDefinitionManager;
private readonly LinkGenerator _linkGenerator;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ILogger<GraphSyncNotifier> _logger;
private readonly IList<NotifyEntry> _entries;
private readonly ISlackMessagePublisher _slackMessagePublisher;
public GraphSyncNotifier(
INodeContentItemLookup nodeContentItemLookup,
IContentDefinitionManager contentDefinitionManager,
LinkGenerator linkGenerator,
IHttpContextAccessor httpContextAccessor,
ILogger<GraphSyncNotifier> logger, ISlackMessagePublisher slackMessagePublisher)
{
_nodeContentItemLookup = nodeContentItemLookup;
_contentDefinitionManager = contentDefinitionManager;
_linkGenerator = linkGenerator;
_httpContextAccessor = httpContextAccessor;
_logger = logger;
_entries = new List<NotifyEntry>();
_slackMessagePublisher = slackMessagePublisher;
}
public async Task AddBlocked(
SyncOperation syncOperation,
ContentItem contentItem,
IEnumerable<(string GraphReplicaSetName, IAllowSync AllowSync)> graphBlockers)
{
string contentType = GetContentTypeDisplayName(contentItem);
_logger.LogWarning("{Operation} the '{ContentItem}' {ContentType} has been cancelled.",
syncOperation, contentItem.DisplayText, contentType);
StringBuilder technicalMessage = new StringBuilder();
StringBuilder technicalHtmlMessage = new StringBuilder();
technicalMessage.AppendLine($"{syncOperation} has been blocked by");
technicalHtmlMessage.AppendLine($"<h5 class=\"card-title\">{syncOperation} has been blocked by</h5>");
foreach (var graphBlocker in graphBlockers)
{
_logger.LogWarning("{GraphReplicaSetName} graph blockers: {AllowSync}.",
graphBlocker.GraphReplicaSetName, graphBlocker.AllowSync);
await AddSyncBlockers(technicalMessage, technicalHtmlMessage, graphBlocker.GraphReplicaSetName, graphBlocker.AllowSync);
}
//todo: need details of the content item with incoming relationships
await Add($"{syncOperation} the '{contentItem.DisplayText}' {contentType} has been cancelled, due to an issue with data syncing.",
technicalMessage.ToString(),
technicalHtmlMessage: new HtmlString(technicalHtmlMessage.ToString()));
}
private async Task AddSyncBlockers(StringBuilder technicalMessage, StringBuilder technicalHtmlMessage, string graphReplicaSetName, IAllowSync allowSync)
{
technicalHtmlMessage.AppendLine($"<div class=\"card mt-3\"><div class=\"card-header\">{graphReplicaSetName} data repositiory</div><div class=\"card-body\">");
technicalHtmlMessage.AppendLine("<ul class=\"list-group list-group-flush\">");
foreach (var syncBlocker in allowSync.SyncBlockers)
{
string? contentItemId = await _nodeContentItemLookup.GetContentItemId((string)syncBlocker.Id, graphReplicaSetName);
string title;
if (contentItemId != null)
{
string editContentItemUrl = _linkGenerator.GetUriByAction(
_httpContextAccessor.HttpContext,
"Edit", "Admin",
new {area = "OrchardCore.Contents", contentItemId});
title = $"<a href=\"{editContentItemUrl}\">'{syncBlocker.Title}'</a>";
}
else
{
title = syncBlocker.Title != null ? $"'{syncBlocker.Title}'" : "[Missing Title]";
}
technicalHtmlMessage.AppendLine($"<li class=\"list-group-item\">'{title}' {syncBlocker.ContentType}</li>");
}
technicalHtmlMessage.AppendLine("</ul></div></div>");
technicalMessage.AppendLine($"{graphReplicaSetName} data repository: {allowSync}");
}
private string GetContentTypeDisplayName(ContentItem contentItem)
{
return ContentDefinitionHelper.GetTypeDefinitionCaseInsensitive(
contentItem.ContentType,
_contentDefinitionManager)!.DisplayName;
}
//todo: add custom styles via scss?
public async Task Add(
string userMessage,
string technicalMessage = "",
Exception? exception = null,
HtmlString? technicalHtmlMessage = null,
HtmlString? userHtmlMessage = null,
NotifyType type = NotifyType.Error)
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation(exception, "Notification '{NotificationType}' with user message '{NotificationUserMessage}' and technical message '{NotificationTechnicalMessage}' and exception '{Exception}'.",
type, userMessage, technicalMessage, exception?.ToString() ?? "None");
}
string exceptionText = GetExceptionText(exception);
HtmlContentBuilder htmlContentBuilder = new HtmlContentBuilder();
string traceId = Activity.Current?.TraceId.ToString() ?? "N/A";
string uniqueId = $"id{Guid.NewGuid():N}";
string onClickFunction = $"click_{uniqueId}";
string clipboardCopy = TechnicalClipboardCopy(
traceId,
userMessage,
technicalMessage,
exceptionText);
try
{
//publish to slack
string slackMessage = BuildSlackMessage(traceId, userMessage, technicalMessage, exception);
await _slackMessagePublisher.SendMessageAsync(slackMessage);
}
catch (Exception e)
{
_logger.LogError(e, e.Message);
}
//fa-angle-double-down, hat-wizard, oil-can, fa-wrench?
htmlContentBuilder
.AppendHtml(TechnicalScript(onClickFunction, clipboardCopy))
.AppendHtml(userHtmlMessage ?? new HtmlString(userMessage))
// .AppendHtml($"<button class=\"close\" style=\"right: 1.25em;\" type=\"button\" data-toggle=\"collapse\" data-target=\"#{uniqueId}\" aria-expanded=\"false\" aria-controls=\"{uniqueId}\"><i class=\"fas fa-wrench\"></i></button>")
.AppendHtml($"<a class=\"close\" style=\"right: 1.25em;\" data-toggle=\"collapse\" href=\"#{uniqueId}\" role=\"button\" aria-expanded=\"false\" aria-controls=\"{uniqueId}\"><i class=\"fas fa-wrench\"></i></a>")
.AppendHtml($"<div class=\"collapse\" id=\"{uniqueId}\">")
.AppendHtml($"<div class=\"card mt-2\"><div class=\"card-header\">Technical Details <button onclick=\"{onClickFunction}()\" style=\"float: right;\" type=\"button\"><i class=\"fas fa-copy\"></i></button></div><div class=\"card-body\">")
.AppendHtml($"<h5 class=\"card-title\">Trace ID</h5><h6 class=\"card-subtitle text-muted\">{traceId}</h6>")
.AppendHtml("<div class=\"mt-3\">")
.AppendHtml(technicalHtmlMessage ?? new HtmlString(technicalMessage))
.AppendHtml("</div>");
if (exception != null)
{
//todo: we only include the exception's message (temporarily) to try to stop the notification message blowing up the page!
//htmlContentBuilder.AppendHtml($"<div class=\"card mt-3\"><div class=\"card-header\">Exception</div><div class=\"card-body\"><pre><code>{exception}</code></pre></div></div>");
htmlContentBuilder.AppendHtml($"<div class=\"card mt-3\"><div class=\"card-header\">Exception</div><div class=\"card-body\"><pre><code>{exceptionText}</code></pre></div></div>");
}
htmlContentBuilder.AppendHtml("</div></div></div>");
if (type != NotifyType.Warning || !_entries.Any(e => e.Type == NotifyType.Warning))
{
var newEntry = new NotifyEntry { Type = type, Message = htmlContentBuilder };
_entries.Add(newEntry);
}
else
{
_logger.LogWarning("Notifier not shown. Type is {Type}. {WarningCount} warnings present. First is {FirstWarning}",
type.ToString(),
_entries.Count(e => e.Type == NotifyType.Warning),
_entries.FirstOrDefault(e => e.Type == NotifyType.Warning)?.Message);
}
}
private string BuildSlackMessage(string traceId, string userMessage, string technicalMessage, Exception? exception)
{
StringBuilder sb =
new StringBuilder(
$"```Trace ID: {traceId}\r\nUser Message: {userMessage}\r\nTechnical Message: {technicalMessage}");
if (exception != null)
{
sb.Append($"\r\nException:\r\n\r\n{exception}");
}
sb.Append("```");
return sb.ToString();
}
private string GetExceptionText(Exception? exception)
{
const int maxExceptionTextLength = 200;
string exceptionMessage = exception?.Message ?? "";
// make sure the exception text doesn't take us over the max notification size
if (exceptionMessage.Length > maxExceptionTextLength)
{
exceptionMessage = $"{exceptionMessage.Substring(0, maxExceptionTextLength)} [truncated]";
}
return exceptionMessage;
}
//todo: add Trace Id to std notifications?
public void Add(NotifyType type, LocalizedHtmlString message)
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Notification '{NotificationType}' with message '{NotificationMessage}'.", type, message);
}
var newEntry = new NotifyEntry { Type = type, Message = message };
if (type != NotifyType.Warning || !_entries.Any(e => e.Type == NotifyType.Warning))
{
_entries.Add(newEntry);
}
}
public IList<NotifyEntry> List()
{
if (_entries.Any(x => x.Type == NotifyType.Error))
{
// orchard core sometimes uses Information, where Success is more appropriate
// and all current Information notifiers seem to really be Success notifiers
return _entries.Where(x => !(x.Type == NotifyType.Success || x.Type == NotifyType.Information)).ToList();
}
return _entries;
}
//todo: one function in ncs.js and call that?
private IHtmlContent TechnicalScript(string onClickFunction, string clipboardText)
{
// we replace any ` (backticks) in the clipboard text to stop them breaking the js
return new HtmlString(
@$"<script type=""text/javascript"">
function {onClickFunction}() {{
navigator.clipboard.writeText(`{clipboardText.Replace('`', '\'')}`).then(function() {{
console.log(""Copied technical error details to clipboard successfully!"");
}}, function(err) {{
console.error(""Unable to write technical error details to clipboard. :-("");
}});
}}
</script>"
);
}
private string TechnicalClipboardCopy(string traceId, string userMessage, string technicalMessage, string exceptionText)
{
return
@$"Trace ID : {traceId}
User Message : {userMessage}
Technical Message : {technicalMessage}
Exception : {exceptionText}";
//todo: we want the full exception really!
//Exception : {exception}";
}
}
}
|
namespace Alabo.Domains.Entities.Core {
/// <summary>
/// 标识
/// </summary>
/// <typeparam name="TKey">标识类型</typeparam>
public interface IKey<TKey> {
/// <summary>
/// 标识
/// </summary>
TKey Id { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace IRAP.Client.User
{
public partial class frmLogoutUserDiary : IRAP.Client.Global.frmCustomBase
{
public frmLogoutUserDiary()
{
InitializeComponent();
}
public string UserDiary
{
get { return edtUserDiary.Text; }
set { edtUserDiary.Text = value; }
}
private void btnOK_Click(object sender, EventArgs e)
{
Close();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace SomeTechie.RoundRobinScheduleGenerator
{
[XmlType()]
public class ScoreKeeper
{
protected static int _idPos = 0;
protected int _id = _idPos++;
[XmlAttribute("Id")]
public int Id
{
get
{
return _id;
}
set
{
_id = value;
if (value > _idPos) _idPos = value;
}
}
protected string _associatedAccessCode;
[XmlIgnore()]
public string AssociatedAccessCode
{
get
{
return _associatedAccessCode;
}
set
{
_associatedAccessCode = value;
}
}
protected string _name;
[XmlAttribute("Name")]
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public ScoreKeeper(string name)
{
_name = name;
}
protected ScoreKeeper()
{
}
public override string ToString()
{
return Name;
}
}
}
|
using System;
using System.Runtime.Serialization;
namespace pjank.BossaAPI.Fixml
{
/// <summary>
/// Każdy błąd wywodzący się z tej biblioteki (zw. z komunikacją FIXML)
/// </summary>
public class FixmlException : Exception
{
public FixmlException() { }
public FixmlException(string message) : base(message) { }
public FixmlException(string message, Exception inner) : base(message, inner) { }
protected FixmlException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}
|
using System;
using System.Windows.Input;
using System.Windows.Media;
namespace WindowsUpdateNotifier
{
public class PopupViewModel : ViewModel
{
public PopupViewModel()
{
}
public PopupViewModel(string title, string message, UpdateState state, Action onCloseCallback, Action openWindowsUpdateControlPanel)
{
ShowUpdateIcon = state == UpdateState.UpdatesAvailable;
Title = title;
Message = message;
BackgroundColor = new SolidColorBrush(ColorHelper.GetWindowsThemeBackgroundColor());
OnCloseCommand = new SimpleCommand(onCloseCallback);
OnOpenWindowsUpdateControlPanelCommand= new SimpleCommand(() =>
{
openWindowsUpdateControlPanel();
onCloseCallback();
});
}
public ICommand OnCloseCommand { get; set; }
public ICommand OnOpenWindowsUpdateControlPanelCommand { get; set; }
public string Title { get; set; }
public string Message { get; set; }
public bool ShowUpdateIcon { get; set; }
public bool StartHiding { get; set; }
public Brush BackgroundColor { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace TestBrokenApp.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class NewSubtask : ContentPage
{
public NewSubtask()
{
InitializeComponent();
}
}
} |
using System.Linq;
using System.Collections.Generic;
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace SchemaObjectMapper
{
public class DelimitedMapping<TSource> : BaseMapping
{
public DelimitedMapping(Expression<Func<TSource, object>> expr, int ordinal)
{
this.PropertyInfo = ReflectionHelper.GetProperty(expr) as PropertyInfo;
this.Ordinal = ordinal;
}
public int Ordinal { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IPTables.Net.Exceptions;
using IPTables.Net.Netfilter;
namespace IPTables.Net.NfTables
{
public class NfTablesChain: INetfilterChain
{
private String _name;
private NfTablesTable _table;
private NfNetfilterHook _hook = null;
private List<NfTablesDataStructure> _dataStructures = new List<NfTablesDataStructure>();
private List<NfTablesRule> _rules = new List<NfTablesRule>();
private int _ipVersion;
public NfTablesChain(string tableName, string chainName, NetfilterSystem netfilterSystem)
{
throw new NotImplementedException();
}
public string Name
{
get { return _name; }
}
public string Table
{
get { return _table.Name; }
}
public int IpVersion
{
get { return _ipVersion; }
}
public IEnumerable<INetfilterRule> Rules
{
get { return _rules.Cast<INetfilterRule>(); }
}
public void AddRule(NfTablesRule rule)
{
_rules.Add(rule);
}
void INetfilterChain.AddRule(INetfilterRule rule)
{
var ruleCast = rule as NfTablesRule;
if(ruleCast == null)
throw new IpTablesNetException("Rule is of the wrong type");
AddRule(ruleCast);
}
}
}
|
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(FIT5032_MyCSS.Startup))]
namespace FIT5032_MyCSS
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
|
using SmartHome.Abstract;
using SmartHome.Model;
namespace SmartHome.Service.Response
{
public class UserResponseCollection :ResponseCollection<User>
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using System.Text;
using MobilePhoneRetailer.BusinessLayer.Order;
namespace MobilePhoneRetailer.DataLayer
{
public class OrderMapper
{
public static string GetOrderID(Order ord){
int oID = 0;
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
SqlDataReader reader;
SqlCommand cmd = new SqlCommand("SELECT OrderID FROM [Order] WHERE OrderID = (SELECT MAX(OrderID) FROM [Order])", con);
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
oID = Convert.ToInt32(reader["OrderID"]);
oID++;
}
reader.Close();
ord.OrderID = oID;
}
catch (SqlException sqlEx)
{
return (sqlEx.Message);
}
finally
{
con.Close();
}
return "complete";
}
public static string CreateOrder(Order ord)
{
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
String sql = "INSERT INTO [Order] VALUES(@OrderID ,@CustomerID, @ProductID, @Address, @Amount, @OrderDate, @SupplierID)";
//if there is an error with the data it will catch the exception and display an error
try
{
if (ord.Product.ProductID > 0)
{
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("@OrderID", SqlDbType.Int);
command.Parameters["@OrderID"].Value = ord.OrderID;
command.Parameters.Add("@CustomerID", SqlDbType.Int);
command.Parameters["@CustomerID"].Value = ord.CustomerID;
command.Parameters.Add("@ProductID", SqlDbType.Int);
command.Parameters["@ProductID"].Value = ord.Product.ProductID;
command.Parameters.Add("@Address", SqlDbType.NVarChar);
command.Parameters["@Address"].Value = ord.Address;
command.Parameters.Add("@Amount", SqlDbType.Float);
command.Parameters["@Amount"].Value = ord.Amount;
command.Parameters.Add("@OrderDate", SqlDbType.DateTime);
command.Parameters["@OrderDate"].Value = ord.Date;
command.Parameters.Add("@SupplierID", SqlDbType.Int);
command.Parameters["@SupplierID"].Value = ord.SupplierID;
command.ExecuteNonQuery();
connection.Close();
return "complete";
}
else
return "ProductID <= 0 for some reason - OrderMapper";
}
catch (SqlException sqlEx)
{
return (sqlEx.Message);
}
}
public static string EditOrder(Order ord)
{
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
String sql = "UPDATE [Order] SET CustomerID = @CustomerID, ProductID = @ProductID," +
"Address = @Address, Amount = @Amount, OrderDate = @OrderDate, SupplierID = @SupplierID WHERE OrderID = @OrderID)";
//if there is an error with the data it will catch the exception and display an error
try
{
if (ord.Product.ProductID > 0)
{
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("@CustomerID", SqlDbType.Int);
command.Parameters["@CustomerID"].Value = ord.CustomerID;
command.Parameters.Add("@ProductID", SqlDbType.Int);
command.Parameters["@ProductID"].Value = ord.Product.ProductID;
command.Parameters.Add("@Address", SqlDbType.NVarChar);
command.Parameters["@Address"].Value = ord.Address;
command.Parameters.Add("@Amount", SqlDbType.Float);
command.Parameters["@Amount"].Value = ord.Amount;
command.Parameters.Add("@OrderDate", SqlDbType.DateTime);
command.Parameters["@OrderDate"].Value = ord.Date;
command.Parameters.Add("@SupplierID", SqlDbType.Int);
command.Parameters["@SupplierID"].Value = ord.SupplierID;
command.ExecuteNonQuery();
connection.Close();
}
}
catch (SqlException sqlEx)
{
return (sqlEx.Message);
}
return "Edit Order COmpleted";
}
public static string AddProduct(Order ord, int pID, double amnt)
{
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
String sql = "INSERT INTO [Order] VALUES(@OrderID ,@CustomerID, @ProductID, @Address, @Amount, @OrderDate, @SupplierID)";
//if there is an error with the data it will catch the exception and display an error
try
{
if (ord.Product.ProductID > 0)
{
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("@OrderID", SqlDbType.Int);
command.Parameters["@OrderID"].Value = ord.OrderID;
command.Parameters.Add("@CustomerID", SqlDbType.Int);
command.Parameters["@CustomerID"].Value = ord.CustomerID;
command.Parameters.Add("@ProductID", SqlDbType.Int);
command.Parameters["@ProductID"].Value = pID;
command.Parameters.Add("@Address", SqlDbType.NVarChar);
command.Parameters["@Address"].Value = ord.Address;
command.Parameters.Add("@Amount", SqlDbType.Float);
command.Parameters["@Amount"].Value = amnt;
command.Parameters.Add("@OrderDate", SqlDbType.DateTime);
command.Parameters["@OrderDate"].Value = ord.Date;
command.Parameters.Add("@SupplierID", SqlDbType.Int);
command.Parameters["@SupplierID"].Value = ord.SupplierID;
command.ExecuteNonQuery();
connection.Close();
return "Add product completed";
}
else
return "Add product - Prod ID < 1";
}
catch (SqlException sqlEx)
{
return (sqlEx.Message);
}
}
public static string RemoveProduct(Order ord, int pID)
{
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
String sql = "DELETE FROM [Order] WHERE [OrderID] = @OrderID AND [ProductID] = @ProductID";
//if there is an error with the data it will catch the exception and display an error
try
{
if (ord.Product.ProductID > 0)
{
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("@OrderID", SqlDbType.Int);
command.Parameters["@OrderID"].Value = ord.OrderID;
command.Parameters.Add("@ProductID", SqlDbType.Int);
command.Parameters["@ProductID"].Value = pID;
command.ExecuteNonQuery();
connection.Close();
return "remove product completed";
}
else
return "ProductID < 1 - remove product";
}
catch (SqlException sqlEx)
{
return (sqlEx.Message);
}
}
public static string GetOrderPrice(int oID)
{
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
SqlDataReader reader;
string price = "";
String sql = "SELECT * FROM [Order] WHERE [OrderID] = @oID";
try
{
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("@oID", SqlDbType.Int);
command.Parameters["@oID"].Value = oID;
reader = command.ExecuteReader();
while (reader.Read())
{
price += reader["Amount"];
}
reader.Close();
command.ExecuteNonQuery();
connection.Close();
return price;
}
catch (SqlException sqlEx)
{
return (sqlEx.Message);
}
}
public static int GetOrderCustID(int oID)
{
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
SqlDataReader reader;
string custID = "";
String sql = "SELECT * FROM [Order] WHERE [OrderID] = @oID";
try
{
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("@oID", SqlDbType.Int);
command.Parameters["@oID"].Value = oID;
reader = command.ExecuteReader();
while (reader.Read())
{
custID += reader["CustomerID"];
}
reader.Close();
command.ExecuteNonQuery();
connection.Close();
return Convert.ToInt32(custID);
}
catch
{
return 0;
}
}
public static int GetOrderProductID(int oID)
{
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
SqlDataReader reader;
string productID = "";
String sql = "SELECT * FROM [Order] WHERE [OrderID] = @oID";
try
{
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("@oID", SqlDbType.Int);
command.Parameters["@oID"].Value = oID;
reader = command.ExecuteReader();
while (reader.Read())
{
productID += reader["ProductID"];
}
reader.Close();
command.ExecuteNonQuery();
connection.Close();
return Convert.ToInt32(productID);
}
catch
{
return 0;
}
}
public static string GetOrderAddress(int oID)
{
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
SqlDataReader reader;
string address = "";
String sql = "SELECT * FROM [Order] WHERE [OrderID] = @oID";
try
{
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("@oID", SqlDbType.Int);
command.Parameters["@oID"].Value = oID;
reader = command.ExecuteReader();
while (reader.Read())
{
address += reader["Address"];
}
reader.Close();
command.ExecuteNonQuery();
connection.Close();
return address;
}
catch
{
return "";
}
}
public static DateTime GetOrderDate(int oID)
{
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
SqlDataReader reader;
string date = "";
DateTime now = DateTime.Now;
String sql = "SELECT * FROM [Order] WHERE [OrderID] = @oID";
try
{
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("@oID", SqlDbType.Int);
command.Parameters["@oID"].Value = oID;
reader = command.ExecuteReader();
while (reader.Read())
{
date += reader["OrderDate"];
}
reader.Close();
command.ExecuteNonQuery();
connection.Close();
return Convert.ToDateTime(date);
}
catch
{
return now;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class garageCutscene1 : MonoBehaviour
{
int cutsceneVar = 0;
[SerializeField] Animator jeff;
[SerializeField] Animator michelle;
[SerializeField] Animator playerCar;
// Start is called before the first frame update
void Start()
{
}
void OnEnable()
{
cutsceneVar++;
if(cutsceneVar == 1)
{
jeff.Play("cutscene1");
michelle.Play("Working On Device");
michelle.transform.position = new Vector3(6.29f, -0.736f, -3.83f);
michelle.transform.rotation = Quaternion.Euler(0,0,0);
}
else if(cutsceneVar == 2)
{
jeff.Play("cutscene2");
}
else if(cutsceneVar == 3)
{
michelle.Play("cutscene3");
michelle.transform.position = new Vector3 (3.55f, -0.736f, -5.28f);
michelle.transform.rotation = Quaternion.Euler(0, -160.4f, 0);
}
else if(cutsceneVar == 4)
{
PlayerPrefs.SetInt("car" + PlayerPrefs.GetInt("currentCar", 0) + "Status", 1);
foreach(Material mat in playerCar.transform.GetChild(0).GetChild(PlayerPrefs.GetInt("currentCar")).GetComponent<Renderer>().materials)
{
if(mat.name == "carMaterial (Instance)")
{
mat.SetTexture("_MainTex", null);
}
}
foreach(Material mat in playerCar.transform.GetChild(0).GetChild(PlayerPrefs.GetInt("currentCar")).GetChild(1).GetComponent<Renderer>().materials)
{
if(mat.name == "carMaterial (Instance)")
{
mat.SetTexture("_MainTex", null);
mat.SetColor("_Color", new Color(PlayerPrefs.GetFloat("car" + PlayerPrefs.GetInt("currentCar") + "Color1"), PlayerPrefs.GetFloat("car" + PlayerPrefs.GetInt("currentCar") + "Color2"), PlayerPrefs.GetFloat("car" + PlayerPrefs.GetInt("currentCar") + "Color3"), 1));
}
}
playerCar.transform.GetChild(0).GetChild(PlayerPrefs.GetInt("currentCar")).GetChild(0).gameObject.SetActive(false);
playerCar.transform.GetChild(0).GetChild(PlayerPrefs.GetInt("currentCar")).GetChild(1).gameObject.SetActive(true);
michelle.Play("cutscene3");
playerCar.Play("playerCar_garage1");
michelle.transform.position = new Vector3(3.39f, -0.736f, -9.602f);
michelle.transform.rotation = Quaternion.Euler(0, 90f, 0);
}
}
// Update is called once per frame
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RoutingControllerBeta
{
class RouterTable
{
List<Router> routerList;
public void addRouter (Router router)
{
routerList.Add(router);
}
public bool doesNotContain(Router searchedRouter)
{
foreach(Router router in routerList)
{
if (router.isEqual(searchedRouter))
return false;
}
return true;
}
public RouterTable()
{
routerList = new List<Router>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Antlr4.Runtime.Misc;
using PropositionalFormulaProver.Grammar;
using PropositionalFormulaProver.Prover.Node;
namespace PropositionalFormulaProver.Prover
{
public class FormulaListener: FormulaBaseListener
{
Stack<INode> stack = new Stack<INode>();
bool isLeftFinished = false;
public override void ExitAtom([NotNull] FormulaParser.AtomContext context)
{
Console.WriteLine("ExitAtom start, stack count = " + stack.Count());
base.ExitAtom(context);
stack.Push(new Atom(context.GetText()));
}
public override void ExitNegation([NotNull] FormulaParser.NegationContext context)
{
Console.WriteLine("ExitNegation start, stack count = " + stack.Count());
base.ExitNegation(context);
Negation negation = new Negation(stack.Pop());
stack.Push(negation);
}
public override void ExitTo([NotNull] FormulaParser.ToContext context)
{
Console.WriteLine("ExitTo start, stack count = " + stack.Count());
base.EnterTo(context);
LeftOrRight right = (LeftOrRight)stack.Pop();
LeftOrRight left = (LeftOrRight)stack.Pop();
To to = new To(left, right);
stack.Push(to);
}
public override void ExitSupset([NotNull] FormulaParser.SupsetContext context)
{
Console.WriteLine("ExitSupset start, stack count = " + stack.Count());
base.ExitSupset(context);
Supset supset = new Supset(stack.Pop(), stack.Pop());
stack.Push(supset);
}
public override void ExitRightOrLeft([NotNull] FormulaParser.RightOrLeftContext context)
{
Console.WriteLine("ExitRightOrLeft start, stack count = " + stack.Count());
base.ExitRightOrLeft(context);
LeftOrRight lr = new LeftOrRight();
if (isLeftFinished)
{
int stackCount = stack.Count();
for (int i = 0; i < stackCount - 1; i++)
lr.appendChild(stack.Pop());
}
else
{
while (stack.Any())
lr.appendChild(stack.Pop());
isLeftFinished = true;
}
stack.Push(lr);
}
public override void ExitDisjunction([NotNull] FormulaParser.DisjunctionContext context)
{
Console.WriteLine("ExitDisjunction start, stack count = " + stack.Count());
base.ExitDisjunction(context);
Disjunction disjunction = new Disjunction(stack.Pop(), stack.Pop());
stack.Push(disjunction);
}
public override void ExitConjunction([NotNull] FormulaParser.ConjunctionContext context)
{
Console.WriteLine("ExitConjunction start, stack count = " + stack.Count());
base.ExitConjunction(context);
Conjunction disjunction = new Conjunction(stack.Pop(), stack.Pop());
stack.Push(disjunction);
}
public INode getTree() => stack.Pop();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyHealth : MonoBehaviour
{
public int vida;
public string nome;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag(nome))
{
vida = vida - 1;
}
if(vida <= 0)
{
Destroy(gameObject);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CodeFirstDataAccess;
using CodeFirstModel;
using CodeFirstWebApp.Models;
using System.Data.Entity;
namespace CodeFirstWebApp.Controllers
{
public class BookController : Controller
{
// GET: Book
public ActionResult Index()
{
try
{
//implementation of IDatabaseInitializer that will delete, recreate,
//and optionally re-seed the database with data only if the model has changed since
//the database was created.
//This implementation require you to use the type of the Database Context because
//it’s a generic class.
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<BookEntityContext>());
return View();
}
catch (Exception)
{
throw;
}
}
public ActionResult GetBookDetails()
{
var model = new List<BookModel>();
try
{
using (var context = new BookEntityContext())
{
var value = context.Books.ToList();
foreach (var book in value)
{
var bookModel = new BookModel();
bookModel.BookName = book.BookName;
bookModel.Author = book.Author;
bookModel.Edition = book.Edition;
bookModel.Publishing = book.Publishing;
model.Add(bookModel);
}
}
}
catch (Exception)
{
throw;
}
return PartialView("_BookDetailView", model);
}
public ActionResult InsertBookDetail()
{
try
{
for (int counter = 0; counter < 5; counter++)
{
var book = new Book()
{
BookName = "Book " + counter,
Author = "Author " + counter,
Edition = "Edition " + counter,
Publishing = "Publishing " + counter
};
using (var context = new BookEntityContext())
{
context.Books.Add(book);
context.SaveChanges();
}
}
}
catch (Exception)
{
throw;
}
return Json(true);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
/**
* src: https://open.kattis.com/problems/fbiuniversal
* Author: Muhammad Fathir Irhas
* Date: 2017-10-29
*/
namespace FBI_UCN
{
class Program
{
static string charset = "0123456789ACDEFHJKLMNPRTVWX";
static Dictionary<char, char> confusionDigits = new Dictionary<char, char>(){
{'B', '8'},
{'G', 'C'},
{'I', '1'},
{'O', '0'},
{'Q', '0'},
{'S', '5'},
{'U', 'V'},
{'Y', 'V'},
{'Z', '2'}
};
static Dictionary<char, int> base27map = new Dictionary<char, int>(){
{'0', 0},
{'1', 1},
{'2', 2},
{'3', 3},
{'4', 4},
{'5', 5},
{'6', 6},
{'7', 7},
{'8', 8},
{'9', 9},
{'A', 10},
{'C', 11},
{'D', 12},
{'E', 13},
{'F', 14},
{'H', 15},
{'J', 16},
{'K', 17},
{'L', 18},
{'M', 19},
{'N', 20},
{'P', 21},
{'R', 22},
{'T', 23},
{'V', 24},
{'W', 25},
{'X', 26}
};
static string CheckConfusionDigits(string digits){
char[] aDigits = digits.ToCharArray();
int n = 0;
foreach(char i in digits){
foreach(KeyValuePair<char, char> item in confusionDigits)
{
if(i == item.Key){
aDigits[n] = item.Value;
}
}
n++;
}
string correctedDigits = new string(aDigits);
return correctedDigits;
}
static int[] ConvertToBase27Value(string correctedDigits){
int[] b27arr = new int[correctedDigits.Length];
int n = 0;
foreach(char i in correctedDigits){
b27arr[n] = base27map[i];
n++;
}
return b27arr;
}
static bool VerifyCheckDigit(string correctedDigits, int[] b27arr){
int check = (2*b27arr[0] + 4*b27arr[1] + 5*b27arr[2] + 7*b27arr[3] + 8*b27arr[4] + 10*b27arr[5]
+ 11*b27arr[6] + 13*b27arr[7]) % 27;
if(base27map[correctedDigits[8]] == check){
return true;
} else {
return false;
}
}
/*
def fromDigits(digits, b):
"""Compute the number given by digits in base b."""
n = 0
for d in digits:
n = b * n + d
return n
*/
static double ConvertToBase27to10(string correctedDigits){
string first8digits = correctedDigits.Remove(correctedDigits.Length - 1);
double result = 0;
foreach(char digit in first8digits)
result = (result * charset.Length) + charset.IndexOf(digit);
return result;
}
static void UCN_Parser(int index, string input){
// 1. check for confusing digits
string correctedDigits = CheckConfusionDigits(input);
// 2. map to corresponding digits in base 27
int[] b27arr = ConvertToBase27Value(correctedDigits);
// 3. verify check digit
bool checkDigit = VerifyCheckDigit(correctedDigits, b27arr);
// 4. if true print its base 10 decimals, else print "Invalid"
if(checkDigit) {
Console.WriteLine(index + " " + ConvertToBase27to10(correctedDigits));
}else {
Console.WriteLine(index + " Invalid");
}
}
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
for(int i = 0;i<n;i++){
string[] input = Console.ReadLine().Split();
UCN_Parser(Convert.ToInt32(input[0]), input[1]);
}
}
}
}
|
using System;
namespace _03_Formatting_Numbers
{
public class _03_Formatting_Numbers
{
public static void Main()
{
var numbers = Console.ReadLine().Split(new[] { ' ', '\t', '\n' }, StringSplitOptions.RemoveEmptyEntries);
var numberOne = int.Parse(numbers[0]);
var hex = $"{numberOne:X}";
var binary = Convert.ToString(numberOne, 2);
binary = binary.PadLeft(10, '0').Substring(0, 10);
var numberTwo = double.Parse(numbers[1]);
var numberThree = double.Parse(numbers[2]);
Console.WriteLine($"|{hex, -10}|{binary}|{numberTwo, 10:f2}|{numberThree, -10:f3}|");
}
}
}
|
using EasyConsoleNG.Selects;
using System;
using System.Linq;
namespace EasyConsoleNG.Menus
{
public class SelectPage : Page
{
protected Select<Action> Select { get; set; }
public SelectPage(Menu menu, params SelectOption<Action>[] options) : base(menu)
{
Select = new Select<Action>();
foreach (var option in options)
{
Select.Add(option);
}
}
public void AddOption(string name, Action callback)
{
Select.Add(new SelectOption<Action>(name, callback));
}
public void AddBackOption(string name)
{
Select.Add(new SelectOption<Action>(name, () => Menu.Pop()));
}
public void AddExitOption(string name)
{
Select.Add(new SelectOption<Action>(name, () => throw new EndMenuException()));
}
public override void Display()
{
do {
var callback = Select.Display();
if (callback != null)
{
callback();
return;
}
} while (true);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using EasyJoystick;
using UnityEngine.SceneManagement;
public class BallMotor : MonoBehaviour
{
public float moveSpeed = 5.0f;
public float drag = 0.5f;
public float terminalRotationSpeed = 25.0f;
public Vector3 MoveVector { set; get; }
private Joystick joystick;
public Joystick joystick1;
public Joystick joystick2;
//for jumping
public float jumpSpeed = 3f;
public float jumpDelay = 2f;
private bool canjump;
private bool isjumping;
private float countDown;
private Rigidbody thisRigidbody;
private int switchjoystick;
// Start is called before the first frame update
private void Start()
{
thisRigidbody = gameObject.AddComponent<Rigidbody>();
thisRigidbody.maxAngularVelocity = terminalRotationSpeed;
thisRigidbody.drag = drag;
//for jumping
canjump = true;
countDown = jumpDelay;
joystick = joystick1;
switchjoystick = -1;
}
public void Switchjoystick()
{
switchjoystick = switchjoystick * -1;
if (switchjoystick > 0)
{
joystick = joystick2;
}
else
{
joystick = joystick1;
}
}
// Update is called once per frame
private void Update()
{
MoveVector = PoolInput();
Move();
//for jumping
if (isjumping && countDown > 0)
countDown -= Time.deltaTime;
else
{
canjump = true;
isjumping = false;
countDown = jumpDelay;
}
}
public void StartLetsJump()
{
if (canjump)
{
canjump = false;
isjumping = true;
thisRigidbody.AddForce(0, jumpSpeed, 0, ForceMode.Impulse);
}
}
private void Move()
{
thisRigidbody.AddForce((MoveVector * moveSpeed));
}
private Vector3 PoolInput()
{
Vector3 dir = Vector3.zero;
dir.x = joystick.Horizontal();
dir.z = joystick.Vertical();
if (dir.magnitude > 1)
dir.Normalize();
return dir;
}
}
|
using AsyncClasses;
using C1.Win.C1FlexGrid;
using Clients.Report;
using Common;
using Common.Exceptions;
using Common.Log;
using Common.Presentation;
using Common.Presentation.Skinning;
using Contracts.Callback;
using SessionSettings;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
namespace Report.ChildForms
{
public partial class MovieActorListForm : SkinnableMDIChildBase, IAsyncServiceCallback
{
#region Private Fields
private ReportAsyncProxy mAsyncProxy = null;
private ClientPresentation mClientPresentation = new ClientPresentation();
private DataTable mDataSource = null;
private int mDestination = -1;
private ReportProxy mProxy = null;
private ReportForm mReportForm = null;
private ReportTableLoader mTableLoader = null;
#endregion
#region Constructors
public MovieActorListForm(ParameterStruct parameters, string caption)
: base(parameters, caption)
{
Logging.ConnectionString = Settings.ConnectionString;
}
#endregion
#region Public Methods
public void Completed(MemoryStream data, int instance, Exception e, bool cancelled, object userState = null)
{
if (e != null)
{
Cursor = Cursors.Default;
SetControlAvailability(false);
string exceptions = GetExceptions(e);
mClientPresentation.ShowError(exceptions);
return;
}
if (data != null)
{
using (DataTable table = new DataTable())
{
data.Position = 0;
table.ReadXml(data);
if (mDataSource == null)
mDataSource = table;
else
mDataSource.Merge(table);
}
}
status.StatusLabel.Text = "Rendering report...";
try
{
if (mReportForm == null || mReportForm.IsDisposed)
{
mReportForm = new ReportForm(base.TitleBar.TitleText, mDataSource, mParameters, null);
mReportForm.MdiParent = this.MdiParent;
}
mReportForm.PrintToPrinter = mDestination == 1;
mReportForm.Show();
}
finally
{
Cursor = Cursors.Default;
status.StatusLabel.Text = "";
SetControlAvailability(false);
}
}
public void ReportProgress(int total, int current, string notFound, int instance, MemoryStream data, bool cancelled, object userState)
{
if (total == 0)
return;
if (data != null)
{
using (DataTable table = new DataTable("Report"))
{
using (XmlTextReader reader = new XmlTextReader(data))
{
//Make sure we are at the beginning of the stream.
data.Position = 0;
table.ReadXml(data);
}
if (mDataSource == null)
{
mDataSource = table.Clone();
mDataSource.TableName = "Report";
}
mDataSource.Merge(table);
}
}
GradientProgressBar bar = status.OverallProgress;
if (!String.IsNullOrEmpty(notFound))
{
bar = status.ItemProgress;
UpdateStatusLabel(notFound);
}
UpdateProgressBar(total, current, bar);
}
#endregion
#region Private Methods
private void CleanUpResources()
{
CloseProxy();
CloseAsyncProxy();
if (mDataSource != null)
mDataSource.Dispose();
mDataSource = null;
if (mTableLoader != null)
mTableLoader.Dispose();
mTableLoader = null;
if (mReportForm != null)
{
mReportForm.MdiParent = null;
mReportForm.Dispose();
}
mReportForm = null;
}
private void ClearAll_Click(object sender, EventArgs e)
{
SelectAllRows(false);
}
/// <summary>
/// Closes the asynchronous proxy.
/// </summary>
private void CloseAsyncProxy()
{
try
{
if (((IContextChannel)mAsyncProxy.InnerChannel).State == CommunicationState.Opened)
((IContextChannel)mAsyncProxy.InnerChannel).Close(new TimeSpan(3000));
}
catch (TimeoutException)
{
//Swallow this because it is not important to track it here, I don't think.
}
mAsyncProxy.Close();
}
private void CloseProxy()
{
if (mProxy != null && mProxy.State != CommunicationState.Closed && mProxy.State != CommunicationState.Faulted)
{
Thread.Sleep(30);
mProxy.Close();
}
mProxy = null;
}
private async void CreateReport(int destination)
{
mDestination = destination;
try
{
Cursor = Cursors.AppStarting;
CreateTableLoader();
SetControlAvailability(true);
OpenAsyncProxy();
await mAsyncProxy.GetMovieActorListAsync(mTableLoader);
}
catch (FaultException fe)
{
Cursor = Cursors.Default;
if (!fe.Message.Equals("A task was canceled."))
{
Logging.Log(new AsyncDataLoadException("Async report generation faulted.", fe));
string message = "FaultException:\n";
message += fe.Message;
message += "\nStack trace: " + fe.StackTrace;
message += "\nInner Exception: ";
if (fe.InnerException != null)
message += fe.InnerException.Message + " - " + fe.InnerException.StackTrace;
mClientPresentation.ShowError(fe.Message + "\n" + fe.StackTrace);
}
SetControlAvailability(false);
mAsyncProxy.Abort();
CloseAsyncProxy();
}
catch (Exception e)
{
Cursor = Cursors.Default;
Logging.Log(new AsyncDataLoadException("Async report generation failed.", e));
mClientPresentation.ShowError(e.Message + "\n" + e.StackTrace);
SetControlAvailability(false);
mAsyncProxy.Abort();
CloseAsyncProxy();
}
}
/// <summary>
/// Creates a TableLoader for this instance.
/// </summary>
private void CreateTableLoader()
{
if (mTableLoader == null)
mTableLoader = new ReportTableLoader(Settings.ConnectionString, Settings.UserName,
Settings.User.Department);
GetSelectedActors();
}
private void Function_Command(int option)
{
if (option != 2)
CreateReport(option);
else
mAsyncProxy.CancelGetMovieActorListAsync();
}
/// <summary>
/// Gets a string representation of exceptions thrown during an operation.
/// </summary>
/// <param name="exception">The base exception.</param>
/// <returns>A string representation of the exception information, including any inner exceptions.</returns>
private string GetExceptions(Exception exception)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(exception.ToString());
if (exception.InnerException != null)
sb.AppendLine(GetExceptions(exception.InnerException));
return sb.ToString();
}
private void GetSelectedActors()
{
int[] rows = actorGrid.GetSelections();
mTableLoader.Ids.Clear();
mTableLoader.StringList.Clear();
foreach (int row in rows)
{
object data = actorGrid.GetData(row, 0);
if (data != null)
mTableLoader.Ids.Add(Convert.ToInt32(data));
string name = "";
data = actorGrid.GetData(row, 1);
if (data != null)
name = data.ToString() + " ";
data = actorGrid.GetData(row, 2);
if (data != null)
name += data.ToString();
mTableLoader.StringList.Add(name);
}
}
private void LoadGrid()
{
Cursor = Cursors.AppStarting;
OpenProxy();
actorGrid.Visible = false;
actorGrid.BeginUpdate();
actorGrid.Redraw = actorGrid.AutoResize = false;
try
{
List<Tuple<int, string, string>> actors = mProxy.GetActors();
foreach (Tuple<int, string, string> actor in actors)
{
Row row = actorGrid.Rows.Add();
actorGrid.SetData(row.Index, 0, actor.Item1);
actorGrid.SetData(row.Index, 1, actor.Item2);
actorGrid.SetData(row.Index, 2, actor.Item3);
}
}
catch (Exception e)
{
Logging.Log(e, "Report", "MovieActorListForm.LoadGrid");
mClientPresentation.ShowError(e.Message + "\n" + e.StackTrace);
}
finally
{
Cursor = Cursors.Default;
actorGrid.EndUpdate();
actorGrid.Redraw = actorGrid.AutoResize = true;
actorGrid.Visible = true;
//Sort by actor first name ascending.
actorGrid.Sort(SortFlags.Ascending, 1);
CloseProxy();
}
}
private void MovieActorListForm_FormClosing(object sender, FormClosingEventArgs e)
{
CleanUpResources();
}
private void MovieActorListForm_KeyUp(object sender, KeyEventArgs e)
{
if ((e.Modifiers & Keys.Alt) != 0)
{
switch (e.KeyCode)
{
case Keys.P:
CreateReport(1);
break;
case Keys.S:
CreateReport(0);
break;
default:
e.Handled = true;
break;
}
}
}
private void MovieActorListForm_Load(object sender, EventArgs e)
{
SetUpForm();
}
/// <summary>
/// Creates the asynchronous proxy.
/// </summary>
private void OpenAsyncProxy()
{
try
{
if (mAsyncProxy != null && (mAsyncProxy.State == CommunicationState.Opened || mAsyncProxy.State == CommunicationState.Created))
mAsyncProxy.Close();
if (mAsyncProxy == null || mAsyncProxy.State == CommunicationState.Closed ||
mAsyncProxy.State == CommunicationState.Faulted)
mAsyncProxy = new ReportAsyncProxy(new InstanceContext(this), Settings.Endpoints["AsyncReport"]);
//Set inner timeouts to prevent the system from hanging during a load.
//Even though we have already set these in the proxy itself, this here is a sanity move.
((IContextChannel)mAsyncProxy.InnerChannel).OperationTimeout = TimeSpan.FromMinutes(30);
((IContextChannel)mAsyncProxy.InnerDuplexChannel).OperationTimeout = TimeSpan.FromMinutes(30);
}
catch (ProtocolException)
{
Logging.Log("ProtocolException", "Report", "MovieActorListForm.OpenAsyncProxy");
}
}
/// <summary>
/// Creates the synchronous proxy.
/// </summary>
private void OpenProxy()
{
if (mProxy == null || mProxy.State == CommunicationState.Closed || mProxy.State == CommunicationState.Faulted)
{
mProxy = new ReportProxy(Settings.Endpoints["Report"]);
mProxy.Open();
mProxy.CreateReportMethods(Settings.ConnectionString, Settings.UserName, Settings.User.Department);
}
}
private void PrintPrinter_Click(object sender, EventArgs e)
{
CreateReport(1);
}
private void PrintScreen_Click(object sender, EventArgs e)
{
CreateReport(0);
}
private void SelectAll_Click(object sender, EventArgs e)
{
SelectAllRows(true);
}
private void SelectAllRows(bool select)
{
if (!select)
actorGrid.ClearSelections();
else
actorGrid.Select(actorGrid.GetCellRange(1, 0, actorGrid.Rows.Count - 1, actorGrid.Cols.Count - 1));
}
/// <summary>
/// Enables or disables controls on the current instance based on ProgressBar visibility (indicating a data load
/// is in progress).
/// </summary>
/// <param name="progressBarVisible">Flag indicating whether the ProgressBar is visible.</param>
private void SetControlAvailability(bool progressBarVisible)
{
status.Visible = false;
function.AddedFunction.Enabled = false;
actorGroup.Enabled = true;
function.PrintPrinter.Enabled = function.PrintScreen.Enabled = true;
if (status.OverallProgress.InvokeRequired)
status.OverallProgress.BeginInvoke(new Action(() =>
{
status.Visible = progressBarVisible;
status.OverallProgress.PercentValue = 0;
status.OverallProgress.TotalValue = 0;
status.ItemProgress.PercentValue = 0;
status.ItemProgress.TotalValue = 0;
}));
else
{
status.Visible = progressBarVisible;
status.OverallProgress.PercentValue = 0;
status.OverallProgress.TotalValue = 0;
status.ItemProgress.PercentValue = 0;
status.ItemProgress.TotalValue = 0;
}
if (progressBarVisible)
{
function.AddedFunction.Enabled = true;
actorGroup.Enabled = false;
function.PrintPrinter.Enabled = function.PrintScreen.Enabled = false;
}
}
private void SetUpForm()
{
SetCaption("Movie Listing by Actor");
LoadGrid();
}
/// <summary>
/// Updates the progress bar during data load.
/// </summary>
/// <param name="total">The total number of records to load.</param>
/// <param name="current">The number of records loaded so far.</param>
private void UpdateProgressBar(int total, int current, GradientProgressBar bar)
{
if (bar.InvokeRequired)
bar.BeginInvoke(new Action(() =>
{
bar.TotalValue = total;
bar.PercentValue = (current * 100) / total;
}));
else
{
bar.TotalValue = total;
bar.PercentValue = (current * 100) / total;
}
}
private void UpdateStatusLabel(string actor)
{
if (status.StatusLabel.InvokeRequired)
status.StatusLabel.BeginInvoke(new Action(() => { status.StatusLabel.Text = actor; }));
else
status.StatusLabel.Text = actor;
}
#endregion
}
} |
using System.Collections.Generic;
using Domain;
namespace DataAccess.Repository
{
public interface IEntryRepository
{
void AddEntry(int blogId, string title, string body);
void RemoveEntry(int blogId, int entryId);
IEnumerable<Entry> GetEntries(int blogId);
Entry GetEntry(int entryId);
void EditEntry(int entryId, string title, string body);
}
}
|
using cyrka.api.domain.jobs;
using cyrka.api.domain.jobs.commands;
using cyrka.api.domain.jobs.commands.change;
using cyrka.api.domain.jobs.commands.register;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
namespace cyrka.api.infra.stores.events
{
public class JobTypeEventsMapping : IDbMapping
{
public void DefineMaps()
{
BsonClassMap.RegisterClassMap<JobTypeEventData>();
BsonClassMap.RegisterClassMap<JobTypeRegistered>(cm =>
{
cm.MapField(cr => cr.Name);
cm.MapField(cr => cr.Description);
cm.MapField(cr => cr.Unit)
.SetSerializer(new EnumSerializer<JobTypeUnit>(BsonType.String));
cm.MapField(cr => cr.Rate);
cm.MapCreator(cr => new JobTypeRegistered(cr.AggregateId, cr.Name, cr.Description, cr.Unit, cr.Rate));
});
BsonClassMap.RegisterClassMap<JobTypeChanged>(cm =>
{
cm.MapField(cr => cr.Name);
cm.MapField(cr => cr.Description);
cm.MapField(cr => cr.Unit)
.SetSerializer(new EnumSerializer<JobTypeUnit>(BsonType.String));
cm.MapField(cr => cr.Rate);
cm.MapCreator(cr => new JobTypeChanged(cr.AggregateId, cr.Name, cr.Description, cr.Unit, cr.Rate));
});
}
}
}
|
using AutoMapper;
using PersonelProject.DTOS;
using PersonelProject.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PersonelProject.Mappers
{
public class MapperProfiles:Profile
{
public MapperProfiles()
{
CreateMap<Sehir, SehirDTO>().
ForMember(des => des.sehirAd, opt => opt.MapFrom(src => src.SehirAd)).
ForMember(des => des.sehirId, opt => opt.MapFrom(src => src.SehirId)).
ForMember(des => des.resimYol, opt => opt.MapFrom(src => src.SehirResim));
CreateMap<SehirDTO, Sehir>().
ForMember(des => des.SehirAd, opt => opt.MapFrom(src => src.sehirAd)).
ForMember(des => des.SehirId, opt => opt.MapFrom(src => src.sehirId)).
ForMember(des => des.SehirResim, opt => opt.MapFrom(src => src.resimYol));
}
}
}
|
using System.Windows;
namespace WpfAppParking.View
{
public partial class EditParkingenWindow : Window
{
public EditParkingenWindow()
{
InitializeComponent();
}
}
} |
using System.ComponentModel.DataAnnotations.Schema;
namespace GradConnect.Models
{
public class UserSkill
{
public string UserId { get; set; }
public virtual User User { get; set; }
public int SkillId { get; set; }
public virtual Skill Skill { get; set; }
}
} |
using EduHome.Models.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EduHome.ViewModels
{
public class ContactVM
{
public Contact Contact { get; set; }
public List<PostMessage> PostMessages { get; set; }
public PostMessage PostMessage { get; set; }
public List<Address> Addresses { get; set; }
public Address Address { get; set; }
public string Image { get; set; }
}
}
|
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace Data.Models.Mapping
{
public class publicationMap : EntityTypeConfiguration<publication>
{
public publicationMap()
{
// Primary Key
this.HasKey(t => new { t.id_gamer, t.id_subject });
// Properties
this.Property(t => t.id_gamer)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.Property(t => t.id_subject)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.Property(t => t.label)
.HasMaxLength(255);
// Table & Column Mappings
this.ToTable("publication", "vgta");
this.Property(t => t.id_gamer).HasColumnName("id_gamer");
this.Property(t => t.id_subject).HasColumnName("id_subject");
this.Property(t => t.label).HasColumnName("label");
// Relationships
this.HasRequired(t => t.gamer)
.WithMany(t => t.publications)
.HasForeignKey(d => d.id_gamer);
this.HasRequired(t => t.subject)
.WithMany(t => t.publications)
.HasForeignKey(d => d.id_subject);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using ContestsPortal.Domain.DataAccess;
using Microsoft.AspNet.Identity.EntityFramework;
namespace ContestsPortal.Domain.Models
{
public partial class UserProfile:IdentityUser<int,CustomIdentityUserLogin,CustomIdentityUserRole,CustomIdentityUserClaim>
{
#region Constructors
public UserProfile()
{
ProfileSettings = new List<ProfileSetting>();
Feedbacks = new List<Feedback>();
Competitors = new List<Competitor>();
}
#endregion
#region Properties
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public DateTime? BirthDate { get; set; }
public long? Age {
get
{
if (BirthDate == null)
return null;
return (DateTime.Now - BirthDate).Value.Ticks;
}
set { }
}
public byte[] Photo { get; set; }
public string FullName { get; set; }
public string NickName { get; set; }
public int IdCountry { get; set; }
public DateTime RegistrationDate { get; set; }
public bool ContestNotificationsEnabled { get; set; }
public string HomePage { get; set; }
public string AboutYourself { get; set; }
[ForeignKey("IdCountry")]
public Country Country { get; set; }
public UserActivity UserActivity { get; set; }
public virtual List<Competitor> Competitors { get; set; }
public virtual List<ProfileSetting> ProfileSettings { get; set; }
public virtual List<Feedback> Feedbacks { get; set; }
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.