text stringlengths 13 6.01M |
|---|
using OrgMan.DomainObjects.Session;
using System;
using System.Collections.Generic;
namespace OrgMan.DomainContracts.Session
{
public class UpdateSessionQuery
{
public List<Guid> MandatorUIDs { get; set; }
public SessionDomainModel Session { get; set; }
}
}
|
using Microsoft.Xna.Framework;
using static OpenOracle.Old.Global;
namespace OpenOracle.Old
{
internal class PlayerOld : MobileActorOld
{
private const int
X_EASING = 5,
Y_EASING_TOP = 6,
Y_EASING_BOTTOM = 1,
X_DIRECTIONAL_EASING = 7,
Y_DIRECTIONAL_EASING_TOP = 6,
Y_DIRECTIONAL_EASING_BOTTOM = 2;
public PlayerOld() {}
public PlayerOld(SpriteSheetBaseOld spriteSheet)
: base(spriteSheet)
{
AddAnimation(00, "RestlessSleep");
AddAnimation(01, "WalkingDown");
AddAnimation(02, "WalkingUp");
AddAnimation(03, "WalkingLeft");
AddAnimation(04, "WalkingRight");
AddAnimation(05, "Shield1SideDown");
AddAnimation(06, "Shield1SideUp");
AddAnimation(07, "Shield1SideLeft");
AddAnimation(08, "Shield1SideRight");
AddAnimation(09, "Shield1FrontDown");
AddAnimation(10, "Shield1FrontUp");
AddAnimation(11, "Shield1FrontLeft");
AddAnimation(12, "Shield1FrontRight");
}
public bool IsMovementEnabled { get; set; } = false;
public bool IsShieldEquipped { get; set; } = false;
public WalkingState WalkingState { get; set; } = WalkingState.Stopped;
public override Point BottomLeft
{
get
{
int xEasing =
WalkingState != WalkingState.Left &&
WalkingState != WalkingState.DownLeft
? X_DIRECTIONAL_EASING
: X_EASING;
int yEasing =
WalkingState != WalkingState.Down &&
WalkingState != WalkingState.DownLeft
? Y_DIRECTIONAL_EASING_BOTTOM
: Y_EASING_BOTTOM;
return new Point(
ScreenPosition.X + xEasing,
ScreenPosition.Y + SpriteSheet.SpriteHeight - yEasing);
}
}
public override Point BottomRight
{
get
{
int xEasing =
WalkingState != WalkingState.Right &&
WalkingState != WalkingState.DownRight
? X_DIRECTIONAL_EASING
: X_EASING;
int yEasing =
WalkingState != WalkingState.Down &&
WalkingState != WalkingState.DownRight
? Y_DIRECTIONAL_EASING_BOTTOM
: Y_EASING_BOTTOM;
return new Point(
ScreenPosition.X + SpriteSheet.SpriteWidth - xEasing,
ScreenPosition.Y + SpriteSheet.SpriteHeight - yEasing);
}
}
public override Point Center => new Point(
(int)(ScreenPosition.X + SpriteSheet.SpriteWidth / 2f),
(int)(ScreenPosition.Y + SpriteSheet.SpriteHeight / 2f));
public override Point TopLeft
{
get
{
int xEasing =
WalkingState != WalkingState.Left &&
WalkingState != WalkingState.UpLeft
? X_DIRECTIONAL_EASING
: X_EASING;
int yEasing =
WalkingState != WalkingState.Up &&
WalkingState != WalkingState.UpLeft
? Y_DIRECTIONAL_EASING_TOP
: Y_EASING_TOP;
return new Point(
ScreenPosition.X + xEasing,
ScreenPosition.Y + yEasing);
}
}
public override Point TopRight
{
get
{
int xEasing =
WalkingState != WalkingState.Right &&
WalkingState != WalkingState.UpRight
? X_DIRECTIONAL_EASING
: X_EASING;
int yEasing =
WalkingState != WalkingState.Up &&
WalkingState != WalkingState.UpRight
? Y_DIRECTIONAL_EASING_TOP
: Y_EASING_TOP;
return new Point(
ScreenPosition.X + SpriteSheet.SpriteWidth - xEasing,
ScreenPosition.Y + yEasing);
}
}
}
}
/*
Well, if you're interested the "collision box" for Link in the Gameboy games isn't a static shape.
It changes depending on the direction he's facing. Left or Right gives him a wider horizontal box,
while moving up and down gives him a taller vertical box. This lets him walk in between spaces in
certain directions that his "overall" size would normally suggest he couldn't fit into(such as the
space between a dresser and table, providing only 8 pixels of space to fit into, which is half the
size of Link).
*/
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class tasks : MonoBehaviour
{
public static tasks instance = null;
private void Awake()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
//Destroy(gameObject);
}
}
GameManager gameManager;
SpawnLobby lobbyScript;
SpawnAdmin adminScript;
SpawnCaff caffScript;
TeacherMono teachermono;
HireSecretary secretaryScript;
taskRewards rewards;
FloorUI floorUI;
[SerializeField] private GameObject[] taskPanels;
// [SerializeField] private GameObject[] taskBTNS;
[SerializeField] private GameObject taskArrow;
[Header("Sparkles/Glow objective indicator")]
[SerializeField] public GameObject[] SparklesForObj;
[Header("Sparkle Spawn point")]
[SerializeField] private Vector3 SparklePos;
[Header("Task SFX")]
public AudioClip sfx;
private AudioSource source { get { return GetComponent<AudioSource>(); } }
[Header("Objectives 0")]
private int classRoom = 1;
[Header("Objectives 1")]
private int Teacher = 1;
[Header("Objectives 2")]
private int LobbyBuilt = 0;
[Header("Objectives 3")]
private int AdminBuilt = 0;
[Header("Objectives 4")]
private int noSecretary = 0;
[Header("Objectives 5")]
private int CaffBuilt = 0;
[Header("Objectives 6")]
private int sfloor = 1;
[Header("Objectives 7")]
private int tfloor = 2;
int indexer = 0;
void Start()
{
gameManager = GameManager.instance;
secretaryScript = HireSecretary.instance;
lobbyScript = SpawnLobby.instance;
adminScript = SpawnAdmin.instance;
caffScript = SpawnCaff.instance;
rewards = taskRewards.instance;
floorUI = FloorUI.instance;
#region hidden task
////second objectives
//taskPanels[1].SetActive(false);
//taskBTNS[1].SetActive(false);
////third objectives
//taskPanels[2].SetActive(false);
//taskBTNS[2].SetActive(false);
////third objectives
//taskPanels[3].SetActive(false);
//taskBTNS[3].SetActive(false);
#endregion
sfxStuff();
SparklesForObj[0].SetActive(true);
}
void Update()
{
switch (indexer)
{
case 0: { classRoomGoals(); } break;
case 1: { TeacherGoals(); } break;
case 2: { LobbyGoals(); } break;
case 3: { AdminGoals(); } break;
case 4: { SecretaryGoal(); } break;
case 5: { CaffGoals(); } break;
case 6: { secondFloor(); } break;
case 7: { thirdFloor(); } break;
case 8: { clearPlayerLog(); } break;
case 9: { payTeacher(); } break;
case 10: { pressY(); } break;
case 11: { zoomCamera(); } break;
case 12: { pressW(); } break;
case 13: { pressA(); } break;
case 14: { pressS(); } break;
case 15: { pressD(); } break;
default:
break;
}
}
#region SFX
public void sfxStuff()
{
gameObject.AddComponent<AudioSource>();
source.clip = sfx;
//SFX volume level
source.volume = 0.2f;
source.playOnAwake = false;
}
public void playSFX()
{
source.PlayOneShot(sfx);
}
#endregion
public void classRoomGoals()
{
if (gameManager.ClassRCount >= classRoom)
{
if (taskPanels[0] != null)
{
taskPanels[0].SetActive(false);
}
taskPanels[1].SetActive(true);
SparklesForObj[1].SetActive(true);
//reward
rewards.rewardSystem();
//sfx
playSFX();
//next task
indexer++;
}
else
{
taskPanels[0].SetActive(true);
}
}
public void TeacherGoals()
{
if (gameManager.TeacherCount >= Teacher)
{
if (taskPanels[1] != null)
{
taskPanels[1].SetActive(false);
}
taskPanels[2].SetActive(true);
SparklesForObj[2].SetActive(true);
//reward
rewards.rewardSystem();
//sfx
playSFX();
//next task
indexer++;
}
else
{
taskPanels[1].SetActive(true);
}
}
public void LobbyGoals()
{
if (lobbyScript.LobbyMade > LobbyBuilt)
{
if (taskPanels[2] != null)
{
taskPanels[2].SetActive(false);
}
SparklesForObj[3].SetActive(true);
taskPanels[3].SetActive(true);
//reward
rewards.rewardSystem();
//sfx
playSFX();
indexer++;
}
else
{
taskPanels[2].SetActive(true);
}
}
public void AdminGoals()
{
if (adminScript.AdminMade > AdminBuilt)
{
if (taskPanels[3] != null)
{
taskPanels[3].SetActive(false);
}
SparklesForObj[4].SetActive(true);
taskPanels[4].SetActive(true);
//reward
rewards.rewardSystem();
//sfx
playSFX();
indexer++;
}
else
{
taskPanels[4].SetActive(true);
}
}
public void SecretaryGoal()
{
if (gameManager.AdminCount > noSecretary)
{
if (taskPanels[4] != null)
{
taskPanels[4].SetActive(false);
}
SparklesForObj[5].SetActive(true);
taskPanels[5].SetActive(true);
//reward
rewards.rewardSystem();
//sfx
playSFX();
indexer++;
}
else
{
taskPanels[4].SetActive(true);
}
}
public void CaffGoals()
{
if (caffScript.CaffMade > CaffBuilt)
{
if (taskPanels[5] != null)
{
taskPanels[5].SetActive(false);
}
taskPanels[6].SetActive(true);
//reward
rewards.rewardSystem();
//sfx
playSFX();
indexer++;
}
else
{
taskPanels[5].SetActive(true);
}
}
//explore different floors
public void secondFloor()
{
if (floorUI.floor > sfloor)
{
if (taskPanels[6] != null)
{
taskPanels[6].SetActive(false);
}
taskPanels[7].SetActive(true);
//reward
rewards.rewardSystem();
//sfx
playSFX();
indexer++;
}
else
{
taskPanels[6].SetActive(true);
}
}
public void thirdFloor()
{
if (floorUI.floor > tfloor)
{
if (taskPanels[7] != null)
{
taskPanels[7].SetActive(false);
}
//taskPanels[8].SetActive(true);
//reward
rewards.rewardSystem();
//sfx
playSFX();
indexer++;
}
else
{
taskPanels[7].SetActive(true);
}
}
//clear player log
public void clearPlayerLog()
{
if (Input.GetKeyDown(KeyCode.C))
{
if (taskPanels[8] != null)
{
taskPanels[8].SetActive(false);
}
//taskPanels[9].SetActive(true);
//reward
rewards.rewardSystem();
//sfx
playSFX();
indexer++;
}
else
{
taskPanels[8].SetActive(true);
}
}
//pay the teacher
public void payTeacher()
{
if (gameManager.playerPaidSalary == true)
{
if (taskPanels[9] != null)
{
taskPanels[9].SetActive(false);
}
taskPanels[10].SetActive(true);
//reward
rewards.rewardSystem();
//sfx
playSFX();
indexer++;
}
else
{
taskPanels[9].SetActive(true);
}
}
//camera quest
public void pressY()
{
if (Input.GetKeyDown(KeyCode.Y))
{
if (taskPanels[10] != null)
{
taskPanels[10].SetActive(false);
}
taskPanels[11].SetActive(true);
//reward
rewards.rewardSystem();
//sfx
playSFX();
indexer++;
}
else
{
taskPanels[10].SetActive(true);
}
}
public void zoomCamera()
{
if(Input.GetAxis("Mouse ScrollWheel") > 0f || Input.GetAxis("Mouse ScrollWheel") > 0f)
{
if (taskPanels[11] != null)
{
taskPanels[11].SetActive(false);
}
taskPanels[12].SetActive(true);
//reward
rewards.rewardSystem();
//sfx
playSFX();
indexer++;
}
else
{
taskPanels[11].SetActive(true);
}
}
// camera basic movement
public void pressW()
{
if (Input.GetKeyDown(KeyCode.W))
{
if (taskPanels[12] != null)
{
taskPanels[12].SetActive(false);
}
taskPanels[13].SetActive(true);
//reward
rewards.rewardSystem();
//sfx
playSFX();
indexer++;
}
else
{
taskPanels[12].SetActive(true);
}
}
public void pressA()
{
if (Input.GetKeyDown(KeyCode.A)) //&& Input.GetKeyDown(KeyCode.S) && Input.GetKeyDown(KeyCode.D)
{
if (taskPanels[13] != null)
{
taskPanels[13].SetActive(false);
}
taskPanels[14].SetActive(true);
//reward
rewards.rewardSystem();
//sfx
playSFX();
indexer++;
}
else
{
taskPanels[13].SetActive(true);
}
}
public void pressS()
{
if (Input.GetKeyDown(KeyCode.S)) //&& Input.GetKeyDown(KeyCode.S) && Input.GetKeyDown(KeyCode.D)
{
if (taskPanels[14] != null)
{
taskPanels[14].SetActive(false);
}
taskPanels[15].SetActive(true);
//reward
rewards.rewardSystem();
//sfx
playSFX();
indexer++;
}
else
{
taskPanels[14].SetActive(true);
}
}
public void pressD()
{
if (Input.GetKeyDown(KeyCode.D)) //&& Input.GetKeyDown(KeyCode.S) && Input.GetKeyDown(KeyCode.D)
{
if (taskPanels[15] != null)
{
taskPanels[15].SetActive(false);
}
//taskPanels[16].SetActive(true);
//reward
rewards.rewardSystem();
//sfx
playSFX();
indexer++;
}
else
{
taskPanels[15].SetActive(true);
}
}
// camera rotation
public void pressQ()
{
if (Input.GetKey("q")) //&& Input.GetKeyDown(KeyCode.S) && Input.GetKeyDown(KeyCode.D)
{
if (taskPanels[16] != null)
{
taskPanels[16].SetActive(false);
}
taskPanels[17].SetActive(true);
//reward
rewards.rewardSystem();
//sfx
playSFX();
indexer++;
}
else
{
taskPanels[16].SetActive(true);
}
}
public void pressE()
{
if (Input.GetKey("e")) //&& Input.GetKeyDown(KeyCode.S) && Input.GetKeyDown(KeyCode.D)
{
if (taskPanels[17] != null)
{
taskPanels[17].SetActive(false);
}
taskPanels[18].SetActive(true);
//reward
rewards.rewardSystem();
//sfx
playSFX();
indexer++;
}
else
{
taskPanels[17].SetActive(true);
}
}
/// TO DO:
/// - go into the setting and select "Controls"
public void RemoveArrow()
{
taskArrow.SetActive(false);
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
[RequireComponent(typeof(Button))]
public abstract class ButtonBase : MonoBehaviour {
private void Awake() {
Button btn = this.GetComponent<Button>();
btn.onClick.AddListener(() => callback());
}
public abstract void callback();
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour {
public Camera MainCamera;
public Camera FinalCamera;
public void ShowMainCamera()
{
MainCamera.enabled = true;
FinalCamera.enabled = false;
}
public void ShowFinalCamera()
{
MainCamera.enabled = false;
FinalCamera.enabled = true;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using UFO.Server;
using UFO.Server.Data;
namespace UFO.WebService.Controllers
{
public class ArtistController : ApiController
{
private IArtistService artistService;
public ArtistController()
{
artistService = ServiceFactory.CreateArtistService(DatabaseConnection.GetDatabase());
}
[HttpGet]
public Artist GetArtistById(uint id)
{
return artistService.GetArtistById(id);
}
[HttpGet]
public Artist GetArtistByName(string name)
{
return artistService.GetArtistByName(name);
}
[HttpGet]
public Artist[] GetAllArtists()
{
return artistService.GetAllArtists().ToArray();
}
[HttpPost]
public void UpdateArtist(Artist artist)
{
artistService.UpdateArtist(artist);
}
[HttpPost]
public void DeleteArtist(Artist artist)
{
artistService.DeleteArtist(artist);
}
[HttpPost]
public Artist CreateArtist(Artist artist)
{
return artistService.CreateArtist(artist.Name, artist.Email, new Category(artist.CategoryId, null, null),
new Country(artist.CountryId, null, null), artist.PicturePath, artist.VideoPath);
}
}
}
|
using Dapper;
using SAAS.FrameWork.Module.Sql.Mysql;
using SAAS.FrameWork.Extensions;
using Newtonsoft.Json.Linq;
namespace SAAS.DB.Dapper
{
public class DapperSqlBuild: SqlBuild
{
public readonly DynamicParameters sqlParam = new DynamicParameters();
public DapperSqlBuild()
{
addSqlParam = (paramName, paramValue) =>
{
if (paramValue is JArray)
{
paramValue = paramValue.ConvertBySerialize<object[]>();
}
sqlParam.Add(paramName, paramValue);
};
}
}
}
|
using gView.Framework.Carto;
using gView.Framework.Carto.Rendering;
using gView.Framework.Data;
using gView.Framework.Data.Cursors;
using gView.Framework.Data.Filters;
using gView.Framework.Geometry;
using gView.Framework.Symbology;
using gView.Framework.Sys.UI.Extensions;
using gView.Framework.UI.Controls;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace gView.Plugins.MapTools.Dialogs
{
public partial class FormChartWizard : Form
{
private IDisplay _display;
private IFeatureLayer _layer;
private gvChart _gvChart;
private List<Series> _series = new List<Series>();
public FormChartWizard(IDisplay display, IFeatureLayer layer)
{
_display = display;
_layer = layer;
InitializeComponent();
_gvChart = new gvChart(chartPreview);
chartPreview.Series.Clear();
chartPreview.ChartAreas.Clear();
cmbDisplayMode.SelectedIndex = (int)gvChart.DisplayMode.EverySerieInTheSameChartArea;
}
private void FormChartWizard_Load(object sender, EventArgs e)
{
#region Tab Chart Type
foreach (gvChart.gvChartType chartType in gvChart.ChartTypes)
{
lstChartTypes.Items.Add(chartType);
}
lstChartTypes.SelectedItem = 0;
Series ser1 = new Series("Serie 1");
ser1.Points.AddXY("A", 10);
ser1.Points.AddXY("B", 6);
ser1.Points.AddXY("C", 8);
ser1.Points.AddXY("D", 12);
ser1.Points.AddXY("E", 3);
ser1.Color = Color.Red;
ser1.ChartArea = "Area1";
Series ser2 = new Series("Serie 2");
ser2.Points.AddXY("A", 5);
ser2.Points.AddXY("B", 3);
ser2.Points.AddXY("C", 7);
ser2.Points.AddXY("D", 8);
ser2.Points.AddXY("E", 6);
ser2.Color = Color.Blue;
ser2.ChartArea = "Area1";
_gvChart.Series.Add(ser1);
_gvChart.Series.Add(ser2);
_gvChart.Refresh();
#endregion
#region Tab Data
ITableClass tc = (ITableClass)_layer.Class;
foreach (IField field in _layer.Fields.ToEnumerable())
{
if (field.type == FieldType.biginteger ||
field.type == FieldType.Double ||
field.type == FieldType.Float ||
field.type == FieldType.integer ||
field.type == FieldType.smallinteger)
{
lstSeries.Items.Add(new FieldItem() { Field = field });
}
if (field.type != FieldType.binary &&
field.type != FieldType.GEOGRAPHY &&
field.type != FieldType.GEOMETRY &&
field.type != FieldType.Shape)
{
cmbDataFields.Items.Add(new FieldItem() { Field = field });
}
}
if (cmbDataFields.Items.Count > 0)
{
cmbDataFields.SelectedIndex = 0;
}
#region Filter
//All Features
//Selected Features
//Features in actual extent
cmbFeatures.Items.Add(new ExportMethodItem("All Features", new QueryFilter()));
if (_layer is IFeatureSelection &&
((IFeatureSelection)_layer).SelectionSet != null &&
((IFeatureSelection)_layer).SelectionSet.Count > 0)
{
ISelectionSet selectionSet = ((IFeatureSelection)_layer).SelectionSet;
IQueryFilter selFilter = null;
if (selectionSet is IIDSelectionSet)
{
selFilter = new RowIDFilter(tc.IDFieldName, ((IIDSelectionSet)selectionSet).IDs);
}
else if (selectionSet is IGlobalIDSelectionSet)
{
selFilter = new GlobalRowIDFilter(tc.IDFieldName, ((IGlobalIDSelectionSet)selectionSet).IDs);
}
else if (selectionSet is IQueryFilteredSelectionSet)
{
selFilter = ((IQueryFilteredSelectionSet)selectionSet).QueryFilter.Clone() as IQueryFilter;
}
if (selFilter != null)
{
selFilter.SubFields = "*";
ExportMethodItem item = new ExportMethodItem("Selected Features", selFilter);
cmbFeatures.Items.Add(item);
cmbFeatures.SelectedItem = item;
}
}
if (_display != null && _display.Envelope != null)
{
SpatialFilter dispFilter = new SpatialFilter();
dispFilter.SubFields = "*";
dispFilter.FilterSpatialReference = _display.SpatialReference;
dispFilter.Geometry = _display.Envelope;
dispFilter.SpatialRelation = spatialRelation.SpatialRelationIntersects;
cmbFeatures.Items.Add(new ExportMethodItem("Features in actual extent", dispFilter));
}
if (cmbFeatures.SelectedIndex == -1)
{
cmbFeatures.SelectedIndex = 0;
}
#endregion
#endregion
}
#region Properties
public Series[] Series
{
get { return _series.ToArray(); }
}
public gvChart.DisplayMode DisplayMode
{
get { return _gvChart.ChartDisplayMode; }
}
public gvChart.gvChartType ChartType
{
get { return _gvChart.ChartType; }
}
public string ChartTitle
{
get { return txtChartTitle.Text; }
set { txtChartTitle.Text = value; }
}
#endregion
#region Item Classes
private class FieldItem
{
public IField Field { get; set; }
public override string ToString()
{
return String.IsNullOrEmpty(Field.aliasname) ?
Field.aliasname : Field.name;
}
}
private class ExportMethodItem
{
private string _text;
private IQueryFilter _filter;
public ExportMethodItem(string text, IQueryFilter filter)
{
_text = text;
_filter = filter;
}
public IQueryFilter QueryFilter
{
get { return _filter; }
}
public override string ToString()
{
return _text;
}
}
#endregion
#region Events
private void lstChartTypes_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
gvChart.gvChartType chartType = (gvChart.gvChartType)lstChartTypes.SelectedItem;
panelDisplayMode.Visible = (chartType.DisplayMode == gvChart.DisplayMode.Mixed);
_gvChart.ChartType = chartType;
if (panelDisplayMode.Visible == true)
{
_gvChart.ChartDisplayMode = (gvChart.DisplayMode)cmbDisplayMode.SelectedIndex;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void lstSeries_SelectedIndexChanged(object sender, EventArgs e)
{
btnApply.Enabled = lstSeries.SelectedIndices != null && lstSeries.SelectedIndices.Count > 0;
}
private void btnApply_Click(object sender, EventArgs e)
{
for (int i = 0; i < lstSeries.SelectedItems.Count; i++)
{
string fieldName = ((FieldItem)lstSeries.SelectedItems[i]).Field.name;
if (seriesListView.Items != null)
{
bool has = false;
foreach (ListViewItem item in seriesListView.Items)
{
if (item.Text == fieldName)
{
has = true;
break;
}
}
if (has)
{
continue;
}
}
SimpleFillSymbol symbol = (SimpleFillSymbol)RendererFunctions.CreateStandardSymbol(GeometryType.Polygon);
symbol.OutlineSymbol = null;
if (symbol is ILegendItem)
{
((ILegendItem)symbol).LegendLabel = fieldName;
seriesListView.addSymbol(symbol, new string[] { fieldName, ((ILegendItem)symbol).LegendLabel });
}
else
{
seriesListView.addSymbol(symbol, new string[] { fieldName, String.Empty });
}
}
}
private void seriesListView_SelectedIndexChanged(object sender, EventArgs e)
{
btnRemove.Enabled = seriesListView.SelectedItems != null && seriesListView.SelectedItems.Count > 0;
}
private void seriesListView_OnLabelChanged(ISymbol symbol, int nr, string label)
{
if (symbol is ILegendItem)
{
((ILegendItem)symbol).LegendLabel = label;
}
}
private void btnRemove_Click(object sender, EventArgs e)
{
seriesListView.RemoveSelected();
}
async private void btnOK_Click(object sender, EventArgs e)
{
ExportMethodItem filterItem = (ExportMethodItem)cmbFeatures.SelectedItem;
IQueryFilter filter = filterItem.QueryFilter;
filter.SubFields = String.Empty;
DataTable tab = new DataTable();
IField dataField = ((FieldItem)cmbDataFields.SelectedItem).Field;
filter.AddField(dataField.name);
tab.Columns.Add(new DataFieldColumn(dataField.name));
FieldCollection seriesFields = new FieldCollection();
foreach (SymbolsListView.SymbolListViewItem item in seriesListView.Items)
{
seriesFields.Add(((ITableClass)_layer.Class).Fields.FindField(item.Text));
filter.AddField(item.Text);
IBrushColor brushColor = item.Symbol as IBrushColor;
Color col = brushColor != null ? brushColor.FillColor.ToGdiColor() : Color.Red;
tab.Columns.Add(new SeriesDataColumn(item.Text) { Color = col, SeriesName = item.SubItems[1].Text });
}
using (ICursor cursor = await ((ITableClass)_layer.Class).Search(filterItem.QueryFilter))
{
IRow row = null;
while ((row = await NextRow(cursor)) != null)
{
object dataValue = row[dataField.name];
if (dataValue == System.DBNull.Value)
{
continue;
}
DataRow dataRow = GetDataRow(tab, dataValue);
for (int i = 1, to = tab.Columns.Count; i < to; i++)
{
double val = Convert.ToDouble((row[tab.Columns[i].ColumnName] == System.DBNull.Value ? 0D : row[tab.Columns[i].ColumnName]));
dataRow[tab.Columns[i].ColumnName] = Convert.ToDouble(dataRow[tab.Columns[i].ColumnName]) + val;
}
}
}
DataFieldColumn dataCol = this.DataFieldCol(tab);
List<SeriesDataColumn> serCols = this.SeriesColumns(tab);
if (tab != null && tab.Rows.Count > 0 && dataCol != null && serCols != null)
{
Series[] ser = new Series[serCols.Count];
for (int i = 0; i < ser.Length; i++)
{
ser[i] = new Series(serCols[i].SeriesName);
ser[i].Color = serCols[i].Color;
}
foreach (DataRow row in tab.Rows)
{
for (int i = 0; i < ser.Length; i++)
{
ser[i].Points.AddXY(row[dataCol.ColumnName], row[serCols[i].ColumnName]);
}
}
for (int i = 0; i < ser.Length; i++)
{
_series.Add(ser[i]);
}
}
}
private void btnNext_Click(object sender, EventArgs e)
{
if (tabWizard.SelectedIndex < tabWizard.TabPages.Count - 1)
{
tabWizard.SelectedIndex++;
}
btnBack.Enabled = tabWizard.SelectedIndex > 0;
btnNext.Enabled = tabWizard.SelectedIndex < tabWizard.TabPages.Count - 1;
}
private void btnBack_Click(object sender, EventArgs e)
{
if (tabWizard.SelectedIndex > 0)
{
tabWizard.SelectedIndex--;
}
btnBack.Enabled = tabWizard.SelectedIndex > 0;
btnNext.Enabled = tabWizard.SelectedIndex < tabWizard.TabPages.Count - 1;
}
private void cmbDisplayMode_SelectedIndexChanged(object sender, EventArgs e)
{
_gvChart.ChartDisplayMode = (gvChart.DisplayMode)cmbDisplayMode.SelectedIndex;
}
#endregion
#region Table
public class SeriesDataColumn : DataColumn
{
public SeriesDataColumn(string name)
: base(name, typeof(object))
{
}
public Color Color { get; set; }
public string SeriesName { get; set; }
}
public class DataFieldColumn : DataColumn
{
public DataFieldColumn(string name)
: base(name, typeof(object))
{
}
}
private DataFieldColumn DataFieldCol(DataTable tab)
{
foreach (DataColumn col in tab.Columns)
{
if (col is DataFieldColumn)
{
return (DataFieldColumn)col;
}
}
return null;
}
public List<SeriesDataColumn> SeriesColumns(DataTable tab)
{
List<SeriesDataColumn> ret = new List<SeriesDataColumn>();
foreach (DataColumn col in tab.Columns)
{
if (col is SeriesDataColumn)
{
ret.Add((SeriesDataColumn)col);
}
}
return ret.Count > 0 ? ret : null;
}
async private Task<IRow> NextRow(ICursor cursor)
{
if (cursor is IFeatureCursor)
{
return await ((IFeatureCursor)cursor).NextFeature();
}
if (cursor is IRowCursor)
{
return await ((IRowCursor)cursor).NextRow();
}
return null;
}
private DataRow GetDataRow(DataTable tab, object dataValue)
{
foreach (DataRow row in tab.Rows)
{
if (row[0].Equals(dataValue))
{
return row;
}
}
DataRow newRow = tab.NewRow();
newRow[0] = dataValue;
tab.Rows.Add(newRow);
for (int i = 1; i < tab.Columns.Count; i++)
{
newRow[i] = 0D;
}
return newRow;
}
#endregion
}
}
|
namespace SocketLite.Logs
{
public interface ILogger
{
bool ServerWrite { get; }
bool AddTime { get; }
void Clear();
void WriteLog(string message);
void WriteLog(string format, params object[] args);
void WriteServerLog(string message);
void WriteServerLog(string format, params object[] args);
}
}
|
namespace com.Sconit.Web.Controllers.ORD
{
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using com.Sconit.Entity.ORD;
using com.Sconit.Service;
using com.Sconit.Web.Models;
using com.Sconit.Web.Models.SearchModels.ORD;
using com.Sconit.Utility;
using Telerik.Web.Mvc;
using com.Sconit.Entity.SCM;
using System;
using AutoMapper;
using com.Sconit.Entity.MD;
using NHibernate.Criterion;
using com.Sconit.Entity.Exception;
using com.Sconit.Web.Models.ORD;
using Telerik.Web.Mvc.UI;
using System.Collections;
using com.Sconit.Entity;
public class ScheduleLineController : WebAppBaseController
{
//public IGenericMgr genericMgr { get; set; }
public IIpMgr ipMgr { get; set; }
//public IOrderMgr orderMgr { get; set; }
public ScheduleLineController()
{
}
[SconitAuthorize(Permissions = "Url_OrderMstr_ScheduleLine_Search")]
public ActionResult Index()
{
return View();
}
[GridAction]
[SconitAuthorize(Permissions = "Url_OrderMstr_ScheduleLine_Search")]
public ActionResult List(GridCommand command, OrderMasterSearchModel searchModel)
{
TempData["OrderMasterSearchModel"] = searchModel;
if (string.IsNullOrWhiteSpace(searchModel.Flow))
{
SaveWarningMessage(Resources.EXT.ControllerLan.Con_PleaseChooseOneFlow);
}
DateTime dateTimeNow = DateTime.Now;
ScheduleView scheduleView = PrepareScheduleView(searchModel.Flow, searchModel.Item, searchModel.ScheduleType, searchModel.DateFrom, searchModel.DateTo, dateTimeNow);
#region grid column
var columns = new List<GridColumnSettings>();
columns.Add(new GridColumnSettings
{
Member = scheduleView.ScheduleHead.OrderNoHead,
Title = Resources.ORD.OrderDetail.OrderDetail_ScheduleLineNo,
Sortable = false
});
columns.Add(new GridColumnSettings
{
Member = scheduleView.ScheduleHead.SequenceHead,
Title = Resources.ORD.OrderDetail.OrderDetail_ScheduleLineSeq,
Sortable = false
});
columns.Add(new GridColumnSettings
{
Member = scheduleView.ScheduleHead.ItemHead,
Title = Resources.ORD.OrderDetail.OrderDetail_Item,
Sortable = false
});
columns.Add(new GridColumnSettings
{
Member = scheduleView.ScheduleHead.ItemDescriptionHead,
Title = Resources.ORD.OrderDetail.OrderDetail_ItemDescription,
Sortable = false
});
columns.Add(new GridColumnSettings
{
Member = scheduleView.ScheduleHead.ReferenceItemCodeHead,
Title = Resources.ORD.OrderDetail.OrderDetail_ReferenceItemCode,
Sortable = false
});
columns.Add(new GridColumnSettings
{
Member = scheduleView.ScheduleHead.UomHead,
Title = Resources.ORD.OrderDetail.OrderDetail_Uom,
Sortable = false
});
columns.Add(new GridColumnSettings
{
Member = scheduleView.ScheduleHead.UnitCountHead,
Title = Resources.ORD.OrderDetail.OrderDetail_UnitCount,
Sortable = false
});
columns.Add(new GridColumnSettings
{
Member = scheduleView.ScheduleHead.LocationToHead,
Title = Resources.ORD.OrderDetail.OrderDetail_LocationTo,
Sortable = false
});
columns.Add(new GridColumnSettings
{
Member = scheduleView.ScheduleHead.CurrentShipQtyToHead,
Title = Resources.ORD.OrderDetail.OrderDetail_CurrentShipQty,
Sortable = false
});
#endregion
#region
if (scheduleView.ScheduleHead.ColumnCellList != null && scheduleView.ScheduleHead.ColumnCellList.Count > 0)
{
for (int i = 0; i < scheduleView.ScheduleHead.ColumnCellList.Count; i++)
{
string ScheduleType = scheduleView.ScheduleHead.ColumnCellList[i].ScheduleType.ToString() == "Firm" ? Resources.EXT.ControllerLan.Con_Settled : Resources.EXT.ControllerLan.Con_Forcast;
columns.Add(new GridColumnSettings
{
Member = "RowCellList[" + i + "].DisplayQty",
MemberType = typeof(string),
Title = (scheduleView.ScheduleHead.ColumnCellList[i].EndDate.Value < dateTimeNow) ? Resources.EXT.ControllerLan.Con_BackOrder : (scheduleView.ScheduleHead.ColumnCellList[i].EndDate.Value.ToString() + "(" + ScheduleType + ")"),
Sortable = false
});
}
}
#endregion
ViewData["columns"] = columns.ToArray();
IList<ScheduleBody> scheduleBodyList = scheduleView.ScheduleBodyList != null && scheduleView.ScheduleBodyList.Count > 0 ? scheduleView.ScheduleBodyList.OrderBy(s => s.Item).ThenBy(s => s.OrderNo).ToList() : new List<ScheduleBody>();
return View(scheduleBodyList);
}
[SconitAuthorize(Permissions = "Url_OrderMstr_ScheduleLine_Search")]
public ActionResult Refresh(string flow)
{
try
{
if (string.IsNullOrEmpty(flow))
{
throw new BusinessException(Resources.EXT.ControllerLan.Con_FlowCodeCanNotBeEmpty);
}
//FlowMaster flowMaster = genericMgr.FindById<FlowMaster>(flow);
//Region region = genericMgr.FindById<Region>(flowMaster.PartyTo);
//SAPService.SAPService sapService = new SAPService.SAPService();
//com.Sconit.Entity.ACC.User user = SecurityContextHolder.Get();
//sapService.GetProcOrders(user.Code, string.Empty, flowMaster.PartyFrom, region.Plant, DateTime.Now);
SaveSuccessMessage(Resources.EXT.ControllerLan.Con_PlanProtocolRefreshSuccessfully);
}
catch (BusinessException ex)
{
SaveErrorMessage(ex.GetMessages()[0].GetMessageString());
}
catch (Exception ex)
{
SaveErrorMessage(ex.Message);
}
TempData["OrderMasterSearchModel"] = new OrderMasterSearchModel { Flow = flow };
return View("Index");
}
[GridAction(EnableCustomBinding = true)]
[SconitAuthorize(Permissions = "Url_OrderMstr_ScheduleLine_Ship")]
public JsonResult ShipOrderByQty(string OrderNoStr, string SequenceStr, string CurrentShipQtyStr)
{
try
{
if (!string.IsNullOrEmpty(OrderNoStr))
{
string[] orderNoArray = OrderNoStr.Split(',');
string[] sequenceArray = SequenceStr.Split(',');
string[] currentShipQtyArray = CurrentShipQtyStr.Split(',');
IList<ScheduleLineInput> scheduleLineInputList = new List<ScheduleLineInput>();
int i = 0;
foreach (string orderNo in orderNoArray)
{
ScheduleLineInput scheduleLineInput = new ScheduleLineInput();
scheduleLineInput.EBELN = orderNoArray[i];
scheduleLineInput.EBELP = sequenceArray[i];
scheduleLineInput.ShipQty = int.Parse(currentShipQtyArray[i]);
scheduleLineInputList.Add(scheduleLineInput);
i++;
}
IpMaster ipMaster = this.orderMgr.ShipScheduleLine(scheduleLineInputList);
object obj = new { SuccessMessage = string.Format(Resources.ORD.OrderMaster.ScheduleLine_Shipped), IpNo = ipMaster.IpNo };
return Json(obj);
}
else
{
throw new BusinessException(Resources.EXT.ControllerLan.Con_ShippingDetailCanNotBeEmpty);
}
}
catch (BusinessException ex)
{
Response.TrySkipIisCustomErrors = true;
Response.StatusCode = 500;
Response.Write(ex.GetMessages()[0].GetMessageString());
return Json(null);
}
}
private RowCell GetRowCell(ScheduleBody scheduleBody, ColumnCell columnCell, IList<RowCell> rowCellList, DateTime dateTimeNow)
{
RowCell rowCell = new RowCell();
var q = rowCellList.Where(r => r.OrderNo == scheduleBody.OrderNo && r.Sequence == scheduleBody.Sequence
&& r.ScheduleType == columnCell.ScheduleType
&& (columnCell.EndDate < dateTimeNow ? r.EndDate < dateTimeNow : r.EndDate == columnCell.EndDate));
if (q != null && q.Count() > 0)
{
rowCell = q.First();
rowCell.OrderQty = q.Sum(oq => oq.OrderQty);
rowCell.ShippedQty = q.Sum(oq => oq.ShippedQty);
if (rowCell.EndDate < dateTimeNow && rowCell.OrderQty == rowCell.ShippedQty)
{
rowCell.OrderQty = 0;
rowCell.ShippedQty = 0;
}
}
else
{
rowCell.OrderNo = scheduleBody.OrderNo;
rowCell.Sequence = scheduleBody.Sequence;
rowCell.ScheduleType = columnCell.ScheduleType;
rowCell.EndDate = columnCell.EndDate;
rowCell.OrderQty = 0;
rowCell.ShippedQty = 0;
}
return rowCell;
}
private ScheduleView PrepareScheduleView(string flow, string item, com.Sconit.CodeMaster.ScheduleType? schedeleType, DateTime? startDate, DateTime? endDate, DateTime dateTimeNow)
{
ScheduleView scheduleView = new ScheduleView();
ScheduleHead scheduleHead = new ScheduleHead();
if (!string.IsNullOrWhiteSpace(flow))
{
if (startDate == null)
{
#region 取能发货的最小日期
string dateSql = "select min(d.EndDate) as EndDate from Ord_OrderDet_8 as d where d.OrderType = ? and d.RecQty < d.OrderQty and exists (select 1 from Ord_OrderMstr_8 as o where o.Flow = ? and d.OrderNo = o.OrderNo) ";
IList<object> dateParam = new List<object>();
dateParam.Add((int)com.Sconit.CodeMaster.OrderType.ScheduleLine);
dateParam.Add(flow);
if (!string.IsNullOrEmpty(item))
{
dateSql += " and d.Item = ?";
dateParam.Add(item);
}
if (schedeleType != null)
{
dateSql += " and d.ScheduleType = ?";
dateParam.Add(schedeleType.Value);
}
IList<DateTime?> dateList = genericMgr.FindAllWithNativeSql<DateTime?>(dateSql, dateParam.ToArray());
if (dateList[0] != null)
{
scheduleView.MinDate = dateList[0];
if (startDate == null)
{
startDate = dateList[0];
}
}
#endregion
}
if (startDate != null)
{
string hql = "select d.EndDate,d.ScheduleType,d.OrderNo,d.ExtNo,left(extseq,charindex('-',extseq)-1),d.Item,d.Uom,d.UC,d.OrderQty,d.ShipQty from Ord_OrderDet_8 as d where d.EndDate >= ? and d.OrderType = ? and exists (select 1 from Ord_OrderMstr_8 as o where o.Flow = ? and d.OrderNo=o.OrderNo)";
IList<object> param = new List<object>();
param.Add(startDate.Value);
param.Add((int)com.Sconit.CodeMaster.OrderType.ScheduleLine);
param.Add(flow);
if (!string.IsNullOrEmpty(item))
{
hql += " and d.Item = ?";
param.Add(item);
}
if (schedeleType != null)
{
hql += " and d.ScheduleType = ?";
param.Add(schedeleType.Value);
}
if (endDate != null)
{
hql += " and d.EndDate <= ?";
param.Add(endDate.Value);
}
IList<object[]> orderDetailList = genericMgr.FindAllWithNativeSql<object[]>(hql, param.ToArray());
#region head
var c = from p in orderDetailList
group p by new
{
EndDate = (DateTime)p[0] < dateTimeNow ? dateTimeNow.AddDays(-1) : (DateTime)p[0],
ScheduleType = (byte)p[1]
} into g
select new ColumnCell
{
EndDate = g.Key.EndDate,
ScheduleType = (com.Sconit.CodeMaster.ScheduleType)g.Key.ScheduleType
};
scheduleHead.ColumnCellList = c.OrderBy(p => p.EndDate).ThenBy(p => p.ScheduleType).ToList();
#endregion
#region body
var s = from p in orderDetailList
group p by new
{
OrderNo = (string)p[2],
ExternalOrderNo = (string)p[3],
ScheduleLineSeq = (string)p[4],
Item = (string)p[5],
// ItemDescription = p.ItemDescription,
// ReferenceItemCode = !string.IsNullOrWhiteSpace(p.ReferenceItemCode) ? p.ReferenceItemCode :string.Empty,
Uom = (string)p[6],
UnitCount = (decimal)p[7]
} into g
where g.Count(det => (decimal)det[8] != (decimal)det[9]) > 0
select new ScheduleBody
{
OrderNo = g.Key.ExternalOrderNo,
Sequence = g.Key.ScheduleLineSeq,
Item = g.Key.Item,
ItemDescription = genericMgr.FindById<Item>(g.Key.Item).Description,
ReferenceItemCode = genericMgr.FindById<Item>(g.Key.Item).ReferenceCode,
Uom = g.Key.Uom,
UnitCount = g.Key.UnitCount,
LocationTo = genericMgr.FindById<OrderMaster>(g.Key.OrderNo).LocationTo
};
var r = from p in orderDetailList
group p by new
{
OrderNo = (string)p[3],
ScheduleLineSeq = (string)p[4],
EndDate = (DateTime)p[0],
ScheduleType = (byte)p[1]
} into g
select new RowCell
{
OrderNo = g.Key.OrderNo,
Sequence = g.Key.ScheduleLineSeq,
EndDate = g.Key.EndDate,
ScheduleType = (com.Sconit.CodeMaster.ScheduleType)g.Key.ScheduleType,
OrderQty = g.Sum(p => (decimal)p[8]),
ShippedQty = g.Sum(p => (decimal)p[9])
};
IList<ScheduleBody> scheduleBodyList = s.ToList();
IList<RowCell> allRowCellList = r.ToList();
if (scheduleBodyList != null && scheduleBodyList.Count > 0)
{
foreach (ScheduleBody scheduleBody in scheduleBodyList)
{
if (scheduleHead.ColumnCellList != null && scheduleHead.ColumnCellList.Count > 0)
{
List<RowCell> rowCellList = new List<RowCell>();
foreach (ColumnCell columnCell in scheduleHead.ColumnCellList)
{
RowCell rowCell = GetRowCell(scheduleBody, columnCell, allRowCellList, dateTimeNow);
rowCellList.Add(rowCell);
}
scheduleBody.RowCellList = rowCellList;
}
}
}
scheduleView.ScheduleBodyList = scheduleBodyList;
#endregion
}
}
scheduleView.ScheduleHead = scheduleHead;
return scheduleView;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MasterBedroomTileset : TileSet
{
}
|
namespace Tutorial.Functional
{
using System;
using System.Collections.Generic;
using System.Linq;
internal static partial class Functions
{
internal static void OutputAsInput()
{
string input = "-2";
int output1 = int.Parse(input); // string -> int
int output2 = Math.Abs(output1); // int -> int
double output3 = Convert.ToDouble(output2); // int -> double
double output4 = Math.Sqrt(output3); // double -> double
}
// string -> double
internal static double Composition(string input) =>
Math.Sqrt(Convert.ToDouble(Math.Abs(int.Parse(input))));
internal static void Compose()
{
Func<string, int> parse = int.Parse; // string -> int
Func<int, int> abs = Math.Abs; // int -> int
Func<int, double> convert = Convert.ToDouble; // int -> double
Func<double, double> sqrt = Math.Sqrt; // double -> double
// string -> double
Func<string, double> composition1 = sqrt.After(convert).After(abs).After(parse);
composition1("-2.0").WriteLine(); // 1.4142135623731
// string -> double
Func<string, double> composition2 = parse.Then(abs).Then(convert).Then(sqrt);
composition2("-2.0").WriteLine(); // 1.4142135623731
}
internal static void Linq()
{
Func<IEnumerable<int>, IEnumerable<int>> where = source => Enumerable.Where(source, int32 => int32 > 0);
Func<IEnumerable<int>, IEnumerable<int>> skip = filtered => Enumerable.Skip(filtered, 1);
Func<IEnumerable<int>, IEnumerable<int>> take = skipped => Enumerable.Take(skipped, 2);
IEnumerable<int> query = take(skip(where(new int[] { 4, 3, 2, 1, 0, -1 })));
foreach (int result in query) // Execute query.
{
result.WriteLine();
}
}
internal static void ComposeLinq()
{
Func<IEnumerable<int>, IEnumerable<int>> composition =
new Func<IEnumerable<int>, IEnumerable<int>>(source => Enumerable.Where(source, int32 => int32 > 0))
.Then(filtered => Enumerable.Skip(filtered, 1))
.Then(skipped => Enumerable.Take(skipped, 2));
IEnumerable<int> query = composition(new int[] { 4, 3, 2, 1, 0, -1 });
foreach (int result in query) // Execute query.
{
result.WriteLine();
}
}
// Func<TSource, bool> -> IEnumerable<TSource> -> IEnumerable<TSource>
internal static Func<IEnumerable<TSource>, IEnumerable<TSource>> Where<TSource>(
Func<TSource, bool> predicate) => (IEnumerable<TSource> source) => Enumerable.Where(source, predicate);
// int -> IEnumerable<TSource> -> IEnumerable<TSource>
internal static Func<IEnumerable<TSource>, IEnumerable<TSource>> Skip<TSource>(
int count) => source => Enumerable.Skip(source, count);
// int -> IEnumerable<TSource> -> IEnumerable<TSource>
internal static Func<IEnumerable<TSource>, IEnumerable<TSource>> Take<TSource>(
int count) => source => Enumerable.Take(source, count);
internal static void LinqWithPartialApplication()
{
// IEnumerable<TSource> -> IEnumerable<TSource>
Func<IEnumerable<int>, IEnumerable<int>> where = Where<int>(int32 => int32 > 0);
Func<IEnumerable<int>, IEnumerable<int>> skip = Skip<int>(1);
Func<IEnumerable<int>, IEnumerable<int>> take = Take<int>(2);
IEnumerable<int> query = take(skip(where(new int[] { 4, 3, 2, 1, 0, -1 })));
foreach (int result in query) // Execute query.
{
result.WriteLine();
}
}
internal static void ComposeLinqWithPartialApplication()
{
Func<IEnumerable<int>, IEnumerable<int>> composition =
Where<int>(int32 => int32 > 0)
.Then(Skip<int>(1))
.Then(Take<int>(2));
IEnumerable<int> query = composition(new int[] { 4, 3, 2, 1, 0, -1 });
foreach (int result in query) // Execute query.
{
result.WriteLine();
}
}
internal static void Forward()
{
"-2"
.Forward(int.Parse) // string -> int
.Forward(Math.Abs) // int -> int
.Forward(Convert.ToDouble) // int -> double
.Forward(Math.Sqrt) // double -> double
.Forward(Console.WriteLine); // double -> void
// Equivalent to:
Console.WriteLine(Math.Sqrt(Convert.ToDouble(Math.Abs(int.Parse("-2")))));
}
internal static void ForwardAndNullConditional(IDictionary<string, object> dictionary, string key)
{
object value = dictionary[key];
DateTime? dateTime1;
if (value != null)
{
dateTime1 = Convert.ToDateTime(value);
}
else
{
dateTime1 = null;
}
// Equivalent to:
DateTime? dateTime2 = dictionary[key]?.Forward(Convert.ToDateTime);
}
internal static void ForwardLinqWithPartialApplication()
{
IEnumerable<int> source = new int[] { 4, 3, 2, 1, 0, -1 };
IEnumerable<int> query = source
.Forward(Where<int>(int32 => int32 > 0))
.Forward(Skip<int>(1))
.Forward(Take<int>(2));
foreach (int result in query) // Execute query.
{
result.WriteLine();
}
}
internal static void InstanceMethodChaining(string @string)
{
string result = @string.TrimStart().Substring(1, 10).Replace("a", "b").ToUpperInvariant();
}
}
}
#if DEMO
namespace System.Collections.Generic
{
public interface IEnumerable<out T> : IEnumerable
{
IEnumerator<T> GetEnumerator();
}
}
namespace System.Linq
{
using System.Collections.Generic;
public static class Enumerable
{
// (IEnumerable<TSource>, TSource -> bool) -> IEnumerable<TSource>
public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source, Func<TSource, bool> predicate);
// (IEnumerable<TSource>, int) -> IEnumerable<TSource>
public static IEnumerable<TSource> Skip<TSource>(
this IEnumerable<TSource> source, int count);
// (IEnumerable<TSource>, int) -> IEnumerable<TSource>
public static IEnumerable<TSource> Take<TSource>(
this IEnumerable<TSource> source, int count);
// Other members.
}
}
namespace System.Linq
{
using System.Collections;
using System.Collections.Generic;
public interface IOrderedEnumerable<TElement> : IEnumerable<TElement>, IEnumerable
{
IOrderedEnumerable<TElement> CreateOrderedEnumerable<TKey>(
Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending);
}
public static class Enumerable
{
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(
this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(
this IOrderedEnumerable<TSource> source, Func<TSource, TKey> keySelector);
public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>(
this IOrderedEnumerable<TSource> source, Func<TSource, TKey> keySelector);
}
}
namespace System.Linq
{
public static class ParallelEnumerable
{
public static ParallelQuery<TSource> Where<TSource>(
this ParallelQuery<TSource> source, Func<TSource, bool> predicate);
public static OrderedParallelQuery<TSource> OrderBy<TSource, TKey>(
this ParallelQuery<TSource> source, Func<TSource, TKey> keySelector);
public static ParallelQuery<TResult> Select<TSource, TResult>(
this ParallelQuery<TSource> source, Func<TSource, TResult> selector);
// Other members.
}
public static class Queryable
{
public static IQueryable<TSource> Where<TSource>(
this IQueryable<TSource> source, Func<TSource, bool> predicate);
public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(
this IQueryable<TSource> source, Func<TSource, TKey> keySelector);
public static IQueryable<TResult> Select<TSource, TResult>(
this IQueryable<TSource> source, Func<TSource, TResult> selector);
// Other members.
}
}
#endif
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler_Logic.Problems {
public class Problem325 : ProblemBase {
public override string ProblemName {
get { return "325: Stone Game II"; }
}
public override string GetAnswer() {
return BruteForce(1000).ToString();
}
private ulong BruteForce(ulong n) {
ulong sum = 0;
for (ulong a = 1; a <= n; a++) {
for (ulong b = a + 1; b <= n; b++) {
var result = BruteForceCanForceWin(a, b);
if (!result) {
sum += a + b;
}
}
}
return sum;
}
private Dictionary<ulong, Dictionary<ulong, bool>> _results = new Dictionary<ulong, Dictionary<ulong, bool>>();
private bool BruteForceCanForceWin(ulong a, ulong b) {
if (!_results.ContainsKey(a)) {
_results.Add(a, new Dictionary<ulong, bool>());
}
if (!_results[a].ContainsKey(b)) {
var result = false;
if (b % a == 0) {
result = true;
} else {
for (ulong m = a; m <= b; m += a) {
if (!BruteForceCanForceWin(Math.Min(b - m, a), Math.Max(b - m, a))) {
result = true;
break;
}
}
}
_results[a].Add(b, result);
}
return _results[a][b];
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoorDetection : MonoBehaviour
{
public GameObject Door;
public OpenLockedDoor openLockedDoor;
private void OnTriggerStay2D(Collider2D collision)
{
if (collision.gameObject.tag == "Door")
{
Debug.Log("ye1");
Door = collision.gameObject;
openLockedDoor = Door.GetComponent<OpenLockedDoor>();
}
}
public void ActivateDoor()
{
openLockedDoor.OpenLDoor();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace IvanovoCity
{
class Apartment : Building
{
public Apartment()
{
active_b = house.apartment;
IsEmpty = false;
state = true;
staff = 20; // количество жителей
level = 0;
maxLevel = 0;
startMoney = 5000;
}
override public void showInfo(Label a, Label b, Label c, Label d, Label e, Label f, Button active, Button destroy, Button repair)
{
a.Text = "Жилой дом";
b.Text = "Количество жильцов: " + staff.ToString();
c.Text = "Состояние: ";
if (state == true)
{
c.Text += "Готово к работе";
repair.Hide();
}
else
{
c.Text += "Нужен ремонт";
repair.Show();
}
d.Hide();
e.Hide();
f.Hide();
active.Hide(); destroy.Show();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web.Script.Serialization;
using Progress.Sitefinity.Translations.MicrosoftMachineTranslatorConnector;
using Progress.Sitefinity.Translations.MicrosoftMachineTranslatorConnector.Exceptions;
using Telerik.Sitefinity.Translations;
[assembly: TranslationConnector(name: Constants.Name,
connectorType: typeof(MicrosoftMachineTranslatorConnector),
title: Constants.Title,
enabled: false,
removeHtmlTags: false,
parameters: new string[] { Constants.ConfigParameters.ApiKey })]
namespace Progress.Sitefinity.Translations.MicrosoftMachineTranslatorConnector
{
/// <summary>
/// Connector for Microsoft Transaltor Text Service API
/// </summary>
public class MicrosoftMachineTranslatorConnector : MachineTranslationConnector
{
protected virtual HttpClient GetClient()
{
return new HttpClient();
}
/// <summary>
/// Configures the connector instance
/// </summary>
/// <param name="config">apiKey key should contain the Azure Transaltor Text Api Service key.</param>
protected override void InitializeConnector(NameValueCollection config)
{
var key = config.Get(Constants.ConfigParameters.ApiKey);
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException(Constants.ExceptionMessages.NoApiKeyExceptionMessage);
}
if (key.Length != Constants.ValidApiKeyLength)
{
throw new ArgumentException(Constants.ExceptionMessages.InvalidApiKeyExceptionMessage);
}
this.key = key;
}
protected override List<string> Translate(List<string> input, ITranslationOptions translationOptions)
{
if (translationOptions == null)
{
throw new ArgumentException(GetTranslаteArgumentExceptionMessage(nameof(translationOptions)));
}
var fromLanguageCode = translationOptions.SourceLanguage;
var toLanguageCode = translationOptions.TargetLanguage;
if (string.IsNullOrWhiteSpace(fromLanguageCode))
{
throw new ArgumentException(GetTranslаteArgumentExceptionMessage($"{nameof(translationOptions)}.{nameof(translationOptions.SourceLanguage)}"));
}
if (string.IsNullOrWhiteSpace(toLanguageCode))
{
throw new ArgumentException(GetTranslаteArgumentExceptionMessage($"{nameof(translationOptions)}.{nameof(translationOptions.TargetLanguage)}"));
}
if (input == null || input.Count == 0)
{
throw new ArgumentException(GetTranslаteArgumentExceptionMessage(nameof(input)));
}
if (fromLanguageCode == toLanguageCode)
{
return input;
}
string uri = GetAzureTranslateEndpointUri(fromLanguageCode, toLanguageCode);
var body = new List<object>();
foreach (var text in input)
{
body.Add(new { Text = text ?? string.Empty });
}
var serializer = new JavaScriptSerializer();
string requestBody = serializer.Serialize(body);
using (var client = this.GetClient())
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(uri);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", this.key);
request.Headers.Add("X-ClientTraceId", Guid.NewGuid().ToString());
var response = client.SendAsync(request).Result;
var responseBody = response.Content.ReadAsStringAsync().Result;
if (!response.IsSuccessStatusCode)
{
this.HandleApiError(responseBody, response);
}
dynamic result;
try
{
result = serializer.DeserializeObject(responseBody);
}
catch (Exception ex)
{
if (IsSerializationException(ex))
{
throw new MicrosoftTranslatorConnectorSerializationException($"{Constants.ExceptionMessages.ErrorSerializingResponseFromServer} Server response: {response.StatusCode} {response.ReasonPhrase} {responseBody}");
}
throw;
}
var translations = new List<string>();
try
{
for (int i = 0; i < input.Count(); i++)
{
// currently Sitefinity does not support sending multiple languages at once, only multiple strings
var translation = result[i]["translations"][0]["text"];
translations.Add(translation);
}
}
catch (Exception ex)
{
if (ex is KeyNotFoundException || ex is NullReferenceException)
{
throw new MicrosoftTranslatorConnectorResponseFormatException($"{Constants.ExceptionMessages.UnexpectedResponseFormat} Server response: {response.StatusCode} {response.ReasonPhrase} {responseBody}");
}
throw;
}
return translations;
}
}
private string GetAzureTranslateEndpointUri(string fromLanguageCode, string toLanguageCode)
{
string uri = string.Format(
$"{Constants.MicrosoftTranslatorEndpointConstants.EndpointUrl}&{Constants.MicrosoftTranslatorEndpointConstants.SourceCultureQueryParam }={{0}}&{Constants.MicrosoftTranslatorEndpointConstants.TargetCultureQueryParam }={{1}}",
fromLanguageCode,
toLanguageCode);
if (!IsRemoveHtmlTagsEnabled())
{
uri += $"&{Constants.MicrosoftTranslatorEndpointConstants.TextTypeQueryParam}=html";
}
return uri;
}
protected virtual bool IsRemoveHtmlTagsEnabled()
{
return this.RemoveHtmlTags;
}
private static string GetTranslаteArgumentExceptionMessage(string paramName)
{
return string.Format(Constants.ExceptionMessages.InvalidParameterForMicrosoftTransaltionRequestExceptionMessageTemplate, paramName);
}
private void HandleApiError(string responseBody, HttpResponseMessage response)
{
var serializer = new JavaScriptSerializer();
dynamic jsonResponse;
try
{
jsonResponse = serializer.DeserializeObject(responseBody);
}
catch (Exception ex)
{
if (IsSerializationException(ex))
{
throw new MicrosoftTranslatorConnectorSerializationException($"{Constants.ExceptionMessages.ErrorSerializingErrorResponseFromServer} Server response: {response.StatusCode} {response.ReasonPhrase} {responseBody}");
}
throw;
}
try
{
throw new MicrosoftTranslatorConnectorException(jsonResponse["error"]["message"]);
}
catch (Exception ex)
{
if (ex is KeyNotFoundException || ex is NullReferenceException)
{
throw new MicrosoftTranslatorConnectorResponseFormatException($"{Constants.ExceptionMessages.UnexpectedErrorResponseFormat} Server response: {response.StatusCode} {response.ReasonPhrase} {responseBody}");
}
throw;
}
}
private static bool IsSerializationException(Exception ex)
{
return ex is ArgumentException || ex is ArgumentNullException || ex is InvalidOperationException;
}
private string key;
}
} |
using Backend.Model;
using Backend.Model.Exceptions;
using Backend.Model.Pharmacies;
using IntegrationAdaptersActionBenefitService.Repository;
using IntegrationAdaptersActionBenefitService.Service;
using Moq;
using Xunit;
namespace IntegrationAdaptersTests.UnitTests
{
public class ActionBenefitServiceTest
{
[Fact]
public void CreateActionBenefit_Valid_VerifyCreateActionBenefit()
{
var mockPharmacyRepo = new Mock<IPharmacyRepo>();
var mockActionBenefitRepo = new Mock<IActionBenefitRepository>();
var exchange = "ex1";
var pharmacy = new PharmacySystem { Id = 1, Name = "apoteka1", ApiKey = "api1", Url = "url1", ActionsBenefitsExchangeName = exchange, ActionsBenefitsSubscribed = true };
var message = new ActionBenefitMessage("akcija1", "blablabla");
mockPharmacyRepo.Setup(r => r.GetPharmacyByExchangeName(exchange)).Returns(pharmacy);
mockActionBenefitRepo.Setup(r => r.CreateActionBenefit(It.Is<ActionBenefit>(ab => ab.PharmacyId == pharmacy.Id && ab.Message.Message == message.Message && ab.Message.Subject == message.Subject))).Verifiable();
ActionBenefitService actionBenefitService = new ActionBenefitService(mockActionBenefitRepo.Object, mockPharmacyRepo.Object);
actionBenefitService.CreateActionBenefit(exchange, message);
mockActionBenefitRepo.Verify();
}
[Fact]
public void CreateActionBenefit_InvalidMessage_ThrowsException()
{
Assert.Throws<ValidationException>(() => new ActionBenefitMessage(null, null));
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BossShooting : MonoBehaviour {
[SerializeField] GameObject BossProjile;
Player player;
[SerializeField] float timeBetweenShooting = 0.3f;
[SerializeField] int shootingWave = 5;
[SerializeField] float projectileMovingSpeed = 10f;
[SerializeField] float shootingBreakTime = 10f;
[SerializeField] AudioClip shootingSound;
[SerializeField] AudioClip shootingSound2;
[SerializeField] AudioClip shootingSound3;
[SerializeField] AudioClip shootingSound4;
[SerializeField] AudioClip shootingSound5;
[SerializeField] [Range(0, 1)] float soundVolume = 0.2f;
List<Vector2> directions_360 = new List<Vector2>();
int numShootingMode = 2;
int shootingMode;
bool shooting = false;
// Use this for initialization
void Start ()
{
player = FindObjectOfType<Player>();
shootingBreakTime = UnityEngine.Random.Range(0.3f, 5f);
shootingMode = UnityEngine.Random.Range(0, numShootingMode);
CreateA360DirectionsList();
}
private void CreateA360DirectionsList()
{
float sqrt_2 = Mathf.Sqrt(2);
float sqrt_3 = Mathf.Sqrt(3);
directions_360.Add(new Vector2(0, -1));
directions_360.Add(new Vector2(0, 1));
directions_360.Add(new Vector2(1, 0));
directions_360.Add(new Vector2(-1, 0));
directions_360.Add(new Vector2(1 / 2, -sqrt_3 / 2));
directions_360.Add(new Vector2(-1 / 2, -sqrt_3 / 2));
directions_360.Add(new Vector2(1 / 2, sqrt_3 / 2));
directions_360.Add(new Vector2(-1 / 2, sqrt_3 / 2));
directions_360.Add(new Vector2(sqrt_2 / 2, sqrt_2 / 2));
directions_360.Add(new Vector2(sqrt_2 / 2, -sqrt_2 / 2));
directions_360.Add(new Vector2(-sqrt_2 / 2, sqrt_2 / 2));
directions_360.Add(new Vector2(-sqrt_2 / 2, -sqrt_2 / 2));
directions_360.Add(new Vector2(sqrt_3 / 2, 1 / 2));
directions_360.Add(new Vector2(-sqrt_3 / 2, 1 / 2));
directions_360.Add(new Vector2(sqrt_3 / 2, -1 / 2));
directions_360.Add(new Vector2(-sqrt_3 / 2, -1 / 2));
}
// Update is called once per frame
void Update () {
shootingBreakTime -= Time.deltaTime;
if (shootingBreakTime <= 0 && !shooting)
{
shooting = true;
StartCoroutine(Fire());
}
}
IEnumerator Fire()
{
if(shootingMode == 0)
{
yield return StartCoroutine(PreciseShootThenReset());
}
else if(shootingMode == 1)
{
yield return StartCoroutine(ShotgunThenReset());
}
}
IEnumerator ShotgunThenReset()
{
yield return StartCoroutine(Shotgun());
Reset();
}
IEnumerator Shotgun()
{
for(int i = 0; i<= shootingWave; i++)
{
for(int directionIndex = 0; directionIndex < directions_360.Count; directionIndex++)
{
var direction = directions_360[directionIndex];
var projectile = Instantiate(BossProjile, transform.position, Quaternion.identity);
projectile.GetComponent<Rigidbody2D>().velocity = new Vector2(direction.x * projectileMovingSpeed, direction.y * projectileMovingSpeed);
}
AudioSource.PlayClipAtPoint(shootingSound, Camera.main.transform.position, soundVolume);
AudioSource.PlayClipAtPoint(shootingSound2, Camera.main.transform.position, soundVolume);
AudioSource.PlayClipAtPoint(shootingSound3, Camera.main.transform.position, soundVolume);
yield return new WaitForSeconds(timeBetweenShooting);
}
}
IEnumerator PreciseShootThenReset()
{
yield return StartCoroutine(preciseShoot());
Reset();
}
private void Reset()
{
shootingBreakTime = UnityEngine.Random.Range(0.3f, 5f);
shootingMode = UnityEngine.Random.Range(0, numShootingMode);
shooting = false;
}
IEnumerator preciseShoot()
{
for(int i = 0; i <= shootingWave; i++)
{
GameObject projectile = Instantiate(BossProjile, transform.position, Quaternion.identity) as GameObject;
var playerPos = player.GetPlayerPos();
var x = playerPos.x - transform.position.x;
var y = playerPos.y - transform.position.y;
var sumXY = Mathf.Sqrt(Mathf.Pow(x, 2f) + Mathf.Pow(y, 2f));
var shootingDirection = new Vector2(x / sumXY, y / sumXY);
projectile.GetComponent<Rigidbody2D>().velocity = new Vector2(shootingDirection.x * projectileMovingSpeed, shootingDirection.y * projectileMovingSpeed);
AudioSource.PlayClipAtPoint(shootingSound, Camera.main.transform.position, soundVolume);
AudioSource.PlayClipAtPoint(shootingSound2, Camera.main.transform.position, soundVolume);
yield return new WaitForSeconds(timeBetweenShooting);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
namespace BAH.BOS.Pattern
{
/// <summary>
/// 单例基类。
/// </summary>
/// <typeparam name="T">实例类型。</typeparam>
public class Singleton<T> : ISingleton<T> where T : class, new()
{
private static readonly T instance = new T();
/// <summary>
/// 单例实例
/// </summary>
public static T Instance
{
get
{
return instance;
}
}
}
}
|
using System;
using System.Collections.Generic;
namespace ServiceDeskSVC.DataAccess.Models
{
public partial class NSLocation
{
public NSLocation()
{
this.AssetManager_Hardware = new List<AssetManager_Hardware>();
this.AssetManager_Hardware1 = new List<AssetManager_Hardware>();
this.HelpDesk_Tickets = new List<HelpDesk_Tickets>();
this.ServiceDesk_Users = new List<ServiceDesk_Users>();
}
public int Id { get; set; }
public string LocationCity { get; set; }
public string LocationState { get; set; }
public int LocationZip { get; set; }
public virtual ICollection<AssetManager_Hardware> AssetManager_Hardware { get; set; }
public virtual ICollection<AssetManager_Hardware> AssetManager_Hardware1 { get; set; }
public virtual ICollection<HelpDesk_Tickets> HelpDesk_Tickets { get; set; }
public virtual ICollection<ServiceDesk_Users> ServiceDesk_Users { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cellar : Room
{
private CellarTileset tileset;
private Orientation orientation;
IntRange shortRange = new IntRange(5, 6);
IntRange longRange = new IntRange(13, 16);
List<Furniture> furnitureOptions;
List<float> furnitureChances;
public Cellar() : base()
{
roomCode = RoomCode.Cellar;
tileset = (CellarTileset)TileSetRegistry.I.GetTileSet(roomCode);
furnitureOptions = new List<Furniture>()
{
tileset.largeWineShelf,
tileset.smallWineShelf
};
furnitureChances = new List<float>()
{
.6f,
.4f
};
}
protected override void SetRoomDimensions()
{
orientation = DirectionUtil.Orientation(doorways[0].roomOutDirection);
if (orientation == Orientation.Horizontal)
{
widthRange = longRange;
heightRange = shortRange;
}
else
{
widthRange = shortRange;
heightRange = longRange;
}
width = widthRange.Random;
height = heightRange.Random;
}
public override void GenerateFurniture()
{
GenerateLightSwitch();
float precompTotal = WeightedChoice.PrecompTotal(furnitureChances);
if (orientation == Orientation.Horizontal)
{
for (int xPos = x + 1; xPos < x + width - 1;)
{
Furniture prefab;
if (xPos < x + width - 2)
prefab = RandomFurniture(precompTotal);
else
prefab = tileset.smallWineShelf;
int furnitureBreadth;
if (prefab == tileset.largeWineShelf)
furnitureBreadth = 2;
else
furnitureBreadth = 1;
InstantiateFurniture(prefab, new Vector2(xPos, y));
xPos += furnitureBreadth;
}
for (int xPos = x + 1; xPos < x + width - 1;)
{
Furniture prefab;
if (xPos < x + width - 2)
prefab = RandomFurniture(precompTotal);
else
prefab = tileset.smallWineShelf;
int furnitureBreadth;
if (prefab == tileset.largeWineShelf)
furnitureBreadth = 2;
else
furnitureBreadth = 1;
InstantiateFurniture(prefab, new Vector2(xPos, y + height - furnitureBreadth));
xPos += furnitureBreadth;
}
}
else //Orientation.Vertical
{
for (int yPos = y + 1; yPos < y + height - 1;)
{
Furniture prefab;
if (yPos < y + height - 2)
prefab = RandomFurniture(precompTotal);
else
prefab = tileset.smallWineShelf;
int furnitureBreadth;
if (prefab == tileset.largeWineShelf)
furnitureBreadth = 2;
else
furnitureBreadth = 1;
InstantiateFurniture(prefab, new Vector2(x, yPos));
yPos += furnitureBreadth;
}
for (int yPos = y + 1; yPos < y + height - 1;)
{
Furniture prefab;
if (yPos < y + height - 2)
prefab = RandomFurniture(precompTotal);
else
prefab = tileset.smallWineShelf;
int furnitureBreadth;
if (prefab == tileset.largeWineShelf)
furnitureBreadth = 2;
else
furnitureBreadth = 1;
InstantiateFurniture(prefab, new Vector2(x + width - furnitureBreadth, yPos));
yPos += furnitureBreadth;
}
}
}
private Furniture RandomFurniture(float precompTotal)
{
return WeightedChoice.Choose(furnitureOptions, furnitureChances, precompTotal);
}
public override bool CanMakeMoreDoors()
{
if (doorways.Count == 2)
return false;
return true;
}
public override Doorway PossibleDoorway()
{
Direction desiredDirection = DirectionUtil.Reverse(doorways[0].roomOutDirection);
switch (desiredDirection)
{
case Direction.North:
return new Doorway(Random.Range(x, x + width - generatedDoorwayBreadth), y + height - 1, Direction.North);
case Direction.South:
return new Doorway(Random.Range(x, x + width - generatedDoorwayBreadth), y, Direction.South);
case Direction.East:
return new Doorway(x + width - 1, Random.Range(y, y + height - generatedDoorwayBreadth), Direction.East);
default:
return new Doorway(x, Random.Range(y, y + height - generatedDoorwayBreadth), Direction.West);
}
}
}
|
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
using NesScripts.Controls.PathFind;
namespace MCUU.SuperTiled2Unity {
public static class SuperMapUtils {
/// <summary>
/// Creates a boolean representation of the given tilemap's boundaries. This
/// boundary map is used as a parameter for other <see cref="SuperMapUtils"/>
/// methods.
/// </summary>
/// <param name="tilemap">
/// A Unity tilemap where all tiles are meant to represent boundaries and empty
/// tiles represent open spaces.
/// </param>
/// <returns>
/// A two-dimensional bool array where boundary tiles are represented as "false"
/// and empty tiles are represented as "true".
/// </returns>
public static bool[,] CreateBoundaryMap(Tilemap tilemap) {
Vector3Int size = tilemap.size;
bool[,] boundaryMap = new bool[size.x, size.y];
for (int x = 0; x < size.x; x++) {
for (int y = 0; y < size.y; y++) {
// We have to negate the y value because SuperTiled2Unity uses negative y tile
// coordinates but the y index in the boundary map needs to be positive
TileBase tile = tilemap.GetTile(new Vector3Int(x, -y, 0));
boundaryMap[x, y] = tile == null;
}
}
return boundaryMap;
}
/// <summary>
/// Calculates the position vector based on the tile coordinates and tile width. This
/// is under the expectation that the tilemap's top left corner is anchored at the
/// origin coordinates of the scene.
/// </summary>
/// <param name="tileCoordinates">
/// The tile coordinates in the tilemap.
/// </param>
/// <param name="tileWidth">
/// The width of the tiles in the tilemap in pixels.
/// </param>
/// <returns>
/// A vector representing the position of the tile coordinates in the 2D world space.
/// </returns>
public static Vector3 GetPositionVector(Vector3Int tileCoordinates, float tileWidth) {
return new Vector3((tileCoordinates.x * tileWidth) + (tileWidth / 2), (tileCoordinates.y * tileWidth) - (tileWidth / 2), 0);
}
/// <summary>
/// Finds a path of tile coordinates between the given starting (exclusive) and
/// destination (inclusive) tile coordinates.
/// </summary>
/// <param name="boundaryMap">
/// A two-dimentional bool array created from <see cref="CreateBoundaryMap"/>.
/// </param>
/// <param name="startingTileCoordinates">
/// The tile coordinates of where to start the pathfinding.
/// </param>
/// <param name="destinationTileCoordinates">
/// The tile coordinates of where to end the pathfinding.
/// </param>
/// <returns>
/// A list of tile coordinates representing the path to the destination tile coordinates.
/// </returns>
public static List<Vector3Int> GetTileCoordinatePath(bool[,] boundaryMap, Vector3Int startingTileCoordinates, Vector3Int destinationTileCoordinates) {
// We have to negate the y value because SuperTiled2Unity uses negative y tile
// coordinates but the y index in the boundary map needs to be positive
if (boundaryMap[destinationTileCoordinates.x, -destinationTileCoordinates.y] == false) {
return new List<Vector3Int>();
}
NesScripts.Controls.PathFind.Grid boundaryGrid = CreatePathFindGrid(boundaryMap);
Point startingPoint = new Point(startingTileCoordinates.x, startingTileCoordinates.y);
Point destinationPoint = new Point(destinationTileCoordinates.x, destinationTileCoordinates.y);
List<Point> pathPoints = Pathfinding.FindPath(boundaryGrid, startingPoint, destinationPoint, Pathfinding.DistanceType.Manhattan);
return ConvertToTileCoordinates(pathPoints);
}
/// <summary>
/// Finds the adjacent tile coordinates to the given tile coordinates that is the furthest
/// from the given reference tile coordinates.
/// </summary>
/// <param name="boundaryMap">
/// A two-dimentional bool array created from <see cref="CreateBoundaryMap"/>.
/// </param>
/// <param name="tileCoordinates">
/// The tile coordinates by which adjacent tile coordinates will be checked.
/// </param>
/// <param name="referenceTileCoordinates">
/// The tile coordinates from which the distance will be calculated to tile coordinates
/// adjacent to <see cref="tileCoordinates"/>.
/// </param>
/// <returns>
/// The adjacent tile coordinates that is the furthest from the reference tile coordinate
/// </returns>
public static Vector3Int? GetFurthestAdjacentTileCoordinate(bool[,] boundaryMap, Vector3Int tileCoordinates, Vector3Int referenceTileCoordinates) {
Vector3Int? furthestAdjacentTileCoordinates = null;
List<Vector3Int> adjacentCandidateTileCoordinates = new List<Vector3Int>();
adjacentCandidateTileCoordinates.Add(tileCoordinates + new Vector3Int(0, 1, 0)); // Up
adjacentCandidateTileCoordinates.Add(tileCoordinates + new Vector3Int(1, 0, 0)); // Right
adjacentCandidateTileCoordinates.Add(tileCoordinates + new Vector3Int(0, -1, 0)); // Down
adjacentCandidateTileCoordinates.Add(tileCoordinates + new Vector3Int(-1, 0, 0)); // Left
float furthestDistance = -1;
float candidateDistance;
foreach (Vector3Int candidateTileCoordinates in adjacentCandidateTileCoordinates) {
candidateDistance = (candidateTileCoordinates - referenceTileCoordinates).magnitude;
// We have to negate the y value because SuperTiled2Unity uses negative y tile
// coordinates but the y index in the boundary map needs to be positive
if (candidateDistance > furthestDistance && boundaryMap[candidateTileCoordinates.x, -candidateTileCoordinates.y]) {
furthestAdjacentTileCoordinates = candidateTileCoordinates;
furthestDistance = candidateDistance;
}
}
return furthestAdjacentTileCoordinates;
}
/// <summary>
/// Creates a grid that will be used for pathfinding.
/// </summary>
/// <param name="boundaryMap">
/// A two-dimentional bool array created from <see cref="CreateBoundaryMap"/>.
/// </param>
/// <returns>
/// A grid that will be used for pathfinding.
/// </returns>
private static NesScripts.Controls.PathFind.Grid CreatePathFindGrid(bool[,] boundaryMap) {
return new NesScripts.Controls.PathFind.Grid(boundaryMap);
}
/// <summary>
/// Converts a list of pathfinding coordinates to tile coordinates.
/// </summary>
/// <param name="pathPoints">
/// A list of points created while pathfinding.
/// </param>
/// <returns>
/// A list of tile coordinates.
/// </returns>
private static List<Vector3Int> ConvertToTileCoordinates(List<Point> pathPoints) {
List<Vector3Int> tileCoordinates = new List<Vector3Int>();
if (pathPoints.Count != 0) {
for (int i = 0; i < pathPoints.Count; i++) {
Point pathPoint = pathPoints[i];
tileCoordinates.Add(new Vector3Int(pathPoint.x, -pathPoint.y, 0));
}
}
return tileCoordinates;
}
}
}
|
using UnityEngine;
using System.Collections;
public class BallMovement : MonoBehaviour {
public float jumpForce = 750f;
private bool collisionWithFlor = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
handleClicks ();
}
void OnCollisionEnter (Collision col) {
if(col.gameObject.name == "Board") {
collisionWithFlor = true;
}
}
void OnCollisionExit (Collision col) {
if(col.gameObject.name == "Board") {
collisionWithFlor = false;
}
}
private void handleClicks() {
// Handle jump if space or A button on pad pressed
if ((Input.GetKeyDown (KeyCode.Space)
|| Input.GetKeyDown (KeyCode.Joystick1Button16)
|| Input.GetKeyDown (KeyCode.Joystick1Button0))
&& collisionWithFlor) {
print ("Jump");
var boardTransform = GameObject.Find ("Board").transform;
GetComponent<Rigidbody> ().AddForce (boardTransform.up * jumpForce);
}
}
}
|
using System.ComponentModel;
namespace CYJ.DingDing.Dto.Enum
{
public enum ApiCodeEnum
{
[Description("系统错误")]
Error = 0,
[Description("对象不能为空")]
NullReferenceException,
[Description("请求Token失败")]
RequestTokenFailure,
[Description("无效的Id")]
InvalidId,
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameController : MonoBehaviour
{
public GameObject waterTower;
public GameObject follower;
public GameObject player;
public static int boardLength;
private float xPos = -2.5f;
public static GameController instance = null;
public static GameObject[] towerArray = new GameObject[boardLength * boardLength];
private float zPos;
private void Awake()
{
if (instance == null)
{
instance = gameObject.AddComponent<GameController>();
}
else if (instance != this)
{
Destroy(gameObject);
}
}
//set up the scene
// Use this for initialization
void Start()
{
////keeps track of index in array holding the tower tiles
//int towerTilePos = 0;
//player.transform.position = new Vector3(-0.5f, 0, -0.5f);
//for (int i = 0; i < boardLength; i++)
//{
// zPos = -2.5f;
// for (int j = 0; j < boardLength; j++)
// {
// GameObject singleTower = Instantiate(waterTower);
// towerArray[towerTilePos] = singleTower;
// singleTower.transform.position = new Vector3(xPos, 0, zPos);
// Debug.Log("x position : " + xPos + " z position: " + zPos);
// zPos = zPos + 1.0f;
// ++towerTilePos;
// }
// xPos = xPos + 1.0f;
//}
}
// Update is called once per frame
void Update()
{
}
}
|
namespace OpenMagic.ErrorTracker.WebApi.Specifications.Settings
{
public class WebApiSettings
{
private static int _lastPort = 9000;
private readonly int _port;
public WebApiSettings()
{
_port = ++_lastPort;
}
public string BaseUri => $"http://localhost:{_port}/";
}
} |
using Microsoft.Extensions.Primitives;
using OpenTelemetry;
using OpenTelemetry.Context.Propagation;
using Sentry.Extensibility;
namespace Sentry.OpenTelemetry;
/// <summary>
/// Sentry OpenTelemetry Propagator.
/// Injects and extracts both <c>sentry-trace</c> and <c>baggage</c> headers from carriers.
/// </summary>
public class SentryPropagator : BaggagePropagator
{
private readonly IHub? _hub;
private IHub Hub => _hub ?? SentrySdk.CurrentHub;
private SentryOptions? Options => Hub.GetSentryOptions();
/// <summary>
/// <para>
/// Creates a new SentryPropagator.
/// </para>
/// <para>
/// You should register the propagator with the OpenTelemetry SDK when initializing your application.
/// </para>
/// <example>
/// OpenTelemetry.Sdk.SetDefaultTextMapPropagator(new SentryPropagator());
/// </example>
/// </summary>
public SentryPropagator() : base()
{
}
internal SentryPropagator(IHub hub) : this()
{
_hub = hub;
}
/// <inheritdoc />
public override ISet<string> Fields => new HashSet<string>
{
SentryTraceHeader.HttpHeaderName,
BaggageHeader.HttpHeaderName
};
private static class OTelKeys
{
public const string SentryBaggageKey = "sentry.baggage";
public const string SentryTraceKey = "sentry.trace";
}
/// <inheritdoc />
public override PropagationContext Extract<T>(PropagationContext context, T carrier, Func<T, string, IEnumerable<string>> getter)
{
Options?.LogDebug("SentryPropagator.Extract");
var result = base.Extract(context, carrier, getter);
var baggage = result.Baggage; // The Otel .NET SDK takes care of baggage headers alread
Options?.LogDebug("Baggage");
foreach (var entry in baggage)
{
Options?.LogDebug(entry.ToString());
}
if (TryGetSentryTraceHeader(carrier, getter) is not {} sentryTraceHeader)
{
Options?.LogDebug("No SentryTraceHeader present in carrier");
return result;
}
Options?.LogDebug($"Extracted SentryTraceHeader from carrier: {sentryTraceHeader}");
var activityContext = new ActivityContext(
sentryTraceHeader.TraceId.AsActivityTraceId(),
sentryTraceHeader.SpanId.AsActivitySpanId(),
// NOTE: Our Java and JavaScript SDKs set sentryTraceHeader.IsSampled = true if any trace header is present.
sentryTraceHeader.IsSampled is true ? ActivityTraceFlags.Recorded : ActivityTraceFlags.None,
traceState:null, // See https://www.w3.org/TR/trace-context/#design-overview
isRemote: true
);
return new PropagationContext(activityContext, baggage);
}
/// <inheritdoc />
public override void Inject<T>(PropagationContext context, T carrier, Action<T, string, string> setter)
{
Options?.LogDebug("SentryPropagator.Inject");
// Don't inject if instrumentation is suppressed
if (Sdk.SuppressInstrumentation)
{
Options?.LogDebug("Not injecting Sentry tracing information. Instrumentation is suppressed.");
return;
}
// Don't inject when the activity context is invalid.
if (!context.ActivityContext.IsValid())
{
Options?.LogDebug("Not injecting Sentry tracing information for invalid activity context.");
return;
}
// Don't inject if this is a request to the Sentry ingest endpoint.
if (carrier is HttpRequestMessage request && (Options?.IsSentryRequest(request.RequestUri) ?? false))
{
return;
}
// Reconstruct SentryTraceHeader from the OpenTelemetry activity/span context
// TODO: Check if this is correct. Although the TraceId will be retained, the SpanId may change. Is that how it's supposed to work?
var traceHeader = new SentryTraceHeader(
context.ActivityContext.TraceId.AsSentryId(),
context.ActivityContext.SpanId.AsSentrySpanId(),
context.ActivityContext.TraceFlags.HasFlag(ActivityTraceFlags.Recorded)
);
// Set the sentry trace header for downstream requests
Options?.LogDebug($"SentryTraceHeader: {traceHeader}");
setter(carrier, SentryTraceHeader.HttpHeaderName, traceHeader.ToString());
base.Inject(context, carrier, setter);
}
private static SentryTraceHeader? TryGetSentryTraceHeader<T>(T carrier, Func<T, string, IEnumerable<string>> getter)
{
var headerValue = getter(carrier, SentryTraceHeader.HttpHeaderName);
try
{
var value = new StringValues(headerValue.ToArray());
return SentryTraceHeader.Parse(value);
}
catch (Exception)
{
return null;
}
}
}
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Don_SampleTrackingApp
{
public class RaportareDbContext : DbContext
{
public RaportareDbContext(DbContextOptions<RaportareDbContext> options)
: base(options)
{ }
public DbSet<TrackingUser> Users { get; set; }
public DbSet<ProbaModel> ProbaModels { get; set; }
}
}
|
namespace ForumSystem.Web.ViewModels.Administration.Posts
{
using System.Collections.Generic;
using ForumSystem.Web.ViewModels.PartialViews;
public class PostCrudModelList
{
public IEnumerable<PostCrudModel> Posts { get; set; }
public PaginationViewModel PaginationModel { get; set; }
public string SearchTerm { get; set; }
}
}
|
namespace Data.Repositories
{
using System.Data.Entity;
using Interfaces;
using Models;
public class UserRepository : Repository<User>, IUserRepository
{
public UserRepository(DbContext context) : base(context)
{
}
}
} |
namespace Fragenkatalog.Model
{
abstract class Benutzer
{
//# benutzer_nr: int
//# login_name : string
//# email_adresse : string
//# passwort : string
// Attribute
protected uint benutzer_nr;
protected string login_name;
protected string email_adresse;
protected string passwort;
protected uint rollen_nr;
protected Fach[] fachListe = new Fach[5];
// Properties
public virtual Fach[] FachListe
{
get { return fachListe; }
protected set
{
if (value is null)
throw new AttributeNotNullException(); fachListe = value;
}
}
public virtual uint Benutzer_nr { get { return benutzer_nr; } protected set { benutzer_nr = value; } }
public virtual string Login_name
{
get { return login_name; }
protected set
{
if (value is null)
throw new AttributeNotNullException();
login_name = value;
}
}
public virtual string Email_adresse
{
get { return email_adresse; }
protected set
{
if (value is null)
throw new AttributeNotNullException();
email_adresse = value;
}
}
public virtual string Passwort
{
get { return passwort; }
protected set
{
if (value is null)
throw new AttributeNotNullException();
passwort = value;
}
}
public virtual uint Rollen_nr { get { return rollen_nr; } protected set { rollen_nr = value; } }
public Benutzer(uint benutzer_nr, string login_name, string email_adresse, string passwort, uint rollen_nr)
{
Benutzer_nr = benutzer_nr;
Login_name = login_name;
Email_adresse = email_adresse;
Passwort = passwort;
Rollen_nr = rollen_nr;
}
}
}
|
using ArquiteturaLimpaMVC.Dominio.Entidades;
using MediatR;
using System.Collections.Generic;
namespace ArquiteturaLimpaMVC.Aplicacao.Produtos.Queries
{
public class TodosProdutosQuery : IRequest<IEnumerable<Produto>>
{
}
} |
using System;
using System.Collections.Generic;
namespace Inventory.Data
{
/// <summary>
/// Особеность (изображение: острое и т.д.)
/// </summary>
public class Mark : BaseEntity
{
public Guid RowGuid { get; set; }
public byte[] Picture { get; set; }
public virtual ICollection<DishMark> DishMarks { get; set; }
}
}
|
namespace Alabo.App.Share.OpenTasks.Base
{
/// <summary>
/// 模板信息
/// </summary>
public class TemplateRule
{
/// <summary>
/// 日志模板
/// </summary>
public string LoggerTemplate { get; set; } =
"会员{OrderUserName}消费,会员{ShareUserName}{AccountName}账户获得资产,金额为:{ShareAmount}";
public string SmsTemplate { get; set; } =
"会员{OrderUserName}消费,会员{ShareUserName}{AccountName}账户获得资产,金额为:{ShareAmount}";
/// <summary>
/// 是否开启短信通知
/// </summary>
public bool SmsNotification { get; set; } = false;
}
} |
using System.Collections;
using System.Collections.Generic;
using System;
using Newtonsoft.Json;
using UnityEngine;
using System.Runtime.CompilerServices;
using Unity;
public static class NoteHendler
{
public static List<Note> notes;
public static List<Note> availableNotes = new List<Note>();
public static GameObject scrollView;
public static List<Note> AvailableNotes
{
get
{
availableNotes.Sort();
return availableNotes;
}
}
static NoteHendler()
{
notes = JsonConvert.DeserializeObject<List<Note>>(System.IO.File.ReadAllText(@"e:\notes.json"));
scrollView = GameObject.Find("ScrollNotes");
}
static void Sort()
{
//TODO sort logic
}
public static void Ping()
{
Debug.Log("ping");
}
public static void AddNote(Note note)
{
notes.Add(note);
}
public static Note GetNote(int x)
{
foreach (Note note in notes)
{
if(note.No == x)
{
return note;
}
}
throw new Exception("There is no note with this number");
}
}
|
/*
* Author: Generated Code
* Date Created: 08.06.2011
* Description: Represents a row in the tblAktenIntActionType table
*/
namespace HTB.Database
{
public class tblAktenIntActionType : Record
{
#region Property Declaration
[MappingAttribute(FieldType = MappingAttribute.FIELD_TYPE_ID, FieldAutoNumber = true)]
public int AktIntActionTypeID { get; set; }
public string AktIntActionTypeCaption { get; set; }
public int ActionTypeNextStepID { get; set; }
public bool AktIntActionTypeIsInstallment { get; set; }
public bool AktIntActionNeedsSpecialCalc { get; set; }
public bool AktIntActionIsDefault { get; set; }
[MappingAttribute(FieldFormat = MappingAttribute.FIELD_FORMAT_CURRENCY)]
public double AktIntActionProvAmount { get; set; }
public double AktIntActionProvPct { get; set; }
[MappingAttribute(FieldFormat = MappingAttribute.FIELD_FORMAT_CURRENCY)]
public double AktIntActionProvAmountForZeroCollection { get; set; }
[MappingAttribute(FieldFormat = MappingAttribute.FIELD_FORMAT_CURRENCY)]
public double AktIntActionProvPrice { get; set; }
public bool AktIntActionIsWithCollection { get; set; }
public bool AktIntActionIsExtensionRequest { get; set; }
public int AktIntActionProvHonGrpID { get; set; }
public bool AktIntActionIsTotalCollection { get; set; }
public bool AktIntActionIsVoid { get; set; }
public bool AktIntActionIsTelAndEmailCollection { get; set; }
public bool AktIntActionIsPositive { get; set; }
public bool AktIntActionIsPersonalCollection { get; set; }
public bool AktIntActionIsInternal { get; set; }
public bool AktIntActionIsThroughPhone { get; set; }
public bool AktIntActionIsAutoRepossessed { get; set; }
public bool AktIntActionIsAutoMoneyCollected { get; set; }
public bool AktIntActionIsAutoNegative { get; set; }
public bool AktIntActionIsAutoPaymentInquiry { get; set; }
public bool AktIntActionIsAutoPayment { get; set; }
public bool AktIntActionIsDirectPayment { get; set; }
public bool AktIntActionIsReceivable { get; set; }
#endregion
}
}
|
using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Com.Colin.Web
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:BBSPager runat=server></{0}:BBSPager>")]
public class BBSPager : WebControl
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string Text
{
get
{
String s = (String)ViewState["Text"];
return ((s == null) ? String.Empty : s);
}
set
{
ViewState["Text"] = value;
}
}
[Bindable(false)]
[Category("Data")]
[DefaultValue("10")]
[Localizable(true)]
public int PageSize
{
get
{
try
{
Int32 s = (Int32)ViewState["PageSize"];
return ((s.ToString() == null) ? 10 : s);
}
catch
{
return 10;
}
}
set
{
ViewState["PageSize"] = value;
}
}
[Bindable(false)]
[Category("Data")]
[DefaultValue("")]
[Localizable(true)]
public string Server
{
get
{
String s = (String)ViewState["Server"];
return ((s == null) ? ("(local)") : s);
}
set
{
ViewState["Server"] = value;
}
}
[Bindable(false)]
[Category("Data")]
[DefaultValue("")]
[Localizable(true)]
public string DataBase
{
get
{
String s = (String)ViewState["DataBase"];
return ((s == null) ? ("none") : s);
}
set
{
ViewState["DataBase"] = value;
}
}
[Bindable(false)]
[Category("Data")]
[DefaultValue("")]
[Localizable(true)]
public string Uid
{
get
{
String s = (String)ViewState["Uid"];
return ((s == null) ? ("uid") : s);
}
set
{
ViewState["Uid"] = value;
}
}
[Bindable(false)]
[Category("Data")]
[DefaultValue("")]
[Localizable(true)]
public string Pwd
{
get
{
String s = (String)ViewState["Pwd"];
return ((s == null) ? ("none") : s);
}
set
{
ViewState["Pwd"] = value;
}
}
[Bindable(false)]
[Category("Data")]
[DefaultValue("")]
[Localizable(true)]
public string Table
{
get
{
String s = (String)ViewState["Table"];
return ((s == null) ? ("none") : s);
}
set
{
ViewState["Table"] = value;
}
}
[Bindable(false)]
[Category("Data")]
[DefaultValue("")]
[Localizable(true)]
public string SqlCommand
{
get
{
String s = (String)ViewState["SqlCommand"];
return ((s == null) ? ("none") : s);
}
set
{
ViewState["SqlCommand"] = value;
}
}
[Bindable(false)]
[Category("Data")]
[DefaultValue("")]
[Localizable(true)]
public string IndexPage
{
get
{
String s = (String)ViewState["IndexPage"];
return ((s == null) ? ("none") : s);
}
set
{
ViewState["IndexPage"] = value;
}
}
[Bindable(false)]
[Category("Data")]
[DefaultValue("")]
[Localizable(true)]
public string PageName
{
get
{
String s = (String)ViewState["PageName"];
return ((s == null) ? ("none") : s);
}
set
{
ViewState["PageName"] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
string html = "";
string str = "server='" + Server + "';database='" + DataBase + "';uid='" + Uid + "';pwd='" + Pwd + "'";
string strsql = "";
SqlConnection con = new SqlConnection(str);
try
{
con.Open();
if (SqlCommand == "none" || SqlCommand == "")
{
strsql = "select count(*) as mycount from " + Table + "";
}
else
{
strsql = SqlCommand;
}
SqlDataAdapter da = new SqlDataAdapter(strsql, con);
DataSet ds = new DataSet();
int count = da.Fill(ds, "count");
int page = 0;
int pageCount = 0;
if (count > 0)
{
page = Convert.ToInt32(ds.Tables["count"].Rows[0]["mycount"].ToString());
}
if (page % PageSize > 0)
{
pageCount = (page / PageSize) + 1;
}
else
{
pageCount = page / PageSize;
}
html += "<table><tr>";
for (int i = 0; i < pageCount; i++)
{
if (IndexPage != i.ToString())
{
html += "<td style=\"padding:5px 5px 5px 5px;background:#f0f0f0;border:1px dashed #ccc;\">";
}
else
{
html += "<td style=\"padding:5px 5px 5px 5px;background:Gray;border:1px dashed #ccc;\">";
}
html += "<a href=\"" + PageName + "?page=" + i + "\">" + i + "</a>";
html += "</td>";
}
html += "</tr></table>";
}
catch (Exception ee)
{
html = ee.ToString();
}
finally
{
output.Write(html);
con.Close();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentAssertions;
using Nancy.Testing;
using Xunit;
namespace Testr.Tests
{
public class Class1
{
[Fact]
public void Test()
{
true.Should().BeTrue();
}
}
}
|
using System;
using System.Collections.Generic;
using com.Sconit.Entity.Exception;
using NHibernate.Type;
namespace com.Sconit.Web.Models
{
public class ProcedureSearchStatementModel : BaseModel
{
public string CountProcedure { get; set; }
public string SelectProcedure { get; set; }
public IList<ProcedureParameter> Parameters { get; set; }
public IList<ProcedureParameter> PageParameters { get; set; }
public DateTime CachedDateTime { get; set; }
public string GetSearchCountStatement()
{
if (!string.IsNullOrWhiteSpace(CountProcedure))
{
return CountProcedure;
}
else
{
throw new TechnicalException("SelectCountProcedure not initialize.");
}
}
public string GetSearchStatement()
{
if (!string.IsNullOrWhiteSpace(SelectProcedure))
{
return SelectProcedure;
}
else
{
throw new TechnicalException("SelectProcedure not initialize.");
}
}
public List<object> GetParameterValues()
{
List<object> values = new List<object>();
if (Parameters.Count > 0)
{
foreach (var parameter in Parameters)
{
values.Add(parameter.Parameter);
}
}
return values;
}
public List<object> GetAllParameterValues()
{
List<object> values = new List<object>();
if (Parameters.Count > 0)
{
foreach (var parameter in Parameters)
{
values.Add(parameter.Parameter);
}
}
if (PageParameters.Count > 0)
{
foreach (var parameter in PageParameters)
{
values.Add(parameter.Parameter);
}
}
return values;
}
public List<IType> GetParameterTypes()
{
List<IType> types = new List<IType>();
if (Parameters.Count > 0)
{
foreach (var parameter in Parameters)
{
types.Add(parameter.Type);
}
}
return types;
}
public List<IType> GetAllParameterTypes()
{
List<IType> types = new List<IType>();
if (Parameters.Count > 0)
{
foreach (var parameter in Parameters)
{
types.Add(parameter.Type);
}
}
if (PageParameters.Count > 0)
{
foreach (var parameter in PageParameters)
{
types.Add(parameter.Type);
}
}
return types;
}
}
public class ProcedureParameter
{
public object Parameter { get; set; }
public IType Type { get; set; }
}
}
|
using BO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebSport.Models;
namespace WebSport.Controllers
{
public class CompetitorController : Controller
{
private DAL.IRepository<Competitor> repo;
public CompetitorController()
{
repo = DAL.RepositoryFactory.GetRepository<Competitor>();
}
// GET: Competitor
public ActionResult Index()
{
return View(repo.GetAll());
}
// GET: Competitor/Details/5
public ActionResult Details(int id)
{
return View(repo.GetById(id));
}
// GET: Competitor/Create
public ActionResult Create()
{
return View();
}
// POST: Competitor/Create
[HttpPost]
public ActionResult Create(Competitor competitor)
{
try
{
repo.Insert(competitor);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Competitor/Edit/5
public ActionResult Edit(int id)
{
var vm = new CreateEditCompetitorVM();
vm.Competitor = repo.GetById(id);
if (vm.Competitor.Race != null)
{
vm.IdSelectedRace = vm.Competitor.Race.Id;
}
vm.Races = new RaceController().RaceRepo.GetAll();
return View(vm);
}
// POST: Competitor/Edit/5
[HttpPost]
public ActionResult Edit(CreateEditCompetitorVM vm)
{
try
{
if (vm.IdSelectedRace.HasValue)
{
vm.Competitor.Race = new RaceController().RaceRepo.GetById(vm.IdSelectedRace.Value);
}
repo.Update(vm.Competitor);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Competitor/Delete/5
public ActionResult Delete(int id)
{
return View(repo.GetById(id));
}
// POST: Competitor/Delete/5
[HttpPost]
public ActionResult Delete(Competitor competitor)
{
try
{
repo.Delete(competitor.Id);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
|
using System.Web.Mvc;
using LearningSystem.Models.ViewModels.Admin;
using LearningSystem.Services;
using LearningSystem.Services.Interfaces;
using LearningSystem.Web.Attributes;
namespace LearningSystem.Web.Areas.Admin.Controllers
{
[MyAuthorize(Roles = "Admin")]
[RouteArea("Admin")]
public class AdminController : Controller
{
private readonly IAdminServices _service;
public AdminController(IAdminServices services)
{
this._service = services;
}
// GET: Admin/Admin
[HttpGet]
[Route]
public ActionResult Index()
{
AdminPageVm vm = this._service.GetAdminPage();
return View(vm);
}
[HttpGet]
[Route("courses/add")]
public ActionResult AddCourse()
{
return this.View();
}
[HttpGet]
[Route("courses/{id}/edit")]
public ActionResult EditCourse(int Id)
{
return this.View();
}
[HttpGet]
[Route("users/{id}/edit")]
public ActionResult EditUser(int Id)
{
return this.View();
}
}
} |
using System;
using UKPR.Hermes.NG.Models.DataContract;
namespace UKPR.Hermes.Models
{
public class NgDispatchMessage : NgBaseRawMessage
{
public InstructionMessage NgRawMessage { get; set; }
public bool Accepted { get; set; }
public string Reason { get; set; }
public Guid? ContractRequestId { get; set; }
}
}
|
using System.Collections.Generic;
namespace Shared
{
public interface IKidService
{
void SaveKids(IEnumerable<KidDto> kids);
void SaveOrUpdateKids(IEnumerable<KidDto> kids);
IEnumerable<KidDto> GetKids();
}
} |
using System.ComponentModel.DataAnnotations;
using Tomelt.ContentManagement;
namespace ArticleManage.Models {
public class ArticlePart : ContentPart<ArticlePartRecord>
{
[Display(Name = "内容摘要")]
public string Summary
{
get { return Record.Summary; }
set { Record.Summary = value; }
}
[Display(Name = "文章栏目")]
public ColumnPartRecord ColumnPartRecord
{
get { return Record.ColumnPartRecord; }
set { Record.ColumnPartRecord = value; }
}
[Display(Name = "副标题")]
public string Subtitle
{
get { return Record.Subtitle; }
set { Record.Subtitle = value; }
}
[Display(Name = "文章外链")]
public string LinkUrl
{
get { return Record.LinkUrl; }
set { Record.LinkUrl = value; }
}
[Display(Name = "排序")]
public int Sort
{
get { return Record.Sort; }
set { Record.Sort = value; }
}
[Display(Name = "轮播")]
public bool IsSlide
{
get { return Record.IsSlide; }
set { Record.IsSlide = value; }
}
[Display(Name = "热点")]
public bool IsHot
{
get { return Record.IsHot; }
set { Record.IsHot = value; }
}
[Display(Name = "置顶")]
public bool IsTop
{
get { return Record.IsTop; }
set { Record.IsTop = value; }
}
[Display(Name = "推荐")]
public bool IsRecommend
{
get { return Record.IsRecommend; }
set { Record.IsRecommend = value; }
}
[Display(Name = "醒目")]
public bool IsStriking
{
get { return Record.IsStriking; }
set { Record.IsStriking = value; }
}
[Display(Name = "来源")]
public string Source
{
get { return Record.Source; }
set { Record.Source = value; }
}
[Display(Name = "作者")]
public string Author
{
get { return Record.Author; }
set { Record.Author = value; }
}
[Display(Name = "人气值")]
public int ClickNum
{
get { return Record.ClickNum; }
set { Record.ClickNum = value; }
}
[Display(Name = "文章栏目")]
public int ColumnPartRecordId
{
get { return Record.ColumnPartRecordId; }
set { Record.ColumnPartRecordId = value; }
}
}
} |
using Cs_Gerencial.Dominio.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Gerencial.Infra.Data.EntityConfig
{
public class SeriesConfig: EntityTypeConfiguration<Series>
{
public SeriesConfig()
{
HasKey(p => p.SerieId);
Property(p => p.SerieId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(p => p.IdCompra)
.IsRequired();
Property(p => p.Letra)
.IsRequired()
.HasMaxLength(4);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace DDMedi.Test.Helper
{
public static class SupplierChannelHelper
{
public static bool HasSupplier<TSupplier>(this object supplierChannel) where TSupplier : class
{
var cachedInstance = supplierChannel.GetHiddenPublicProperty<IBaseContext>();
if (cachedInstance != null)
return typeof(TSupplier).IsAssignableFrom(cachedInstance.Instance.GetType());
return supplierChannel.GetNonePublicField<TSupplier>() != null;
}
public static TSupplier GetSupplier<TSupplier>(this object supplierChannel) where TSupplier : class
=> supplierChannel.GetHiddenPublicProperty<IBaseContext>().Instance as TSupplier ??
supplierChannel.GetNonePublicField<TSupplier>();
public static bool HasSupplier<TSupplier>(this object supplierChannel, TSupplier supplier)
where TSupplier: class
{
var prop = supplierChannel.GetHiddenPublicProperty<IBaseContext>();
if(prop != null)
return prop.Instance == supplier;
return supplierChannel.GetNonePublicField<TSupplier>() == supplier;
}
public static bool HasProperty<TSupplier>(this object supplierChannel) where TSupplier : class
{
var decoratorType = typeof(TSupplier);
var decorator = supplierChannel.GetHiddenPublicProperty<TSupplier>();
if (decorator == null) return false;
return decoratorType.IsAssignableFrom(decorator.GetType());
}
public static TSupplier GetHiddenPublicProperty<TSupplier>(this object supplierChannel) where TSupplier : class
{
var supplierType = typeof(TSupplier);
var serivceProp = supplierChannel.GetHiddenPublicProperty(supplierType);
return serivceProp?.GetValue(supplierChannel) as TSupplier;
}
public static Dictionary<Type, Dictionary<Type, SupplierDescriptor[]>> GetAllDescriptorDic(this object supplierChannel)
=> supplierChannel.GetNonePublicProperty<Dictionary<Type, Dictionary<Type, SupplierDescriptor[]>>>();
public static Dictionary<Type, SupplierDescriptor[]> GetDescriptorDic(this object supplierChannel)
=> supplierChannel.GetNonePublicProperty<Dictionary<Type, SupplierDescriptor[]>>();
public static TSupplier GetNonePublicProperty<TSupplier>(this object supplierChannel) where TSupplier : class
{
var supplierType = typeof(TSupplier);
var serivceProp = supplierChannel.GetNonePublicProperty(supplierType);
return serivceProp?.GetValue(supplierChannel) as TSupplier;
}
public static TSupplier GetHiddenPublicField<TSupplier>(this object supplierChannel) where TSupplier : class
{
var supplierType = typeof(TSupplier);
var serivceProp = supplierChannel.GetHiddenPublicField(supplierType);
return serivceProp?.GetValue(supplierChannel) as TSupplier;
}
public static TSupplier GetNonePublicField<TSupplier>(this object supplierChannel) where TSupplier : class
{
var supplierType = typeof(TSupplier);
var serivceProp = supplierChannel.GetNonePublicField(supplierType);
return serivceProp?.GetValue(supplierChannel) as TSupplier;
}
static PropertyInfo GetHiddenPublicProperty(this object supplierChannel, Type supplierType) =>
supplierChannel.GetType().GetProperties()
.FirstOrDefault(e => e.PropertyType.IsAssignableFrom(supplierType) ||
supplierType.IsAssignableFrom(e.PropertyType));
static PropertyInfo GetNonePublicProperty(this object supplierChannel, Type supplierType) =>
supplierChannel.GetType().GetProperties(BindingFlags.Instance|BindingFlags.NonPublic)
.FirstOrDefault(e => e.PropertyType.IsAssignableFrom(supplierType) ||
supplierType.IsAssignableFrom(e.PropertyType));
static FieldInfo GetHiddenPublicField(this object supplierChannel, Type supplierType) =>
supplierChannel.GetType().GetFields()
.FirstOrDefault(e => e.FieldType.IsAssignableFrom(supplierType) ||
supplierType.IsAssignableFrom(e.FieldType));
static FieldInfo GetNonePublicField(this object supplierChannel, Type supplierType) =>
supplierChannel.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
.FirstOrDefault(e => e.FieldType.IsAssignableFrom(supplierType) ||
supplierType.IsAssignableFrom(e.FieldType));
public static TService Get<TService>(this IServiceProvider serviceProvider)
=> (TService)serviceProvider.GetService(typeof(TService));
public static bool ValidateLifeTime(this ISupplierScopeFactory scopeFactory, Type implementType, SupplierLifetime ExpectedLifeTime)
{
var provider1 = scopeFactory.CreateScope().ServiceProvider;
var obj1 = provider1.GetService(implementType);
if (ExpectedLifeTime == SupplierLifetime.Scoped)
return obj1 == provider1.GetService(implementType) &&
obj1 != scopeFactory.CreateScope().ServiceProvider.GetService(implementType);
if (ExpectedLifeTime == SupplierLifetime.Singleton)
return obj1 == scopeFactory.CreateScope().ServiceProvider.GetService(implementType);
return obj1 != provider1.GetService(implementType);
}
}
}
|
using System;
using System.Collections.Generic;
using SignInCheckIn.Models.DTO;
using Microsoft.AspNet.SignalR;
namespace SignInCheckIn.Services.Interfaces
{
public interface IWebsocketService
{
void PublishRoomCapacity(int eventId, int roomId, EventRoomDto data);
void PublishCheckinParticipantsCheckedIn(int eventId, int roomId, ParticipantDto data);
void PublishCheckinParticipantsAdd(int eventId, int roomId, List<ParticipantDto> data);
void PublishCheckinParticipantsCheckedInRemove(int eventId, int roomId, ParticipantDto data);
void PublishCheckinParticipantsSignedInRemove(int eventId, int roomId, ParticipantDto data);
void PublishCheckinParticipantsOverrideCheckin(int eventId, int roomId, ParticipantDto data);
}
}
|
using LimenawebApp.Models;
using Newtonsoft.Json;
using Postal;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Microsoft.SharePoint.Client;
using System.Security;
using System.Data.SqlClient;
using LimenawebApp.Controllers.Session;
namespace LimenawebApp.Controllers
{
public class ManagementController : Controller
{
private dbLimenaEntities dblim = new dbLimenaEntities();
private dbComerciaEntities dbcmk = new dbComerciaEntities();
private DLI_PROEntities dlipro = new DLI_PROEntities();
private Interna_DLIEntities internadli = new Interna_DLIEntities();
private Cls_session cls_session = new Cls_session();
public class repsU {
public int id_Sales_Rep { get; set; }
public string Slp_name { get; set; }
public int issel { get; set; }
}
public ActionResult Users()
{
Sys_Users activeuser = Session["activeUser"] as Sys_Users;
if (activeuser != null)
{
//HEADER
//PAGINAS ACTIVAS
ViewData["Menu"] = "Management";
ViewData["Page"] = "Users";
ViewBag.menunameid = "manag_menu";
ViewBag.submenunameid = "users_submenu";
List<string> d = new List<string>(activeuser.Departments.Split(new string[] { "," }, StringSplitOptions.None));
ViewBag.lstDepartments = JsonConvert.SerializeObject(d);
List<string> r = new List<string>(activeuser.Roles.Split(new string[] { "," }, StringSplitOptions.None));
ViewBag.lstRoles = JsonConvert.SerializeObject(r);
ViewData["nameUser"] = activeuser.Name + " " + activeuser.Lastname;
//NOTIFICATIONS
DateTime now = DateTime.Today;
List<Tb_Alerts> lstAlerts = (from a in dblim.Tb_Alerts where (a.ID_user == activeuser.ID_User && a.Active == true && a.Date == now) select a).OrderByDescending(x => x.Date).Take(5).ToList();
ViewBag.lstAlerts = lstAlerts;
//FIN HEADER
List<Sys_Users> lstUsers = (from a in dblim.Sys_Users select a).ToList();
return View(lstUsers);
}
else
{
return RedirectToAction("Login", "Home", new { access = false });
}
}
public ActionResult SendToSharepoint(int? id, string emailresp)
{
try
{
var user = (from a in dblim.Tb_NewCustomers where (a.ID_customer == id) select a).FirstOrDefault();
if (user != null) {
user.Validated = true;
user.status = 1;
dblim.Entry(user).State = EntityState.Modified;
dblim.SaveChanges();
try //Enviamos a lista de Sharepoint
{
var contrasena = "VaL3nZuEl@2017";
ClientContext ClienteCTX = new ClientContext("https://limenainc.sharepoint.com/sites/DatosMaestrosFlujos");
var seguridad = new SecureString();
foreach (Char item in contrasena) {
seguridad.AppendChar(item);
}
ClienteCTX.Credentials = new SharePointOnlineCredentials("s.valenzuela@limenainc.net", seguridad);
Web oWebsite = ClienteCTX.Web;
ListCollection CollList = oWebsite.Lists;
List oList = CollList.GetByTitle("A_Customer_Web");
ClienteCTX.Load(oList);
ClienteCTX.ExecuteQuery();
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem oListItem = oList.AddItem(itemCreateInfo);
oListItem["Title"] = user.ID_customer.ToString();
//Cardname
oListItem["_x006a_525"] = user.CardName;
//Phone1
oListItem["f5nt"] = user.Phone1;
//Email
oListItem["_x007a_vg9"] = user.E_Mail;
//Website
oListItem["g0qp"] = user.IntrntSite;
//TAXID
oListItem["_x006a_357"] = user.TAXID;
//TAC CERT NUM
oListItem["svcl"] = user.TAXCERTNUM;
//FirstName
oListItem["jhpd"] = user.FirstName;
//Lastname
oListItem["_x0076_ai5"] = user.LastName;
//Position
oListItem["_x0073_qi8"] = user.Position;
//Tel1
oListItem["tlej"] = user.Tel1;
//EmailL
oListItem["b3yn"] = user.E_MailL;
//Street
oListItem["tila"] = user.Street;
//City
oListItem["geny"] = user.City;
//State
oListItem["bnwd"] = user.State;
//ZipCode
oListItem["s0nc"] = user.ZipCode;
//Country
oListItem["x2nn"] = user.Country;
//StoreServices
//Se utiilizara para enviar imagenes
var imgName1 = user.url_imageTAXCERT.Substring(19);
var imgName2 = "";
try
{
imgName2 = user.url_imageTAXCERNUM.Substring(19);
}
catch {
imgName2 = "";
}
oListItem["ilow"] = imgName1;
//Etnias
//Se utilizara para enviar imagenes
oListItem["_x0066_dt3"] = imgName2;
//URL Image TAX ID
oListItem["hzfz"] = user.url_imageTAXCERT;
//URL IMAGE TAX CERT NUM
oListItem["iiah"] = user.url_imageTAXCERNUM;
//Operation Time
oListItem["yvmx"] = user.OperationTime;
//Recibo Mercaderia Dia
oListItem["odzu"] = user.ReciboMercaderia_dia;
//Recibo Mercaderia Area
oListItem["tzqf"] = user.ReciboMercaderia_area;
//Muelle descarga //Tipo Boolean Evaluamos que cadena enviar
//if (user.Muelle_descarga == true)
//{
oListItem["MuelleDeCarga"] = user.Muelle_descarga;
//}
//else {
// oListItem["MuelleDeCarga"] = "NO";
//}
//Store Size
oListItem["rzmy"] = user.Store_size;
//Validated
oListItem["Validated1"] = true;
//OnSharepoint
oListItem["NewColumn3"] = true;
////Modificado
//oListItem["Modified"] = DateTime.UtcNow;
////Creado
//oListItem["Created"] = DateTime.UtcNow;
////Creador
//oListItem["Author"] = "Limena";
////Editor
//oListItem["Editor"] = "Limena";
//Servicios
List<string> servicesIDs = user.StoreServices.Split(',').ToList();
if (servicesIDs.Contains("s1")) { oListItem["_x0033_7_GROCERY_DRY_PRODUCT"] = true; } else { oListItem["_x0033_7_GROCERY_DRY_PRODUCT"] = false; }
if (servicesIDs.Contains("s2")) { oListItem["_x0033_8_DAIRY_x0020_SECTION"] = true; } else { oListItem["_x0033_8_DAIRY_x0020_SECTION"] = false; }
if (servicesIDs.Contains("s3")) { oListItem["_x0033_9_FROZEN_SECTION"] = true; } else { oListItem["_x0033_9_FROZEN_SECTION"] = false; }
if (servicesIDs.Contains("s4")) { oListItem["_x0034_0_PRODUCE"] = true; } else { oListItem["_x0034_0_PRODUCE"] = false; }
if (servicesIDs.Contains("s5")) { oListItem["_x0034_1_MEAT_DEPARTAMENT"] = true; } else { oListItem["_x0034_1_MEAT_DEPARTAMENT"] = false; }
if (servicesIDs.Contains("s6")) { oListItem["_x0034_2_RESTAURANT"] = true; } else { oListItem["_x0034_2_RESTAURANT"] = false; }
if (servicesIDs.Contains("s7")) { oListItem["_x0034_3_MONEY_SERVICES"] = true; } else { oListItem["_x0034_3_MONEY_SERVICES"] = false; }
if (servicesIDs.Contains("s8")) { oListItem["_x0034_4_OTC"] = true; } else { oListItem["_x0034_4_OTC"] = false; }
if (servicesIDs.Contains("s9")) { oListItem["_x0034_5_KITCHENWARE"] = true; } else { oListItem["_x0034_5_KITCHENWARE"] = false; }
if (servicesIDs.Contains("s10")) { oListItem["_x0034_6_ETHNIC_SOURVENIRS"] = true; } else { oListItem["_x0034_6_ETHNIC_SOURVENIRS"] = false; }
if (servicesIDs.Contains("s11")) { oListItem["_x0034_7_CLOTHING"] = true; } else { oListItem["_x0034_7_CLOTHING"] = false; }
if (servicesIDs.Contains("s12")) { oListItem["_x0034_8_JEWELRY"] = true; } else { oListItem["_x0034_8_JEWELRY"] = false; }
if (servicesIDs.Contains("s13")) { oListItem["_x0034_9_CELLPHONE_STORE"] = true; } else { oListItem["_x0034_9_CELLPHONE_STORE"] = false; }
//Etnias
List<string> etniasIDs = user.Etnias.Split(',').ToList();
if (etniasIDs.Contains("e1")) { oListItem["_x0035_5_ELSALVADOR"] = true; } else { oListItem["_x0035_5_ELSALVADOR"] = false; }
if (etniasIDs.Contains("e2")) { oListItem["_x0035_6_GUATEMALA"] = true; } else { oListItem["_x0035_6_GUATEMALA"] = false; }
if (etniasIDs.Contains("e3")) { oListItem["_x0035_7_COSTARICA"] = true; } else { oListItem["_x0035_7_COSTARICA"] = false; }
if (etniasIDs.Contains("e4")) { oListItem["_x0035_8_MEXICO"] = true; } else { oListItem["_x0035_8_MEXICO"] = false; }
if (etniasIDs.Contains("e5")) { oListItem["_x0035_9_COLOMBIA"] = true; } else { oListItem["_x0035_9_COLOMBIA"] = false; }
if (etniasIDs.Contains("e6")) { oListItem["_x0036_0_PERU"] = true; } else { oListItem["_x0036_0_PERU"] = false; }
if (etniasIDs.Contains("e7")) { oListItem["_x0036_1_VENEZUELA"] = true; } else { oListItem["_x0036_1_VENEZUELA"] = false; }
if (etniasIDs.Contains("e8")) { oListItem["_x0036_2_CUBA"] = true; } else { oListItem["_x0036_2_CUBA"] = false; }
if (etniasIDs.Contains("e9")) { oListItem["_x0036_3_PUERTORICO"] = true; } else { oListItem["_x0036_3_PUERTORICO"] = false; }
if (etniasIDs.Contains("e10")) { oListItem["_x0036_4_HONDURAS"] = true; } else { oListItem["_x0036_4_HONDURAS"] = false; }
oListItem.Update();
ClienteCTX.ExecuteQuery();
int newID = oListItem.Id; //Here I reference the ID from the newly created list item
var commercialid = newID + 22;
var urltosharepoint = "https://limenainc.sharepoint.com/sites/DatosMaestrosFlujos/Lists/Customer_Commercial/DispForm.aspx?ID=" + commercialid;
user.urlsharepoint = urltosharepoint;
user.idsharepoint = newID;
user.status = 2;
user.OnSharepoint = true;
dblim.Entry(user).State = EntityState.Modified;
dblim.SaveChanges();
//Enviar correo a supervisor asignado o si es gerencia comercial, enviarselo a JOHAN 05/08/2020
TempData["exito"] = "User uploaded to Sharepoint successfully.";
try
{ //Enviamos correos
if (emailresp == "supervisors")
{
var sup = user.Supervisor.ToString();
var emailsupervisor = (from g in dblim.Sys_Users where (g.IDSAP == sup && g.Roles.Contains("Sales Supervisor")) select g).FirstOrDefault();
if (emailsupervisor != null) {
//Send the email
dynamic semail = new Email("email_notificationEnrollSharepoint");
semail.To = emailsupervisor.Email;
semail.From = "donotreply@limenainc.net";
semail.customer = user.CardName;
semail.url = urltosharepoint;
semail.Send();
}
}
else {
//Send the email
dynamic semail = new Email("email_notificationEnrollSharepoint");
semail.To = emailresp;
semail.From = "donotreply@limenainc.net";
semail.customer = user.CardName;
semail.url = urltosharepoint;
semail.Send();
}
}
catch {
}
}
catch (Exception ex) {
TempData["advertencia"] = "Something wrong happened, try again." + ex.Message;
}
}
return RedirectToAction("New_customers", "Management", null);
}
catch (Exception ex2)
{
TempData["advertencia"] = "Something wrong happened, try again." + ex2.Message;
return RedirectToAction("New_customers", "Management", null);
}
}
//0 - espera
//1 - validado
//2 - sharepoint
//3 - edit
//4 - rechazado
public ActionResult SendMessageEdit(int? id, string mensaje)
{
try
{
var user = (from a in dblim.Tb_NewCustomers where (a.ID_customer == id) select a).FirstOrDefault();
//Send the email
dynamic semail = new Email("email_notificationEnrollEdit");
semail.To = user.E_MailL.ToString();
semail.From = "donotreply@limenainc.net";
semail.user = user.FirstName + " " + user.LastName;
//semail.user = user.FirstName + " " + user.LastName;
semail.url = "https://limenainc.net/Home/Enroll_edit/?request=" + user.ID_customer;
semail.message = mensaje;
if (user.emailRep == "") { semail.ccrep = "donotreply@limenainc.net"; } else { semail.ccrep = user.emailRep; }
semail.Send();
user.Validated = false;
user.status = 3;
dblim.Entry(user).State = EntityState.Modified;
dblim.SaveChanges();
TempData["exito"] = "Message sent to customer successfully.";
return RedirectToAction("New_customers", "Management", null);
}
catch (Exception ex2)
{
TempData["advertencia"] = "Something wrong happened, try again." + ex2.Message;
return RedirectToAction("New_customers", "Management", null);
}
}
public ActionResult DeleteRequest(int id)
{
try
{
Tb_NewCustomers newCustomer = dblim.Tb_NewCustomers.Find(id);
if (newCustomer != null)
{
var urlimg1 = newCustomer.url_imageTAXCERNUM;
var urlimg2 = newCustomer.url_imageTAXCERT;
dblim.Tb_NewCustomers.Remove(newCustomer);
dblim.SaveChanges();
try
{
if (System.IO.File.Exists(Server.MapPath(urlimg1)))
{
try
{
System.IO.File.Delete(Server.MapPath(urlimg1));
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
}
}
if (System.IO.File.Exists(Server.MapPath(urlimg2)))
{
try
{
System.IO.File.Delete(Server.MapPath(urlimg2));
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
}
}
}
catch
{
}
}
TempData["exito"] = "User deleted successfully.";
return RedirectToAction("New_customers", "Management", null);
}
catch(Exception ex)
{
TempData["advertencia"] = "Something wrong happened, try again." + ex.Message;
return RedirectToAction("New_customers", "Management", null);
}
}
public ActionResult New_customers()
{
Sys_Users activeuser = Session["activeUser"] as Sys_Users;
if (activeuser != null)
{
//HEADER
//PAGINAS ACTIVAS
ViewData["Menu"] = "Management";
ViewData["Page"] = "New Customers";
ViewBag.menunameid = "manag_menu";
ViewBag.submenunameid = "newcustomers_submenu";
List<string> d = new List<string>(activeuser.Departments.Split(new string[] { "," }, StringSplitOptions.None));
ViewBag.lstDepartments = JsonConvert.SerializeObject(d);
List<string> r = new List<string>(activeuser.Roles.Split(new string[] { "," }, StringSplitOptions.None));
ViewBag.lstRoles = JsonConvert.SerializeObject(r);
ViewData["nameUser"] = activeuser.Name + " " + activeuser.Lastname;
//NOTIFICATIONS
DateTime now = DateTime.Today;
List<Tb_Alerts> lstAlerts = (from a in dblim.Tb_Alerts where (a.ID_user == activeuser.ID_User && a.Active == true && a.Date == now) select a).OrderByDescending(x => x.Date).Take(5).ToList();
ViewBag.lstAlerts = lstAlerts;
//FIN HEADER
List<Tb_NewCustomers> lstCustomers = new List<Tb_NewCustomers>();
lstCustomers = (from a in dblim.Tb_NewCustomers where(a.FirstName !="" && a.E_Mail !="" && a.OnSharepoint==false) select a).ToList();
foreach (var item in lstCustomers) {
var slp = (from des in dlipro.OSLP where (des.SlpCode == item.idSAPRep) select des).FirstOrDefault();
if (slp != null) {
item.emailRep = slp.SlpName;
}
}
return View(lstCustomers);
}
else
{
return RedirectToAction("Login", "Home", new { access = false });
}
}
//MERCHANDISING
public ActionResult deleteUser(string id_user)
{
try
{
var id = Convert.ToInt32(id_user);
var user = dblim.Sys_Users.Where(c => c.ID_User == id).Select(c => c).FirstOrDefault();
if (user != null)
{
dblim.Sys_Users.Remove(user);
dblim.SaveChanges();
var rrresult = "SUCCESS";
return Json(rrresult, JsonRequestBehavior.AllowGet);
}
else
{
string result = "NO DATA FOUND";
return Json(result, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
string result = "ERROR: " + ex.Message;
return Json(result, JsonRequestBehavior.AllowGet);
}
}
public class userData
{
public int ID_User { get; set; }
public string Name { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Telephone { get; set; }
public string Position { get; set; }
public bool Active { get; set; }
public string Departments { get; set; }
public string Roles { get; set; }
}
public ActionResult getUser(string id_user)
{
try
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
var id = Convert.ToInt32(id_user);
var user = (from a in dblim.Sys_Users where(a.ID_User == id) select new userData { ID_User=a.ID_User, Name= a.Name, Lastname =a.Lastname, Email=a.Email, Password = a.Password, Telephone=a.Telephone, Position=a.Position,Active=a.Active, Departments=a.Departments, Roles=a.Roles } ).ToArray();
var user2 = (from a in dblim.Sys_Users
where (a.ID_User == id)
select a).FirstOrDefault();
var result2 = javaScriptSerializer.Serialize(user);
var lstReps = new List<repsU>();
lstReps = (from b in dlipro.SalesRep select new repsU { id_Sales_Rep = b.id_SalesRep, Slp_name = b.Slp_Name, issel = 0 }).ToList();
if (user2.prop01 != null) {
if (user2.prop01 == "")
{
}
else {
List<int> TagIds = user2.prop01.Split(',').Select(int.Parse).ToList();
if (TagIds.Count() > 0)
{
foreach (var item in lstReps)
{
if (TagIds.Contains(item.id_Sales_Rep))
{
item.issel = 1;
}
}
}
}
}
var result = new { result = result2, result2 = javaScriptSerializer.Serialize(lstReps.ToArray()) };
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
string result = "ERROR: " + ex.Message;
return Json(result, JsonRequestBehavior.AllowGet);
}
}
public JsonResult CreateUser(string name, string lastname, string email, string password, string telephone, string position, string departments, string roles)
{
Sys_Users activeuser = Session["activeUser"] as Sys_Users;
Sys_Users User = new Sys_Users();
try
{
User.Name = name;
User.Lastname = lastname;
User.Email = email;
User.Password = password;
User.Telephone = telephone;
User.Position = position;
User.Departments = departments;
User.Roles = roles;
User.BolsaValor = 0;
User.PorcentajeBolsa = 0;
User.IDSAP = "";
User.ID_Truck = "";
User.Truck_name = "";
User.Url_image = "";
if (User.Position == null)
{
User.Position = "";
}
if (User.Departments == null)
{
User.Departments = "";
}
if (User.Roles == null)
{
User.Roles = "";
}
if (User.Telephone == null)
{
User.Telephone = "";
}
if (User.prop01 == null)
{
User.prop01 = "";
}
if (User.prop02 == null)
{
User.prop02 = "";
}
User.ID_Company = activeuser.ID_Company;
User.Registration_Date = DateTime.UtcNow;
User.Active = true;
dblim.Sys_Users.Add(User);
dblim.SaveChanges();
//Send the email
dynamic semail = new Email("email_confirmation");
semail.To = User.Email.ToString();
semail.From = "donotreply@limenainc.net";
semail.user = User.Name + " " + User.Lastname;
semail.email = User.Email;
semail.password = User.Password;
semail.Send();
//FIN email
return Json(new { Result = "Success" });
}
catch (Exception ex){
return Json(new { Result = "Something wrong happened, try again. " + ex.Message});
}
}
public JsonResult EditUser(string id,string name, string lastname, string email, string password, string telephone, string position, string departments, string roles, string reps)
{
Sys_Users activeuser = Session["activeUser"] as Sys_Users;
int idr = Convert.ToInt32(id);
Sys_Users User = (from a in dblim.Sys_Users where (a.ID_User == idr) select a).FirstOrDefault();
try
{
User.Name = name;
User.Lastname = lastname;
User.Email = email;
User.Password = password;
User.Telephone = telephone;
User.Position = position;
User.Departments = departments;
User.Roles = roles;
User.prop01 = reps;
if (User.Position == null)
{
User.Position = "";
}
if (User.Departments == null)
{
User.Departments = "";
}
if (User.Roles == null)
{
User.Roles = "";
}
if (User.Telephone == null)
{
User.Telephone = "";
}
if (User.prop01 == null)
{
User.prop01 = "";
}
if (User.prop02 == null)
{
User.prop02 = "";
}
dblim.Entry(User).State = EntityState.Modified;
dblim.SaveChanges();
//Send the email
//dynamic semail = new Email("email_confirmation");
//semail.To = User.Email.ToString();
//semail.From = "donotreply@limenainc.net";
//semail.user = User.Name + " " + User.Lastname;
//semail.email = User.Email;
//semail.password = User.Password;
//semail.Send();
//FIN email
return Json(new { Result = "Success" });
}
catch (Exception ex)
{
return Json(new { Result = "Something wrong happened, try again. " + ex.Message });
}
}
public ActionResult FormsM()
{
Sys_Users activeuser = Session["activeUser"] as Sys_Users;
if (activeuser != null)
{
//HEADER
//PAGINAS ACTIVAS
ViewData["Menu"] = "Management";
ViewData["Page"] = "Forms";
ViewBag.menunameid = "manag_menu";
ViewBag.submenunameid = "forms_submenu";
List<string> d = new List<string>(activeuser.Departments.Split(new string[] { "," }, StringSplitOptions.None));
ViewBag.lstDepartments = JsonConvert.SerializeObject(d);
List<string> r = new List<string>(activeuser.Roles.Split(new string[] { "," }, StringSplitOptions.None));
ViewBag.lstRoles = JsonConvert.SerializeObject(r);
ViewData["nameUser"] = activeuser.Name + " " + activeuser.Lastname;
//NOTIFICATIONS
DateTime now = DateTime.Today;
List<Tb_Alerts> lstAlerts = (from a in dblim.Tb_Alerts where (a.ID_user == activeuser.ID_User && a.Active == true && a.Date == now) select a).OrderByDescending(x => x.Date).Take(5).ToList();
ViewBag.lstAlerts = lstAlerts;
var forms = (from a in dbcmk.FormsM where(a.ID_empresa==11) select a
);
foreach (var item in forms)
{
var tp = (from b in dbcmk.ActivitiesM_types where (b.ID_activity == item.ID_activity) select b).FirstOrDefault();
if (tp == null) { item.query1 = ""; }
else
{
item.query1 = tp.description;
}
}
ViewBag.ID_activity = new SelectList(dbcmk.ActivitiesM_types.Where(x=>x.ID_activity==1 || x.ID_activity==6), "ID_activity", "description");
//Seleccionamos los tipos de recursos a utilizar en el caso de Merchandising
List<string> uids = new List<string>() { "1", "3", "5", "6", "8", "9", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25","28","29","30","31","38" };
ViewBag.ID_formresourcetype = new SelectList(dbcmk.form_resource_type.Where(c => uids.Contains(c.ID_formresourcetype.ToString())).OrderBy(c => c.fdescription), "ID_formresourcetype", "fdescription");
//PARA RECURSOS DE RETAIL AUDIT O COLUMN
List<string> uidsColumn = new List<string>() { "16", "21", "3" };
ViewBag.ID_formresourcetypeRetail = new SelectList(dbcmk.form_resource_type.Where(c => uidsColumn.Contains(c.ID_formresourcetype.ToString())).OrderBy(c => c.fdescription), "ID_formresourcetype", "fdescription");
ViewBag.vendors = (from b in dlipro.OCRD where (b.Series == 61 && b.CardName != null && b.CardName != "") select b).OrderBy(b => b.CardName).ToList();
//ViewBag.displaylist = (from d in dbcmk.Items_displays where (d.ID_empresa == GlobalVariables.ID_EMPRESA_USUARIO) select d).ToList();
ViewBag.formslist = forms.ToList();
return View();
}
else
{
return RedirectToAction("Login", "Home", new { access = false });
}
}
//CREACION DE JERARQUIAS Y OBJETOS
//FORMULARIOS Y DETALLES DE FORMULARIOS (Se utiliza en Activities)
public class tablahijospadre
{
public int ID_details { get; set; }
public int id_resource { get; set; }
public string fsource { get; set; }
public string fdescription { get; set; }
public int fvalue { get; set; }
public decimal fvalueDecimal { get; set; }
public string fvalueText { get; set; }
public int ID_formM { get; set; }
public int ID_visit { get; set; }
public bool original { get; set; }
public int obj_order { get; set; }
public int obj_group { get; set; }
public int idkey { get; set; }
public int parent { get; set; }
public string query1 { get; set; }
public string query2 { get; set; }
public int ID_empresa { get; set; }
}
public class MyObj_tablapadre
{
public int ID_details { get; set; }
public int id_resource { get; set; }
public string fsource { get; set; }
public string fdescription { get; set; }
public int fvalue { get; set; }
public decimal fvalueDecimal { get; set; }
public string fvalueText { get; set; }
public int ID_formM { get; set; }
public int ID_visit { get; set; }
public bool original { get; set; }
public int obj_order { get; set; }
public int obj_group { get; set; }
public int idkey { get; set; }
public int parent { get; set; }
public string query1 { get; set; }
public string query2 { get; set; }
public int ID_empresa { get; set; }
public List<MyObj_tablapadre> children { get; set; }
}
public static List<MyObj_tablapadre> ObtenerCategoriarJerarquiaByID(List<MyObj_tablapadre> Categoriaspadre, List<tablahijospadre> Categoriashijas)
{
List<MyObj_tablapadre> query = (from item in Categoriaspadre
select new MyObj_tablapadre
{
ID_details = item.ID_details,
id_resource = item.id_resource,
fsource = item.fsource,
fdescription = item.fdescription,
fvalue = item.fvalue,
fvalueDecimal = item.fvalueDecimal,
fvalueText = item.fvalueText,
ID_formM = item.ID_formM,
ID_visit = item.ID_visit,
original = item.original,
obj_order = item.obj_order,
obj_group = item.obj_group,
idkey = item.idkey,
parent = item.parent,
query1 = item.query1,
query2 = item.query2,
ID_empresa = item.ID_empresa,
children = ObtenerHijosByID(item.idkey, Categoriashijas)
}).ToList();
return query;
}
private static List<MyObj_tablapadre> ObtenerHijosByID(int ID_parent, List<tablahijospadre> categoriashijas)
{
List<MyObj_tablapadre> query = (from item in categoriashijas
where item.parent == ID_parent
select new MyObj_tablapadre
{
ID_details = item.ID_details,
id_resource = item.id_resource,
fsource = item.fsource,
fdescription = item.fdescription,
fvalue = item.fvalue,
fvalueDecimal = item.fvalueDecimal,
fvalueText = item.fvalueText,
ID_formM = item.ID_formM,
ID_visit = item.ID_visit,
original = item.original,
obj_order = item.obj_order,
obj_group = item.obj_group,
idkey = item.idkey,
parent = item.parent,
query1 = item.query1,
query2 = item.query2,
ID_empresa = item.ID_empresa,
children = ObtenerHijosByID(item.idkey, categoriashijas)
}).ToList();
return query;
}
//CLASE PARA ALMACENAR OBJETOS
public class MyObj
{
public string id_resource { get; set; }
public string fsource { get; set; }
public string fdescription { get; set; }
public string fvalue { get; set; }
public int idkey { get; set; }
public int parent { get; set; }
public IList<MyObj> children { get; set; }
}
public ActionResult Template_preview(int? id)
{
if (cls_session.checkSession())
{
Sys_Users activeuser = Session["activeUser"] as Sys_Users;
//HEADER
//ACTIVE PAGES
ViewData["Menu"] = "Management";
ViewData["Page"] = "Form Builder Preview";
List<string> s = new List<string>(activeuser.Departments.Split(new string[] { "," }, StringSplitOptions.None));
ViewBag.lstDepartments = JsonConvert.SerializeObject(s);
List<string> r = new List<string>(activeuser.Roles.Split(new string[] { "," }, StringSplitOptions.None));
ViewBag.lstRoles = JsonConvert.SerializeObject(r);
//NOTIFICATIONS
DateTime now = DateTime.Today;
//List<Sys_Notifications> lstAlerts = (from a in db.Sys_Notifications where (a.ID_user == activeuser.ID_User && a.Active == true) select a).OrderByDescending(x => x.Date).Take(4).ToList();
//ViewBag.notifications = lstAlerts;
ViewBag.activeuser = activeuser;
//FIN HEADER
FormsM formsM = dbcmk.FormsM.Find(id);
//LISTADO DE CLIENTES
//VERIFICAMOS SI SELECCIONARON CLIENTE PREDEFINIDO
var customers = (from b in dlipro.OCRD where (b.Series == 61 && b.CardName != null && b.CardName != "") select b).OrderBy(b => b.CardName).ToList();
ViewBag.customers = customers.ToList();
//NUEVO
//ID VISIT SE UTILIZA COMO RELACION
List<MyObj_tablapadre> listapadresActivities = (from item in dbcmk.FormsM_details
where (item.ID_formM == id && item.parent == 0 && item.original == true)
select
new MyObj_tablapadre
{
ID_details = item.ID_details,
id_resource = item.ID_formresourcetype,
fsource = item.fsource,
fdescription = item.fdescription,
fvalue = item.fvalue,
fvalueDecimal = item.fvalueDecimal,
fvalueText = item.fvalueText,
ID_formM = item.ID_formM,
ID_visit = item.ID_visit,
original = item.original,
obj_order = item.obj_order,
obj_group = item.obj_group,
idkey = item.idkey,
parent = item.parent,
query1 = item.query1,
query2 = item.query2,
ID_empresa = item.ID_empresa
}
).ToList();
List<tablahijospadre> listahijasActivities = (from item in dbcmk.FormsM_details
where (item.ID_formM == id && item.original == true)
select new tablahijospadre
{
ID_details = item.ID_details,
id_resource = item.ID_formresourcetype,
fsource = item.fsource,
fdescription = item.fdescription,
fvalue = item.fvalue,
fvalueDecimal = item.fvalueDecimal,
fvalueText = item.fvalueText,
ID_formM = item.ID_formM,
ID_visit = item.ID_visit,
original = item.original,
obj_order = item.obj_order,
obj_group = item.obj_group,
idkey = item.idkey,
parent = item.parent,
query1 = item.query1,
query2 = item.query2,
ID_empresa = item.ID_empresa
}).ToList();
List<MyObj_tablapadre> categoriasListActivities = ObtenerCategoriarJerarquiaByID(listapadresActivities, listahijasActivities);
///
//Deserealizamos los datos
JavaScriptSerializer js = new JavaScriptSerializer();
MyObj[] details = js.Deserialize<MyObj[]>(formsM.query2);
ViewBag.idvisitareal = "0";
ViewBag.idvisita = "0";
ViewBag.details = categoriasListActivities;
ViewBag.detailssql = (from a in dbcmk.FormsM_details where (a.ID_formM == id && a.original == true) select a).ToList();
return View();
}
else
{
return RedirectToAction("Login", "Home", new { access = false });
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateSurvey(string ID_form, string ID_Vendor, string ID_rep)
{
try
{
int IDForm = Convert.ToInt32(ID_form);
//CREAMOS LA ESTRUCTURA DE LA ACTIVIDAD
Tasks nuevaActividad = new Tasks();
nuevaActividad.ID_formM = Convert.ToInt32(ID_form);
nuevaActividad.ID_Store = "";
nuevaActividad.store = "";
nuevaActividad.ID_brands = "";
nuevaActividad.Brands = "";
nuevaActividad.ID_Customer = ID_Vendor;
var vendor = (from c in dlipro.OCRD where (c.CardCode == ID_Vendor) select c).FirstOrDefault();
if (vendor != null)
{
nuevaActividad.Customer = vendor.CardName;
}
nuevaActividad.desnormalizado = false;
nuevaActividad.ID_Store = "";
nuevaActividad.store = "";
nuevaActividad.address = "";
nuevaActividad.city = "";
nuevaActividad.zipcode = "";
nuevaActividad.state = "";
nuevaActividad.geoLong = "";
nuevaActividad.geoLat = "";
//FIN
int idrepint = Convert.ToInt32(ID_rep);
nuevaActividad.ID_taskstatus = 3;
nuevaActividad.comments = "";
nuevaActividad.check_in = DateTime.Today.Date;
nuevaActividad.end_date = DateTime.Today.Date;
nuevaActividad.ID_empresa = 11;
nuevaActividad.ID_userCreate = 0;
nuevaActividad.visit_date = DateTime.Today.Date;
nuevaActividad.ID_formM = Convert.ToInt32(ID_form);
nuevaActividad.ID_userEnd = idrepint;
nuevaActividad.ID_ExternalUser = "";
nuevaActividad.extra_hours = 0;
//1 - Inventario
//2 - Survey
nuevaActividad.ID_taskType = 2;
nuevaActividad.TaskType = "UPDATE DATA FORM";
nuevaActividad.Task_description = "PEPPERI ONLINE CUSTOMER";
var usuario = (from a in dblim.Sys_Users where (a.ID_User == idrepint) select a).FirstOrDefault();
nuevaActividad.UserName = usuario.Name + " " + usuario.Lastname;
//guardamos
dbcmk.Tasks.Add(nuevaActividad);
dbcmk.SaveChanges();
//LUEGO ASIGNAMOS LA PLANTILLA DE FORMULARIO A LA ACTIVIDAD
//Guardamos el detalle
var detalles_acopiar = (from a in dbcmk.FormsM_details where (a.ID_formM == IDForm && a.original == true) select a).AsNoTracking().ToList();
List<FormsM_detailsTasks> targetList = detalles_acopiar.Select(c=> new FormsM_detailsTasks {
ID_details = c.ID_details,
ID_formresourcetype =c.ID_formresourcetype,
fsource = c.fsource,
fdescription=c.fdescription,
fvalue=c.fvalue,
fvalueDecimal=c.fvalueDecimal,
fvalueText=c.fvalueText,
ID_formM=c.ID_formM,
ID_visit= nuevaActividad.ID_task,
original=false,
obj_order=c.obj_order,
obj_group=c.obj_group,
idkey=c.idkey,
parent=c.parent,
query1=c.query1,
query2=c.query2,
ID_empresa=11
}).ToList();
dbcmk.BulkInsert(targetList);
TempData["exito"] = "Form created successfully.";
return RedirectToAction("SurveyFormC", "Commercial", new { id= nuevaActividad.ID_task});
}
catch (Exception ex)
{
TempData["advertencia"] = "Something wrong happened, try again." + ex.Message;
return RedirectToAction("SurveysC", "Commercial", null);
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateContact(string name, string lastname, string tel, string email, string position, string idcustomer)
{
try
{
var existe = 0;
var contacts = (from a in dlipro.BI_Contact_Person
where (a.Email==email)
select a).Count();
if (contacts > 0) { existe = 1; }
var contactsLocal = (from a in internadli.Tb_customerscontacts
where (a.Email == email && a.Accion !=3)
select a).Count();
if (contactsLocal > 0) { existe = 1; }
if (existe == 0)
{
Tb_customerscontacts newcontact = new Tb_customerscontacts();
newcontact.Name = name.ToUpper();
newcontact.LastName = lastname.ToUpper();
newcontact.Telephone = tel;
newcontact.Email = email.ToUpper();
newcontact.Position = position.ToUpper();
newcontact.Error = 0;
newcontact.ErrorMessage = "";
newcontact.DocEntry = "";
newcontact.IDSAP = 0;
newcontact.CardCode = idcustomer;
newcontact.Accion = 1;
newcontact.creationdate = DateTime.UtcNow;
internadli.Tb_customerscontacts.Add(newcontact);
internadli.SaveChanges();
TempData["exito"] = "Contact created successfully.";
return RedirectToAction("Contacts_details", "Commercial", new { id = idcustomer });
}
else {
TempData["advertencia"] = "This email is already registered.";
return RedirectToAction("Contacts_details", "Commercial", new { id = idcustomer });
}
}
catch (Exception ex)
{
TempData["advertencia"] = "Something wrong happened, try again." + ex.Message;
return RedirectToAction("Contacts_details", "Commercial", new { id = idcustomer });
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditContact(string nameED, string lastnameED, string telED, string emailED, string positionED, string idcustomerED, string idsapcontactED)
{
try
{
int idsapexiste = Convert.ToInt32(idsapcontactED);
var existe = internadli.Tb_customerscontacts.Where(a => a.IDSAP==idsapexiste).FirstOrDefault();
if (existe == null)
{
}
else {
internadli.Tb_customerscontacts.Remove(existe);
internadli.SaveChanges();
}
Tb_customerscontacts newcontact = new Tb_customerscontacts();
newcontact.Name = nameED.ToUpper();
newcontact.LastName = lastnameED.ToUpper();
newcontact.Telephone = telED;
newcontact.Email = emailED.ToUpper();
newcontact.Position = positionED.ToUpper();
newcontact.Error = 0;
newcontact.ErrorMessage = "";
newcontact.DocEntry = "";
newcontact.creationdate = DateTime.UtcNow;
newcontact.CardCode = idcustomerED;
newcontact.IDSAP = Convert.ToInt32(idsapcontactED);
newcontact.Accion = 2;
internadli.Tb_customerscontacts.Add(newcontact);
internadli.SaveChanges();
TempData["exito"] = "Contact saved successfully.";
return RedirectToAction("Contacts_details", "Commercial", new { id = idcustomerED });
}
catch (Exception ex)
{
TempData["advertencia"] = "Something wrong happened, try again." + ex.Message;
return RedirectToAction("Contacts_details", "Commercial", new { id = idcustomerED });
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteContact(string nameDEL, string lastnameDEL, string telDEL, string emailDEL, string positionDEL, string idcustomerDEL, string idsapcontactDEL)
{
try
{
int idsapexiste = Convert.ToInt32(idsapcontactDEL);
var existe = internadli.Tb_customerscontacts.Where(a => a.IDSAP == idsapexiste).FirstOrDefault();
if (existe == null)
{
}
else
{
internadli.Tb_customerscontacts.Remove(existe);
internadli.SaveChanges();
}
Tb_customerscontacts newcontact = new Tb_customerscontacts();
newcontact.Name = nameDEL.ToUpper();
newcontact.LastName = lastnameDEL.ToUpper();
newcontact.Telephone = telDEL;
newcontact.Email = emailDEL.ToUpper();
newcontact.Position = positionDEL.ToUpper();
newcontact.Error = 0;
newcontact.ErrorMessage = "";
newcontact.creationdate = DateTime.UtcNow;
newcontact.DocEntry = "";
newcontact.CardCode = idcustomerDEL;
newcontact.IDSAP = Convert.ToInt32(idsapcontactDEL);
newcontact.Accion = 3;
internadli.Tb_customerscontacts.Add(newcontact);
internadli.SaveChanges();
TempData["exito"] = "Contact deleted successfully.";
return RedirectToAction("Contacts_details", "Commercial", new { id = idcustomerDEL });
}
catch (Exception ex)
{
TempData["advertencia"] = "Something wrong happened, try again." + ex.Message;
return RedirectToAction("Contacts_details", "Commercial", new { id = idcustomerDEL });
}
}
public ActionResult DeleteTask(int id)
{
try
{
//Eliminamos detalle
var deletelist = (from a in dbcmk.FormsM_detailsTasks where (a.ID_visit == id) select a).ToList();
dbcmk.BulkDelete(deletelist);
Tasks activity = dbcmk.Tasks.Find(id);
dbcmk.Tasks.Remove(activity);
dbcmk.SaveChanges();
TempData["exito"] = "Survey deleted successfully.";
return RedirectToAction("Surveys", "Commercial", null);
}
catch (Exception ex)
{
TempData["advertencia"] = "Something wrong happened, try again." + ex.Message;
return RedirectToAction("Surveys", "Commercial", null);
}
}
}
} |
using System;
using System.Collections;
using System.ComponentModel;
using DelftTools.Utils;
using DelftTools.Utils.Collections;
using DelftTools.Utils.Data;
namespace DelftTools.Functions
{
///<summary>
/// Multi-dimensional array.
///
/// <remarks>
/// When values are accessed using <see cref="IList"/> index of the element is computed in the following way:
/// <c>index = sum { length(dimension(i)) * indexOf(dimension(i)) }</c>
/// </remarks>
///</summary>
public interface IMultiDimensionalArray : IList, ICloneable, INotifyPropertyChange, IUnique<long>
{
/// <summary>
/// Changes lenghts of the dimensions.
/// </summary>
/// <returns></returns>
void Resize(params int[] newShape);
/// <summary>
/// Gets value at the specified dimension index.
/// </summary>
object this[params int[] index] { get; set; }
#if MONO
new object this[int index] { get; set; }
#endif
/// <summary>
/// Total number of elements in array.
/// </summary>
new int Count { get; }
new void Clear();
new void RemoveAt(int index);
/// <summary>
/// Default value to be used when array is resized.
/// </summary>
object DefaultValue { get; set; }
/// <summary>
/// Gets lengths of the dimensions. Use Count to check total number of elements.
/// </summary>
/// <returns></returns>
int[] Shape { get; }
int[] Stride { get; }
/// <summary>
/// Gets rank (number of dimensions).
/// </summary>
int Rank { get; }
/// <summary>
/// Selects subset of an original array. Keeps reference to the parent array.
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns>View of the original array where reference to the parent array is in <see cref="IMultiDimensionalArrayView.Parent"/></returns>
IMultiDimensionalArrayView Select(int[] start, int[] end);
/// <summary>
/// Allows to select only specific part of the parent array.
/// </summary>
/// <param name="dimension"></param>
/// <param name="start">Start offset in the parent or <seealso cref="int.MinValue"/> if it is equal to the parent</param>
/// <param name="end">Start offset in the parent or <seealso cref="int.MaxValue"/> if it is equal to the parent</param>
/// <returns>View of the original array where reference to the parent array is in <see cref="IMultiDimensionalArrayView.Parent"/></returns>
IMultiDimensionalArrayView Select(int dimension, int start, int end);
/// <summary>
/// Selects subset of an original array based on dimension and indexes for that dimenion. Keeps reference to the parent array.
/// </summary>
/// <param name="dimension">Dimension to filter</param>
/// <param name="indexes">Indexes which will be selected</param>
/// <returns>View of the original array where reference to the parent array is in <see cref="IMultiDimensionalArrayView.Parent"/></returns>
IMultiDimensionalArrayView Select(int dimension, int[] indexes);
/// <summary>
/// Removes one slice on a given dimension, <see cref="index"/>.
/// </summary>
/// <param name="dimension">Dimension index</param>
/// <param name="index">Starting index</param>
void RemoveAt(int dimension, int index);
/// <summary>
/// Removes <see cref="length"/> slices on a given dimension, <see cref="index"/>.
/// </summary>
/// <param name="dimension">Dimension index</param>
/// <param name="index">Starting index</param>
/// <param name="length">Number of indexes to remove</param>
void RemoveAt(int dimension, int index, int length);
/// <summary>
/// Inserts one slice on a given dimension, at the <see cref="index"/>.
/// </summary>
/// <param name="dimension">Dimension index</param>
/// <param name="index">Index on the specified dimension</param>
void InsertAt(int dimension, int index);
/// <summary>
/// Inserts <see cref="length"/> slices on a given dimension starting at <see cref="index"/>.
/// </summary>
/// <param name="dimension">Dimension index</param>
/// <param name="index">Starting index</param>
/// <param name="length">Number of indexes to remove</param>
void InsertAt(int dimension, int index, int length);
/// <summary>
/// Moves <see cref="length"/> elements at the given <see cref="dimension"/> and <see cref="index"/> to a new index: <see cref="newIndex"/>
/// </summary>
/// <param name="dimension"></param>
/// <param name="index"></param>
/// <param name="length"></param>
/// <param name="newIndex"></param>
void Move(int dimension, int index, int length, int newIndex);
/// <summary>
/// CollectionChanging and CollectionChanged events are not fired when this property is false.
/// Default value is true - events are fired.
/// </summary>
bool FireEvents { get; set; }
/// <summary>
/// Adds elements to the end of array.
/// </summary>
/// <param name="values"></param>
void AddRange(IList values);
/// <summary>
/// TODO: remove it, higher-level logica
/// Gets the maximal value in the array or throws an exception if the array type is not support
/// </summary>
object MaxValue { get; }
/// <summary>
/// TODO: remove it, higher-level logica
/// Gets the minimal value in the array or throws an exception if the array type is not support
/// </summary>
object MinValue { get; }
/// <summary>
/// Determines whether the array maintains a sort by modifying inserts and updates to values.
/// Only works in 1D situations for now
/// </summary>
bool IsAutoSorted { get; set; }
event EventHandler<MultiDimensionalArrayChangingEventArgs> CollectionChanging;
event EventHandler<MultiDimensionalArrayChangingEventArgs> CollectionChanged;
/// <summary>
/// Insert a slices of value(s) for a given dimension
/// </summary>
/// <param name="dimension"></param>
/// <param name="index"></param>
/// <param name="length"></param>
/// <param name="valuesToInsert"></param>
/// <returns></returns>
int InsertAt(int dimension, int index, int length, IList valuesToInsert);
}
} |
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;
namespace ZM.TiledScreenDesigner.WinApp
{
public partial class frmGetRotation : Form
{
public frmGetRotation()
{
InitializeComponent();
lstOptions.Items.Add(Rotation.None);
lstOptions.Items.Add(Rotation.Clockwise90);
lstOptions.Items.Add(Rotation.Clockwise180);
lstOptions.Items.Add(Rotation.Clockwise270);
}
private void btnOk_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
this.Hide();
}
private void btnCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
this.Hide();
}
public static Rotation? GetRotation(Rotation source)
{
Rotation? result = null;
var f = new frmGetRotation();
f.lstOptions.SelectedItem = source;
f.ShowDialog();
if (f.DialogResult == DialogResult.OK)
result = (Rotation)f.lstOptions.SelectedItem;
f.Close();
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ejercicio_19
{
public class Sumador
{
private int cantidadSumas;
public Sumador(int cantidadSumas)
{
this.cantidadSumas = cantidadSumas;
}
public Sumador() : this(0) //reutiliza el anterior
{
}
public long Sumar(long a, long b)
{
this.cantidadSumas++;//suma una suma
return a+b;
}
public string Sumar(string a, string b)
{
this.cantidadSumas++;//suma una suma
return $"{a}{b}";
//return a+b; tambien esta bien
}
/// <summary>
/// Retorna cantidad de sumas de un sumador
/// </summary>
/// <param name="s"></param>
public static explicit operator int(Sumador s)
{
//recibe un sumador, devuelve un int
return s.cantidadSumas;
}
/// <summary>
/// Suma dos cantidades de sumas
/// </summary>
/// <param name="s1"></param>
/// <param name="s2"></param>
/// <returns></returns>
public static long operator +(Sumador s1, Sumador s2)
{
return s1.cantidadSumas + s2.cantidadSumas;
}
/// <summary>
/// Compara cantidad de sumas de dos sumadores
/// </summary>
/// <param name="s1"></param>
/// <param name="s2"></param>
/// <returns></returns>
public static bool operator |(Sumador s1, Sumador s2)
{
return (int)s1 == (int)s2;//utilizo el casteo que declare arriba
}
}
}
|
using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace GYOMU_CHECK
{
public partial class GC0050 : Form
{
private User user;
CommonUtil comU = new CommonUtil();
public bool torokuFlg = false;
bool errorFlg = false;
bool changeFlg = false;
bool headerChangeFlg = false;
private string sagyoState;
private string stateMode;
MySqlCommand command = new MySqlCommand();
public enum column
{
MST_SAGYO_CD,
MST_SAGYO_NAME,
MST_SAGYO_PARENT_FLG,
TRN_CHECK_B_DISUSE_FLG,
TRN_CHECK_B_DISUSE_FLG_OLD,
TRN_CHECK_B_SAGYO_STATUS,
STATUS_NAME,
TRN_CHECK_B_SAGYO_USER,
TRN_CHECK_B_SAGYO_DATE
}
public enum mode
{
INSERT,
UPDATE
}
int gamenMode;
string sagyoYYMM;
string gyomuCd;
string programId = "GC0050";
public GC0050(User user)
{
this.user = user;
gamenMode = (int)mode.INSERT;
InitializeComponent();
}
public GC0050(User user, string yyyyMM, string Cd, string state)
{
this.user = user;
gamenMode = (int)mode.UPDATE;
sagyoYYMM = comU.CReplace(yyyyMM);
gyomuCd = Cd;
stateMode = state;
InitializeComponent();
}
/// <summary>
/// 初期表示
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void GC0050_Load(object sender, EventArgs e)
{
Initialization();
lblUserNm.Text = user.Name;
}
private void Proto_FormClosing(object sender, FormClosingEventArgs e)
{
if (!errorFlg && !torokuFlg)
{
if (ChangeDetection())
{
DialogResult result = MessageBox.Show("内容が変更されています。 変更は破棄されますが、よろしいですか?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
//何が選択されたか調べる
if (result == DialogResult.Yes)
{
if (gamenMode == (int)mode.UPDATE)
{
DeleteHaita();
}
else
{
return;
}
}
else
{
e.Cancel = true;
}
}
else
{
if (gamenMode == (int)mode.UPDATE)
{
DeleteHaita();
}
}
}
}
/// <summary>
/// 初期化
/// </summary>
public void Initialization()
{
//新規の場合
if (gamenMode == (int)mode.INSERT)
{
DataSet dataSet = new DataSet();
if (!comU.CGyomu(ref dataSet, false))
{
errorFlg = true;
this.Close();
return;
}
pnlIns.Visible = true;
pnlUpd.Visible = false;
// コンボボックスにデータテーブルをセット
this.cmbKbn.DataSource = dataSet.Tables[0];
// 表示用の列を設定
this.cmbKbn.DisplayMember = "NAME";
//// データ用の列を設定
this.cmbKbn.ValueMember = "CD";
this.cmbKbn.SelectedIndex = -1;
//コンボボックス設定(年月)
DateTime dt = System.DateTime.Now;
cmbYear.DataSource = comU.CYear(false).ToArray();
cmbYear.Text = dt.ToString("yyyy");
cmbMonth.DataSource = comU.CMonth(false).ToArray();
cmbMonth.Text = dt.ToString("MM");
btnDelete.Visible = false;
btnInsert.Enabled = false;
lblUpd.Visible = false;
this.ActiveControl = this.cmbKbn;
}
//更新の場合
else
{
pnlIns.Visible = false;
pnlUpd.Visible = true;
lblYear.Text = sagyoYYMM.Substring(0, 4) + "/" + sagyoYYMM.Substring(4, 2);
string gyomuName ="";
GetGyomuName(ref gyomuName);
lblGyomu.Text = gyomuName;
btnDisply.Visible = false;
cmbYear.Enabled = false;
cmbMonth.Enabled = false;
cmbKbn.Enabled = false;
btnInsert.Text = "更新";
TorokuHaita();
DisplyUpdate();
}
}
private void GetGyomuName(ref string gyomuName)
{
StringBuilder sql = new StringBuilder();
sql.Append(" SELECT ");
sql.Append(" NAME");
sql.Append(" FROM mst_gyomu");
sql.Append(" WHERE ");
sql.Append(" DEL_FLG = 0 ");
sql.Append($" AND CD = {gyomuCd} ");
sql.Append(" ORDER BY ");
sql.Append(" HYOJI_JUN ");
DataSet ds = new DataSet();
if (!comU.CSerch(sql.ToString(), ref ds))
{
return;
}
if (ds.Tables["Table1"].Rows.Count != 0)
{
gyomuName = ds.Tables["Table1"].Rows[0]["NAME"].ToString();
}
else
{
return;
}
}
/// <summary>
/// 排他登録
/// </summary>
private void TorokuHaita()
{
MySqlTransaction transaction = null;
if (!comU.CConnect(ref transaction, ref command))
{
errorFlg = true;
return;
}
if (!comU.InsertHaitaTrn(transaction, ref command, sagyoYYMM, gyomuCd, user.Id, programId))
{
errorFlg = true;
Close();
}
else
{
transaction.Commit();
}
}
/// <summary>
/// 排他削除
/// </summary>
private void DeleteHaita()
{
MySqlTransaction transaction = null;
if (!comU.CConnect(ref transaction, ref command))
{
return;
}
if (!comU.DeleteHaitaTrn(transaction, ref command, sagyoYYMM, gyomuCd))
{
Close();
}
transaction.Commit();
command.Connection.Close();
}
/// <summary>
/// 戻るボタン
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnReturn_Click(object sender, EventArgs e)
{
this.Close();
}
/// <summary>
/// 作成ボタン
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCreate_Click(object sender, EventArgs e)
{
sagyoYYMM = cmbYear.SelectedValue.ToString() + cmbMonth.SelectedValue.ToString();
//業務の作成チェック
if (!SearchGyomu())
{
return;
}
if (dgvIchiran.RowCount != 0)
{
if (changeFlg)
{
DialogResult result = MessageBox.Show("内容が変更されています。 変更は破棄されますが、よろしいですか?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
//何が選択されたか調べる
if (result == DialogResult.No)
{
return;
}
}
}
Clear();
DisplyInsert();
}
/// <summary>
/// 業務検索
/// </summary>
/// <returns></returns>
private bool SearchGyomu()
{
StringBuilder sql = new StringBuilder();
sql.Append(" SELECT * ");
sql.Append(" FROM TRN_CHECK_H");
sql.Append($" WHERE GYOMU_CD = {cmbKbn.SelectedValue}");
sql.Append($" AND SAGYO_YYMM = {sagyoYYMM}");
if (this.cmbKbn.SelectedIndex == -1)
{
MessageBox.Show("業務を選択してください。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
DataSet ds = new DataSet();
if (!comU.CSerch(sql.ToString(), ref ds))
{
return false;
}
if (ds.Tables["Table1"].Rows.Count > 0)
{
MessageBox.Show("すでに作成済みの業務です。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
return true;
}
private void DisplyInsert()
{
StringBuilder sql = new StringBuilder();
sql.Append(" SELECT ");
sql.Append(" CD");
sql.Append(" ,NAME");
sql.Append(" ,PARENT_FLG");
sql.Append(" FROM mst_sagyo");
sql.Append(" WHERE DEL_FLG = 0");
sql.Append($" AND GYOMU_CD = {cmbKbn.SelectedValue}");
sql.Append(" ORDER BY HYOJI_JUN");
DataSet ds = new DataSet();
if (!comU.CSerch(sql.ToString(), ref ds))
{
btnInsert.Enabled = false;
return;
}
if (ds.Tables["Table1"].Rows.Count == 0)
{
MessageBox.Show("指定した業務の作業が登録されていません。\n\r作業マスタの登録を行ってください。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
btnInsert.Enabled = false;
return;
}
dgvIchiran.DataSource = ds.Tables[0];
btnInsert.Enabled = true;
headerChangeFlg = false;
changeFlg = false;
DataGridViewCheckBoxColumn dgvcbc = new DataGridViewCheckBoxColumn();
dgvcbc.Name = "実施要否";
dgvcbc.Width = 80;
dgvIchiran.Columns.Insert((int)column.TRN_CHECK_B_DISUSE_FLG, dgvcbc);
dgvcbc.TrueValue = true;
dgvcbc.FalseValue = false;
//一覧表示
dgvIchiran.Columns[(int)column.MST_SAGYO_CD].Visible = false;
dgvIchiran.Columns[(int)column.MST_SAGYO_PARENT_FLG].Visible = false;
dgvIchiran.Columns[(int)column.MST_SAGYO_NAME].HeaderText = "";
dgvIchiran.Columns[(int)column.MST_SAGYO_NAME].Width = 400;
//実施要否チェック済み
for (int i = 0; i < dgvIchiran.RowCount; i++)
{
if (i % 2 == 1)
{
dgvIchiran.Rows[i].DefaultCellStyle.BackColor = Color.LightBlue;
}
if ((bool)dgvIchiran[(int)column.MST_SAGYO_PARENT_FLG, i].Value)
{
dgvIchiran[(int)column.TRN_CHECK_B_DISUSE_FLG, i] = new DataGridViewTextBoxCell();
dgvIchiran[(int)column.TRN_CHECK_B_DISUSE_FLG, i].Value = "";
dgvIchiran.Rows[i].DefaultCellStyle.BackColor = Color.LightGreen;
dgvIchiran.Rows[i].ReadOnly = true;
}
else
{
DataGridViewCheckBoxCell cell = new DataGridViewCheckBoxCell();
dgvIchiran[2, i] = cell;
dgvIchiran[(int)column.TRN_CHECK_B_DISUSE_FLG, i].Value = true;
}
}
dgvIchiran.Columns[1].ReadOnly = true;
foreach (DataGridViewColumn column in this.dgvIchiran.Columns)
{
column.SortMode = DataGridViewColumnSortMode.NotSortable;
}
}
private void DisplyUpdate()
{
StringBuilder sql = new StringBuilder();
sql.Append(" SELECT ");
sql.Append(" TRN_CHECK_B.SAGYO_CD");
sql.Append(" ,MST_SAGYO.NAME");
sql.Append(" ,MST_SAGYO.PARENT_FLG");
sql.Append(" ,TRN_CHECK_B.DISUSE_FLG");
sql.Append(" ,TRN_CHECK_B.SAGYO_STATUS");
sql.Append(" ,CASE WHEN MST_SAGYO.PARENT_FLG = '1' THEN ''");
sql.Append(" WHEN trn_check_B.SAGYO_STATUS = '0' THEN '未着手'");
sql.Append(" WHEN trn_check_B.SAGYO_STATUS = '1' THEN '処理中'");
sql.Append(" ELSE '完了' END");
sql.Append(" ,TRN_CHECK_B.SAGYO_END_USER");
sql.Append(" ,TRN_CHECK_B.SAGYO_END_DATE");
sql.Append(" FROM TRN_CHECK_B");
sql.Append(" LEFT JOIN MST_SAGYO");
sql.Append(" ON TRN_CHECK_B.SAGYO_CD = MST_SAGYO.CD");
sql.Append(" WHERE MST_SAGYO.DEL_FLG = 0");
sql.Append($" AND TRN_CHECK_B.GYOMU_CD = {gyomuCd}");
sql.Append($" AND TRN_CHECK_B.SAGYO_YYMM = {sagyoYYMM}");
sql.Append(" ORDER BY MST_SAGYO.HYOJI_JUN");
DataSet ds = new DataSet();
if (!comU.CSerch(sql.ToString(), ref ds))
{
this.Close();
return;
}
if (ds.Tables["Table1"].Rows.Count == 0)
{
MessageBox.Show("指定した業務の作業が登録されていません。\n\r作業マスタの登録を行ってください。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
}
dgvIchiran.DataSource = ds.Tables[0];
//セルチェックボックス作成
DataGridViewCheckBoxColumn dgvcbc = new DataGridViewCheckBoxColumn();
dgvIchiran.Columns.Insert((int)column.TRN_CHECK_B_DISUSE_FLG, dgvcbc);
dgvcbc.TrueValue = true;
dgvcbc.FalseValue = false;
//一覧表示
dgvIchiran.Columns[(int)column.MST_SAGYO_CD].Visible = false;
dgvIchiran.Columns[(int)column.MST_SAGYO_PARENT_FLG].Visible = false;
dgvIchiran.Columns[(int)column.TRN_CHECK_B_DISUSE_FLG_OLD].Visible = false;
dgvIchiran.Columns[(int)column.TRN_CHECK_B_SAGYO_STATUS].Visible = false;
dgvIchiran.Columns[(int)column.TRN_CHECK_B_SAGYO_USER].Visible = false;
dgvIchiran.Columns[(int)column.TRN_CHECK_B_SAGYO_DATE].Visible = false;
dgvIchiran.Columns[(int)column.MST_SAGYO_NAME].HeaderText = "";
dgvIchiran.Columns[(int)column.MST_SAGYO_NAME].Width = 400;
dgvIchiran.Columns[(int)column.TRN_CHECK_B_DISUSE_FLG].HeaderText = "実施要否";
dgvIchiran.Columns[(int)column.STATUS_NAME].HeaderText = "状況";
dgvIchiran.Columns[(int)column.TRN_CHECK_B_DISUSE_FLG].Width = 80;
dgvIchiran.Columns[(int)column.MST_SAGYO_NAME].ReadOnly = true;
dgvIchiran.Columns[(int)column.STATUS_NAME].ReadOnly = true;
dgvIchiran.Columns[(int)column.STATUS_NAME].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
//明細背景色変更
for (int i = 0; i < dgvIchiran.RowCount; i++)
{
if (i % 2 == 1)
{
dgvIchiran.Rows[i].DefaultCellStyle.BackColor = Color.LightBlue;
}
//親作業の場合、背景色緑、テキスト非活性
if ((bool)dgvIchiran[(int)column.MST_SAGYO_PARENT_FLG, i].Value)
{
dgvIchiran[(int)column.TRN_CHECK_B_DISUSE_FLG, i] = new DataGridViewTextBoxCell();
dgvIchiran[(int)column.TRN_CHECK_B_DISUSE_FLG, i].Value = "";
dgvIchiran.Rows[i].DefaultCellStyle.BackColor = Color.LightGreen;
dgvIchiran.Rows[i].ReadOnly = true;
}
else
{
DataGridViewCheckBoxCell cell = new DataGridViewCheckBoxCell();
dgvIchiran[(int)column.TRN_CHECK_B_DISUSE_FLG, i] = cell;
dgvIchiran[(int)column.TRN_CHECK_B_DISUSE_FLG, i].Value = dgvIchiran[(int)column.TRN_CHECK_B_DISUSE_FLG_OLD, i].Value;
}
//STATUSが未実施以外の場合、編集不可
//「処理中」「完了」を赤文字
if ((string)dgvIchiran[(int)column.TRN_CHECK_B_SAGYO_STATUS, i].Value != "0")
{
dgvIchiran.Rows[i].ReadOnly = true;
dgvIchiran.Rows[i].Cells[(int)column.STATUS_NAME].Style.ForeColor = Color.Red;
}
}
foreach (DataGridViewColumn column in this.dgvIchiran.Columns)
{
column.SortMode = DataGridViewColumnSortMode.NotSortable;
}
}
/// <summary>
/// クリアボタン
/// </summary>
private void Clear()
{
if (dgvIchiran.RowCount != 0)
{
dgvIchiran.DataSource = null;
dgvIchiran.Rows.Clear();
dgvIchiran.Columns.Clear();
}
}
private void dgvIchiran_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1)
{
return;
}
if (e.ColumnIndex == (int)column.TRN_CHECK_B_DISUSE_FLG)
{
//変更フラグ
changeFlg = true;
}
}
private void btnInsert_Click(object sender, EventArgs e)
{
//新規の場合
if (gamenMode == (int)mode.INSERT)
{
if (headerChangeFlg)
{
MessageBox.Show("ヘッダーの値が変更されています。\n\r一覧の再表示を行ってください。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
Toroku();
}
}
else
{
Update();
}
}
/// <summary>
///更新処理
/// </summary>
private void Update()
{
if (!CheckToroku())
{
return;
}
DialogResult result = MessageBox.Show("更新を行います。よろしいでしょうか。?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
//何が選択されたか調べる
if (result == DialogResult.Yes)
{
//変更が行われていない場合
if (!ChangeDetection())
{
MessageBox.Show("明細が変更されていません。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
MySqlTransaction transaction = null;
if (!comU.CConnect(ref transaction, ref command))
{
return;
}
if (CheckUpdateGyomuHeader())
{
if (!UpdateGyomuCheckHeader(transaction))
{
MessageBox.Show("業務チェックヘッダの更新に失敗しました。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
if (!UpdateGyomuCheckBody(transaction))
{
MessageBox.Show("業務チェック明細の更新に失敗しました。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
transaction.Commit();
MessageBox.Show("更新が完了しました。", "");
if (gamenMode == (int)mode.UPDATE)
{
DeleteHaita();
}
torokuFlg = true;
this.Close();
}
}
private bool UpdateGyomuCheckHeader(MySqlTransaction transaction)
{
String sagyoDate = null;
String sagyoUser = null;
if (stateMode != "2")
{
if (sagyoState == "1")
{
DataSet ds = new DataSet();
if (!GetCheckMeisai(ref ds))
{
return false;
}
sagyoUser = ds.Tables["Table1"].Rows[0]["SAGYO_START_USER"].ToString();
sagyoDate = ((DateTime)ds.Tables["Table1"].Rows[0]["SAGYO_START_DATE"]).ToString("yyyyMMdd");
}
else
{
DataSet ds = new DataSet();
if (!GetCheckMeisai(ref ds))
{
return false;
}
sagyoUser = ds.Tables["Table1"].Rows[0]["SAGYO_END_USER"].ToString();
sagyoDate = ((DateTime)ds.Tables["Table1"].Rows[0]["SAGYO_END_DATE"]).ToString("yyyyMMdd");
}
}
StringBuilder sql = new StringBuilder();
sql.Append(" UPDATE TRN_CHECK_H ");
sql.Append($" SET SAGYO_STATUS = {sagyoState}");
//完了モードの場合最終作業を更新しない
if (stateMode != "2")
{
sql.Append($" , SAGYO_LAST_USER = {sagyoUser} ");
sql.Append($" , SAGYO_LAST_DATE = {sagyoDate} ");
}
sql.Append(" , UPD_DT = now() ");
sql.Append($" , UPD_USER = {user.Id} ");
sql.Append($" , UPD_PGM = {comU.CAddQuotation(programId)} ");
sql.Append($" WHERE GYOMU_CD = {gyomuCd}");
sql.Append($" AND SAGYO_YYMM = {sagyoYYMM}");
if (!comU.CExecute(ref transaction, ref command, sql.ToString()))
{
return false;
}
return true;
}
private bool GetCheckMeisai(ref DataSet ds)
{
StringBuilder sql = new StringBuilder();
sql.Append(" SELECT ");
sql.Append(" SAGYO_START_USER");
sql.Append(" ,SAGYO_START_DATE");
sql.Append(" ,SAGYO_END_USER");
sql.Append(" ,SAGYO_END_DATE");
sql.Append(" FROM TRN_CHECK_B");
sql.Append($" WHERE SAGYO_STATUS = {sagyoState}");
sql.Append($" AND GYOMU_CD = {gyomuCd}");
sql.Append($" AND SAGYO_YYMM = {sagyoYYMM}");
if (sagyoState == "1")
{
sql.Append(" ORDER BY SAGYO_START_DATE desc");
}
else
{
sql.Append(" ORDER BY SAGYO_END_DATE desc");
}
if (!comU.CSerch(sql.ToString(), ref ds))
{
return false;
}
return true;
}
private bool CheckUpdateGyomuHeader()
{
for (int i = 0; i <= dgvIchiran.Rows.Count - 1; i++)
{
//親項目の場合スキップ
if ((bool)dgvIchiran[(int)column.MST_SAGYO_PARENT_FLG, i].Value)
{
continue;
}
//実施する
if ((bool)dgvIchiran[(int)column.TRN_CHECK_B_DISUSE_FLG, i].Value)
{
//未実施の場合
if ((string)dgvIchiran[(int)column.TRN_CHECK_B_SAGYO_STATUS, i].Value == "0")
{
//完了状態から実施する業務を追加する/場合
if (stateMode == "2")
{
sagyoState = "1";
return true;
}
return false;
}
//処理中の場合
else if ((string)dgvIchiran[(int)column.TRN_CHECK_B_SAGYO_STATUS, i].Value == "1")
{
sagyoState = "1";
return true;
}
else
{
continue;
}
}
else
{
continue;
}
}
//すべてが完了済み、または実施不要
sagyoState = "2";
return true;
}
private bool UpdateGyomuCheckBody(MySqlTransaction transaction)
{
bool flg = true;
for (int i = 0; i <= dgvIchiran.Rows.Count - 1; i++)
{
//親項目の場合スキップ
if ((bool)dgvIchiran[(int)column.MST_SAGYO_PARENT_FLG, i].Value)
{
continue;
}
///変更のあった行のみを対象
if ((bool)dgvIchiran[(int)column.TRN_CHECK_B_DISUSE_FLG, i].Value)
{
if ((bool)dgvIchiran[(int)column.TRN_CHECK_B_DISUSE_FLG_OLD, i].Value)
{
continue;
}
}
else
{
if (!(bool)dgvIchiran[(int)column.TRN_CHECK_B_DISUSE_FLG_OLD, i].Value)
{
continue;
}
}
StringBuilder sql = new StringBuilder();
sql.Append(" UPDATE TRN_CHECK_B ");
sql.Append($" SET DISUSE_FLG = {dgvIchiran[(int)column.TRN_CHECK_B_DISUSE_FLG, i].Value}");
sql.Append(" , UPD_DT = now() ");
sql.Append($" , UPD_USER = {user.Id} ");
sql.Append($" , UPD_PGM = {comU.CAddQuotation(programId)} ");
sql.Append($" WHERE GYOMU_CD = {gyomuCd}");
sql.Append($" AND SAGYO_YYMM = {sagyoYYMM}");
sql.Append($" AND SAGYO_CD = {dgvIchiran[(int)column.MST_SAGYO_CD, i].Value}");
if (!comU.CExecute(ref transaction, ref command, sql.ToString()))
{
flg = false;
break;
}
}
return flg;
}
private void Toroku()
{
if (!CheckToroku())
{
return;
}
DialogResult result = MessageBox.Show("登録を行います。よろしいでしょうか。?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
//何が選択されたか調べる
if (result == DialogResult.Yes)
{
MySqlTransaction transaction = null;
if (!comU.CConnect(ref transaction, ref command))
{
return;
}
if (!InsertGyomuCheckHeader(transaction))
{
MessageBox.Show("業務チェックヘッダの作成に失敗しました。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!InsertGyomuCheckBody(transaction))
{
MessageBox.Show("業務チェック明細の作成に失敗しました。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
transaction.Commit();
MessageBox.Show("登録が完了しました。", "");
torokuFlg = true;
this.Close();
}
}
private bool CheckToroku()
{
for (int i = 0; i < dgvIchiran.RowCount; i++)
{
if ((bool)dgvIchiran[(int)column.MST_SAGYO_PARENT_FLG, i].Value)
{
continue;
}
if ((bool)dgvIchiran[(int)column.TRN_CHECK_B_DISUSE_FLG, i].Value)
{
return true;
}
}
MessageBox.Show("実施要否は1つ以上選択してください。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
private bool InsertGyomuCheckHeader(MySqlTransaction transaction)
{
StringBuilder sql = new StringBuilder();
sql.Append(" INSERT INTO TRN_CHECK_H ");
sql.Append(" (GYOMU_CD ");
sql.Append(" ,SAGYO_YYMM ");
sql.Append(" ,SAGYO_STATUS ");
sql.Append(" ,INS_DT ");
sql.Append(" ,INS_USER ");
sql.Append(" ,INS_PGM ");
sql.Append(" ,UPD_DT ");
sql.Append(" ,UPD_USER ");
sql.Append(" ,UPD_PGM) ");
sql.Append(" VALUES ");
sql.Append($" ({comU.CAddQuotation(cmbKbn.SelectedValue.ToString())} ");
sql.Append($" ,{sagyoYYMM} ");
sql.Append(" ,0 ");
sql.Append(" ,now() ");
sql.Append($" ,{user.Id} ");
sql.Append($" ,{comU.CAddQuotation(programId)} ");
sql.Append(" ,now() ");
sql.Append($" ,{user.Id} ");
sql.Append($" ,{comU.CAddQuotation(programId)}) ");
if (!comU.CExecute(ref transaction, ref command, sql.ToString()))
{
return false;
}
return true;
}
private bool InsertGyomuCheckBody(MySqlTransaction transaction)
{
bool flg = true;
for (int i = 0; i <= dgvIchiran.Rows.Count - 1; i++)
{
StringBuilder sql = new StringBuilder();
sql.Append(" INSERT INTO TRN_CHECK_B ");
sql.Append(" (GYOMU_CD ");
sql.Append(" ,SAGYO_YYMM ");
sql.Append(" ,SAGYO_CD ");
sql.Append(" ,SAGYO_STATUS ");
sql.Append(" ,DISUSE_FLG ");
sql.Append(" ,INS_DT ");
sql.Append(" ,INS_USER ");
sql.Append(" ,INS_PGM ");
sql.Append(" ,UPD_DT ");
sql.Append(" ,UPD_USER ");
sql.Append(" ,UPD_PGM) ");
sql.Append(" VALUES ");
sql.Append($" ({comU.CAddQuotation(cmbKbn.SelectedValue.ToString())} ");
sql.Append($" ,{sagyoYYMM} ");
sql.Append($" ,{comU.CAddQuotation(dgvIchiran.Rows[i].Cells[(int)column.MST_SAGYO_CD].Value.ToString())} ");
sql.Append(" ,0 ");
if ((bool)dgvIchiran[(int)column.MST_SAGYO_PARENT_FLG, i].Value)
{
sql.Append(" ,false ");
}
else
{
sql.Append($" ,{dgvIchiran.Rows[i].Cells[(int)column.TRN_CHECK_B_DISUSE_FLG].Value} ");
}
sql.Append(" ,now() ");
sql.Append($" ,{user.Id} ");
sql.Append($" ,{comU.CAddQuotation(programId)} ");
sql.Append(" ,now() ");
sql.Append($" ,{user.Id} ");
sql.Append($" ,{comU.CAddQuotation(programId)}) ");
if (!comU.CExecute(ref transaction, ref command, sql.ToString()))
{
flg = false;
break;
}
}
return flg;
}
private void btnDelete_Click(object sender, EventArgs e)
{
MySqlTransaction transaction = null;
DialogResult result = MessageBox.Show("削除を行います。よろしいでしょうか。?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
//何が選択されたか調べる
if (result == DialogResult.Yes)
{
if (CheckSagyoStart())
{
DialogResult dialogResult = MessageBox.Show("作業開始済みの作業が含まれます。よろしいでしょうか。?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
//何が選択されたか調べる
if (dialogResult == DialogResult.No)
{
return;
}
}
if (!comU.CConnect(ref transaction, ref command))
{
return;
}
if (!DeleteGyomuCheckHeader(transaction))
{
MessageBox.Show("業務チェックヘッダの削除に失敗しました。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!DelteGyomuCheckBody(transaction))
{
MessageBox.Show("業務チェック明細の削除に失敗しました。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
transaction.Commit();
if (gamenMode == (int)mode.UPDATE)
{
DeleteHaita();
}
torokuFlg = true;
MessageBox.Show("削除が完了しました。", "");
this.Close();
}
}
private bool DeleteGyomuCheckHeader(MySqlTransaction transaction)
{
StringBuilder sql = new StringBuilder();
sql.Append(" DELETE FROM TRN_CHECK_H ");
sql.Append($" WHERE GYOMU_CD = {gyomuCd}");
sql.Append($" AND SAGYO_YYMM = {sagyoYYMM}");
if (!comU.CExecute(ref transaction, ref command, sql.ToString()))
{
return false;
}
return true;
}
private bool DelteGyomuCheckBody(MySqlTransaction transaction)
{
bool flg = true;
for (int i = 0; i <= dgvIchiran.Rows.Count - 1; i++)
{
StringBuilder sql = new StringBuilder();
sql.Append(" DELETE FROM TRN_CHECK_B ");
sql.Append($" WHERE GYOMU_CD = {gyomuCd}");
sql.Append($" AND SAGYO_YYMM = {sagyoYYMM}");
if (!comU.CExecute(ref transaction, ref command, sql.ToString()))
{
flg = false;
break;
}
}
return flg;
}
private bool ChangeDetection()
{
//新規の場合
if (gamenMode == (int)mode.INSERT)
{
return changeFlg;
}
for (int i = 0; i <= dgvIchiran.Rows.Count - 1; i++)
{
if ((bool)dgvIchiran[(int)column.MST_SAGYO_PARENT_FLG, i].Value)
{
continue;
}
if ((bool)dgvIchiran[(int)column.TRN_CHECK_B_DISUSE_FLG, i].Value & !(bool)dgvIchiran[(int)column.TRN_CHECK_B_DISUSE_FLG_OLD, i].Value)
{
return true;
}
if (!(bool)dgvIchiran[(int)column.TRN_CHECK_B_DISUSE_FLG, i].Value & (bool)dgvIchiran[(int)column.TRN_CHECK_B_DISUSE_FLG_OLD, i].Value)
{
return true;
}
}
return false;
}
private bool CheckSagyoStart()
{
for (int i = 0; i <= dgvIchiran.Rows.Count - 1; i++)
{
if ((bool)dgvIchiran[(int)column.MST_SAGYO_PARENT_FLG, i].Value)
{
continue;
}
else if ((string)dgvIchiran[(int)column.TRN_CHECK_B_SAGYO_STATUS, i].Value != "0")
{
return true;
}
}
return false;
}
private void cmbYear_SelectedIndexChanged(object sender, EventArgs e)
{
headerChangeFlg = true;
}
private void cmbMonth_SelectedIndexChanged(object sender, EventArgs e)
{
headerChangeFlg = true;
}
private void cmbKbn_SelectedIndexChanged(object sender, EventArgs e)
{
headerChangeFlg = true;
}
}
}
|
namespace Motherload.Interfaces.Unity
{
/// <summary>
/// Lida com carregamento dos Resources
/// </summary>
public interface IResourceLoader
{
/// <summary>
/// Carrega um arquivo json da pasta Assets/Resources
/// </summary>
/// <param name="path">Caminho para o resource</param>
/// <returns></returns>
string LoadJson(string path);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NetNote.Models;
using NetNote.Repository;
using NetNote.ViewModels;
namespace NetNote.Api
{
[Route("api/note")]
public class NoteApiController : Controller
{
private INoteRepository _noteRepository;
private INoteTypeRepository _noteTypeRepository;
public NoteApiController(INoteRepository noteRepository, INoteTypeRepository noteTypeRepository)
{
_noteRepository = noteRepository;
_noteTypeRepository = noteTypeRepository;
}
// GET: api/note
[HttpGet]
public async Task<IActionResult> Get(int pageindex = 1)
{
var pagesize = 10;
var notes = await _noteRepository.PageListAsync(pageindex, pagesize);
ViewBag.PageCount = notes.Item2;
ViewBag.PageIndex = pageindex;
var result = notes.Item1.Select(r => new NoteDTO
{
Id = r.Id,
Title = string.IsNullOrEmpty(r.Password) ? r.Title : "加密内容",
Content = string.IsNullOrEmpty(r.Password) ? r.Content : "",
Attachment = string.IsNullOrEmpty(r.Password) ? r.Attachment : "",
Type = r.Type.Name
});
return Ok(result);
}
// GET api/note/5
// GET api/note/5?password=123
[HttpGet("{id}")]
public async Task<IActionResult> Detail(int id, string password)
{
var note = await _noteRepository.GetByIdAsync(id);
if (note == null)
return NotFound();
if (!string.IsNullOrEmpty(note.Password) && !note.Password.Equals(password))
return Unauthorized();
var result = new NoteDTO
{
Id = note.Id,
Title = note.Title,
Content = note.Content,
Attachment = note.Attachment,
Type = note.Type.Name
};
return Ok(result);
}
// POST api/note
[HttpPost]
public async Task<IActionResult> Post([FromBody]NoteModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
string filename = string.Empty;
await _noteRepository.AddAsync(new Note
{
Title = model.Title,
Content = model.Content,
Create = DateTime.Now,
TypeId = model.Type,
Password = model.Password,
Attachment = filename
});
return CreatedAtAction("Index", "");
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Responsible for initializing the text in the winner scene
/// along with background music.
/// </summary>
public class WinnerSceneGui : MonoBehaviour
{
/// <summary>
/// Initializes dynamic text in the winner scene
/// along with background music.
/// </summary>
void Start()
{
// SET THE TEXT IDENTIFYING THE WINNING TEAM.
Text winningTeamText = GameObject.Find("WinnerText").GetComponent<Text>();
switch (Referee.Winner)
{
case Referee.WinnerType.LEFT_TEAM:
winningTeamText.text = "LEFT TEAM WINS!";
break;
case Referee.WinnerType.RIGHT_TEAM:
winningTeamText.text = "RIGHT TEAM WINS!";
break;
case Referee.WinnerType.TIE:
winningTeamText.text = "TIED GAME";
break;
default:
// Leave the text alone to make it easier to debug errors.
break;
}
// SET THE LEFT TEAM'S SCORE.
Text leftTeamScoreText = GameObject.Find("LeftTeamScoreText").GetComponent<Text>();
leftTeamScoreText.text = "Left Team Score: " + Referee.LeftTeamScore.ToString();
// SET THE RIGHT TEAM'S SCORE.
Text rightTeamScoreText = GameObject.Find("RightTeamScoreText").GetComponent<Text>();
rightTeamScoreText.text = "Right Team Score: " + Referee.RightTeamScore.ToString();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _10.CalculateSumAccuracy
{
class CalculateAccuracy
{
static void Main()
{
double firstNum = 3d;
double secondNum = 2d;
double sumFirst = 0.0d, sumSecond = 0.0d;
double sum;
for (int index = 0; index < 5000; index++)
{
sumSecond = sumSecond + (1d / firstNum);
firstNum = firstNum + 2d;
sumFirst = sumFirst + (1d / secondNum);
secondNum = secondNum + 2d;
}
sum = 1.0d + sumFirst - sumSecond;
Console.WriteLine("The sum of the numbers with required accuracy is: {0:F3}", sum);
}
}
}
|
using System;
using Utilities;
namespace EddiEvents
{
[PublicAPI]
public class RespawnedEvent : Event
{
public const string NAME = "Respawned";
public const string DESCRIPTION = "Triggered when you respawn (either after injury or after handing yourself in to local authorities)";
public const string SAMPLE = @"{ ""timestamp"":""2016-09-20T12:27:59Z"", ""event"":""Resurrect"", ""Option"":""rebuy"", ""Cost"":36479, ""Bankrupt"":false }";
[PublicAPI("The action triggering the respawn. One of 'rebuy', 'recover', 'rejoin', or 'handin'")]
public string trigger { get; private set; }
[PublicAPI("The price paid to complete the respawn, if any")]
public long price { get; private set; }
public RespawnedEvent(DateTime timestamp, string option, long price) : base(timestamp, NAME)
{
this.trigger = option;
this.price = price;
}
}
} |
using UnityEngine;
[RequireComponent(typeof(Collider))]
[RequireComponent(typeof(Rigidbody))]
public class TRex : MonoBehaviour
{
public float rushSpeed;
public float timeUntilRush;
private float initRushTime;
private bool rushing = false;
private bool outOfPoint = false;
private Collider collider;
private Rigidbody rb;
public GameObject tRexStill;
public GameObject tRexWalking;
public Transform rushPoint;
private Vector3 initPosition;
private Quaternion initRotation;
private Vector3 rushDirection;
private void Awake()
{
initRushTime = timeUntilRush;
collider = GetComponent<Collider>();
rb = GetComponent<Rigidbody>();
initPosition = transform.position;
initRotation = transform.rotation;
tRexStill.SetActive(true);
tRexWalking.SetActive(false);
}
private void Start()
{
rushDirection = rushPoint.position - initPosition;
rushDirection.Normalize();
}
private void OnTriggerEnter(Collider col)
{
if (col.gameObject.CompareTag("Player"))
{
Destroy(col.gameObject);
}
}
private void Update()
{
if (0.0f < timeUntilRush)
{
timeUntilRush -= Time.deltaTime;
}
else if (!rushing)
{
rushing = true;
if (collider.bounds.Contains(initPosition))
{
rb.velocity = rushDirection * rushSpeed;
}
else if (collider.bounds.Contains(rushPoint.position))
{
rb.velocity = -rushDirection * rushSpeed;
}
tRexStill.SetActive(false);
tRexWalking.SetActive(true);
}
else if (rushing && !outOfPoint)
{
if (!collider.bounds.Contains(initPosition) &&
!collider.bounds.Contains(rushPoint.position))
{
outOfPoint = true;
}
}
else if (rushing && outOfPoint)
{
if (collider.bounds.Contains(initPosition) ||
collider.bounds.Contains(rushPoint.position))
{
rb.velocity = Vector3.zero;
timeUntilRush = initRushTime;
outOfPoint = false;
rushing = false;
if (collider.bounds.Contains(initPosition))
{
transform.position = initPosition;
transform.rotation = initRotation;
}
else
{
transform.position = rushPoint.position;
transform.rotation = new Quaternion(
transform.rotation.x,
transform.rotation.y + 180,
transform.rotation.z,
0.0f
);
}
tRexStill.SetActive(true);
tRexWalking.SetActive(false);
}
}
}
}
|
using DChild.Gameplay.Objects.Characters;
using Sirenix.OdinInspector;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace DChild.Gameplay.Combat.StatusEffects
{
public class HealthRegeneration : MonoBehaviour
{
[SerializeField]
private float m_duration;
[SerializeField]
private int m_regenValue;
private Character m_character;
private float m_durationTimer;
public void SetDuration(float duration)
{
m_duration = duration;
m_durationTimer = duration;
enabled = true;
StopAllCoroutines();
StartCoroutine(Seconds());
}
private IEnumerator Seconds()
{
do
{
m_character.health.Heal(m_regenValue);
Debug.Log(m_regenValue);
yield return new WaitForSeconds(1);
} while (m_durationTimer > 0);
}
private void Awake()
{
m_character = GetComponentInParent<Character>();
m_durationTimer = 0f;
enabled = false;
}
private void Update()
{
if (m_durationTimer > 0)
{
m_durationTimer -= Time.deltaTime;
if(m_durationTimer < 0)
{
enabled = false;
}
}
}
//Temp
#if UNITY_EDITOR
[Button("Regenerate")]
private void Stop()
{
SetDuration(m_duration);
}
#endif
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Rwd.Framework.Extensions
{
public static class NumberExtensions
{
public static int ToInt(this decimal number)
{
return (int)number;
}
public static int IntTryParse(this string text)
{
var newInt = 0;
int.TryParse(text, out newInt);
return newInt;
}
public static string ToCardinal(this int number)
{
string suffix = string.Empty;
var numberStr = number.ToString();
var lastDigit = int.Parse(numberStr.Substring(numberStr.Length - 1, 1));
switch (lastDigit)
{
case 1:
suffix = "st";
break;
case 2:
suffix = "nd";
break;
case 3:
suffix = "rd";
break;
default:
suffix = "th";
break;
}
if (numberStr.Length > 1)
{
var lastTwoDigits = int.Parse(numberStr.Substring(numberStr.Length - 2, 2));
if (11 <= lastTwoDigits && lastTwoDigits <= 13) suffix = "th";
}
return number.ToString() + suffix;
}
public static string ToMoney(this decimal number)
{
return string.Format("{0:c}", number);
}
}
}
|
using System;
namespace PT
{
class Program
{
static void Main(string[] args)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
for (int i = 0; i < 250000; i++)
{
Console.WriteLine(1);
}
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Exemplo.Application.ViewModel;
namespace Exemplo.Application.Service
{
public interface IContatoService
{
Task<IEnumerable<ContatoViewModel>> GetAll();
Task<ContatoViewModel> RetornaPorId(int id);
Task<ContatoViewModel> Incluir(ContatoViewModel obj);
Task<ContatoViewModel> Desativar(int id);
Task<ContatoViewModel> Excluir(int id);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chapter03_03
{
class CPoint2<T>
{
private T theX;
private T theY;
public CPoint2()
{
}
public CPoint2(T aX, T aY)
{
theX = aX;
theY = aY;
}
public void SetXY(T aX, T aY)
{
theX = aX;
theY = aY;
}
public T GetX()
{
return (theX);
}
public T GetY()
{
return (theY);
}
public T X
{
get
{
return (theX);
}
set
{
theX = value;
}
}
public T Y
{
get
{
return (theY);
}
set
{
theY = value;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
using System.IO;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public static GameManager gameManager;
[SerializeField] private float money;
public Text moneyText;
private int StudentCount;
Text StudentCountText;//"StudentCount"
Vector3 LocationOfSpawn=new Vector3(6,1,2);
public static GameManager instance = null;
string[] Clasesbogth;
//Percy wtf is Haking? like stealing paswoords type of shit
string[] AvalableClases= {"Magic","Surfing","Hacking","Axe Trowing"};
List<string> Clases;
[Header("Student Prefab Toinstanciate")]
[SerializeField]private GameObject Student;
private void Awake()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(gameObject);
}
}
void Start()
{
gameManager = this; //only one
UpdateUI();
StudentCountText =GameObject.FindGameObjectWithTag("StudentCount").GetComponent<Text>();
}
void Update()
{
RefreshTextOnUI();
UpdateUI();
}
/// money
public void AddMoney(float amount)
{
money += amount;
UpdateUI();
}
public void ReduceMoney(float amount)
{
money -= amount;
UpdateUI();
}
public bool RequestMoney(float amount)
{
if (amount <= money)
{
return true;
}
return false;
}
void UpdateUI()
{
moneyText.text = "$ " + money.ToString("N0");
}
/// student
public void AddStudent()
{
StudentCount++;
}
public void RefreshTextOnUI()
{
StudentCountText.text = "Students: "+StudentCount;
}
public void Spawn(InputAction.CallbackContext context)
{
if (context.performed)
{
Instantiate(Student, LocationOfSpawn, Quaternion.identity);
}
}
}
|
using UnityEngine;
public class Credits: MonoBehaviour
{
public delegate void BackButtonClickedEvent();
[SerializeField]
private Canvas canvas;
[SerializeField]
private Camera camera;
[SerializeField]
private AutoScroll scroll;
[SerializeField]
private AutoPlayAnimations playAnimations;
public void Show()
{
canvas.gameObject.SetActive(true);
camera.gameObject.SetActive(true);
scroll.Restart();
playAnimations.Restart();
}
public void Hide()
{
camera.gameObject.SetActive(false);
canvas.gameObject.SetActive(false);
}
#region GUI Event Handlers
public void btnBack_OnClick()
{
OnBackButtonClicked();
}
#endregion
#region MonoBehaviour
void Awake()
{
GameSystem.RegisterModule(this);
Hide();
}
void OnDestroy()
{
BackButtonClicked = null;
}
#endregion
#region Delegates
public BackButtonClickedEvent BackButtonClicked;
protected void OnBackButtonClicked()
{
var handler = BackButtonClicked;
if (handler != null)
handler();
}
#endregion
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
interface IPlayerWeapon
{
int DamageValue
{
get;
set;
}
void OnAttackEvent();
Collider AttackHitBox
{
get;
set;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour
{
Rigidbody rb;
float pnoise;
float searchspeed;
float attackspeed;
float damagedist;
float incr;
int walking;
bool seenyou;
MeshCollider sight;
Collider player;
void Start()
{
damagedist = 1;
searchspeed = 15;
attackspeed = 4.5f;
rb = GetComponent<Rigidbody>();
incr = (int)(Random.value * 1000);
sight = GetComponent<MeshCollider>();
}
void Update()
{
if (!seenyou)
{
Search();
}
else
{
Attack();
}
}
void Search()
{
if (Random.value > 0.7)
{
walking = 1;
}
else
{
walking = 0;
}
rb.AddRelativeForce(walking * searchspeed, 0, 0);
transform.Rotate(new Vector3(0, (Mathf.PerlinNoise((incr + 500) / 1000, (incr + 400) / 1000) - 0.5f), 0));
incr += 1;
}
void Attack()
{
transform.LookAt(player.transform);
transform.position += transform.forward * attackspeed * Time.deltaTime;
if (Vector3.Distance(transform.position, player.transform.position) <= damagedist)
{
player.gameObject.GetComponent<PlayerHealth>().health -= 3;
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "player")
{
seenyou = true;
player = other;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "player")
{
seenyou = false;
player = null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HomeWork5
{
class Program
{
static void Main(string[] args)
{
//проверяем является ли число степенью двойки//
int x = 0;
int s;
Console.WriteLine("Введите число: ");
x =Convert.ToInt32(Console.ReadLine());
s = x & (x - 1);
if (s==0)
{
Console.WriteLine(" число является степенью двойки");
}
else
{
Console.WriteLine(" число не является степенью двойки");
}
Console.ReadKey();
}
}
}
|
using Nancy.Hosting.Self;
using Newtonsoft.Json;
using RazorEngine;
using RazorEngine.Templating;
using RingCentral;
using System;
using System.IO;
namespace csharp_client_nancy
{
class Program
{
static void Main(string[] args)
{
var uri = new Uri(string.Format("http://{0}:{1}", Config.Instance.AppHost, Config.Instance.AppPort));
using (var host = new NancyHost(uri))
{
host.Start();
Console.WriteLine("Your application is running on " + uri);
Console.WriteLine("Press any [Enter] to close the host.");
Console.ReadLine();
}
}
}
public class DefaultModule : Nancy.NancyModule
{
private const string MyState = "myState";
// must be static. Because every time there is new request, a new instance of this class is created.
static RestClient rc = new RestClient(Config.Instance.AppKey, Config.Instance.AppSecret, Config.Instance.ServerUrl);
public DefaultModule()
{
var authorizeUri = rc.AuthorizeUri(Config.Instance.RedirectUrl, MyState);
var template = File.ReadAllText("index.html");
Get["/"] = _ =>
{
var tokenJson = "";
var authData = rc.token;
if (rc.token != null && rc.token.access_token != null)
{
tokenJson = JsonConvert.SerializeObject(rc.token, Formatting.Indented);
}
var page = Engine.Razor.RunCompile(template, "templateKey", null,
new { authorize_uri = authorizeUri, redirect_uri = Config.Instance.RedirectUrl, token_json = tokenJson });
return page;
};
Get["/callback"] = _ =>
{
var authCode = Request.Query.code.Value;
rc.Authorize(authCode, Config.Instance.RedirectUrl);
return ""; // js will close this window and reload parent window
};
}
}
}
|
using System;
using System.IO;
using Vlc.DotNet.Core.Interops.Signatures;
namespace Vlc.DotNet.Core.Interops
{
public sealed partial class VlcManager
{
public bool TakeSnapshot(VlcMediaPlayerInstance mediaPlayerInstance, uint outputNumber, string filePath, uint width, uint height)
{
if (mediaPlayerInstance == IntPtr.Zero)
throw new ArgumentException("Media player instance is not initialized.");
if(filePath == null)
throw new ArgumentNullException(nameof(filePath));
using (var filePathHandle = Utf8InteropStringConverter.ToUtf8StringHandle(filePath))
{
return myLibraryLoader.GetInteropDelegate<TakeSnapshot>().Invoke(mediaPlayerInstance, outputNumber, filePathHandle, width, height) == 0;
}
}
}
}
|
using Google.Apis.Auth.OAuth2;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MailClient
{
class MailChecker
{
private string[] Scopes = { GmailService.Scope.GmailReadonly };
private string ApplicationName = "CSharpClient";
private UserCredential credential;
private GmailService service;
private static MailChecker instance = null;
private MailChecker()
{
AuthenticateClient();
CreateService();
}
public static MailChecker GetInstance()
{
if (instance == null)
instance = new MailChecker();
return instance;
}
private void AuthenticateClient()
{
using (var stream =
new FileStream("client_id.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, "../../client_id.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
}
private void CreateService()
{
service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
}
public IList<Google.Apis.Gmail.v1.Data.Thread> ThreadListRequest()
{
UsersResource.ThreadsResource.ListRequest request = service.Users.Threads.List("me");
return request.Execute().Threads;
}
public Message GetMessageById(string id)
{
UsersResource.MessagesResource.GetRequest request = service.Users.Messages.Get("me", id);
try
{
return request.Execute();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
return null;
}
/// <summary>
/// List History of all changes to the user's mailbox.
/// </summary>
/// <param name="service">Gmail API service instance.</param>
/// <param name="userId">User's email address. The special value "me"
/// can be used to indicate the authenticated user.</param>
/// <param name="startHistoryId">Only return changes at or after startHistoryId.</param>
public List<History> ListHistory(ulong startHistoryId)
{
List<History> result = new List<History>();
UsersResource.HistoryResource.ListRequest request = service.Users.History.List("me");
request.StartHistoryId = startHistoryId;
do
{
try
{
ListHistoryResponse response = request.Execute();
if (response.History != null)
{
result.AddRange(response.History);
}
request.PageToken = response.NextPageToken;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
} while (!String.IsNullOrEmpty(request.PageToken));
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Data.SqlClient;
using System.Web.Configuration;
using GreenValleyAuctionsSystem;
namespace GreenValleyAuctionsSystems
{
public partial class ManageCustomerAccount : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpdatePassword_Click(object sender, EventArgs e)
{
string username = Session["CustomerUsername"].ToString();
try
{
System.Data.SqlClient.SqlConnection sc = new SqlConnection(WebConfigurationManager.ConnectionStrings["AUTH"].ConnectionString.ToString());
sc.Open();
System.Data.SqlClient.SqlCommand findPass = new System.Data.SqlClient.SqlCommand();
findPass.Connection = sc;
// SELECT PASSWORD STRING WHERE THE SAVED USERNAME MATCHES
findPass.CommandText = "SELECT dbo.CPASSWORD.PASSWORD_HASH FROM dbo.CPASSWORD, dbo.USERS WHERE dbo.USERS.USERNAME = @Username AND dbo.USERS.USER_TYPE = @Type AND dbo.CPASSWORD.USER_ID = dbo.USERS.USER_ID";
// ADD PARAMETERS
findPass.Parameters.Add(new SqlParameter("@Username", HttpUtility.HtmlEncode(username)));
findPass.Parameters.Add(new SqlParameter("@Type", "Customer"));
// Create a Reader
SqlDataReader reader = findPass.ExecuteReader();
// if the username exists, it will continue
if (reader.HasRows)
{
// this will read the single record that matches the saved username
while (reader.Read())
{
// store the database password into this variable
string storedHash = reader["PASSWORD_HASH"].ToString();
SqlConnection dbConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["AUTH"].ConnectionString.ToString());
SqlCommand loginCommand = new SqlCommand();
// Properties for object above
loginCommand.Connection = dbConnection;
loginCommand.CommandType = System.Data.CommandType.StoredProcedure;
// **THIS MIGHT CAUSE AN ERROR**
loginCommand.CommandText = "dbo.SP_EMPLOYEELOGIN";
// Parameters
loginCommand.Parameters.AddWithValue("@UserName", HttpUtility.HtmlEncode(username));
loginCommand.Parameters.AddWithValue("@Password", storedHash);
// **THIS MIGHT CAUSE AN ERROR**
loginCommand.Parameters.AddWithValue("@Type", "Customer");
dbConnection.Open();
SqlDataReader loginResults = loginCommand.ExecuteReader();
dbConnection.Close();
// if the entered passwork matches what is stored within the dB, it will pass to the next if-statement
if (PasswordHash.ValidatePassword(HttpUtility.HtmlEncode(txtOldPassword.Text), storedHash))
{
// if the new passwords amtch, update password in dB
if (txtNewPasswordOne.Text.Equals(txtNewPasswordTwo.Text))
{
try
{
System.Data.SqlClient.SqlConnection sconnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["AUTH"].ConnectionString.ToString());
sconnection.Open();
System.Data.SqlClient.SqlCommand updatePass = new System.Data.SqlClient.SqlCommand();
updatePass.Connection = sconnection;
// store hashed password into variable
string hashedPassword = PasswordHash.HashPassword(txtNewPasswordOne.Text);
// UPDATE PASSWORD
updatePass.CommandText = "UPDATE CPASSWORD SET PASSWORD_HASH = @hash WHERE USERNAME = @Username";
updatePass.Parameters.Add(new SqlParameter("@hash", PasswordHash.HashPassword(txtNewPasswordOne.Text)));
updatePass.Parameters.Add(new SqlParameter("@Username", username));
updatePass.ExecuteNonQuery();
lblResponse.Text = "SUCCESS: Password updated!";
lblResponse.CssClass = "alert alert-success arrow-left quick";
sconnection.Close();
}
catch
{
lblResponse.Text = "Database Error.";
lblResponse.CssClass = "alert alert-danger arrow-left quick";
}
}
else
{
lblResponse.Text = "ERROR: New passwords do not match, please try again.";
lblResponse.CssClass = "alert alert-danger arrow-left quick";
}
}
else
{
lblResponse.Text = "ERROR: Incorrect Password";
lblResponse.CssClass = "alert alert-danger arrow-left quick";
}
}
}
else
{
lblResponse.Text = "ERROR: Username does not exist in this context.";
lblResponse.CssClass = "alert alert-danger arrow-left quick";
}
sc.Close();
}
catch
{
lblResponse.Text = "Database Error.";
lblResponse.CssClass = "alert alert-danger arrow-left quick";
}
}
}
}
|
using System;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Phenix.Core.Security.Cryptography;
using Phenix.Web.Client.Security;
namespace Phenix.Web.Client
{
internal class ClientHandler : HttpClientHandler
{
public ClientHandler(UserIdentity userIdentity)
: base()
{
_userIdentity = userIdentity;
}
public ClientHandler(UserIdentity userIdentity, bool contentVerify, bool contentEncrypt)
: this(userIdentity)
{
_contentVerify = contentVerify;
_contentEncrypt = contentEncrypt;
}
#region 属性
private const string METHOD_OVERRIDE_HEADER_NAME = "X-HTTP-Method-Override";
private readonly UserIdentity _userIdentity;
private readonly bool _contentVerify;
private readonly bool _contentEncrypt;
#endregion
#region 方法
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
//测试突破某些HTTP代理对方法的限制, 真实环境可注释掉
if (request.Method == HttpMethod.Put || request.Method == HttpMethod.Delete)
{
request.Headers.Add(METHOD_OVERRIDE_HEADER_NAME, request.Method.ToString());
request.Method = HttpMethod.Post;
}
string timestamp = Guid.NewGuid().ToString(); //也允许采用其他随机数形式, 只要在一个LogOn到LogOff周期内不发生重复即可
if ((_contentVerify || _contentEncrypt) && !request.Content.IsMimeMultipartContent())
{
//身份认证格式: [UserNumber],[timestamp],[contentMD5 = MD5(content)/""],[contentEncrypted = 0/1],[signature = Encrypt(Password, timestamp+contentMD5)]
string content = request.Content.ReadAsStringAsync().Result;
string contentMD5 = _contentVerify ? MD5CryptoTextProvider.ComputeHash(content) : String.Empty;
request.Headers.Add(HttpClient.AUTHORIZATION_HEADER_NAME,
String.Format("{0},{1},{2},{3},{4}", Uri.EscapeDataString(_userIdentity.UserNumber), timestamp, contentMD5, _contentEncrypt ? 1 : 0,
RijndaelCryptoTextProvider.Encrypt(_userIdentity.Password, timestamp + contentMD5)));
if (_contentEncrypt)
request.Content = new StringContent(RijndaelCryptoTextProvider.Encrypt(_userIdentity.Password, content),
request.Content.Headers.ContentType != null && !String.IsNullOrEmpty(request.Content.Headers.ContentType.CharSet) ? Encoding.GetEncoding(request.Content.Headers.ContentType.CharSet) : null,
request.Content.Headers.ContentType != null ? request.Content.Headers.ContentType.MediaType : null);
}
else
{
//身份认证格式: [UserNumber],[timestamp],[signature = Encrypt(Password, timestamp)]
request.Headers.Add(HttpClient.AUTHORIZATION_HEADER_NAME,
String.Format("{0},{1},{2}", Uri.EscapeDataString(_userIdentity.UserNumber), timestamp,
RijndaelCryptoTextProvider.Encrypt(_userIdentity.Password, timestamp)));
}
return base.SendAsync(request, cancellationToken);
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FragmentAddon : ExplodableAddon
{
[Header("Destroy after")]
public float seconds = 5;
[Header("Damage")]
public Team originTeam;
public LayerMask playerLayer;
public int damage = 1;
public float minVelocity = 1;
public override void OnFragmentsGenerated(List<GameObject> fragments)
{
foreach (var fragment in fragments)
{
//Destroy after
DestroyAfter destroyAfter = fragment.AddComponent<DestroyAfter>();
destroyAfter.seconds = seconds;
//Damage
DamageParticle damageParticle = fragment.AddComponent<DamageParticle>();
damageParticle.originTeam = originTeam;
damageParticle.playerLayer = playerLayer;
damageParticle.damage = damage;
damageParticle.minVelocity = minVelocity;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections;
using System.IO.IsolatedStorage;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Countly
{
public class PersistantQueue<T> : IEnumerable<T>
{
Queue<T> queue;
public PersistantQueue()
{
queue = new Queue<T>();
LoadState();
}
private void LoadState()
{
try {
using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) {
using (var stream = myIsolatedStorage.OpenFile("countly-state", FileMode.OpenOrCreate)) {
var formatter = new BinaryFormatter();
queue = stream.Length > 0 ? (Queue<T>)formatter.Deserialize(stream) : new Queue<T>();
Console.WriteLine("Items to be synced:{0}", queue.Count);
}
}
}
catch (Exception ex) {
Console.WriteLine(ex);
queue = new Queue<T>();
}
}
private void SaveState()
{
try {
using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) {
using (var stream = myIsolatedStorage.OpenFile("countly-state", FileMode.Create)) {
var formatter = new BinaryFormatter();
formatter.Serialize(stream, queue);
stream.Close();
}
}
}
catch (Exception ex) {
Console.WriteLine(ex);
}
}
#region IEnumerable implementation
public IEnumerator<T> GetEnumerator()
{
return queue.GetEnumerator();
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
public int Count {
get { return queue.Count; }
}
public void Enqueue(T item)
{
queue.Enqueue(item);
SaveState();
}
public T Peek()
{
return queue.Peek();
}
public T Dequeue()
{
var item = queue.Dequeue();
SaveState();
return item;
}
}
}
|
namespace SubC.Attachments {
using UnityEngine;
public static class ClingyUtils {
public static Quaternion LookAt2D(Vector3 currentPos, Vector3 lookAtPos, bool flipX = false) {
Vector2 delta = lookAtPos - currentPos;
float radians = Mathf.Atan2(delta.y, delta.x);
return Quaternion.Euler(0, 0, radians * Mathf.Rad2Deg + (flipX ? 180 : 0));
}
public static void MovePosition(Vector3 position, Transform transform, MoveMethod moveMethod,
Rigidbody rb = null, Rigidbody2D rb2D = null) {
if (moveMethod == MoveMethod.Translate) {
transform.position = position;
} else if (moveMethod == MoveMethod.SetPhysics) {
if (rb)
rb.position = position;
else if (rb2D && rb2D.simulated)
rb2D.position = position;
else
transform.position = position;
} else if (moveMethod == MoveMethod.MovePhysics) {
if (rb)
rb.MovePosition(position);
else if (rb2D && rb2D.simulated)
rb2D.MovePosition(position);
else
transform.position = position;
}
}
public static void MoveRotation(Quaternion rotation, Transform transform, RotateMethod rotateMethod,
Rigidbody rb = null, Rigidbody2D rb2D = null) {
if (rotateMethod == RotateMethod.Translate) {
transform.rotation = rotation;
} else if (rotateMethod == RotateMethod.SetPhysics) {
if (rb)
rb.rotation = rotation;
else if (rb2D && rb2D.simulated)
rb2D.rotation = rotation.eulerAngles.z;
else
transform.rotation = rotation;
} else if (rotateMethod == RotateMethod.MovePhysics) {
if (rb)
rb.MoveRotation(rotation);
else if (rb2D && rb2D.simulated)
rb2D.MoveRotation(rotation.eulerAngles.z);
else
transform.rotation = rotation;
}
}
}
} |
using eMAM.Data.Models;
using eMAM.Service.DTO;
using System.Threading.Tasks;
namespace eMAM.Service.DbServices.Contracts
{
public interface IGmailUserDataService
{
Task CreateAsync(GmailUserDataDTO gmailUserData);
Task UpdateAsync(GmailUserDataDTO gmailUserData);
Task<GmailUserData> GetAsync();
Task<bool> IsAccessTokenValidAsync();
}
}
|
using AppJCDV.Models;
using Refit;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Essentials;
namespace AppJCDV.Services
{
public class UsuarioService
{
//No inicio vou considerar que o usuario já existe e vou somente atualizar a posição com intuito de repassar
const string URL_API_USUARIO = "https://backendjcdv20181201083159.azurewebsites.net/api";
public async Task SendLocation(Location location)
{
try
{
var mockUser = new Usuario()
{
Id = new Guid("a2a2a40a-1c6b-4097-9131-4e0de5ac5cd4"),
Email = "thiago-alvesp@live.com",
Senha = "123"
};
var token = await new LoginService().GetToken();
var usuarioApi = RestService.For<IUsuarioService>(URL_API_USUARIO);
await usuarioApi.SendLocation(
mockUser.Id.ToString(),
location,
$"Bearer {token.accessToken}");
}
catch (Exception ex) //send msg to UI
{
throw;
}
}
public async Task<Location> GetLocation(Guid id)
{
try
{
var token = await new LoginService().GetToken();
var usuarioApi = RestService.For<IUsuarioService>(URL_API_USUARIO);
var location = await usuarioApi.GetLocation(
id,
$"Bearer {token.accessToken}");
return location;
}
catch (Exception ex) //send msg to UI
{
throw;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Groceries.Domain;
namespace Groceries.MonoDroid
{
[Activity (Label = "ShoppingCartAdapter")]
public class ShoppingCartAdapter : BaseAdapter<ShoppingCart>
{
HomeViewModel Model;
public Activity context;
public List<ShoppingCart> shoppingcard;
public ShoppingCartAdapter (Activity context, HomeViewModel model)
{
this.Model = model;
this.context = context;
}
public override long GetItemId (int position)
{
return position;
}
public override View GetView (int position, View convertView, ViewGroup parent)
{
CartHolder holder;
if (convertView == null) {
var inflater = LayoutInflater.FromContext (context);
convertView = inflater.Inflate (Resource.Layout.row_Tab_Active_Lists, null, false);
holder = new CartHolder ();
holder.name = convertView.FindViewById<TextView> (Resource.Id.ActiveListName);
holder.total = convertView.FindViewById<TextView> (Resource.Id.txtTotal);
holder.left = convertView.FindViewById<TextView> (Resource.Id.txtLeft);
holder.bought = convertView.FindViewById<TextView> (Resource.Id.txtBought);
holder.timeRemaining = convertView.FindViewById<TextView> (Resource.Id.hourRemaining);
holder.dateCreated = convertView.FindViewById<TextView>(Resource.Id.date);
convertView.Tag = holder;
}
holder = convertView.Tag as CartHolder;
holder.name.Text = this [position].NameList;
holder.total.Text = this [position].Total.ToString();
holder.left.Text = this [position].Left.ToString();
holder.bought.Text = this [position].Bought.ToString();
holder.timeRemaining.Text = string.Format("{0} hours {1} minutes",
this[position].DateTimeRemaining.Hours,
this[position].DateTimeRemaining.Minutes);
holder.dateCreated.Text = string.Format("{0}", DateTime.Now);
return convertView;
}
class CartHolder : Java.Lang.Object
{
public TextView name { get; set; }
public TextView total { get; set; }
public TextView left { get; set; }
public TextView bought { get; set; }
public TextView timeRemaining { get; set; }
public TextView dateCreated { get; set; }
}
public override int Count {
get {
return shoppingcard!=null?shoppingcard.Count:0;
}
}
public override ShoppingCart this[int index] {
get {
return shoppingcard [index];
}
}
}
}
|
#if UNITY_2018_1_OR_NEWER
using System;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace PumpEditor
{
public class SaveProjectAsTemplateEditorWindow : EditorWindow
{
private static readonly string UnityEditorApplicationProjectTemplatesPath = Path.Combine(
Path.GetDirectoryName(EditorApplication.applicationPath),
"Data",
"Resources",
"PackageManager",
"ProjectTemplates"
);
private static readonly string[] TemplateFolderNames = new string[]
{
"Assets",
"Packages",
"ProjectSettings",
};
private string targetPath;
private string templateName;
private string templateDisplayName;
private string templateDescription;
private string templateDefaultScene;
private string templateVersion;
private SceneAsset templateDefaultSceneAsset;
private bool replaceTemplate;
[MenuItem("Window/Pump Editor/Project Templates/Save Project As Template")]
private static void ShowWindow()
{
var window = EditorWindow.GetWindow<SaveProjectAsTemplateEditorWindow>();
var icon = EditorGUIUtility.Load("saveas@2x") as Texture2D;
window.titleContent = new GUIContent("Save Project As Template", icon);
window.Show();
}
private void DeleteTemplateFolders()
{
try
{
foreach (var tempateFolderName in TemplateFolderNames)
{
var path = Path.Combine(targetPath, tempateFolderName);
if (Directory.Exists(path))
{
Directory.Delete(path, true);
}
}
}
catch (Exception e)
{
Debug.LogErrorFormat("Failed to delete template folders, exception: {0}", e.Message);
}
}
// Use 2018.2 references as 2018.1 does not have this method (but it's called from 2018.1 UnityEditor.ProjectTemplateWindow).
private void InvokeSaveProjectAsTemplate()
{
// Unity C# reference: https://github.com/Unity-Technologies/UnityCsReference/blob/4aea4dc4/Editor/Mono/EditorUtility.bindings.cs#L16
Assembly editorAssembly = Assembly.GetAssembly(typeof(Editor));
Type editorUtilityType = editorAssembly.GetType("UnityEditor.EditorUtility");
// Unity C# reference: https://github.com/Unity-Technologies/UnityCsReference/blob/4aea4dc4/Editor/Mono/EditorUtility.bindings.cs#L172
MethodInfo methodInfo = editorUtilityType.GetMethod("SaveProjectAsTemplate", BindingFlags.Static | BindingFlags.NonPublic);
methodInfo.Invoke(editorUtilityType, new object[]{ targetPath, templateName, templateDisplayName, templateDescription, templateDefaultScene, templateVersion});
}
private void DeleteProjectVersionTxt()
{
var projectVersionTxtPath = Path.Combine(targetPath, "ProjectSettings", "ProjectVersion.txt");
if (File.Exists(projectVersionTxtPath))
{
File.Delete(projectVersionTxtPath);
}
else
{
Debug.LogErrorFormat("File ProjectVersion.txt does not exist at path: {0}", projectVersionTxtPath);
}
}
private void SetTemplateDataFromPackageJson()
{
var packageJsonPath = Path.Combine(targetPath, "package.json");
if (File.Exists(packageJsonPath))
{
var packageJson = File.ReadAllText(packageJsonPath);
var templateData = JsonUtility.FromJson<TemplateData>(packageJson);
templateName = templateData.Name;
templateDisplayName = templateData.DisplayName;
templateDescription = templateData.Description;
templateDefaultScene = templateData.DefaultScene;
templateVersion = templateData.Version;
SetDefaultSceneAssetFromPath();
}
}
private void SetDefaultSceneAssetFromPath()
{
if (templateDefaultScene != String.Empty)
{
templateDefaultSceneAsset = AssetDatabase.LoadAssetAtPath<SceneAsset>(templateDefaultScene);
Debug.AssertFormat(templateDefaultSceneAsset != null, "Failed to load scene asset at path from package.json, path: {0}", templateDefaultScene);
}
else
{
templateDefaultSceneAsset = null;
}
}
private void DefaultSceneGUI()
{
templateDefaultSceneAsset = (SceneAsset)EditorGUILayout.ObjectField("Default scene asset:", templateDefaultSceneAsset, typeof(SceneAsset), false);
if (templateDefaultSceneAsset != null)
{
templateDefaultScene = AssetDatabase.GetAssetPath(templateDefaultSceneAsset);
}
else
{
templateDefaultScene = null;
}
using (new EditorGUI.DisabledGroupScope(true))
{
EditorGUILayout.TextField("Default scene:", templateDefaultScene);
}
}
private void OnGUI()
{
if (GUILayout.Button("Select Target Folder"))
{
targetPath = EditorUtility.SaveFolderPanel("Choose target folder", UnityEditorApplicationProjectTemplatesPath, String.Empty);
SetTemplateDataFromPackageJson();
}
using (var check = new EditorGUI.ChangeCheckScope())
{
targetPath = EditorGUILayout.TextField("Path:", targetPath);
if (check.changed)
{
SetTemplateDataFromPackageJson();
}
}
templateName = EditorGUILayout.TextField("Name:", templateName);
templateDisplayName = EditorGUILayout.TextField("Display name:", templateDisplayName);
templateDescription = EditorGUILayout.TextField("Description:", templateDescription);
DefaultSceneGUI();
templateVersion = EditorGUILayout.TextField("Version:", templateVersion);
replaceTemplate = EditorGUILayout.Toggle("Replace template:", replaceTemplate);
if (GUILayout.Button("Save"))
{
if (replaceTemplate)
{
DeleteTemplateFolders();
}
AssetDatabase.SaveAssets();
InvokeSaveProjectAsTemplate();
DeleteProjectVersionTxt();
}
}
[Serializable]
private class TemplateData
{
#pragma warning disable 0649
[SerializeField]
private string name;
[SerializeField]
private string displayName;
[SerializeField]
private string description;
[SerializeField]
private string defaultScene;
[SerializeField]
private string version;
#pragma warning restore 0649
public string Name { get { return name; } }
public string DisplayName { get { return displayName; } }
public string Description { get { return description; } }
public string DefaultScene { get { return defaultScene; } }
public string Version { get { return version; } }
}
}
}
#endif
|
using Memory;
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace LAdotNET.GameLauncher
{
class Program
{
static void Main(string[] args)
{
Mem m = new Mem();
if (File.Exists("Binaries//Win64//LOSTARK.exe")) // Check EXE
{
try
{
Process startProcess = new Process();
startProcess.StartInfo.Arguments = "--launch_from_launcher -AUTOLOGIN -ID=TESTUSER -PASSWORD=TESTPASS -PCNAME=TESTPCNAME";
startProcess.StartInfo.FileName = "LOSTARK.exe";
startProcess.StartInfo.WorkingDirectory = "Binaries//Win64";
startProcess.Start();
}
catch
{
Console.WriteLine("Failed to start LOSTARK.exe");
}
Thread.Sleep(1000);
Console.WriteLine("Starting LOSTARK.exe");
if (m.OpenProcess("LOSTARK"))
{
Console.WriteLine("Attached to LOSTARK.exe");
Console.WriteLine("Injecting x64lahook.dll");
Thread.Sleep(1500);
// FULL PATH TO DLL FILE
m.InjectDLL("E:\\Games\\LOSTARK\\x64lahook.dll");
//var baseAddress = m.theProc.MainModule.BaseAddress.ToInt64();
//Console.WriteLine("BASE ADDRESS: 0x" + baseAddress.ToString("X"));
}
m.closeProcess();
}
else
{
Console.WriteLine("Cant find LOSTARK.exe");
}
StartPipes();
Console.ReadKey();
}
public static void StartPipes()
{
Console.WriteLine("Starting pipe server: sgup_ipc_server");
using (NamedPipeServerStream server = new NamedPipeServerStream("sgup_ipc_server"))
{
Console.WriteLine("Waiting for connection");
server.WaitForConnection(); // blocks
Console.WriteLine("LOSTARK Client connected");
while(server.IsConnected)
{
byte[] buffer = new byte[516]; // client communicates in blocks of 516 bytes
server.Read(buffer, 0, 516);
Console.WriteLine(HexDump.Dump(buffer));
// SEND BACK PASSWORD
//server.Write(Reply.TestReply, 0, Reply.TestReply.Length);
byte[] reply;
using (MemoryStream stream = new MemoryStream())
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Write((byte)0);
writer.Write((byte)7);
writer.Write((byte)8);
writer.Write((byte)16);
writer.Write((int)318926848); // must be random each time?
writer.Write((long)1); // must be 1
var user = Encoding.ASCII.GetBytes("testuser");
writer.Write(user);
writer.Write(new byte[(512 - user.Length)]);
writer.Write(new byte[512]); // spacer
var pass = Encoding.ASCII.GetBytes("testpass");
//var pass = Encoding.ASCII.GetBytes("eyJhbGciOiJIUzI1NiJ9.eyJhcHBsaWNhdGlvbl9ubyI6MzIwMDAsInRva2VuIjoiMmQwMjIyOTAwMDk5NDBkODhkMzlkNjg0ZGEwODc3MWFlMjMyMzI0NTRmNzJjMGJiMGFiZjk2ODQ0YmNkZWFhYSIsImV4cGlyZV90aW1lIjoxNTcyNzU0MTQxNDYzLCJtZW1iZXJfbm8iOjg4MDgwOTI5fQ.JgfQmKtz0yDhffcxoQQw0e3RaXQqcZt21OF6wnyLE1A");
writer.Write(pass);
writer.Write(new byte[(512 - pass.Length)]);
writer.Write(new byte[512]); // spacer
writer.Write(21599); // ??
reply = stream.ToArray();
}
server.Write(reply, 0, reply.Length);
server.Flush();
Console.WriteLine($"REPLIED WITH\n{HexDump.Dump(reply)}");
}
Console.WriteLine("Client disconnected. Launcher closing...");
}
}
//182.162.7.47:44333
}
}
|
using System.ComponentModel;
namespace MainTool.Enums
{
public enum TaskType
{
[Description("Найкоротший шлях на мережі")]
ShortestWay,
[Description("Максимальний потік на мережі")]
MaxFlow
}
} |
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestHouse.Application.Infastructure.Repositories;
using TestHouse.Domain.Models;
namespace TestHouse.Infrastructure.Repositories
{
public class ProjectRespository : DbContext, IProjectRepository
{
public ProjectRespository(DbContextOptions<ProjectRespository> options)
: base(options)
{
}
public DbSet<ProjectAggregate> Projects { get; set; }
public DbSet<Suit> Suits { get; set; }
public DbSet<TestCase> TestCases { get; set; }
public DbSet<TestRun> TestRuns { get; set; }
public DbSet<TestRunCase> TestRunCases { get; set; }
public DbSet<Step> Steps { get; set; }
public DbSet<StepRun> TestRunSteps { get; set; }
public void Add(ProjectAggregate project)
{
Projects.Add(project);
}
public async Task<List<ProjectAggregate>> GetAllAsync()
{
return await Projects.ToListAsync();
}
public async Task<ProjectAggregate> GetAsync(long id)
{
return await Projects.Include(p=>p.RootSuit)
.ThenInclude(rootSuit => rootSuit.TestCases)
.ThenInclude(testCase=>testCase.Steps)
.Include(project => project.Suits)
.ThenInclude(suit => suit.TestCases)
.ThenInclude(testCase=> testCase.Steps)
.Include(project => project.TestRuns)
.Where(p => p.Id == id)
.SingleOrDefaultAsync();
}
public async Task<ProjectAggregate> GetAsync(long id, long testRunId)
{
var project = await GetAsync(id);
//load data for test run to context memory
var run = TestRuns.Include(testRun => testRun.TestCases)
.ThenInclude(testRunCase => testRunCase.Steps)
.ThenInclude(runStep => runStep.Step)
.Include(testRun => testRun.TestCases)
.ThenInclude(testRunCase => testRunCase.TestCase)
.Where(t => t.Id == testRunId)
.Single();
return project;
}
public Task SaveAsync()
{
return this.SaveChangesAsync();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization.Json;
namespace _4._4_JSON_serialization
{
class Program
{
static void Main(string[] args)
{
UpdateJson update = new UpdateJson();
update.RemoveCarcter();
//Lembrando que o Id e Desc nao sera serializado/salvo
/*Product prod = new Product
{
id = 3,
name = "Kit Kat",
price = 2.50m,
desc = "Meio Amargo"
};
if (prod.id.HasValue)
{
Console.WriteLine("Tem valor!!!!");
}
// Serialize
//Sera salvo na pasta /bin/Debug
Stream stream = new FileStream("Product.json", FileMode.Create);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Product));
ser.WriteObject(stream, prod); // Note: call WriteObject method instead of Serialize
stream.Close();
// Deserialize
Product prod2 = new Product();
Stream stream2 = new FileStream("Product.json", FileMode.Open);
DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(Product));
prod2 = (Product)ser.ReadObject(stream2); // Note: call ReadObject method instead of Deserialize
stream2.Close();
Console.WriteLine("Id: {0} \nName: {1} \nprice {2:C} \nDesc {3}", prod2.id, prod2.name, prod2.price, prod2.desc);
*/
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entities;
namespace DataAccessLayer.Repository
{
public class LoginRepository : BaseRepository<Login>
{
public LoginRepository(TaskManagementContext context) : base(context)
{
}
}
}
|
using System.Data;
namespace Samples.AspNetCore.Mvc;
public class GameService : IGameService
{
private readonly ILogger<GameService> _gameLogger;
public GameService(ILogger<GameService> gameLogger) => _gameLogger = gameLogger;
public async Task<(int dungeonsIds, int userMana)> FetchNextPhaseDataAsync()
{
_gameLogger.LogInformation("Fetching dungeons and mana level in parallel.");
var getDungeonsTask = Task.Run(new Func<int>(() => throw new HttpRequestException("Failed to fetch available Dungeons")));
var getUserMana = Task.Run(new Func<int>(() => throw new DataException("Invalid Mana level: -10")));
var whenAll = Task.WhenAll(getDungeonsTask, getUserMana);
try
{
var ids = await whenAll;
return (ids[0], ids[1]);
}
// await unwraps AggregateException and throws the first one
catch when (whenAll.Exception is { } ae && ae.InnerExceptions.Count > 1)
{
throw ae; // re-throw the AggregateException to capture all errors
}
}
}
|
using System;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Newtonsoft.Json;
namespace CYJ.Utils.Extension.ObjectExtension
{
public static class ObjectExtension
{
#region 类型转换
/// <summary>
/// 转换源目标类型到目标对象类型
/// </summary>
/// <typeparam name="T">Generic type parameter. The specified type.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <returns>The object as the specified type.</returns>
public static T To<T>(this object @this)
{
return (T) @this;
}
/// <summary>
/// 判断对象是否为null
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static bool IsNull(this object obj)
{
return obj == null;
}
/// <summary>
/// 转换源目标类型到目标对象类型,无法转换的话转换成默认值
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <returns>A T.</returns>
public static T ToOrDefault<T>(this object @this)
{
try
{
return (T) @this;
}
catch (Exception)
{
return default(T);
}
}
/// <summary>
/// A T extension method that makes a deep copy of '@this' object.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <returns>the copied object.</returns>
public static T DeepClone<T>(this T @this)
{
IFormatter formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
{
formatter.Serialize(stream, @this);
stream.Seek(0, SeekOrigin.Begin);
return (T) formatter.Deserialize(stream);
}
}
/// <summary>
/// 使用Json序列化的方式深拷贝
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="this"></param>
/// <returns></returns>
public static T DeepCloneModel<T>(this T @this)
{
var json = JsonConvert.SerializeObject(@this);
try
{
return JsonConvert.DeserializeObject<T>(json);
}
catch (Exception e)
{
return default(T);
}
}
/// <summary>
/// A T extension method that shallow copy.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <returns>A T.</returns>
public static T ShallowCopy<T>(this T @this)
{
var method = @this.GetType().GetMethod("MemberwiseClone", BindingFlags.NonPublic | BindingFlags.Instance);
return (T) method.Invoke(@this, null);
}
/// <summary>
/// 转换源目标类型到目标对象类型,无法转换的话转换成默认值
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>A T.</returns>
public static T ToOrDefault<T>(this object @this, T defaultValue)
{
try
{
return (T) @this;
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// 转换源目标类型到目标对象类型,无法转换的话转换成默认值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="this"></param>
/// <param name="defaultValueFactory"></param>
/// <returns></returns>
public static T ToOrDefault<T>(this object @this, Func<T> defaultValueFactory)
{
try
{
return (T) @this;
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// 转换源目标类型到目标对象类型,无法转换的话转换成默认值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="this"></param>
/// <param name="defaultValueFactory"></param>
/// <returns></returns>
public static T ToOrDefault<T>(this object @this, Func<object, T> defaultValueFactory)
{
try
{
return (T) @this;
}
catch (Exception)
{
return defaultValueFactory(@this);
}
}
#endregion
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using BezierMasterNS;
using BezierMasterNS.MeshesCreating;
[CustomEditor(typeof(CreateMeshBase), true)]
public class MeshCreatorEditor : Editor
{
protected CreateMeshBase meshCreator;
protected BezierMaster master;
protected SerializedProperty lenghtSegmentsProperty;
protected SerializedProperty widhtSegmentsProperty;
protected SerializedProperty widthProperty;
protected SerializedProperty twoSidedProperty;
protected SerializedProperty textureOrientationProperty;
protected SerializedProperty fixTextureStretchProperty;
protected SerializedProperty TextureScaleProperty;
string lenghtSegmentsPropertyName = "lenghtSegmentsCount";
string widhtSegmentsPropertyName = "widhtSegmentsCount";
string widthPropertyName = "Radius1";
string twoSidedPropertyName = "twoSided";
string textureOrientationPropertyName = "textureOrientation";
string fixTextureStretchPropertyName = "fixTextureStretching";
string textureScalePropertyName = "textureScale";
private void OnEnable()
{
meshCreator = target as CreateMeshBase;
try
{
lenghtSegmentsProperty = serializedObject.FindProperty(lenghtSegmentsPropertyName);
widhtSegmentsProperty = serializedObject.FindProperty(widhtSegmentsPropertyName);
widthProperty = serializedObject.FindProperty(widthPropertyName);
twoSidedProperty = serializedObject.FindProperty(twoSidedPropertyName);
textureOrientationProperty = serializedObject.FindProperty(textureOrientationPropertyName);
fixTextureStretchProperty = serializedObject.FindProperty(fixTextureStretchPropertyName);
TextureScaleProperty = serializedObject.FindProperty(textureScalePropertyName);
}
catch
{
DestroyImmediate(this);
}
}
public virtual void Setup(BezierMaster bezierMaster)
{
master = bezierMaster;
}
public void DrawCopyPasteMenu()
{
GUILayout.BeginHorizontal();
if (GUILayout.Button("Copy mesh"))
{
BezierMaster.CopyMesh(meshCreator);
}
if (GUILayout.Button("Paste mesh"))
{
Undo.RecordObject(master, "Paste spline");
master.PasteMesh();
EditorUtility.SetDirty(master);
}
GUILayout.EndHorizontal();
}
}
|
// CrowdSimulator - Form1.cs
//
// Copyright (c) 2012, Dominik Gander
// Copyright (c) 2012, Pascal Minder
//
// Permission to use, copy, modify, and distribute this software for any
// purpose without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Imaging;
namespace CrowdSimulator
{
public partial class Form1 : Form
{
private readonly Bitmap image;
private readonly Crowd crowd;
public Form1()
{
InitializeComponent();
this.image = new Bitmap(field.Width, field.Height, PixelFormat.Format32bppArgb);
this.crowd = new Crowd(image);
this.crowd.Init(400, 3);
this.ticker.Start();
}
private void Update(object Sender, EventArgs E)
{
this.crowd.Update();
this.field.Image = image;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace com.Sconit.Web.Models.SearchModels.SI.SAP
{
public class SupplierSearchModel : SearchModelBase
{
//Id, Code, OldSupplierCode, Name, IOStatus, InboundDate, OutBoundDate
public int Id { get; set; }
public string Code { get; set; }
public string OldSupplierCode { get; set; }
public string Name { get; set; }
public int? IOStatus { get; set; }
public DateTime? InboundDateStart { get; set; }
public DateTime? OutboundDateStart { get; set; }
public DateTime? EndOutboundDate { get; set; }
public DateTime? EndInboundDate { get; set; }
}
} |
using GUI.Models;
using Windows.UI.Xaml;
namespace GUI.ViewModels
{
/// <summary>
/// Bunch of View converter helpers to improve the views
/// </summary>
public static class Converters
{
/// <summary>
/// Returns the reverse of the provided value.
/// </summary>
public static bool Not(bool value) => !value;
/// <summary>
/// Returns true if the specified value is not null; otherwise, returns false.
/// </summary>
public static bool IsNotNull(object value) => value != null;
/// <summary>
/// Returns a default integer value of 0 if the object is null.
/// </summary>
public static int DefaultIntegerIfNull(object value) => value == null ? 0 : (int)value;
/// <summary>
/// Returns Visibility.Collapsed if the specified value is true; otherwise, returns Visibility.Visible.
/// </summary>
public static Visibility BooleanToVisibility(bool value) =>
value ? Visibility.Visible : Visibility.Collapsed;
public static bool OnlyForDeviceIoControlIrp(IrpViewModel irp) =>
irp != null && irp.Model.header.Type == (uint)IrpMajorType.IRP_MJ_DEVICE_CONTROL;
public static Visibility VisibleOnlyForDeviceIoControlIrp(IrpViewModel irp) =>
irp != null && irp.Model.header.Type == (uint)IrpMajorType.IRP_MJ_DEVICE_CONTROL ? Visibility.Visible : Visibility.Collapsed;
/// <summary>
/// Returns Visibility.Collapsed if the specified value is true; otherwise, returns Visibility.Visible.
/// </summary>
public static Visibility CollapsedIf(bool value) =>
value ? Visibility.Collapsed : Visibility.Visible;
/// <summary>
/// Returns Visibility.Collapsed if the specified value is true; otherwise, returns Visibility.Visible.
/// </summary>
public static Visibility VisibleIfGreaterThanZero(uint value) =>
value > 0 ? Visibility.Visible : Visibility.Collapsed ;
/// <summary>
/// Returns Visibility.Collapsed if the specified value is null; otherwise, returns Visibility.Visible.
/// </summary>
public static Visibility CollapsedIfNull(object value) =>
value == null ? Visibility.Collapsed : Visibility.Visible;
/// <summary>
/// Returns Visibility.Collapsed if the specified string is null or empty; otherwise, returns Visibility.Visible.
/// </summary>
public static Visibility CollapsedIfNullOrEmpty(string value) =>
string.IsNullOrEmpty(value) ? Visibility.Collapsed : Visibility.Visible;
/// <summary>
/// Display an address as hexa string
/// </summary>
/// <param name="Address"></param>
/// <returns></returns>
public static string FormatAddressAsHex(ulong Address) =>
$"0x{Address.ToString("X")}";
}
}
|
using Newtonsoft.Json;
using System;
namespace Project2Service.Models
{
public class Contact
{
[JsonProperty("ID")]
public int Id { get; set; }
[JsonProperty("Email")]
public string Email { get; set; }
[JsonProperty("Password")]
public string Password { get; set; }
[JsonProperty("DateAdded")]
public DateTime DateAdded { get; set; }
[JsonProperty("DateModified")]
public DateTime DateModified { get; set; }
}
}
|
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using VesApp.iOS;
using VesApp.CustomRender;
[assembly: ExportRenderer(typeof(ShortLabel), typeof(ShortLabelRender))]
namespace VesApp.iOS
{
public class ShortLabelRender : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
if (Control != null)
{
UILabel label = Control;
label.Lines = 7;
}
}
}
} |
using LoowooTech.Stock.Common;
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Text;
namespace LoowooTech.Stock.Tool
{
public class ValueCompareTool2:ValueBaseTool2,IVTool
{
public string Name
{
get
{
var sb = new StringBuilder(string.Format("规则{0}:表【{1}】中字段【{2}】等于字段【{3}];", ID, TableName, string.Join(",", CheckLeftFieldNames), string.Join(",", CheckRightFieldNames)));
if (Relative.HasValue)
{
sb.AppendFormat("容差相对值【{0}%】;", Relative * 100);
}
if (Absolute.HasValue)
{
sb.AppendFormat("容差绝对值【{0}】;", Absolute);
}
sb.AppendFormat("保留{0}位小数位", Decimals);
return sb.ToString();
}
}
public string[] CheckLeftFieldNames { get; set; }
public string[] CheckRightFieldNames { get; set; }
/// <summary>
/// 相对值 百分比
/// </summary>
public double? Relative { get; set; }
/// <summary>
/// 绝对值 具体数值
/// </summary>
public double? Absolute { get; set; }
public int Decimals { get; set; }
private string _SQL
{
get
{
return string.Format("SELECT {0},{1},{2} FROM {3}", Key, string.Join(",", CheckLeftFieldNames), string.Join(",", CheckRightFieldNames), TableName);
}
}
public bool Check(OleDbConnection connection)
{
var reader = ADOSQLHelper.ExecuteReader(connection, _SQL);
if (reader == null)
{
return false;
}
while (reader.Read())
{
var keyValue = reader[0].ToString().Trim();
if (string.IsNullOrEmpty(keyValue) == false)
{
var leftValue = GetValue(reader, 1, 1 + CheckLeftFieldNames.Length);
var rightValue = GetValue(reader, 1 + CheckLeftFieldNames.Length, 1 + CheckLeftFieldNames.Length + CheckRightFieldNames.Length);
var abs = Math.Abs(leftValue - rightValue);
var flag = false;
if (Relative.HasValue)
{
var pp = abs / leftValue;
flag = pp < Relative.Value;
}
if (Absolute.HasValue)
{
flag = abs < Absolute.Value;
}
}
}
return true;
}
private double GetValue(OleDbDataReader reader,int start,int end)
{
double sum = .0;
var a = .0;
for(var i = start; i < end; i++)
{
if(double.TryParse(reader[i].ToString().Trim(),out a))
{
sum += Math.Round(a, Decimals);
}
}
return sum;
}
}
}
|
using System.Windows.Forms;
namespace gView.Framework.Carto.Rendering.UI
{
public partial class FormGroupRendererProperties : Form
{
public FormGroupRendererProperties(Control panel)
{
InitializeComponent();
Controls.Add(panel);
panel.BringToFront();
}
}
} |
using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Wpf.Model
{
class Index : ObservableObject
{
public string IndexName { get; set; }
public string IndexPage { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PROnline.Models.Users;
using System.ComponentModel.DataAnnotations;
namespace PROnline.Models.Assessments
{
//测评结果
public class AssessmentResult
{
public Guid AssessmentResultID { get; set; }
//接受测评的学生
public Guid StudentID { get; set; }
public virtual Student Student { get; set; }
//结论
[MaxLength(100)]
[Display(Name = "结论")]
public String Conclusion { get; set; }
//建议
[MaxLength(100)]
[Display(Name = "建议")]
public String Advice { get; set; }
public virtual IList<AssessmentResultOption> ResultOptionList { get; set; }
//下一步措施:继续治疗、治愈、转院
[MaxLength(100)]
[Display(Name = "下一步措施")]
public String Action { get; set; }
public DateTime CreateDate { get; set; }
}
} |
using System.Collections.Generic;
using Properties.Core.Objects;
namespace Properties.Core.Interfaces
{
public interface IVideoService
{
List<Video> GetVideosForProperty(string propertyReference);
Video GetVideoForProperty(string propertyReference, string videoReference);
string CreateVideo(string propertyReference, Video video);
bool UpdateVideo(string propertyReference, string videoReference, Video video);
bool DeleteVideo(string propertyReference, string videoReference);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RTreeCodeApproach
{
public interface ISpatialDatabase<T> : ISpatialIndex<T>
{
void Insert(T item);
void Delete(T item);
void Clear();
void BulkLoad(IEnumerable<T> items);
}
}
|
using System;
using System.Collections.Generic;
using Hl7.Fhir.Support;
using System.Xml.Linq;
/*
Copyright (c) 2011-2012, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
//
// Generated on Mon, Apr 15, 2013 13:14+1000 for FHIR v0.08
//
using Hl7.Fhir.Model;
using System.Xml;
namespace Hl7.Fhir.Parsers
{
/// <summary>
/// Parser for Conformance instances
/// </summary>
internal static partial class ConformanceParser
{
/// <summary>
/// Parse Conformance
/// </summary>
public static Conformance ParseConformance(IFhirReader reader, ErrorList errors, Conformance existingInstance = null )
{
Conformance result = existingInstance != null ? existingInstance : new Conformance();
try
{
string currentElementName = reader.CurrentElementName;
reader.EnterElement();
while (reader.HasMoreElements())
{
// Parse element extension
if( ParserUtils.IsAtFhirElement(reader, "extension") )
{
result.Extension = new List<Extension>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "extension") )
result.Extension.Add(ExtensionParser.ParseExtension(reader, errors));
reader.LeaveArray();
}
// Parse element language
else if( ParserUtils.IsAtFhirElement(reader, "language") )
result.Language = CodeParser.ParseCode(reader, errors);
// Parse element text
else if( ParserUtils.IsAtFhirElement(reader, "text") )
result.Text = NarrativeParser.ParseNarrative(reader, errors);
// Parse element contained
else if( ParserUtils.IsAtFhirElement(reader, "contained") )
{
result.Contained = new List<Resource>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "contained") )
result.Contained.Add(ParserUtils.ParseContainedResource(reader,errors));
reader.LeaveArray();
}
// Parse element internalId
else if( reader.IsAtRefIdElement() )
result.InternalId = Id.Parse(reader.ReadRefIdContents());
// Parse element date
else if( ParserUtils.IsAtFhirElement(reader, "date") )
result.Date = FhirDateTimeParser.ParseFhirDateTime(reader, errors);
// Parse element publisher
else if( ParserUtils.IsAtFhirElement(reader, "publisher") )
result.Publisher = ConformanceParser.ParseConformancePublisherComponent(reader, errors);
// Parse element software
else if( ParserUtils.IsAtFhirElement(reader, "software") )
result.Software = ConformanceParser.ParseConformanceSoftwareComponent(reader, errors);
// Parse element implementation
else if( ParserUtils.IsAtFhirElement(reader, "implementation") )
result.Implementation = ConformanceParser.ParseConformanceImplementationComponent(reader, errors);
// Parse element proposal
else if( ParserUtils.IsAtFhirElement(reader, "proposal") )
result.Proposal = ConformanceParser.ParseConformanceProposalComponent(reader, errors);
// Parse element version
else if( ParserUtils.IsAtFhirElement(reader, "version") )
result.Version = IdParser.ParseId(reader, errors);
// Parse element acceptUnknown
else if( ParserUtils.IsAtFhirElement(reader, "acceptUnknown") )
result.AcceptUnknown = FhirBooleanParser.ParseFhirBoolean(reader, errors);
// Parse element format
else if( ParserUtils.IsAtFhirElement(reader, "format") )
{
result.Format = new List<Code>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "format") )
result.Format.Add(CodeParser.ParseCode(reader, errors));
reader.LeaveArray();
}
// Parse element rest
else if( ParserUtils.IsAtFhirElement(reader, "rest") )
{
result.Rest = new List<Conformance.ConformanceRestComponent>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "rest") )
result.Rest.Add(ConformanceParser.ParseConformanceRestComponent(reader, errors));
reader.LeaveArray();
}
// Parse element messaging
else if( ParserUtils.IsAtFhirElement(reader, "messaging") )
{
result.Messaging = new List<Conformance.ConformanceMessagingComponent>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "messaging") )
result.Messaging.Add(ConformanceParser.ParseConformanceMessagingComponent(reader, errors));
reader.LeaveArray();
}
// Parse element document
else if( ParserUtils.IsAtFhirElement(reader, "document") )
{
result.Document = new List<Conformance.ConformanceDocumentComponent>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "document") )
result.Document.Add(ConformanceParser.ParseConformanceDocumentComponent(reader, errors));
reader.LeaveArray();
}
else
{
errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader);
reader.SkipSubElementsFor(currentElementName);
result = null;
}
}
reader.LeaveElement();
}
catch (Exception ex)
{
errors.Add(ex.Message, reader);
}
return result;
}
/// <summary>
/// Parse ConformanceSoftwareComponent
/// </summary>
public static Conformance.ConformanceSoftwareComponent ParseConformanceSoftwareComponent(IFhirReader reader, ErrorList errors, Conformance.ConformanceSoftwareComponent existingInstance = null )
{
Conformance.ConformanceSoftwareComponent result = existingInstance != null ? existingInstance : new Conformance.ConformanceSoftwareComponent();
try
{
string currentElementName = reader.CurrentElementName;
reader.EnterElement();
while (reader.HasMoreElements())
{
// Parse element extension
if( ParserUtils.IsAtFhirElement(reader, "extension") )
{
result.Extension = new List<Extension>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "extension") )
result.Extension.Add(ExtensionParser.ParseExtension(reader, errors));
reader.LeaveArray();
}
// Parse element internalId
else if( reader.IsAtRefIdElement() )
result.InternalId = Id.Parse(reader.ReadRefIdContents());
// Parse element name
else if( ParserUtils.IsAtFhirElement(reader, "name") )
result.Name = FhirStringParser.ParseFhirString(reader, errors);
// Parse element version
else if( ParserUtils.IsAtFhirElement(reader, "version") )
result.Version = FhirStringParser.ParseFhirString(reader, errors);
// Parse element releaseDate
else if( ParserUtils.IsAtFhirElement(reader, "releaseDate") )
result.ReleaseDate = FhirDateTimeParser.ParseFhirDateTime(reader, errors);
else
{
errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader);
reader.SkipSubElementsFor(currentElementName);
result = null;
}
}
reader.LeaveElement();
}
catch (Exception ex)
{
errors.Add(ex.Message, reader);
}
return result;
}
/// <summary>
/// Parse ConformanceRestComponent
/// </summary>
public static Conformance.ConformanceRestComponent ParseConformanceRestComponent(IFhirReader reader, ErrorList errors, Conformance.ConformanceRestComponent existingInstance = null )
{
Conformance.ConformanceRestComponent result = existingInstance != null ? existingInstance : new Conformance.ConformanceRestComponent();
try
{
string currentElementName = reader.CurrentElementName;
reader.EnterElement();
while (reader.HasMoreElements())
{
// Parse element extension
if( ParserUtils.IsAtFhirElement(reader, "extension") )
{
result.Extension = new List<Extension>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "extension") )
result.Extension.Add(ExtensionParser.ParseExtension(reader, errors));
reader.LeaveArray();
}
// Parse element internalId
else if( reader.IsAtRefIdElement() )
result.InternalId = Id.Parse(reader.ReadRefIdContents());
// Parse element mode
else if( ParserUtils.IsAtFhirElement(reader, "mode") )
result.Mode = CodeParser.ParseCode<Conformance.RestfulConformanceMode>(reader, errors);
// Parse element documentation
else if( ParserUtils.IsAtFhirElement(reader, "documentation") )
result.Documentation = FhirStringParser.ParseFhirString(reader, errors);
// Parse element security
else if( ParserUtils.IsAtFhirElement(reader, "security") )
result.Security = ConformanceParser.ParseConformanceRestSecurityComponent(reader, errors);
// Parse element resource
else if( ParserUtils.IsAtFhirElement(reader, "resource") )
{
result.Resource = new List<Conformance.ConformanceRestResourceComponent>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "resource") )
result.Resource.Add(ConformanceParser.ParseConformanceRestResourceComponent(reader, errors));
reader.LeaveArray();
}
// Parse element batch
else if( ParserUtils.IsAtFhirElement(reader, "batch") )
result.Batch = FhirBooleanParser.ParseFhirBoolean(reader, errors);
// Parse element history
else if( ParserUtils.IsAtFhirElement(reader, "history") )
result.History = FhirBooleanParser.ParseFhirBoolean(reader, errors);
else
{
errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader);
reader.SkipSubElementsFor(currentElementName);
result = null;
}
}
reader.LeaveElement();
}
catch (Exception ex)
{
errors.Add(ex.Message, reader);
}
return result;
}
/// <summary>
/// Parse ConformanceMessagingComponent
/// </summary>
public static Conformance.ConformanceMessagingComponent ParseConformanceMessagingComponent(IFhirReader reader, ErrorList errors, Conformance.ConformanceMessagingComponent existingInstance = null )
{
Conformance.ConformanceMessagingComponent result = existingInstance != null ? existingInstance : new Conformance.ConformanceMessagingComponent();
try
{
string currentElementName = reader.CurrentElementName;
reader.EnterElement();
while (reader.HasMoreElements())
{
// Parse element extension
if( ParserUtils.IsAtFhirElement(reader, "extension") )
{
result.Extension = new List<Extension>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "extension") )
result.Extension.Add(ExtensionParser.ParseExtension(reader, errors));
reader.LeaveArray();
}
// Parse element internalId
else if( reader.IsAtRefIdElement() )
result.InternalId = Id.Parse(reader.ReadRefIdContents());
// Parse element endpoint
else if( ParserUtils.IsAtFhirElement(reader, "endpoint") )
result.Endpoint = FhirUriParser.ParseFhirUri(reader, errors);
// Parse element documentation
else if( ParserUtils.IsAtFhirElement(reader, "documentation") )
result.Documentation = FhirStringParser.ParseFhirString(reader, errors);
// Parse element event
else if( ParserUtils.IsAtFhirElement(reader, "event") )
{
result.Event = new List<Conformance.ConformanceMessagingEventComponent>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "event") )
result.Event.Add(ConformanceParser.ParseConformanceMessagingEventComponent(reader, errors));
reader.LeaveArray();
}
else
{
errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader);
reader.SkipSubElementsFor(currentElementName);
result = null;
}
}
reader.LeaveElement();
}
catch (Exception ex)
{
errors.Add(ex.Message, reader);
}
return result;
}
/// <summary>
/// Parse ConformanceImplementationComponent
/// </summary>
public static Conformance.ConformanceImplementationComponent ParseConformanceImplementationComponent(IFhirReader reader, ErrorList errors, Conformance.ConformanceImplementationComponent existingInstance = null )
{
Conformance.ConformanceImplementationComponent result = existingInstance != null ? existingInstance : new Conformance.ConformanceImplementationComponent();
try
{
string currentElementName = reader.CurrentElementName;
reader.EnterElement();
while (reader.HasMoreElements())
{
// Parse element extension
if( ParserUtils.IsAtFhirElement(reader, "extension") )
{
result.Extension = new List<Extension>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "extension") )
result.Extension.Add(ExtensionParser.ParseExtension(reader, errors));
reader.LeaveArray();
}
// Parse element internalId
else if( reader.IsAtRefIdElement() )
result.InternalId = Id.Parse(reader.ReadRefIdContents());
// Parse element description
else if( ParserUtils.IsAtFhirElement(reader, "description") )
result.Description = FhirStringParser.ParseFhirString(reader, errors);
// Parse element url
else if( ParserUtils.IsAtFhirElement(reader, "url") )
result.Url = FhirUriParser.ParseFhirUri(reader, errors);
// Parse element software
else if( ParserUtils.IsAtFhirElement(reader, "software") )
result.Software = ConformanceParser.ParseConformanceSoftwareComponent(reader, errors);
else
{
errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader);
reader.SkipSubElementsFor(currentElementName);
result = null;
}
}
reader.LeaveElement();
}
catch (Exception ex)
{
errors.Add(ex.Message, reader);
}
return result;
}
/// <summary>
/// Parse ConformanceRestResourceComponent
/// </summary>
public static Conformance.ConformanceRestResourceComponent ParseConformanceRestResourceComponent(IFhirReader reader, ErrorList errors, Conformance.ConformanceRestResourceComponent existingInstance = null )
{
Conformance.ConformanceRestResourceComponent result = existingInstance != null ? existingInstance : new Conformance.ConformanceRestResourceComponent();
try
{
string currentElementName = reader.CurrentElementName;
reader.EnterElement();
while (reader.HasMoreElements())
{
// Parse element extension
if( ParserUtils.IsAtFhirElement(reader, "extension") )
{
result.Extension = new List<Extension>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "extension") )
result.Extension.Add(ExtensionParser.ParseExtension(reader, errors));
reader.LeaveArray();
}
// Parse element internalId
else if( reader.IsAtRefIdElement() )
result.InternalId = Id.Parse(reader.ReadRefIdContents());
// Parse element type
else if( ParserUtils.IsAtFhirElement(reader, "type") )
result.Type = CodeParser.ParseCode(reader, errors);
// Parse element profile
else if( ParserUtils.IsAtFhirElement(reader, "profile") )
result.Profile = FhirUriParser.ParseFhirUri(reader, errors);
// Parse element operation
else if( ParserUtils.IsAtFhirElement(reader, "operation") )
{
result.Operation = new List<Conformance.ConformanceRestResourceOperationComponent>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "operation") )
result.Operation.Add(ConformanceParser.ParseConformanceRestResourceOperationComponent(reader, errors));
reader.LeaveArray();
}
// Parse element readHistory
else if( ParserUtils.IsAtFhirElement(reader, "readHistory") )
result.ReadHistory = FhirBooleanParser.ParseFhirBoolean(reader, errors);
// Parse element searchInclude
else if( ParserUtils.IsAtFhirElement(reader, "searchInclude") )
{
result.SearchInclude = new List<FhirString>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "searchInclude") )
result.SearchInclude.Add(FhirStringParser.ParseFhirString(reader, errors));
reader.LeaveArray();
}
// Parse element searchParam
else if( ParserUtils.IsAtFhirElement(reader, "searchParam") )
{
result.SearchParam = new List<Conformance.ConformanceRestResourceSearchParamComponent>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "searchParam") )
result.SearchParam.Add(ConformanceParser.ParseConformanceRestResourceSearchParamComponent(reader, errors));
reader.LeaveArray();
}
else
{
errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader);
reader.SkipSubElementsFor(currentElementName);
result = null;
}
}
reader.LeaveElement();
}
catch (Exception ex)
{
errors.Add(ex.Message, reader);
}
return result;
}
/// <summary>
/// Parse ConformanceRestResourceOperationComponent
/// </summary>
public static Conformance.ConformanceRestResourceOperationComponent ParseConformanceRestResourceOperationComponent(IFhirReader reader, ErrorList errors, Conformance.ConformanceRestResourceOperationComponent existingInstance = null )
{
Conformance.ConformanceRestResourceOperationComponent result = existingInstance != null ? existingInstance : new Conformance.ConformanceRestResourceOperationComponent();
try
{
string currentElementName = reader.CurrentElementName;
reader.EnterElement();
while (reader.HasMoreElements())
{
// Parse element extension
if( ParserUtils.IsAtFhirElement(reader, "extension") )
{
result.Extension = new List<Extension>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "extension") )
result.Extension.Add(ExtensionParser.ParseExtension(reader, errors));
reader.LeaveArray();
}
// Parse element internalId
else if( reader.IsAtRefIdElement() )
result.InternalId = Id.Parse(reader.ReadRefIdContents());
// Parse element code
else if( ParserUtils.IsAtFhirElement(reader, "code") )
result.Code = CodeParser.ParseCode<Conformance.RestfulOperation>(reader, errors);
// Parse element documentation
else if( ParserUtils.IsAtFhirElement(reader, "documentation") )
result.Documentation = FhirStringParser.ParseFhirString(reader, errors);
else
{
errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader);
reader.SkipSubElementsFor(currentElementName);
result = null;
}
}
reader.LeaveElement();
}
catch (Exception ex)
{
errors.Add(ex.Message, reader);
}
return result;
}
/// <summary>
/// Parse ConformanceProposalComponent
/// </summary>
public static Conformance.ConformanceProposalComponent ParseConformanceProposalComponent(IFhirReader reader, ErrorList errors, Conformance.ConformanceProposalComponent existingInstance = null )
{
Conformance.ConformanceProposalComponent result = existingInstance != null ? existingInstance : new Conformance.ConformanceProposalComponent();
try
{
string currentElementName = reader.CurrentElementName;
reader.EnterElement();
while (reader.HasMoreElements())
{
// Parse element extension
if( ParserUtils.IsAtFhirElement(reader, "extension") )
{
result.Extension = new List<Extension>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "extension") )
result.Extension.Add(ExtensionParser.ParseExtension(reader, errors));
reader.LeaveArray();
}
// Parse element internalId
else if( reader.IsAtRefIdElement() )
result.InternalId = Id.Parse(reader.ReadRefIdContents());
// Parse element description
else if( ParserUtils.IsAtFhirElement(reader, "description") )
result.Description = FhirStringParser.ParseFhirString(reader, errors);
else
{
errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader);
reader.SkipSubElementsFor(currentElementName);
result = null;
}
}
reader.LeaveElement();
}
catch (Exception ex)
{
errors.Add(ex.Message, reader);
}
return result;
}
/// <summary>
/// Parse ConformanceMessagingEventComponent
/// </summary>
public static Conformance.ConformanceMessagingEventComponent ParseConformanceMessagingEventComponent(IFhirReader reader, ErrorList errors, Conformance.ConformanceMessagingEventComponent existingInstance = null )
{
Conformance.ConformanceMessagingEventComponent result = existingInstance != null ? existingInstance : new Conformance.ConformanceMessagingEventComponent();
try
{
string currentElementName = reader.CurrentElementName;
reader.EnterElement();
while (reader.HasMoreElements())
{
// Parse element extension
if( ParserUtils.IsAtFhirElement(reader, "extension") )
{
result.Extension = new List<Extension>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "extension") )
result.Extension.Add(ExtensionParser.ParseExtension(reader, errors));
reader.LeaveArray();
}
// Parse element internalId
else if( reader.IsAtRefIdElement() )
result.InternalId = Id.Parse(reader.ReadRefIdContents());
// Parse element code
else if( ParserUtils.IsAtFhirElement(reader, "code") )
result.Code = CodeParser.ParseCode(reader, errors);
// Parse element mode
else if( ParserUtils.IsAtFhirElement(reader, "mode") )
result.Mode = CodeParser.ParseCode<Conformance.ConformanceEventMode>(reader, errors);
// Parse element protocol
else if( ParserUtils.IsAtFhirElement(reader, "protocol") )
{
result.Protocol = new List<Coding>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "protocol") )
result.Protocol.Add(CodingParser.ParseCoding(reader, errors));
reader.LeaveArray();
}
// Parse element focus
else if( ParserUtils.IsAtFhirElement(reader, "focus") )
result.Focus = CodeParser.ParseCode(reader, errors);
// Parse element request
else if( ParserUtils.IsAtFhirElement(reader, "request") )
result.Request = FhirUriParser.ParseFhirUri(reader, errors);
// Parse element response
else if( ParserUtils.IsAtFhirElement(reader, "response") )
result.Response = FhirUriParser.ParseFhirUri(reader, errors);
// Parse element documentation
else if( ParserUtils.IsAtFhirElement(reader, "documentation") )
result.Documentation = FhirStringParser.ParseFhirString(reader, errors);
else
{
errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader);
reader.SkipSubElementsFor(currentElementName);
result = null;
}
}
reader.LeaveElement();
}
catch (Exception ex)
{
errors.Add(ex.Message, reader);
}
return result;
}
/// <summary>
/// Parse ConformanceRestSecurityCertificateComponent
/// </summary>
public static Conformance.ConformanceRestSecurityCertificateComponent ParseConformanceRestSecurityCertificateComponent(IFhirReader reader, ErrorList errors, Conformance.ConformanceRestSecurityCertificateComponent existingInstance = null )
{
Conformance.ConformanceRestSecurityCertificateComponent result = existingInstance != null ? existingInstance : new Conformance.ConformanceRestSecurityCertificateComponent();
try
{
string currentElementName = reader.CurrentElementName;
reader.EnterElement();
while (reader.HasMoreElements())
{
// Parse element extension
if( ParserUtils.IsAtFhirElement(reader, "extension") )
{
result.Extension = new List<Extension>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "extension") )
result.Extension.Add(ExtensionParser.ParseExtension(reader, errors));
reader.LeaveArray();
}
// Parse element internalId
else if( reader.IsAtRefIdElement() )
result.InternalId = Id.Parse(reader.ReadRefIdContents());
// Parse element type
else if( ParserUtils.IsAtFhirElement(reader, "type") )
result.Type = CodeParser.ParseCode(reader, errors);
// Parse element blob
else if( ParserUtils.IsAtFhirElement(reader, "blob") )
result.Blob = Base64BinaryParser.ParseBase64Binary(reader, errors);
else
{
errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader);
reader.SkipSubElementsFor(currentElementName);
result = null;
}
}
reader.LeaveElement();
}
catch (Exception ex)
{
errors.Add(ex.Message, reader);
}
return result;
}
/// <summary>
/// Parse ConformanceDocumentComponent
/// </summary>
public static Conformance.ConformanceDocumentComponent ParseConformanceDocumentComponent(IFhirReader reader, ErrorList errors, Conformance.ConformanceDocumentComponent existingInstance = null )
{
Conformance.ConformanceDocumentComponent result = existingInstance != null ? existingInstance : new Conformance.ConformanceDocumentComponent();
try
{
string currentElementName = reader.CurrentElementName;
reader.EnterElement();
while (reader.HasMoreElements())
{
// Parse element extension
if( ParserUtils.IsAtFhirElement(reader, "extension") )
{
result.Extension = new List<Extension>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "extension") )
result.Extension.Add(ExtensionParser.ParseExtension(reader, errors));
reader.LeaveArray();
}
// Parse element internalId
else if( reader.IsAtRefIdElement() )
result.InternalId = Id.Parse(reader.ReadRefIdContents());
// Parse element mode
else if( ParserUtils.IsAtFhirElement(reader, "mode") )
result.Mode = CodeParser.ParseCode<Conformance.DocumentMode>(reader, errors);
// Parse element documentation
else if( ParserUtils.IsAtFhirElement(reader, "documentation") )
result.Documentation = FhirStringParser.ParseFhirString(reader, errors);
// Parse element profile
else if( ParserUtils.IsAtFhirElement(reader, "profile") )
result.Profile = FhirUriParser.ParseFhirUri(reader, errors);
else
{
errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader);
reader.SkipSubElementsFor(currentElementName);
result = null;
}
}
reader.LeaveElement();
}
catch (Exception ex)
{
errors.Add(ex.Message, reader);
}
return result;
}
/// <summary>
/// Parse ConformanceRestSecurityComponent
/// </summary>
public static Conformance.ConformanceRestSecurityComponent ParseConformanceRestSecurityComponent(IFhirReader reader, ErrorList errors, Conformance.ConformanceRestSecurityComponent existingInstance = null )
{
Conformance.ConformanceRestSecurityComponent result = existingInstance != null ? existingInstance : new Conformance.ConformanceRestSecurityComponent();
try
{
string currentElementName = reader.CurrentElementName;
reader.EnterElement();
while (reader.HasMoreElements())
{
// Parse element extension
if( ParserUtils.IsAtFhirElement(reader, "extension") )
{
result.Extension = new List<Extension>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "extension") )
result.Extension.Add(ExtensionParser.ParseExtension(reader, errors));
reader.LeaveArray();
}
// Parse element internalId
else if( reader.IsAtRefIdElement() )
result.InternalId = Id.Parse(reader.ReadRefIdContents());
// Parse element service
else if( ParserUtils.IsAtFhirElement(reader, "service") )
{
result.Service = new List<CodeableConcept>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "service") )
result.Service.Add(CodeableConceptParser.ParseCodeableConcept(reader, errors));
reader.LeaveArray();
}
// Parse element description
else if( ParserUtils.IsAtFhirElement(reader, "description") )
result.Description = FhirStringParser.ParseFhirString(reader, errors);
// Parse element certificate
else if( ParserUtils.IsAtFhirElement(reader, "certificate") )
{
result.Certificate = new List<Conformance.ConformanceRestSecurityCertificateComponent>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "certificate") )
result.Certificate.Add(ConformanceParser.ParseConformanceRestSecurityCertificateComponent(reader, errors));
reader.LeaveArray();
}
else
{
errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader);
reader.SkipSubElementsFor(currentElementName);
result = null;
}
}
reader.LeaveElement();
}
catch (Exception ex)
{
errors.Add(ex.Message, reader);
}
return result;
}
/// <summary>
/// Parse ConformancePublisherComponent
/// </summary>
public static Conformance.ConformancePublisherComponent ParseConformancePublisherComponent(IFhirReader reader, ErrorList errors, Conformance.ConformancePublisherComponent existingInstance = null )
{
Conformance.ConformancePublisherComponent result = existingInstance != null ? existingInstance : new Conformance.ConformancePublisherComponent();
try
{
string currentElementName = reader.CurrentElementName;
reader.EnterElement();
while (reader.HasMoreElements())
{
// Parse element extension
if( ParserUtils.IsAtFhirElement(reader, "extension") )
{
result.Extension = new List<Extension>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "extension") )
result.Extension.Add(ExtensionParser.ParseExtension(reader, errors));
reader.LeaveArray();
}
// Parse element internalId
else if( reader.IsAtRefIdElement() )
result.InternalId = Id.Parse(reader.ReadRefIdContents());
// Parse element name
else if( ParserUtils.IsAtFhirElement(reader, "name") )
result.Name = FhirStringParser.ParseFhirString(reader, errors);
// Parse element address
else if( ParserUtils.IsAtFhirElement(reader, "address") )
result.Address = AddressParser.ParseAddress(reader, errors);
// Parse element contact
else if( ParserUtils.IsAtFhirElement(reader, "contact") )
{
result.Contact = new List<Contact>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "contact") )
result.Contact.Add(ContactParser.ParseContact(reader, errors));
reader.LeaveArray();
}
else
{
errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader);
reader.SkipSubElementsFor(currentElementName);
result = null;
}
}
reader.LeaveElement();
}
catch (Exception ex)
{
errors.Add(ex.Message, reader);
}
return result;
}
/// <summary>
/// Parse ConformanceRestResourceSearchParamComponent
/// </summary>
public static Conformance.ConformanceRestResourceSearchParamComponent ParseConformanceRestResourceSearchParamComponent(IFhirReader reader, ErrorList errors, Conformance.ConformanceRestResourceSearchParamComponent existingInstance = null )
{
Conformance.ConformanceRestResourceSearchParamComponent result = existingInstance != null ? existingInstance : new Conformance.ConformanceRestResourceSearchParamComponent();
try
{
string currentElementName = reader.CurrentElementName;
reader.EnterElement();
while (reader.HasMoreElements())
{
// Parse element extension
if( ParserUtils.IsAtFhirElement(reader, "extension") )
{
result.Extension = new List<Extension>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "extension") )
result.Extension.Add(ExtensionParser.ParseExtension(reader, errors));
reader.LeaveArray();
}
// Parse element internalId
else if( reader.IsAtRefIdElement() )
result.InternalId = Id.Parse(reader.ReadRefIdContents());
// Parse element name
else if( ParserUtils.IsAtFhirElement(reader, "name") )
result.Name = FhirStringParser.ParseFhirString(reader, errors);
// Parse element source
else if( ParserUtils.IsAtFhirElement(reader, "source") )
result.Source = FhirUriParser.ParseFhirUri(reader, errors);
// Parse element type
else if( ParserUtils.IsAtFhirElement(reader, "type") )
result.Type = CodeParser.ParseCode<SearchParamType>(reader, errors);
// Parse element repeats
else if( ParserUtils.IsAtFhirElement(reader, "repeats") )
result.Repeats = CodeParser.ParseCode<SearchRepeatBehavior>(reader, errors);
// Parse element documentation
else if( ParserUtils.IsAtFhirElement(reader, "documentation") )
result.Documentation = FhirStringParser.ParseFhirString(reader, errors);
// Parse element target
else if( ParserUtils.IsAtFhirElement(reader, "target") )
{
result.Target = new List<Code>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "target") )
result.Target.Add(CodeParser.ParseCode(reader, errors));
reader.LeaveArray();
}
// Parse element chain
else if( ParserUtils.IsAtFhirElement(reader, "chain") )
{
result.Chain = new List<FhirString>();
reader.EnterArray();
while( ParserUtils.IsAtArrayElement(reader, "chain") )
result.Chain.Add(FhirStringParser.ParseFhirString(reader, errors));
reader.LeaveArray();
}
else
{
errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader);
reader.SkipSubElementsFor(currentElementName);
result = null;
}
}
reader.LeaveElement();
}
catch (Exception ex)
{
errors.Add(ex.Message, reader);
}
return result;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.