text stringlengths 13 6.01M |
|---|
using UnityEngine;
namespace TBeeD
{
public class Splotch : MonoBehaviour
{
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
FindObjectOfType<GameController>().SplotchesCovered++;
Destroy(gameObject);
}
}
}
} |
namespace MyApp.Services
{
using System.Linq;
using Data.Repositories;
using Models;
using MyApp.Services.Contracts;
public class DirectorsService : IDirectorsService
{
private readonly IRepository<Director> directors;
public DirectorsService( IRepository<Director> directors )
{
this.directors = directors;
}
public Director Create( string firstName, string lastName )
{
var director = new Director()
{
FirstName = firstName,
LastName = lastName
};
this.directors.Add( director );
return director;
}
public IQueryable<Director> GetAll()
{
return this.directors.All();
}
public Director GetById( int id )
{
return this.directors.GetById( id );
}
public void UpdateFirstNameById( int id, string firstName )
{
this.directors.GetById( id ).FirstName = firstName;
}
public void DeleteById( int id )
{
this.directors.Delete( id );
}
public int SaveChanges()
{
return this.directors.SaveChanges();
}
}
}
|
#region Usings
using Zengo.WP8.FAS.Models;
using System;
using System.Windows;
using System.Windows.Controls;
#endregion
namespace Zengo.WP8.FAS.Controls
{
public partial class LongListCountriesControl : UserControl
{
public class CountrySelectionChangedEventArgs : EventArgs
{
public CountryRecord Country { get; set; }
}
#region Events
public event EventHandler<CountrySelectionChangedEventArgs> SelectionChanged;
#endregion
#region Properties
private bool forAccountPage;
public bool ForAccountPage
{
get { return forAccountPage; }
set
{
forAccountPage = value;
if (forAccountPage)
{
countriesLongList.ItemTemplate = (DataTemplate)Resources["countriesItemForAccountTemplate"];
}
else
{
countriesLongList.ItemTemplate = (DataTemplate)Resources["countriesItemForSearchTemplate"];
}
}
}
#endregion
#region Constructors
public LongListCountriesControl()
{
InitializeComponent();
countriesLongList.SelectionChanged += new SelectionChangedEventHandler(countriesLongList_SelectionChanged);
}
#endregion
#region Events
void countriesLongList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (SelectionChanged != null)
{
SelectionChanged(this, new CountrySelectionChangedEventArgs() { Country = (CountryRecord)countriesLongList.SelectedItem });
}
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerBehavior : MonoBehaviour, IKillable
{
// Use this for initialization
PlayerData data;
public void Die()
{
data.alive = false;
if (data.alive == false)
transform.Rotate(90, 0, 0);
}
void Start()
{
data = ScriptableObject.CreateInstance<PlayerData>();
data.sprintTimer = 10;
}
// Update is called once per frame
void Update()
{
float moveh = Input.GetAxis("Horizontal");
float movev = Input.GetAxis("Vertical");
float roth = Input.GetAxis("Mouse X");
transform.Translate(moveh * .2f, 0, movev * .2f);
transform.Rotate(0, roth * 2, 0);
if (Input.GetKey(KeyCode.LeftShift))
{
if (data.sprintTimer <= 0)
{
transform.Translate(moveh * -.4f, 0, movev * -.4f);
data.sprintTimer = 0;
}
transform.Translate(moveh * .4f, 0, movev * .4f);
data.sprintTimer -= .1f;
}
if (!Input.GetKey(KeyCode.LeftShift))
{
data.sprintTimer += .1f;
if (data.sprintTimer >= 10)
data.sprintTimer = 10;
}
}
}
|
using Ambassador.Models.LocationModels.Interfaces;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Ambassador.Entities
{
[DisplayName("Location")]
public class Location : IOrganizationLocationManagerCreateModel, IOrganizationLocationManagerEditViewModel
{
[Key]
[Required]
[MaxLength(450)]
public string Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Address { get; set; }
public bool Deleted { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
[Required]
[MaxLength(450)]
public string OrganizationId { get; set; }
public Organization Organization { get; set; }
public ICollection<Event> Events { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Task 10
namespace Matrix_of_Numbers
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter n: ");
int n = int.Parse(Console.ReadLine());
for (int rows = 0; rows < n; rows++)
{
for (int cols = rows+1; cols <= rows+n; cols++)
{
Console.Write(cols);
}
Console.WriteLine();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsultingManager.Dto
{
public class ChartResultDto
{
public string Description { get; set; }
public decimal Value { get; set; }
}
}
|
#region License
/***
* Copyright © 2018-2025, 张强 (943620963@qq.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* without warranties or conditions of any kind, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using Force.DeepCloner;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Web.Routing;
using System.Xml.Serialization;
/****************************
* [Author] 张强
* [Date] 2018-05-15
* [Describe] object扩展类
* **************************/
namespace ZqUtils.Extensions
{
/// <summary>
/// object扩展类
/// </summary>
public static class ObjectExtensions
{
#region ToJson
/// <summary>
/// 对象序列化为json字符串
/// </summary>
/// <param name="this">待序列化的对象</param>
/// <returns>string</returns>
public static string ToJson(this object @this)
{
return JsonConvert.SerializeObject(@this);
}
/// <summary>
/// 对象序列化为json字符串
/// </summary>
/// <param name="this">待序列化的对象</param>
/// <param name="settings">JsonSerializerSettings配置</param>
/// <returns></returns>
public static string ToJson(this object @this, JsonSerializerSettings settings)
{
return JsonConvert.SerializeObject(@this, settings ?? new JsonSerializerSettings());
}
/// <summary>
/// 对象序列化为json字符串
/// </summary>
/// <param name="this">待序列化的对象</param>
/// <param name="camelCase">是否驼峰</param>
/// <param name="indented">是否缩进</param>
/// <param name="nullValueHandling">空值处理</param>
/// <param name="converter">json转换,如:new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }</param>
/// <returns>string</returns>
public static string ToJson(this object @this, bool camelCase = false, bool indented = false, NullValueHandling nullValueHandling = NullValueHandling.Include, JsonConverter converter = null)
{
var options = new JsonSerializerSettings();
if (camelCase)
{
options.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
if (indented)
{
options.Formatting = Formatting.Indented;
}
options.NullValueHandling = nullValueHandling;
if (converter != null)
{
options.Converters?.Add(converter);
}
return JsonConvert.SerializeObject(@this, options);
}
#endregion
#region ToExpando
/// <summary>
/// 匿名对象转换为ExpandoObject,用于mvc中view返回model值
/// </summary>
/// <param name="this">匿名类型对象</param>
/// <param name="isAnonymousType">是否是匿名类型,为false时返回null</param>
/// <returns></returns>
public static ExpandoObject ToExpando(this object @this, bool isAnonymousType)
{
if (isAnonymousType)
{
IDictionary<string, object> anonymousDictionary = new RouteValueDictionary(@this);
IDictionary<string, object> expando = new ExpandoObject();
foreach (var item in anonymousDictionary)
{
expando.Add(item);
}
return expando as ExpandoObject;
}
else if (typeof(IDictionary<string, object>).IsAssignableFrom(@this.GetType()))
{
return (@this as IDictionary<string, object>)?.ToExpando();
}
else
{
return null;
}
}
#endregion
#region ToSafeValue
/// <summary>
/// 转换为安全类型的值
/// </summary>
/// <param name="this">object对象</param>
/// <param name="type">type</param>
/// <returns>object</returns>
public static object ToSafeValue(this object @this, Type type)
{
return @this == null ? null : Convert.ChangeType(@this, type.GetCoreType());
}
#endregion
#region As
/// <summary>
/// Used to simplify and beautify casting an object to a type.
/// </summary>
/// <typeparam name="T">Type to be casted</typeparam>
/// <param name="this">object to cast</param>
/// <returns>Casted object</returns>
public static T As<T>(this object @this) where T : class
{
return (T)@this;
}
#endregion
#region AsOrDefault
/// <summary>
/// An object extension method that converts the @this to an or default.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <returns>A T.</returns>
public static T AsOrDefault<T>(this object @this)
{
try
{
return (T)@this;
}
catch (Exception)
{
return default(T);
}
}
/// <summary>
/// An object extension method that converts the @this to an or default.
/// </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 AsOrDefault<T>(this object @this, T defaultValue)
{
try
{
return (T)@this;
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts the @this to an or default.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>A T.</returns>
/// <example>
/// <code>
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_AsOrDefault
/// {
/// [TestMethod]
/// public void AsOrDefault()
/// {
/// // Type
/// object intValue = 1;
/// object invalidValue = "Fizz";
///
/// // Exemples
/// var result1 = intValue.AsOrDefault<int>(); // return 1;
/// var result2 = invalidValue.AsOrDefault<int>(); // return 0;
/// int result3 = invalidValue.AsOrDefault(3); // return 3;
/// int result4 = invalidValue.AsOrDefault(() => 4); // return 4;
///
/// // Unit Test
/// Assert.AreEqual(1, result1);
/// Assert.AreEqual(0, result2);
/// Assert.AreEqual(3, result3);
/// Assert.AreEqual(4, result4);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_AsOrDefault
/// {
/// [TestMethod]
/// public void AsOrDefault()
/// {
/// // Type
/// object intValue = 1;
/// object invalidValue = "Fizz";
///
/// // Exemples
/// var result1 = intValue.AsOrDefault<int>(); // return 1;
/// var result2 = invalidValue.AsOrDefault<int>(); // return 0;
/// int result3 = invalidValue.AsOrDefault(3); // return 3;
/// int result4 = invalidValue.AsOrDefault(() => 4); // return 4;
///
/// // Unit Test
/// Assert.AreEqual(1, result1);
/// Assert.AreEqual(0, result2);
/// Assert.AreEqual(3, result3);
/// Assert.AreEqual(4, result4);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_AsOrDefault
/// {
/// [TestMethod]
/// public void AsOrDefault()
/// {
/// // Type
/// object intValue = 1;
/// object invalidValue = "Fizz";
///
/// // Exemples
/// var result1 = intValue.AsOrDefault<int>(); // return 1;
/// var result2 = invalidValue.AsOrDefault<int>(); // return 0;
/// int result3 = invalidValue.AsOrDefault(3); // return 3;
/// int result4 = invalidValue.AsOrDefault(() => 4); // return 4;
///
/// // Unit Test
/// Assert.AreEqual(1, result1);
/// Assert.AreEqual(0, result2);
/// Assert.AreEqual(3, result3);
/// Assert.AreEqual(4, result4);
/// }
/// }
/// }
/// </code>
/// </example>
public static T AsOrDefault<T>(this object @this, Func<T> defaultValueFactory)
{
try
{
return (T)@this;
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts the @this to an or default.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>A T.</returns>
/// <example>
/// <code>
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_AsOrDefault
/// {
/// [TestMethod]
/// public void AsOrDefault()
/// {
/// // Type
/// object intValue = 1;
/// object invalidValue = "Fizz";
///
/// // Exemples
/// var result1 = intValue.AsOrDefault<int>(); // return 1;
/// var result2 = invalidValue.AsOrDefault<int>(); // return 0;
/// int result3 = invalidValue.AsOrDefault(3); // return 3;
/// int result4 = invalidValue.AsOrDefault(() => 4); // return 4;
///
/// // Unit Test
/// Assert.AreEqual(1, result1);
/// Assert.AreEqual(0, result2);
/// Assert.AreEqual(3, result3);
/// Assert.AreEqual(4, result4);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_AsOrDefault
/// {
/// [TestMethod]
/// public void AsOrDefault()
/// {
/// // Type
/// object intValue = 1;
/// object invalidValue = "Fizz";
///
/// // Exemples
/// var result1 = intValue.AsOrDefault<int>(); // return 1;
/// var result2 = invalidValue.AsOrDefault<int>(); // return 0;
/// int result3 = invalidValue.AsOrDefault(3); // return 3;
/// int result4 = invalidValue.AsOrDefault(() => 4); // return 4;
///
/// // Unit Test
/// Assert.AreEqual(1, result1);
/// Assert.AreEqual(0, result2);
/// Assert.AreEqual(3, result3);
/// Assert.AreEqual(4, result4);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_AsOrDefault
/// {
/// [TestMethod]
/// public void AsOrDefault()
/// {
/// // Type
/// object intValue = 1;
/// object invalidValue = "Fizz";
///
/// // Exemples
/// var result1 = intValue.AsOrDefault<int>(); // return 1;
/// var result2 = invalidValue.AsOrDefault<int>(); // return 0;
/// int result3 = invalidValue.AsOrDefault(3); // return 3;
/// int result4 = invalidValue.AsOrDefault(() => 4); // return 4;
///
/// // Unit Test
/// Assert.AreEqual(1, result1);
/// Assert.AreEqual(0, result2);
/// Assert.AreEqual(3, result3);
/// Assert.AreEqual(4, result4);
/// }
/// }
/// }
/// </code>
/// </example>
public static T AsOrDefault<T>(this object @this, Func<object, T> defaultValueFactory)
{
try
{
return (T)@this;
}
catch (Exception)
{
return defaultValueFactory(@this);
}
}
#endregion
#region To
/// <summary>
/// A System.Object extension method that toes the given this.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">this.</param>
/// <returns>A T.</returns>
/// <example>
/// <code>
/// using System;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_To
/// {
/// [TestMethod]
/// public void To()
/// {
/// string nullValue = null;
/// string value = "1";
/// object dbNullValue = DBNull.Value;
///
/// // Exemples
/// var result1 = value.To<int>(); // return 1;
/// var result2 = value.To<int?>(); // return 1;
/// var result3 = nullValue.To<int?>(); // return null;
/// var result4 = dbNullValue.To<int?>(); // return null;
///
/// // Unit Test
/// Assert.AreEqual(1, result1);
/// Assert.AreEqual(1, result2.Value);
/// Assert.IsFalse(result3.HasValue);
/// Assert.IsFalse(result4.HasValue);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using System;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_To
/// {
/// [TestMethod]
/// public void To()
/// {
/// string nullValue = null;
/// string value = "1";
/// object dbNullValue = DBNull.Value;
///
/// // Exemples
/// var result1 = value.To<int>(); // return 1;
/// var result2 = value.To<int?>(); // return 1;
/// var result3 = nullValue.To<int?>(); // return null;
/// var result4 = dbNullValue.To<int?>(); // return null;
///
/// // Unit Test
/// Assert.AreEqual(1, result1);
/// Assert.AreEqual(1, result2.Value);
/// Assert.IsFalse(result3.HasValue);
/// Assert.IsFalse(result4.HasValue);
/// }
/// }
/// }
/// </code>
/// </example>
public static T To<T>(this object @this)
{
if (@this != null)
{
Type targetType = typeof(T);
if (@this.GetType() == targetType)
{
return (T)@this;
}
TypeConverter converter = TypeDescriptor.GetConverter(@this);
if (converter != null)
{
if (converter.CanConvertTo(targetType))
{
return (T)converter.ConvertTo(@this, targetType);
}
}
converter = TypeDescriptor.GetConverter(targetType);
if (converter != null)
{
if (converter.CanConvertFrom(@this.GetType()))
{
return (T)converter.ConvertFrom(@this);
}
}
if (@this == DBNull.Value)
{
return (T)(object)null;
}
}
return @this == null ? default : (T)@this;
}
/// <summary>
/// A System.Object extension method that toes the given this.
/// </summary>
/// <param name="this">this.</param>
/// <param name="type">The type.</param>
/// <returns>An object.</returns>
/// <example>
/// <code>
/// using System;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_To
/// {
/// [TestMethod]
/// public void To()
/// {
/// string nullValue = null;
/// string value = "1";
/// object dbNullValue = DBNull.Value;
///
/// // Exemples
/// var result1 = value.To<int>(); // return 1;
/// var result2 = value.To<int?>(); // return 1;
/// var result3 = nullValue.To<int?>(); // return null;
/// var result4 = dbNullValue.To<int?>(); // return null;
///
/// // Unit Test
/// Assert.AreEqual(1, result1);
/// Assert.AreEqual(1, result2.Value);
/// Assert.IsFalse(result3.HasValue);
/// Assert.IsFalse(result4.HasValue);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using System;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_To
/// {
/// [TestMethod]
/// public void To()
/// {
/// string nullValue = null;
/// string value = "1";
/// object dbNullValue = DBNull.Value;
///
/// // Exemples
/// var result1 = value.To<int>(); // return 1;
/// var result2 = value.To<int?>(); // return 1;
/// var result3 = nullValue.To<int?>(); // return null;
/// var result4 = dbNullValue.To<int?>(); // return null;
///
/// // Unit Test
/// Assert.AreEqual(1, result1);
/// Assert.AreEqual(1, result2.Value);
/// Assert.IsFalse(result3.HasValue);
/// Assert.IsFalse(result4.HasValue);
/// }
/// }
/// }
/// </code>
/// </example>
public static object To(this Object @this, Type type)
{
if (@this != null)
{
Type targetType = type;
if (@this.GetType() == targetType)
{
return @this;
}
TypeConverter converter = TypeDescriptor.GetConverter(@this);
if (converter != null)
{
if (converter.CanConvertTo(targetType))
{
return converter.ConvertTo(@this, targetType);
}
}
converter = TypeDescriptor.GetConverter(targetType);
if (converter != null)
{
if (converter.CanConvertFrom(@this.GetType()))
{
return converter.ConvertFrom(@this);
}
}
if (@this == DBNull.Value)
{
return null;
}
}
return @this;
}
#endregion
#region ToOrDefault
/// <summary>
/// A System.Object extension method that converts this object to an or default.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">this.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a T.</returns>
/// <example>
/// <code>
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_ToOrDefault
/// {
/// [TestMethod]
/// public void ToOrDefault()
/// {
/// // Type
/// object intValue = "1";
/// object invalidValue = "Fizz";
///
/// // Exemples
/// var result1 = intValue.ToOrDefault<int>(); // return 1;
/// var result2 = invalidValue.ToOrDefault<int>(); // return 0;
/// int result3 = invalidValue.ToOrDefault(3); // return 3;
/// int result4 = invalidValue.ToOrDefault(() => 4); // return 4;
///
/// // Unit Test
/// Assert.AreEqual(1, result1);
/// Assert.AreEqual(0, result2);
/// Assert.AreEqual(3, result3);
/// Assert.AreEqual(4, result4);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_ToOrDefault
/// {
/// [TestMethod]
/// public void ToOrDefault()
/// {
/// // Type
/// object intValue = "1";
/// object invalidValue = "Fizz";
///
/// // Exemples
/// var result1 = intValue.ToOrDefault<int>(); // return 1;
/// var result2 = invalidValue.ToOrDefault<int>(); // return 0;
/// int result3 = invalidValue.ToOrDefault(3); // return 3;
/// int result4 = invalidValue.ToOrDefault(() => 4); // return 4;
///
/// // Unit Test
/// Assert.AreEqual(1, result1);
/// Assert.AreEqual(0, result2);
/// Assert.AreEqual(3, result3);
/// Assert.AreEqual(4, result4);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_ToOrDefault
/// {
/// [TestMethod]
/// public void ToOrDefault()
/// {
/// // Type
/// object intValue = "1";
/// object invalidValue = "Fizz";
///
/// // Exemples
/// var result1 = intValue.ToOrDefault<int>(); // return 1;
/// var result2 = invalidValue.ToOrDefault<int>(); // return 0;
/// int result3 = invalidValue.ToOrDefault(3); // return 3;
/// int result4 = invalidValue.ToOrDefault(() => 4); // return 4;
///
/// // Unit Test
/// Assert.AreEqual(1, result1);
/// Assert.AreEqual(0, result2);
/// Assert.AreEqual(3, result3);
/// Assert.AreEqual(4, result4);
/// }
/// }
/// }
/// </code>
/// </example>
public static T ToOrDefault<T>(this object @this, Func<object, T> defaultValueFactory)
{
try
{
if (@this != null)
{
Type targetType = typeof(T);
if (@this.GetType() == targetType)
{
return (T)@this;
}
TypeConverter converter = TypeDescriptor.GetConverter(@this);
if (converter != null)
{
if (converter.CanConvertTo(targetType))
{
return (T)converter.ConvertTo(@this, targetType);
}
}
converter = TypeDescriptor.GetConverter(targetType);
if (converter != null)
{
if (converter.CanConvertFrom(@this.GetType()))
{
return (T)converter.ConvertFrom(@this);
}
}
if (@this == DBNull.Value)
{
return (T)(object)null;
}
}
return (T)@this;
}
catch (Exception)
{
return defaultValueFactory(@this);
}
}
/// <summary>
/// A System.Object extension method that converts this object to an or default.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">this.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a T.</returns>
/// <example>
/// <code>
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_ToOrDefault
/// {
/// [TestMethod]
/// public void ToOrDefault()
/// {
/// // Type
/// object intValue = "1";
/// object invalidValue = "Fizz";
///
/// // Exemples
/// var result1 = intValue.ToOrDefault<int>(); // return 1;
/// var result2 = invalidValue.ToOrDefault<int>(); // return 0;
/// int result3 = invalidValue.ToOrDefault(3); // return 3;
/// int result4 = invalidValue.ToOrDefault(() => 4); // return 4;
///
/// // Unit Test
/// Assert.AreEqual(1, result1);
/// Assert.AreEqual(0, result2);
/// Assert.AreEqual(3, result3);
/// Assert.AreEqual(4, result4);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_ToOrDefault
/// {
/// [TestMethod]
/// public void ToOrDefault()
/// {
/// // Type
/// object intValue = "1";
/// object invalidValue = "Fizz";
///
/// // Exemples
/// var result1 = intValue.ToOrDefault<int>(); // return 1;
/// var result2 = invalidValue.ToOrDefault<int>(); // return 0;
/// int result3 = invalidValue.ToOrDefault(3); // return 3;
/// int result4 = invalidValue.ToOrDefault(() => 4); // return 4;
///
/// // Unit Test
/// Assert.AreEqual(1, result1);
/// Assert.AreEqual(0, result2);
/// Assert.AreEqual(3, result3);
/// Assert.AreEqual(4, result4);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_ToOrDefault
/// {
/// [TestMethod]
/// public void ToOrDefault()
/// {
/// // Type
/// object intValue = "1";
/// object invalidValue = "Fizz";
///
/// // Exemples
/// var result1 = intValue.ToOrDefault<int>(); // return 1;
/// var result2 = invalidValue.ToOrDefault<int>(); // return 0;
/// int result3 = invalidValue.ToOrDefault(3); // return 3;
/// int result4 = invalidValue.ToOrDefault(() => 4); // return 4;
///
/// // Unit Test
/// Assert.AreEqual(1, result1);
/// Assert.AreEqual(0, result2);
/// Assert.AreEqual(3, result3);
/// Assert.AreEqual(4, result4);
/// }
/// }
/// }
/// </code>
/// </example>
public static T ToOrDefault<T>(this Object @this, Func<T> defaultValueFactory)
{
return @this.ToOrDefault(x => defaultValueFactory());
}
/// <summary>
/// A System.Object extension method that converts this object to an or default.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">this.</param>
/// <returns>The given data converted to a T.</returns>
public static T ToOrDefault<T>(this Object @this)
{
return @this.ToOrDefault(x => default(T));
}
/// <summary>
/// A System.Object extension method that converts this object to an or default.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">this.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a T.</returns>
public static T ToOrDefault<T>(this Object @this, T defaultValue)
{
return @this.ToOrDefault(x => defaultValue);
}
#endregion
#region IsIn
/// <summary>
/// Check if an item is in a list.
/// </summary>
/// <param name="this">Item to check</param>
/// <param name="list">List of items</param>
/// <typeparam name="T">Type of the items</typeparam>
public static bool IsIn<T>(this T @this, params T[] list)
{
return list.Contains(@this);
}
#endregion
#region ToValueType
#region ToInt
/// <summary>
/// 转为整数,转换失败时返回默认值。支持字符串、全角、字节数组(小端)、时间(Unix秒)
/// </summary>
/// <remarks>
/// Int16/UInt32/long等,可以先转为最常用的int后再二次处理
/// </remarks>
/// <param name="this">待转换对象</param>
/// <param name="defaultValue">默认值。待转换对象无效时使用</param>
/// <returns></returns>
public static int ToInt(this object @this, int defaultValue = 0)
{
if (@this == null || @this == DBNull.Value) return defaultValue;
// 特殊处理字符串,也是最常见的
if (@this is string str)
{
// 拷贝而来的逗号分隔整数
str = str.Replace(",", null);
str = str.ToDBC().Trim();
if (str.IsNullOrEmpty()) return defaultValue;
if (int.TryParse(str, out var n)) return n;
return defaultValue;
}
// 特殊处理时间,转Unix秒
if (@this is DateTime dt)
{
//// 先转UTC时间再相减,以得到绝对时间差
return (int)(dt - new DateTime(1970, 1, 1)).TotalSeconds;
}
if (@this is byte[] buf)
{
if (buf == null || buf.Length < 1) return defaultValue;
switch (buf.Length)
{
case 1:
return buf[0];
case 2:
return BitConverter.ToInt16(buf, 0);
case 3:
return BitConverter.ToInt32(new byte[] { buf[0], buf[1], buf[2], 0 }, 0);
case 4:
return BitConverter.ToInt32(buf, 0);
default:
break;
}
}
try
{
return Convert.ToInt32(@this);
}
catch
{
return defaultValue;
}
}
#endregion
#region ToLong
/// <summary>
/// 转为长整数,转换失败时返回默认值。支持字符串、全角、字节数组(小端)
/// </summary>
/// <param name="this">待转换对象</param>
/// <param name="defaultValue">默认值。待转换对象无效时使用</param>
/// <returns></returns>
public static long ToLong(this object @this, long defaultValue = 0)
{
if (@this == null || @this == DBNull.Value) return defaultValue;
// 特殊处理字符串,也是最常见的
if (@this is string str)
{
// 拷贝而来的逗号分隔整数
str = str.Replace(",", null);
str = str.ToDBC().Trim();
if (str.IsNullOrEmpty()) return defaultValue;
if (long.TryParse(str, out var n)) return n;
return defaultValue;
}
//暂时不做处理 先处理异常转换
try
{
return Convert.ToInt64(@this);
}
catch { return defaultValue; }
}
#endregion
#region ToLongOrDefault
/// <summary>
/// An object extension method that converts this object to a long or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a long.</returns>
public static long ToLongOrDefault(this object @this)
{
try
{
return Convert.ToInt64(@this);
}
catch (Exception)
{
return default(long);
}
}
/// <summary>
/// An object extension method that converts this object to a long or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a long.</returns>
public static long ToLongOrDefault(this object @this, long defaultValue)
{
try
{
return Convert.ToInt64(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a long or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a long.</returns>
public static long ToLongOrDefault(this object @this, long defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToInt64(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a long or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a long.</returns>
public static long ToLongOrDefault(this object @this, Func<long> defaultValueFactory)
{
try
{
return Convert.ToInt64(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to a long or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a long.</returns>
public static long ToLongOrDefault(this object @this, Func<long> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToInt64(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToDouble
/// <summary>
/// 转为浮点数,转换失败时返回默认值。支持字符串、全角、字节数组(小端)
/// </summary>
/// <remarks>
/// single可以先转为最常用的double后再二次处理
/// </remarks>
/// <param name="this">待转换对象</param>
/// <param name="defaultValue">默认值。待转换对象无效时使用</param>
/// <returns></returns>
public static double ToDouble(this object @this, double defaultValue = 0)
{
if (@this == null || @this == DBNull.Value) return defaultValue;
// 特殊处理字符串,也是最常见的
if (@this is string str)
{
str = str.ToDBC().Trim();
if (str.IsNullOrEmpty()) return defaultValue;
if (double.TryParse(str, out var n)) return n;
return defaultValue;
}
else if (@this is byte[] buf)
{
if (buf == null || buf.Length < 1) return defaultValue;
switch (buf.Length)
{
case 1:
return buf[0];
case 2:
return BitConverter.ToInt16(buf, 0);
case 3:
return BitConverter.ToInt32(new byte[] { buf[0], buf[1], buf[2], 0 }, 0);
case 4:
return BitConverter.ToInt32(buf, 0);
default:
// 凑够8字节
if (buf.Length < 8)
{
var bts = new byte[8];
Buffer.BlockCopy(buf, 0, bts, 0, buf.Length);
buf = bts;
}
return BitConverter.ToDouble(buf, 0);
}
}
try
{
return Convert.ToDouble(@this);
}
catch
{
return defaultValue;
}
}
#endregion
#region ToDoubleOrDefault
/// <summary>
/// An object extension method that converts this object to a double or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a double.</returns>
public static double ToDoubleOrDefault(this object @this)
{
try
{
return Convert.ToDouble(@this);
}
catch (Exception)
{
return default(double);
}
}
/// <summary>
/// An object extension method that converts this object to a double or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a double.</returns>
public static double ToDoubleOrDefault(this object @this, double defaultValue)
{
try
{
return Convert.ToDouble(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a double or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a double.</returns>
public static double ToDoubleOrDefault(this object @this, double defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToDouble(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a double or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a double.</returns>
public static double ToDoubleOrDefault(this object @this, Func<double> defaultValueFactory)
{
try
{
return Convert.ToDouble(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to a double or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a double.</returns>
public static double ToDoubleOrDefault(this object @this, Func<double> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToDouble(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToBoolean
/// <summary>
/// 转为布尔型,转换失败时返回默认值。支持大小写True/False、0和非零
/// </summary>
/// <param name="this">待转换对象</param>
/// <param name="defaultValue">默认值。待转换对象无效时使用</param>
/// <returns></returns>
public static bool ToBoolean(this object @this, bool defaultValue = false)
{
if (@this == null || @this == DBNull.Value) return defaultValue;
// 特殊处理字符串,也是最常见的
if (@this is string str)
{
str = str.ToDBC().Trim();
if (str.IsNullOrEmpty()) return defaultValue;
if (bool.TryParse(str, out var b)) return b;
if (string.Equals(str, bool.TrueString, StringComparison.OrdinalIgnoreCase)) return true;
if (string.Equals(str, bool.FalseString, StringComparison.OrdinalIgnoreCase)) return false;
// 特殊处理用数字0和1表示布尔型
if (int.TryParse(str, out var n)) return n > 0;
return defaultValue;
}
try
{
return Convert.ToBoolean(@this);
}
catch
{
return defaultValue;
}
}
#endregion
#region ToBooleanOrDefault
/// <summary>
/// An object extension method that converts this object to a boolean or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a bool.</returns>
public static bool ToBooleanOrDefault(this object @this)
{
try
{
return Convert.ToBoolean(@this);
}
catch (Exception)
{
return default(bool);
}
}
/// <summary>
/// An object extension method that converts this object to a boolean or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">true to default value.</param>
/// <returns>The given data converted to a bool.</returns>
public static bool ToBooleanOrDefault(this object @this, bool defaultValue)
{
try
{
return Convert.ToBoolean(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a boolean or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">true to default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a bool.</returns>
public static bool ToBooleanOrDefault(this object @this, bool defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToBoolean(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a boolean or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a bool.</returns>
public static bool ToBooleanOrDefault(this object @this, Func<bool> defaultValueFactory)
{
try
{
return Convert.ToBoolean(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to a boolean or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a bool.</returns>
public static bool ToBooleanOrDefault(this object @this, Func<bool> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToBoolean(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToDateTime
/// <summary>
/// 转为时间日期,转换失败时返回最小时间。支持字符串、整数(Unix秒)
/// </summary>
/// <param name="this">待转换对象</param>
/// <returns></returns>
public static DateTime ToDateTime(this object @this)
{
return ToDateTime(@this, DateTime.MinValue);
}
/// <summary>
/// 转为时间日期,转换失败时返回默认值
/// </summary>
/// <remarks>
/// <see cref="DateTime.MinValue"/>不是常量无法做默认值
/// </remarks>
/// <param name="this">待转换对象</param>
/// <param name="defaultValue">默认值。待转换对象无效时使用</param>
/// <returns></returns>
public static DateTime ToDateTime(this object @this, DateTime defaultValue)
{
if (@this == null || @this == DBNull.Value) return defaultValue;
// 特殊处理字符串,也是最常见的
if (@this is string str)
{
str = str.ToDBC().Trim();
if (str.IsNullOrEmpty()) return defaultValue;
if (DateTime.TryParse(str, out var n)) return n;
if (str.Contains("-") && DateTime.TryParseExact(str, "yyyy-M-d", null, DateTimeStyles.None, out n)) return n;
if (str.Contains("/") && DateTime.TryParseExact(str, "yyyy/M/d", null, DateTimeStyles.None, out n)) return n;
if (DateTime.TryParse(str, out n)) return n;
return defaultValue;
}
// 特殊处理整数,Unix秒,绝对时间差,不考虑UTC时间和本地时间。
var _dt1970 = new DateTime(1970, 1, 1);
if (@this is int k) return _dt1970.AddSeconds(k);
if (@this is long m)
{
if (m > 100 * 365 * 24 * 3600L)
return _dt1970.AddMilliseconds(m);
else
return _dt1970.AddSeconds(m);
}
try
{
return Convert.ToDateTime(@this);
}
catch
{
return defaultValue;
}
}
#endregion
#region ToDateTimeOrDefault
/// <summary>
/// An object extension method that converts this object to a date time or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a DateTime.</returns>
public static DateTime ToDateTimeOrDefault(this object @this)
{
try
{
return Convert.ToDateTime(@this);
}
catch (Exception)
{
return default(DateTime);
}
}
/// <summary>
/// An object extension method that converts this object to a date time or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a DateTime.</returns>
public static DateTime ToDateTimeOrDefault(this object @this, DateTime defaultValue)
{
try
{
return Convert.ToDateTime(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a date time or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a DateTime.</returns>
public static DateTime ToDateTimeOrDefault(this object @this, DateTime defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToDateTime(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a date time or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a DateTime.</returns>
public static DateTime ToDateTimeOrDefault(this object @this, Func<DateTime> defaultValueFactory)
{
try
{
return Convert.ToDateTime(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to a date time or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a DateTime.</returns>
public static DateTime ToDateTimeOrDefault(this object @this, Func<DateTime> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToDateTime(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToDateTimeOffSet
/// <summary>
/// An object extension method that converts the @this to a date time off set.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a DateTimeOffset.</returns>
public static DateTimeOffset ToDateTimeOffSet(this object @this)
{
return new DateTimeOffset(Convert.ToDateTime(@this), TimeSpan.Zero);
}
#endregion
#region ToDateTimeOffSetOrDefault
/// <summary>
/// An object extension method that converts this object to a date time off set or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a DateTimeOffset.</returns>
public static DateTimeOffset ToDateTimeOffSetOrDefault(this object @this)
{
try
{
return new DateTimeOffset(Convert.ToDateTime(@this), TimeSpan.Zero);
}
catch (Exception)
{
return default(DateTimeOffset);
}
}
/// <summary>
/// An object extension method that converts this object to a date time off set or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a DateTimeOffset.</returns>
public static DateTimeOffset ToDateTimeOffSetOrDefault(this object @this, DateTimeOffset defaultValue)
{
try
{
return new DateTimeOffset(Convert.ToDateTime(@this), TimeSpan.Zero);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a date time off set or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a DateTimeOffset.</returns>
public static DateTimeOffset ToDateTimeOffSetOrDefault(this object @this, DateTimeOffset defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return new DateTimeOffset(Convert.ToDateTime(@this), TimeSpan.Zero);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a date time off set or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a DateTimeOffset.</returns>
public static DateTimeOffset ToDateTimeOffSetOrDefault(this object @this, Func<DateTimeOffset> defaultValueFactory)
{
try
{
return new DateTimeOffset(Convert.ToDateTime(@this), TimeSpan.Zero);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to a date time off set or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a DateTimeOffset.</returns>
public static DateTimeOffset ToDateTimeOffSetOrDefault(this object @this, Func<DateTimeOffset> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return new DateTimeOffset(Convert.ToDateTime(@this), TimeSpan.Zero);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToByte
/// <summary>
/// An object extension method that converts the @this to a byte.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a byte.</returns>
public static byte ToByte(this object @this)
{
return Convert.ToByte(@this);
}
#endregion
#region ToByteOrDefault
/// <summary>
/// An object extension method that converts this object to a byte or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a byte.</returns>
public static byte ToByteOrDefault(this object @this)
{
try
{
return Convert.ToByte(@this);
}
catch (Exception)
{
return default(byte);
}
}
/// <summary>
/// An object extension method that converts this object to a byte or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a byte.</returns>
public static byte ToByteOrDefault(this object @this, byte defaultValue)
{
try
{
return Convert.ToByte(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a byte or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a byte.</returns>
public static byte ToByteOrDefault(this object @this, byte defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToByte(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a byte or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a byte.</returns>
public static byte ToByteOrDefault(this object @this, Func<byte> defaultValueFactory)
{
try
{
return Convert.ToByte(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to a byte or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a byte.</returns>
public static byte ToByteOrDefault(this object @this, Func<byte> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToByte(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToChar
/// <summary>
/// An object extension method that converts the @this to a character.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a char.</returns>
public static char ToChar(this object @this)
{
return Convert.ToChar(@this);
}
#endregion
#region ToCharOrDefault
/// <summary>
/// An object extension method that converts this object to a character or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a char.</returns>
public static char ToCharOrDefault(this object @this)
{
try
{
return Convert.ToChar(@this);
}
catch (Exception)
{
return default(char);
}
}
/// <summary>
/// An object extension method that converts this object to a character or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a char.</returns>
public static char ToCharOrDefault(this object @this, char defaultValue)
{
try
{
return Convert.ToChar(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a character or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a char.</returns>
public static char ToCharOrDefault(this object @this, char defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToChar(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a character or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a char.</returns>
public static char ToCharOrDefault(this object @this, Func<char> defaultValueFactory)
{
try
{
return Convert.ToChar(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to a character or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a char.</returns>
public static char ToCharOrDefault(this object @this, Func<char> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToChar(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToDecimal
/// <summary>
/// An object extension method that converts the @this to a decimal.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a decimal.</returns>
public static decimal ToDecimal(this object @this)
{
return Convert.ToDecimal(@this);
}
#endregion
#region ToDecimalOrDefault
/// <summary>
/// An object extension method that converts this object to a decimal or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a decimal.</returns>
public static decimal ToDecimalOrDefault(this object @this)
{
try
{
return Convert.ToDecimal(@this);
}
catch (Exception)
{
return default(decimal);
}
}
/// <summary>
/// An object extension method that converts this object to a decimal or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a decimal.</returns>
public static decimal ToDecimalOrDefault(this object @this, decimal defaultValue)
{
try
{
return Convert.ToDecimal(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a decimal or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a decimal.</returns>
public static decimal ToDecimalOrDefault(this object @this, decimal defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToDecimal(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a decimal or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a decimal.</returns>
public static decimal ToDecimalOrDefault(this object @this, Func<decimal> defaultValueFactory)
{
try
{
return Convert.ToDecimal(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to a decimal or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a decimal.</returns>
public static decimal ToDecimalOrDefault(this object @this, Func<decimal> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToDecimal(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToFloat
/// <summary>
/// An object extension method that converts the @this to a float.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a float.</returns>
public static float ToFloat(this object @this)
{
return Convert.ToSingle(@this);
}
#endregion
#region ToFloatOrDefault
/// <summary>
/// An object extension method that converts this object to a float or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a float.</returns>
public static float ToFloatOrDefault(this object @this)
{
try
{
return Convert.ToSingle(@this);
}
catch (Exception)
{
return default(float);
}
}
/// <summary>
/// An object extension method that converts this object to a float or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a float.</returns>
public static float ToFloatOrDefault(this object @this, float defaultValue)
{
try
{
return Convert.ToSingle(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a float or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a float.</returns>
public static float ToFloatOrDefault(this object @this, float defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToSingle(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a float or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a float.</returns>
public static float ToFloatOrDefault(this object @this, Func<float> defaultValueFactory)
{
try
{
return Convert.ToSingle(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to a float or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a float.</returns>
public static float ToFloatOrDefault(this object @this, Func<float> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToSingle(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToGuid
/// <summary>
/// An object extension method that converts the @this to a unique identifier.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a GUID.</returns>
public static Guid ToGuid(this object @this)
{
return new Guid(@this.ToString());
}
#endregion
#region ToGuidOrDefault
/// <summary>
/// An object extension method that converts this object to a unique identifier or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a GUID.</returns>
public static Guid ToGuidOrDefault(this object @this)
{
try
{
return new Guid(@this.ToString());
}
catch (Exception)
{
return Guid.Empty;
}
}
/// <summary>
/// An object extension method that converts this object to a unique identifier or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a GUID.</returns>
public static Guid ToGuidOrDefault(this object @this, Guid defaultValue)
{
try
{
return new Guid(@this.ToString());
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a unique identifier or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a GUID.</returns>
public static Guid ToGuidOrDefault(this object @this, Guid defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return new Guid(@this.ToString());
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a unique identifier or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a GUID.</returns>
public static Guid ToGuidOrDefault(this object @this, Func<Guid> defaultValueFactory)
{
try
{
return new Guid(@this.ToString());
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to a unique identifier or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a GUID.</returns>
public static Guid ToGuidOrDefault(this object @this, Func<Guid> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return new Guid(@this.ToString());
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToInt16
/// <summary>
/// An object extension method that converts the @this to an int 16.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a short.</returns>
public static short ToInt16(this object @this)
{
return Convert.ToInt16(@this);
}
#endregion
#region ToInt16OrDefault
/// <summary>
/// An object extension method that converts this object to an int 16 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a short.</returns>
public static short ToInt16OrDefault(this object @this)
{
try
{
return Convert.ToInt16(@this);
}
catch (Exception)
{
return default(short);
}
}
/// <summary>
/// An object extension method that converts this object to an int 16 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a short.</returns>
public static short ToInt16OrDefault(this object @this, short defaultValue)
{
try
{
return Convert.ToInt16(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to an int 16 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a short.</returns>
public static short ToInt16OrDefault(this object @this, short defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToInt16(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to an int 16 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a short.</returns>
public static short ToInt16OrDefault(this object @this, Func<short> defaultValueFactory)
{
try
{
return Convert.ToInt16(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to an int 16 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a short.</returns>
public static short ToInt16OrDefault(this object @this, Func<short> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToInt16(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToInt32
/// <summary>
/// An object extension method that converts the @this to an int 32.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as an int.</returns>
public static int ToInt32(this object @this)
{
return Convert.ToInt32(@this);
}
#endregion
#region ToInt32OrDefault
/// <summary>
/// An object extension method that converts this object to an int 32 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to an int.</returns>
public static int ToInt32OrDefault(this object @this)
{
try
{
return Convert.ToInt32(@this);
}
catch (Exception)
{
return default(int);
}
}
/// <summary>
/// An object extension method that converts this object to an int 32 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to an int.</returns>
public static int ToInt32OrDefault(this object @this, int defaultValue)
{
try
{
return Convert.ToInt32(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to an int 32 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to an int.</returns>
public static int ToInt32OrDefault(this object @this, int defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToInt32(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to an int 32 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to an int.</returns>
public static int ToInt32OrDefault(this object @this, Func<int> defaultValueFactory)
{
try
{
return Convert.ToInt32(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to an int 32 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to an int.</returns>
public static int ToInt32OrDefault(this object @this, Func<int> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToInt32(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToInt64
/// <summary>
/// An object extension method that converts the @this to an int 64.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a long.</returns>
public static long ToInt64(this object @this)
{
return Convert.ToInt64(@this);
}
#endregion
#region ToInt64OrDefault
/// <summary>
/// An object extension method that converts this object to an int 64 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a long.</returns>
public static long ToInt64OrDefault(this object @this)
{
try
{
return Convert.ToInt64(@this);
}
catch (Exception)
{
return default(long);
}
}
/// <summary>
/// An object extension method that converts this object to an int 64 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a long.</returns>
public static long ToInt64OrDefault(this object @this, long defaultValue)
{
try
{
return Convert.ToInt64(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to an int 64 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a long.</returns>
public static long ToInt64OrDefault(this object @this, long defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToInt64(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to an int 64 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a long.</returns>
public static long ToInt64OrDefault(this object @this, Func<long> defaultValueFactory)
{
try
{
return Convert.ToInt64(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to an int 64 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a long.</returns>
public static long ToInt64OrDefault(this object @this, Func<long> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToInt64(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToSByte
/// <summary>
/// An object extension method that converts the @this to the s byte.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a sbyte.</returns>
public static sbyte ToSByte(this object @this)
{
return Convert.ToSByte(@this);
}
#endregion
#region ToSByteOrDefault
/// <summary>
/// An object extension method that converts this object to the s byte or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a sbyte.</returns>
public static sbyte ToSByteOrDefault(this object @this)
{
try
{
return Convert.ToSByte(@this);
}
catch (Exception)
{
return default(sbyte);
}
}
/// <summary>
/// An object extension method that converts this object to the s byte or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a sbyte.</returns>
public static sbyte ToSByteOrDefault(this object @this, sbyte defaultValue)
{
try
{
return Convert.ToSByte(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to the s byte or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a sbyte.</returns>
public static sbyte ToSByteOrDefault(this object @this, sbyte defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToSByte(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to the s byte or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a sbyte.</returns>
public static sbyte ToSByteOrDefault(this object @this, Func<sbyte> defaultValueFactory)
{
try
{
return Convert.ToSByte(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to the s byte or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a sbyte.</returns>
public static sbyte ToSByteOrDefault(this object @this, Func<sbyte> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToSByte(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToShort
/// <summary>
/// An object extension method that converts the @this to a short.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a short.</returns>
public static short ToShort(this object @this)
{
return Convert.ToInt16(@this);
}
#endregion
#region ToShortOrDefault
/// <summary>
/// An object extension method that converts this object to a short or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a short.</returns>
public static short ToShortOrDefault(this object @this)
{
try
{
return Convert.ToInt16(@this);
}
catch (Exception)
{
return default(short);
}
}
/// <summary>
/// An object extension method that converts this object to a short or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a short.</returns>
public static short ToShortOrDefault(this object @this, short defaultValue)
{
try
{
return Convert.ToInt16(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a short or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a short.</returns>
public static short ToShortOrDefault(this object @this, short defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToInt16(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a short or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a short.</returns>
public static short ToShortOrDefault(this object @this, Func<short> defaultValueFactory)
{
try
{
return Convert.ToInt16(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to a short or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a short.</returns>
public static short ToShortOrDefault(this object @this, Func<short> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToInt16(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToSingle
/// <summary>
/// An object extension method that converts the @this to a single.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a float.</returns>
public static float ToSingle(this object @this)
{
return Convert.ToSingle(@this);
}
#endregion
#region ToSingleOrDefault
/// <summary>
/// An object extension method that converts this object to a single or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a float.</returns>
public static float ToSingleOrDefault(this object @this)
{
try
{
return Convert.ToSingle(@this);
}
catch (Exception)
{
return default(float);
}
}
/// <summary>
/// An object extension method that converts this object to a single or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a float.</returns>
public static float ToSingleOrDefault(this object @this, float defaultValue)
{
try
{
return Convert.ToSingle(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a single or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a float.</returns>
public static float ToSingleOrDefault(this object @this, float defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToSingle(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a single or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a float.</returns>
public static float ToSingleOrDefault(this object @this, Func<float> defaultValueFactory)
{
try
{
return Convert.ToSingle(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to a single or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a float.</returns>
public static float ToSingleOrDefault(this object @this, Func<float> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToSingle(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToString
/// <summary>
/// An object extension method that convert this object into a string representation.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>A string that represents this object.</returns>
public static string ToString(this object @this)
{
return Convert.ToString(@this);
}
#endregion
#region ToStringOrDefault
/// <summary>
/// An object extension method that converts this object to a string or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a string.</returns>
public static string ToStringOrDefault(this object @this)
{
try
{
return Convert.ToString(@this);
}
catch (Exception)
{
return default(string);
}
}
/// <summary>
/// An object extension method that converts this object to a string or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a string.</returns>
public static string ToStringOrDefault(this object @this, string defaultValue)
{
try
{
return Convert.ToString(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a string or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a string.</returns>
public static string ToStringOrDefault(this object @this, string defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToString(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a string or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a string.</returns>
public static string ToStringOrDefault(this object @this, Func<string> defaultValueFactory)
{
try
{
return Convert.ToString(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to a string or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to a string.</returns>
public static string ToStringOrDefault(this object @this, Func<string> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToString(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToUInt16
/// <summary>
/// An object extension method that converts the @this to an u int 16.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as an ushort.</returns>
public static ushort ToUInt16(this object @this)
{
return Convert.ToUInt16(@this);
}
#endregion
#region ToUInt16OrDefault
/// <summary>
/// An object extension method that converts this object to an u int 16 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to an ushort.</returns>
public static ushort ToUInt16OrDefault(this object @this)
{
try
{
return Convert.ToUInt16(@this);
}
catch (Exception)
{
return default(ushort);
}
}
/// <summary>
/// An object extension method that converts this object to an u int 16 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to an ushort.</returns>
public static ushort ToUInt16OrDefault(this object @this, ushort defaultValue)
{
try
{
return Convert.ToUInt16(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to an u int 16 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to an ushort.</returns>
public static ushort ToUInt16OrDefault(this object @this, ushort defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToUInt16(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to an u int 16 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to an ushort.</returns>
public static ushort ToUInt16OrDefault(this object @this, Func<ushort> defaultValueFactory)
{
try
{
return Convert.ToUInt16(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to an u int 16 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to an ushort.</returns>
public static ushort ToUInt16OrDefault(this object @this, Func<ushort> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToUInt16(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToUInt32
/// <summary>
/// An object extension method that converts the @this to an u int 32.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as an uint.</returns>
public static uint ToUInt32(this object @this)
{
return Convert.ToUInt32(@this);
}
#endregion
#region ToUInt32OrDefault
/// <summary>
/// An object extension method that converts this object to an u int 32 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to an uint.</returns>
public static uint ToUInt32OrDefault(this object @this)
{
try
{
return Convert.ToUInt32(@this);
}
catch (Exception)
{
return default(uint);
}
}
/// <summary>
/// An object extension method that converts this object to an u int 32 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to an uint.</returns>
public static uint ToUInt32OrDefault(this object @this, uint defaultValue)
{
try
{
return Convert.ToUInt32(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to an u int 32 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to an uint.</returns>
public static uint ToUInt32OrDefault(this object @this, uint defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToUInt32(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to an u int 32 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to an uint.</returns>
public static uint ToUInt32OrDefault(this object @this, Func<uint> defaultValueFactory)
{
try
{
return Convert.ToUInt32(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to an u int 32 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to an uint.</returns>
public static uint ToUInt32OrDefault(this object @this, Func<uint> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToUInt32(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToUInt64
/// <summary>
/// An object extension method that converts the @this to an u int 64.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as an ulong.</returns>
public static ulong ToUInt64(this object @this)
{
return Convert.ToUInt64(@this);
}
#endregion
#region ToUInt64OrDefault
/// <summary>
/// An object extension method that converts this object to an u int 64 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to an ulong.</returns>
public static ulong ToUInt64OrDefault(this object @this)
{
try
{
return Convert.ToUInt64(@this);
}
catch (Exception)
{
return default(ulong);
}
}
/// <summary>
/// An object extension method that converts this object to an u int 64 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to an ulong.</returns>
public static ulong ToUInt64OrDefault(this object @this, ulong defaultValue)
{
try
{
return Convert.ToUInt64(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to an u int 64 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to an ulong.</returns>
public static ulong ToUInt64OrDefault(this object @this, ulong defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToUInt64(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to an u int 64 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to an ulong.</returns>
public static ulong ToUInt64OrDefault(this object @this, Func<ulong> defaultValueFactory)
{
try
{
return Convert.ToUInt64(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to an u int 64 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to an ulong.</returns>
public static ulong ToUInt64OrDefault(this object @this, Func<ulong> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToUInt64(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToULong
/// <summary>
/// An object extension method that converts the @this to an u long.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as an ulong.</returns>
public static ulong ToULong(this object @this)
{
return Convert.ToUInt64(@this);
}
#endregion
#region ToULongOrDefault
/// <summary>
/// An object extension method that converts this object to an u long or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to an ulong.</returns>
public static ulong ToULongOrDefault(this object @this)
{
try
{
return Convert.ToUInt64(@this);
}
catch (Exception)
{
return default(ulong);
}
}
/// <summary>
/// An object extension method that converts this object to an u long or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to an ulong.</returns>
public static ulong ToULongOrDefault(this object @this, ulong defaultValue)
{
try
{
return Convert.ToUInt64(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to an u long or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to an ulong.</returns>
public static ulong ToULongOrDefault(this object @this, ulong defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToUInt64(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to an u long or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to an ulong.</returns>
public static ulong ToULongOrDefault(this object @this, Func<ulong> defaultValueFactory)
{
try
{
return Convert.ToUInt64(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to an u long or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to an ulong.</returns>
public static ulong ToULongOrDefault(this object @this, Func<ulong> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToUInt64(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToUShort
/// <summary>
/// An object extension method that converts the @this to an u short.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as an ushort.</returns>
public static ushort ToUShort(this object @this)
{
return Convert.ToUInt16(@this);
}
#endregion
#region ToUShortOrDefault
/// <summary>
/// An object extension method that converts this object to an u short or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to an ushort.</returns>
public static ushort ToUShortOrDefault(this object @this)
{
try
{
return Convert.ToUInt16(@this);
}
catch (Exception)
{
return default(ushort);
}
}
/// <summary>
/// An object extension method that converts this object to an u short or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to an ushort.</returns>
public static ushort ToUShortOrDefault(this object @this, ushort defaultValue)
{
try
{
return Convert.ToUInt16(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to an u short or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to an ushort.</returns>
public static ushort ToUShortOrDefault(this object @this, ushort defaultValue, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValue;
}
try
{
return Convert.ToUInt16(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to an u short or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to an ushort.</returns>
public static ushort ToUShortOrDefault(this object @this, Func<ushort> defaultValueFactory)
{
try
{
return Convert.ToUInt16(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// An object extension method that converts this object to an u short or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="useDefaultIfNull">true to use default if null.</param>
/// <returns>The given data converted to an ushort.</returns>
public static ushort ToUShortOrDefault(this object @this, Func<ushort> defaultValueFactory, bool useDefaultIfNull)
{
if (useDefaultIfNull && @this == null)
{
return defaultValueFactory();
}
try
{
return Convert.ToUInt16(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableBoolean
/// <summary>
/// An object extension method that converts the @this to a nullable boolean.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a bool?</returns>
public static bool? ToNullableBoolean(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToBoolean(@this);
}
#endregion
#region ToNullableBooleanOrDefault
/// <summary>
/// An object extension method that converts this object to a nullable boolean or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a bool?</returns>
public static bool? ToNullableBooleanOrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToBoolean(@this);
}
catch (Exception)
{
return default(bool);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable boolean or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a bool?</returns>
public static bool? ToNullableBooleanOrDefault(this object @this, bool? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToBoolean(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable boolean or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a bool?</returns>
public static bool? ToNullableBooleanOrDefault(this object @this, Func<bool?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToBoolean(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableByte
/// <summary>
/// An object extension method that converts the @this to a nullable byte.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a byte?</returns>
public static byte? ToNullableByte(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToByte(@this);
}
#endregion
#region ToNullableByteOrDefault
/// <summary>
/// An object extension method that converts this object to a nullable byte or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a byte?</returns>
public static byte? ToNullableByteOrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToByte(@this);
}
catch (Exception)
{
return default(byte);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable byte or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a byte?</returns>
public static byte? ToNullableByteOrDefault(this object @this, byte? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToByte(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable byte or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a byte?</returns>
public static byte? ToNullableByteOrDefault(this object @this, Func<byte?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToByte(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableChar
/// <summary>
/// An object extension method that converts the @this to a nullable character.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a char?</returns>
public static char? ToNullableChar(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToChar(@this);
}
#endregion
#region ToNullableCharOrDefault
/// <summary>
/// An object extension method that converts this object to a nullable character or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a char?</returns>
public static char? ToNullableCharOrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToChar(@this);
}
catch (Exception)
{
return default(char);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable character or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a char?</returns>
public static char? ToNullableCharOrDefault(this object @this, char? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToChar(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable character or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a char?</returns>
public static char? ToNullableCharOrDefault(this object @this, Func<char?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToChar(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableDateTime
/// <summary>
/// An object extension method that converts the @this to a nullable date time.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a DateTime?</returns>
public static DateTime? ToNullableDateTime(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToDateTime(@this);
}
#endregion
#region ToNullableDateTimeOrDefault
/// <summary>
/// An object extension method that converts this object to a nullable date time or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a DateTime?</returns>
public static DateTime? ToNullableDateTimeOrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToDateTime(@this);
}
catch (Exception)
{
return default(DateTime);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable date time or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a DateTime?</returns>
public static DateTime? ToNullableDateTimeOrDefault(this object @this, DateTime? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToDateTime(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable date time or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a DateTime?</returns>
public static DateTime? ToNullableDateTimeOrDefault(this object @this, Func<DateTime?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToDateTime(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableDateTimeOffSet
/// <summary>
/// An object extension method that converts the @this to a nullable date time off set.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a DateTimeOffset?</returns>
public static DateTimeOffset? ToNullableDateTimeOffSet(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return new DateTimeOffset(Convert.ToDateTime(@this), TimeSpan.Zero);
}
#endregion
#region ToNullableDateTimeOffSetOrDefault
/// <summary>
/// An object extension method that converts this object to a nullable date time off set or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a DateTimeOffset?</returns>
public static DateTimeOffset? ToNullableDateTimeOffSetOrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return new DateTimeOffset(Convert.ToDateTime(@this), TimeSpan.Zero);
}
catch (Exception)
{
return default(DateTimeOffset);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable date time off set or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a DateTimeOffset?</returns>
public static DateTimeOffset? ToNullableDateTimeOffSetOrDefault(this object @this, DateTimeOffset? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return new DateTimeOffset(Convert.ToDateTime(@this), TimeSpan.Zero);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable date time off set or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a DateTimeOffset?</returns>
public static DateTimeOffset? ToNullableDateTimeOffSetOrDefault(this object @this, Func<DateTimeOffset?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return new DateTimeOffset(Convert.ToDateTime(@this), TimeSpan.Zero);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableDecimal
/// <summary>
/// An object extension method that converts the @this to a nullable decimal.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a decimal?</returns>
public static decimal? ToNullableDecimal(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToDecimal(@this);
}
#endregion
#region ToNullableDecimalOrDefault
/// <summary>
/// An object extension method that converts this object to a nullable decimal or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a decimal?</returns>
public static decimal? ToNullableDecimalOrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToDecimal(@this);
}
catch (Exception)
{
return default(decimal);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable decimal or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a decimal?</returns>
public static decimal? ToNullableDecimalOrDefault(this object @this, decimal? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToDecimal(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable decimal or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a decimal?</returns>
public static decimal? ToNullableDecimalOrDefault(this object @this, Func<decimal?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToDecimal(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableDouble
/// <summary>
/// An object extension method that converts the @this to a nullable double.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a double?</returns>
public static double? ToNullableDouble(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToDouble(@this);
}
#endregion
#region ToNullableDoubleOrDefault
/// <summary>
/// An object extension method that converts this object to a nullable double or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a double?</returns>
public static double? ToNullableDoubleOrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToDouble(@this);
}
catch (Exception)
{
return default(double);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable double or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a double?</returns>
public static double? ToNullableDoubleOrDefault(this object @this, double? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToDouble(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable double or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a double?</returns>
public static double? ToNullableDoubleOrDefault(this object @this, Func<double?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToDouble(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableFloat
/// <summary>
/// An object extension method that converts the @this to a nullable float.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a float?</returns>
public static float? ToNullableFloat(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToSingle(@this);
}
#endregion
#region ToNullableFloatOrDefault
/// <summary>
/// An object extension method that converts this object to a nullable float or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a float?</returns>
public static float? ToNullableFloatOrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToSingle(@this);
}
catch (Exception)
{
return default(float);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable float or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a float?</returns>
public static float? ToNullableFloatOrDefault(this object @this, float? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToSingle(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable float or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a float?</returns>
public static float? ToNullableFloatOrDefault(this object @this, Func<float?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToSingle(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableGuid
/// <summary>
/// An object extension method that converts the @this to a nullable unique identifier.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a Guid?</returns>
public static Guid? ToNullableGuid(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return new Guid(@this.ToString());
}
#endregion
#region ToNullableGuidOrDefault
/// <summary>
/// An object extension method that converts this object to a nullable unique identifier or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a Guid?</returns>
public static Guid? ToNullableGuidOrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return new Guid(@this.ToString());
}
catch (Exception)
{
return Guid.Empty;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable unique identifier or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a Guid?</returns>
public static Guid? ToNullableGuidOrDefault(this object @this, Guid? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return new Guid(@this.ToString());
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable unique identifier or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a Guid?</returns>
public static Guid? ToNullableGuidOrDefault(this object @this, Func<Guid?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return new Guid(@this.ToString());
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableInt16
/// <summary>
/// An object extension method that converts the @this to a nullable int 16.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a short?</returns>
public static short? ToNullableInt16(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt16(@this);
}
#endregion
#region ToNullableInt16OrDefault
/// <summary>
/// An object extension method that converts this object to a nullable int 16 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a short?</returns>
public static short? ToNullableInt16OrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt16(@this);
}
catch (Exception)
{
return default(short);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable int 16 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a short?</returns>
public static short? ToNullableInt16OrDefault(this object @this, short? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt16(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable int 16 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a short?</returns>
public static short? ToNullableInt16OrDefault(this object @this, Func<short?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt16(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableInt32
/// <summary>
/// An object extension method that converts the @this to a nullable int 32.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as an int?</returns>
public static int? ToNullableInt32(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt32(@this);
}
#endregion
#region ToNullableInt32OrDefault
/// <summary>
/// An object extension method that converts this object to a nullable int 32 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to an int?</returns>
public static int? ToNullableInt32OrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt32(@this);
}
catch (Exception)
{
return default(int);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable int 32 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to an int?</returns>
public static int? ToNullableInt32OrDefault(this object @this, int? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt32(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable int 32 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to an int?</returns>
public static int? ToNullableInt32OrDefault(this object @this, Func<int?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt32(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableInt64
/// <summary>
/// An object extension method that converts the @this to a nullable int 64.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a long?</returns>
public static long? ToNullableInt64(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt64(@this);
}
#endregion
#region ToNullableInt64OrDefault
/// <summary>
/// An object extension method that converts this object to a nullable int 64 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a long?</returns>
public static long? ToNullableInt64OrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt64(@this);
}
catch (Exception)
{
return default(long);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable int 64 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a long?</returns>
public static long? ToNullableInt64OrDefault(this object @this, long? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt64(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable int 64 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a long?</returns>
public static long? ToNullableInt64OrDefault(this object @this, Func<long?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt64(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableLong
/// <summary>
/// An object extension method that converts the @this to a nullable long.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a long?</returns>
public static long? ToNullableLong(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt64(@this);
}
#endregion
#region ToNullableLongOrDefault
/// <summary>
/// An object extension method that converts this object to a nullable long or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a long?</returns>
public static long? ToNullableLongOrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt64(@this);
}
catch (Exception)
{
return default(long);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable long or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a long?</returns>
public static long? ToNullableLongOrDefault(this object @this, long? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt64(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable long or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a long?</returns>
public static long? ToNullableLongOrDefault(this object @this, Func<long?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt64(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableSByte
/// <summary>
/// An object extension method that converts the @this to a nullable s byte.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a sbyte?</returns>
public static sbyte? ToNullableSByte(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToSByte(@this);
}
#endregion
#region ToNullableSByteOrDefault
/// <summary>
/// An object extension method that converts this object to a nullable s byte or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a sbyte?</returns>
public static sbyte? ToNullableSByteOrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToSByte(@this);
}
catch (Exception)
{
return default(sbyte);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable s byte or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a sbyte?</returns>
public static sbyte? ToNullableSByteOrDefault(this object @this, sbyte? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToSByte(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable s byte or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a sbyte?</returns>
public static sbyte? ToNullableSByteOrDefault(this object @this, Func<sbyte?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToSByte(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableShort
/// <summary>
/// An object extension method that converts the @this to a nullable short.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a short?</returns>
public static short? ToNullableShort(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt16(@this);
}
#endregion
#region ToNullableShortOrDefault
/// <summary>
/// An object extension method that converts this object to a nullable short or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a short?</returns>
public static short? ToNullableShortOrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt16(@this);
}
catch (Exception)
{
return default(short);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable short or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a short?</returns>
public static short? ToNullableShortOrDefault(this object @this, short? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt16(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable short or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a short?</returns>
public static short? ToNullableShortOrDefault(this object @this, Func<short?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToInt16(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableSingle
/// <summary>
/// An object extension method that converts the @this to a nullable single.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a float?</returns>
public static float? ToNullableSingle(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToSingle(@this);
}
#endregion
#region ToNullableSingleOrDefault
/// <summary>
/// An object extension method that converts this object to a nullable single or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to a float?</returns>
public static float? ToNullableSingleOrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToSingle(@this);
}
catch (Exception)
{
return default(float);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable single or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to a float?</returns>
public static float? ToNullableSingleOrDefault(this object @this, float? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToSingle(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable single or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to a float?</returns>
public static float? ToNullableSingleOrDefault(this object @this, Func<float?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToSingle(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableUInt16
/// <summary>
/// An object extension method that converts the @this to a nullable u int 16.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as an ushort?</returns>
public static ushort? ToNullableUInt16(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt16(@this);
}
#endregion
#region ToNullableUInt16OrDefault
/// <summary>
/// An object extension method that converts this object to a nullable u int 16 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to an ushort?</returns>
public static ushort? ToNullableUInt16OrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt16(@this);
}
catch (Exception)
{
return default(ushort);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable u int 16 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to an ushort?</returns>
public static ushort? ToNullableUInt16OrDefault(this object @this, ushort? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt16(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable u int 16 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to an ushort?</returns>
public static ushort? ToNullableUInt16OrDefault(this object @this, Func<ushort?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt16(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableUInt32
/// <summary>
/// An object extension method that converts the @this to a nullable u int 32.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as an uint?</returns>
public static uint? ToNullableUInt32(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt32(@this);
}
#endregion
#region ToNullableUInt32OrDefault
/// <summary>
/// An object extension method that converts this object to a nullable u int 32 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to an uint?</returns>
public static uint? ToNullableUInt32OrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt32(@this);
}
catch (Exception)
{
return default(uint);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable u int 32 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to an uint?</returns>
public static uint? ToNullableUInt32OrDefault(this object @this, uint? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt32(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable u int 32 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to an uint?</returns>
public static uint? ToNullableUInt32OrDefault(this object @this, Func<uint?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt32(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableUInt64
/// <summary>
/// An object extension method that converts the @this to a nullable u int 64.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as an ulong?</returns>
public static ulong? ToNullableUInt64(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt64(@this);
}
#endregion
#region ToNullableUInt64OrDefault
/// <summary>
/// An object extension method that converts this object to a nullable u int 64 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to an ulong?</returns>
public static ulong? ToNullableUInt64OrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt64(@this);
}
catch (Exception)
{
return default(ulong);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable u int 64 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to an ulong?</returns>
public static ulong? ToNullableUInt64OrDefault(this object @this, ulong? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt64(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable u int 64 or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to an ulong?</returns>
public static ulong? ToNullableUInt64OrDefault(this object @this, Func<ulong?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt64(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableULong
/// <summary>
/// An object extension method that converts the @this to a nullable u long.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as an ulong?</returns>
public static ulong? ToNullableULong(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt64(@this);
}
#endregion
#region ToNullableULongOrDefault
/// <summary>
/// An object extension method that converts this object to a nullable u long or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to an ulong?</returns>
public static ulong? ToNullableULongOrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt64(@this);
}
catch (Exception)
{
return default(ulong);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable u long or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to an ulong?</returns>
public static ulong? ToNullableULongOrDefault(this object @this, ulong? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt64(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable u long or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to an ulong?</returns>
public static ulong? ToNullableULongOrDefault(this object @this, Func<ulong?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt64(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#region ToNullableUShort
/// <summary>
/// An object extension method that converts the @this to a nullable u short.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as an ushort?</returns>
public static ushort? ToNullableUShort(this object @this)
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt16(@this);
}
#endregion
#region ToNullableUShortOrDefault
/// <summary>
/// An object extension method that converts this object to a nullable u short or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The given data converted to an ushort?</returns>
public static ushort? ToNullableUShortOrDefault(this object @this)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt16(@this);
}
catch (Exception)
{
return default(ushort);
}
}
/// <summary>
/// An object extension method that converts this object to a nullable u short or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The given data converted to an ushort?</returns>
public static ushort? ToNullableUShortOrDefault(this object @this, ushort? defaultValue)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt16(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// An object extension method that converts this object to a nullable u short or default.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The given data converted to an ushort?</returns>
public static ushort? ToNullableUShortOrDefault(this object @this, Func<ushort?> defaultValueFactory)
{
try
{
if (@this == null || @this == DBNull.Value)
{
return null;
}
return Convert.ToUInt16(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
#endregion
#endregion
#region IsValidValueType
#region IsValidBoolean
/// <summary>
/// An object extension method that query if '@this' is valid bool.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid bool, false if not.</returns>
public static bool IsValidBoolean(this object @this)
{
if (@this == null)
return false;
return bool.TryParse(@this.ToString(), out bool result);
}
#endregion
#region IsValidByte
/// <summary>
/// An object extension method that query if '@this' is valid byte.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid byte, false if not.</returns>
public static bool IsValidByte(this object @this)
{
if (@this == null)
return false;
return byte.TryParse(@this.ToString(), out byte result);
}
#endregion
#region IsValidChar
/// <summary>
/// An object extension method that query if '@this' is valid char.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid char, false if not.</returns>
public static bool IsValidChar(this object @this)
{
if (@this == null)
return false;
return char.TryParse(@this.ToString(), out char result);
}
#endregion
#region IsValidDateTime
/// <summary>
/// An object extension method that query if '@this' is valid System.DateTime.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid System.DateTime, false if not.</returns>
public static bool IsValidDateTime(this object @this)
{
if (@this == null)
return false;
return DateTime.TryParse(@this.ToString(), out DateTime result);
}
#endregion
#region IsValidDateTimeOffSet
/// <summary>
/// An object extension method that query if '@this' is valid System.DateTimeOffset.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid System.DateTimeOffset, false if not.</returns>
public static bool IsValidDateTimeOffSet(this object @this)
{
if (@this == null)
return false;
return DateTimeOffset.TryParse(@this.ToString(), out DateTimeOffset result);
}
#endregion
#region IsValidDecimal
/// <summary>
/// An object extension method that query if '@this' is valid decimal.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid decimal, false if not.</returns>
public static bool IsValidDecimal(this object @this)
{
if (@this == null)
return false;
return decimal.TryParse(@this.ToString(), out decimal result);
}
#endregion
#region IsValidDouble
/// <summary>
/// An object extension method that query if '@this' is valid double.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid double, false if not.</returns>
public static bool IsValidDouble(this object @this)
{
if (@this == null)
return false;
return double.TryParse(@this.ToString(), out double result);
}
#endregion
#region IsValidFloat
/// <summary>
/// An object extension method that query if '@this' is valid float.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid float, false if not.</returns>
public static bool IsValidFloat(this object @this)
{
if (@this == null)
return false;
return float.TryParse(@this.ToString(), out float result);
}
#endregion
#region IsValidGuid
/// <summary>
/// An object extension method that query if '@this' is valid System.Guid.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid System.Guid, false if not.</returns>
public static bool IsValidGuid(this object @this)
{
if (@this == null)
return false;
return Guid.TryParse(@this.ToString(), out Guid result);
}
#endregion
#region IsValidInt16
/// <summary>
/// An object extension method that query if '@this' is valid short.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid short, false if not.</returns>
public static bool IsValidInt16(this object @this)
{
if (@this == null)
return false;
return short.TryParse(@this.ToString(), out short result);
}
#endregion
#region IsValidInt32
/// <summary>
/// An object extension method that query if '@this' is valid int.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid int, false if not.</returns>
public static bool IsValidInt32(this object @this)
{
if (@this == null)
return false;
return int.TryParse(@this.ToString(), out int result);
}
#endregion
#region IsValidInt64
/// <summary>
/// An object extension method that query if '@this' is valid long.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid long, false if not.</returns>
public static bool IsValidInt64(this object @this)
{
if (@this == null)
return false;
return long.TryParse(@this.ToString(), out long result);
}
#endregion
#region IsValidLong
/// <summary>
/// An object extension method that query if '@this' is valid long.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid long, false if not.</returns>
public static bool IsValidLong(this object @this)
{
if (@this == null)
return false;
return long.TryParse(@this.ToString(), out long result);
}
#endregion
#region IsValidSByte
/// <summary>
/// An object extension method that query if '@this' is valid sbyte.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid sbyte, false if not.</returns>
public static bool IsValidSByte(this object @this)
{
if (@this == null)
return false;
return sbyte.TryParse(@this.ToString(), out sbyte result);
}
#endregion
#region IsValidShort
/// <summary>
/// An object extension method that query if '@this' is valid short.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid short, false if not.</returns>
public static bool IsValidShort(this object @this)
{
if (@this == null)
return false;
return short.TryParse(@this.ToString(), out short result);
}
#endregion
#region IsValidSingle
/// <summary>
/// An object extension method that query if '@this' is valid float.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid float, false if not.</returns>
public static bool IsValidSingle(this object @this)
{
if (@this == null)
return false;
return float.TryParse(@this.ToString(), out float result);
}
#endregion
#region IsValidString
/// <summary>
/// An object extension method that query if '@this' is valid string.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid string, false if not.</returns>
public static bool IsValidString(this object @this)
{
return true;
}
#endregion
#region IsValidUInt16
/// <summary>
/// An object extension method that query if '@this' is valid ushort.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid ushort, false if not.</returns>
public static bool IsValidUInt16(this object @this)
{
if (@this == null)
return false;
return ushort.TryParse(@this.ToString(), out ushort result);
}
#endregion
#region IsValidUInt32
/// <summary>
/// An object extension method that query if '@this' is valid uint.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid uint, false if not.</returns>
public static bool IsValidUInt32(this object @this)
{
if (@this == null)
return false;
return uint.TryParse(@this.ToString(), out uint result);
}
#endregion
#region IsValidUInt64
/// <summary>
/// An object extension method that query if '@this' is valid ulong.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid ulong, false if not.</returns>
public static bool IsValidUInt64(this object @this)
{
if (@this == null)
return false;
return ulong.TryParse(@this.ToString(), out ulong result);
}
#endregion
#region IsValidULong
/// <summary>
/// An object extension method that query if '@this' is valid ulong.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid ulong, false if not.</returns>
public static bool IsValidULong(this object @this)
{
if (@this == null)
return false;
return ulong.TryParse(@this.ToString(), out ulong result);
}
#endregion
#region IsValidUShort
/// <summary>
/// An object extension method that query if '@this' is valid ushort.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if valid ushort, false if not.</returns>
public static bool IsValidUShort(this object @this)
{
if (@this == null)
return false;
return ushort.TryParse(@this.ToString(), out ushort result);
}
#endregion
#endregion
#region IsAssignableFrom
/// <summary>
/// An object extension method that query if '@this' is assignable from.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <returns>true if assignable from, false if not.</returns>
public static bool IsAssignableFrom<T>(this object @this)
{
Type type = @this.GetType();
return type.IsAssignableFrom(typeof(T));
}
/// <summary>
/// An object extension method that query if '@this' is assignable from.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="targetType">Type of the target.</param>
/// <returns>true if assignable from, false if not.</returns>
public static bool IsAssignableFrom(this object @this, Type targetType)
{
Type type = @this.GetType();
return type.IsAssignableFrom(targetType);
}
#endregion
#region Chain
/// <summary>
/// A T extension method that chains actions.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="action">The action.</param>
/// <returns>The @this acted on.</returns>
public static T Chain<T>(this T @this, Action<T> action)
{
action(@this);
return @this;
}
#endregion
#region DeepClone
/// <summary>
/// Performs deep (full) copy of object and related graph
/// </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)
{
return DeepClonerExtensions.DeepClone(@this);
}
#endregion
#region DeepCloneTo
/// <summary>
/// Performs deep (full) copy of object and related graph to existing object
/// </summary>
/// <returns>existing filled object</returns>
/// <remarks>Method is valid only for classes, classes should be descendants in reality, not in declaration</remarks>
public static TTo DeepCloneTo<TFrom, TTo>(this TFrom @this, TTo to) where TTo : class, TFrom
{
return DeepClonerExtensions.DeepCloneTo(@this, to);
}
#endregion
#region ShallowClone
/// <summary>
/// Performs shallow (only new object returned, without cloning of dependencies) copy of object
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <returns>A T.</returns>
public static T ShallowClone<T>(this T @this)
{
return DeepClonerExtensions.ShallowClone(@this);
}
#endregion
#region ShallowCloneTo
/// <summary>
/// Performs shallow copy of object to existing object
/// </summary>
/// <returns>existing filled object</returns>
/// <remarks>Method is valid only for classes, classes should be descendants in reality, not in declaration</remarks>
public static TTo ShallowCloneTo<TFrom, TTo>(this TFrom @this, TTo to) where TTo : class, TFrom
{
return DeepClonerExtensions.ShallowCloneTo(@this, to);
}
#endregion
#region ChangeType
/// <summary>
/// Returns an object of the specified type whose value is equivalent to the specified object.
/// </summary>
/// <param name="this">An object that implements the interface.</param>
/// <param name="typeCode">The type of object to return.</param>
/// <returns>
/// An object whose underlying type is and whose value is equivalent to .-or-A null reference (Nothing in Visual
/// Basic), if is null and is , , or .
/// </returns>
public static object ChangeType(this object @this, TypeCode typeCode)
{
return Convert.ChangeType(@this, typeCode);
}
/// <summary>
/// Returns an object of the specified type whose value is equivalent to the specified object. A parameter
/// supplies culture-specific formatting information.
/// </summary>
/// <param name="this">An object that implements the interface.</param>
/// <param name="typeCode">The type of object to return.</param>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <returns>
/// An object whose underlying type is and whose value is equivalent to .-or- A null reference (Nothing in
/// Visual Basic), if is null and is , , or .
/// </returns>
public static object ChangeType(this object @this, TypeCode typeCode, IFormatProvider provider)
{
return Convert.ChangeType(@this, typeCode, provider);
}
/// <summary>
/// Returns an object of the specified type whose value is equivalent to the specified object. A parameter
/// supplies culture-specific formatting information.
/// </summary>
/// <param name="this">An object that implements the interface.</param>
/// <param name="conversionType">The type of object to return.</param>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <returns>
/// An object whose type is and whose value is equivalent to .-or- , if the of and are equal.-or- A null
/// reference (Nothing in Visual Basic), if is null and is not a value type.
/// </returns>
public static object ChangeType(this object @this, Type conversionType, IFormatProvider provider)
{
return Convert.ChangeType(@this, conversionType, provider);
}
/// <summary>
/// Returns an object of the specified type whose value is equivalent to the specified object. A parameter
/// supplies culture-specific formatting information.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">An object that implements the interface.</param>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <returns>
/// An object whose type is and whose value is equivalent to .-or- , if the of and are equal.-or- A null
/// reference (Nothing in Visual Basic), if is null and is not a value type.
/// </returns>
public static object ChangeType<T>(this object @this, IFormatProvider provider)
{
return (T)Convert.ChangeType(@this, typeof(T), provider);
}
/// <summary>
/// 将一个对象转换为指定类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="this"></param>
/// <returns></returns>
public static T ChangeType<T>(this object @this)
{
return (T)ChangeType(@this, typeof(T));
}
/// <summary>
/// 将一个对象转换为指定类型
/// </summary>
/// <param name="this">待转换的对象</param>
/// <param name="type">目标类型</param>
/// <returns>转换后的对象</returns>
public static object ChangeType(this object @this, Type type)
{
if (type == null)
return @this;
if (@this == null)
return type.IsValueType ? Activator.CreateInstance(type) : null;
var underlyingType = Nullable.GetUnderlyingType(type);
if (type.IsAssignableFrom(@this.GetType()))
return @this;
else if ((underlyingType ?? type).IsEnum)
{
if (underlyingType != null && string.IsNullOrEmpty(@this.ToString()))
return null;
else
return Enum.Parse(underlyingType ?? type, @this.ToString());
}
// 处理DateTime -> DateTimeOffset 类型
else if (@this.GetType().Equals(typeof(DateTime)) && (underlyingType ?? type).Equals(typeof(DateTimeOffset)))
{
return ((DateTime)@this).ConvertToDateTimeOffset();
}
// 处理 DateTimeOffset -> DateTime 类型
else if (@this.GetType().Equals(typeof(DateTimeOffset)) && (underlyingType ?? type).Equals(typeof(DateTime)))
{
return ((DateTimeOffset)@this).ConvertToDateTime();
}
else if (typeof(IConvertible).IsAssignableFrom(underlyingType ?? type))
{
try
{
return Convert.ChangeType(@this, underlyingType ?? type, null);
}
catch
{
return underlyingType == null ? Activator.CreateInstance(type) : null;
}
}
else
{
var converter = TypeDescriptor.GetConverter(type);
if (converter.CanConvertFrom(@this.GetType()))
return converter.ConvertFrom(@this);
var constructor = type.GetConstructor(Type.EmptyTypes);
if (constructor != null)
{
var o = constructor.Invoke(null);
var propertys = type.GetProperties();
var oldType = @this.GetType();
foreach (var property in propertys)
{
var p = oldType.GetProperty(property.Name);
if (property.CanWrite && p != null && p.CanRead)
{
property.SetValue(o, ChangeType(p.GetValue(@this, null), property.PropertyType), null);
}
}
return o;
}
}
return @this;
}
#endregion
#region GetTypeCode
/// <summary>
/// Returns the for the specified object.
/// </summary>
/// <param name="this">An object that implements the interface.</param>
/// <returns>The for , or if is null.</returns>
public static TypeCode GetTypeCode(this object @this)
{
return Convert.GetTypeCode(@this);
}
#endregion
#region Coalesce
/// <summary>
/// A T extension method that that return the first not null value (including the @this).
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="values">A variable-length parameters list containing values.</param>
/// <returns>The first not null value.</returns>
public static T Coalesce<T>(this T @this, params T[] values) where T : class
{
if (@this != null)
{
return @this;
}
foreach (T value in values)
{
if (value != null)
{
return value;
}
}
return null;
}
#endregion
#region CoalesceOrDefault
/// <summary>
/// A T extension method that that return the first not null value (including the @this) or a default value.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="values">A variable-length parameters list containing values.</param>
/// <returns>The first not null value or a default value.</returns>
public static T CoalesceOrDefault<T>(this T @this, params T[] values) where T : class
{
if (@this != null)
{
return @this;
}
foreach (T value in values)
{
if (value != null)
{
return value;
}
}
return default(T);
}
/// <summary>
/// A T extension method that that return the first not null value (including the @this) or a default value.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="values">A variable-length parameters list containing values.</param>
/// <returns>The first not null value or a default value.</returns>
/// <example>
/// <code>
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_CoalesceOrDefault
/// {
/// [TestMethod]
/// public void CoalesceOrDefault()
/// {
/// // Varable
/// object nullObject = null;
///
/// // Type
/// object @thisNull = null;
/// object @thisNotNull = "Fizz";
///
/// // Exemples
/// object result1 = @thisNull.CoalesceOrDefault(nullObject, nullObject, "Buzz"); // return "Buzz";
/// object result2 = @thisNull.CoalesceOrDefault(() => "Buzz", null, null); // return "Buzz";
/// object result3 = @thisNull.CoalesceOrDefault((x) => "Buzz", null, null); // return "Buzz";
/// object result4 = @thisNotNull.CoalesceOrDefault(nullObject, nullObject, "Buzz"); // return "Fizz";
///
/// // Unit Test
/// Assert.AreEqual("Buzz", result1);
/// Assert.AreEqual("Buzz", result2);
/// Assert.AreEqual("Buzz", result3);
/// Assert.AreEqual("Fizz", result4);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_CoalesceOrDefault
/// {
/// [TestMethod]
/// public void CoalesceOrDefault()
/// {
/// // Varable
/// object nullObject = null;
///
/// // Type
/// object @thisNull = null;
/// object @thisNotNull = "Fizz";
///
/// // Exemples
/// object result1 = @thisNull.CoalesceOrDefault(nullObject, nullObject, "Buzz"); // return "Buzz";
/// object result2 = @thisNull.CoalesceOrDefault(() => "Buzz", null, null); // return "Buzz";
/// object result3 = @thisNull.CoalesceOrDefault(x => "Buzz", null, null); // return "Buzz";
/// object result4 = @thisNotNull.CoalesceOrDefault(nullObject, nullObject, "Buzz"); // return "Fizz";
///
/// // Unit Test
/// Assert.AreEqual("Buzz", result1);
/// Assert.AreEqual("Buzz", result2);
/// Assert.AreEqual("Buzz", result3);
/// Assert.AreEqual("Fizz", result4);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_CoalesceOrDefault
/// {
/// [TestMethod]
/// public void CoalesceOrDefault()
/// {
/// // Varable
/// object nullObject = null;
///
/// // Type
/// object @thisNull = null;
/// object @thisNotNull = "Fizz";
///
/// // Exemples
/// object result1 = @thisNull.CoalesceOrDefault(nullObject, nullObject, "Buzz"); // return "Buzz";
/// object result2 = @thisNull.CoalesceOrDefault(() => "Buzz", null, null); // return "Buzz";
/// object result3 = @thisNull.CoalesceOrDefault(x => "Buzz", null, null); // return "Buzz";
/// object result4 = @thisNotNull.CoalesceOrDefault(nullObject, nullObject, "Buzz"); // return "Fizz";
///
/// // Unit Test
/// Assert.AreEqual("Buzz", result1);
/// Assert.AreEqual("Buzz", result2);
/// Assert.AreEqual("Buzz", result3);
/// Assert.AreEqual("Fizz", result4);
/// }
/// }
/// }
/// </code>
/// </example>
public static T CoalesceOrDefault<T>(this T @this, Func<T> defaultValueFactory, params T[] values) where T : class
{
if (@this != null)
{
return @this;
}
foreach (T value in values)
{
if (value != null)
{
return value;
}
}
return defaultValueFactory();
}
/// <summary>
/// A T extension method that that return the first not null value (including the @this) or a default value.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <param name="values">A variable-length parameters list containing values.</param>
/// <returns>The first not null value or a default value.</returns>
/// <example>
/// <code>
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_CoalesceOrDefault
/// {
/// [TestMethod]
/// public void CoalesceOrDefault()
/// {
/// // Varable
/// object nullObject = null;
///
/// // Type
/// object @thisNull = null;
/// object @thisNotNull = "Fizz";
///
/// // Exemples
/// object result1 = @thisNull.CoalesceOrDefault(nullObject, nullObject, "Buzz"); // return "Buzz";
/// object result2 = @thisNull.CoalesceOrDefault(() => "Buzz", null, null); // return "Buzz";
/// object result3 = @thisNull.CoalesceOrDefault((x) => "Buzz", null, null); // return "Buzz";
/// object result4 = @thisNotNull.CoalesceOrDefault(nullObject, nullObject, "Buzz"); // return "Fizz";
///
/// // Unit Test
/// Assert.AreEqual("Buzz", result1);
/// Assert.AreEqual("Buzz", result2);
/// Assert.AreEqual("Buzz", result3);
/// Assert.AreEqual("Fizz", result4);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_CoalesceOrDefault
/// {
/// [TestMethod]
/// public void CoalesceOrDefault()
/// {
/// // Varable
/// object nullObject = null;
///
/// // Type
/// object @thisNull = null;
/// object @thisNotNull = "Fizz";
///
/// // Exemples
/// object result1 = @thisNull.CoalesceOrDefault(nullObject, nullObject, "Buzz"); // return "Buzz";
/// object result2 = @thisNull.CoalesceOrDefault(() => "Buzz", null, null); // return "Buzz";
/// object result3 = @thisNull.CoalesceOrDefault(x => "Buzz", null, null); // return "Buzz";
/// object result4 = @thisNotNull.CoalesceOrDefault(nullObject, nullObject, "Buzz"); // return "Fizz";
///
/// // Unit Test
/// Assert.AreEqual("Buzz", result1);
/// Assert.AreEqual("Buzz", result2);
/// Assert.AreEqual("Buzz", result3);
/// Assert.AreEqual("Fizz", result4);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_CoalesceOrDefault
/// {
/// [TestMethod]
/// public void CoalesceOrDefault()
/// {
/// // Varable
/// object nullObject = null;
///
/// // Type
/// object @thisNull = null;
/// object @thisNotNull = "Fizz";
///
/// // Exemples
/// object result1 = @thisNull.CoalesceOrDefault(nullObject, nullObject, "Buzz"); // return "Buzz";
/// object result2 = @thisNull.CoalesceOrDefault(() => "Buzz", null, null); // return "Buzz";
/// object result3 = @thisNull.CoalesceOrDefault(x => "Buzz", null, null); // return "Buzz";
/// object result4 = @thisNotNull.CoalesceOrDefault(nullObject, nullObject, "Buzz"); // return "Fizz";
///
/// // Unit Test
/// Assert.AreEqual("Buzz", result1);
/// Assert.AreEqual("Buzz", result2);
/// Assert.AreEqual("Buzz", result3);
/// Assert.AreEqual("Fizz", result4);
/// }
/// }
/// }
/// </code>
/// </example>
public static T CoalesceOrDefault<T>(this T @this, Func<T, T> defaultValueFactory, params T[] values) where T : class
{
if (@this != null)
{
return @this;
}
foreach (T value in values)
{
if (value != null)
{
return value;
}
}
return defaultValueFactory(@this);
}
#endregion
#region GetValueOrDefault
/// <summary>
/// A T extension method that gets value or default.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <typeparam name="TResult">Type of the result.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="func">The function.</param>
/// <returns>The value or default.</returns>
public static TResult GetValueOrDefault<T, TResult>(this T @this, Func<T, TResult> func)
{
try
{
return func(@this);
}
catch (Exception)
{
return default(TResult);
}
}
/// <summary>
/// A T extension method that gets value or default.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <typeparam name="TResult">Type of the result.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="func">The function.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The value or default.</returns>
public static TResult GetValueOrDefault<T, TResult>(this T @this, Func<T, TResult> func, TResult defaultValue)
{
try
{
return func(@this);
}
catch (Exception)
{
return defaultValue;
}
}
/// <summary>
/// A T extension method that gets value or default.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <typeparam name="TResult">Type of the result.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="func">The function.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The value or default.</returns>
/// <example>
/// <code>
/// using System.Xml;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_GetValueOrDefault
/// {
/// [TestMethod]
/// public void GetValueOrDefault()
/// {
/// // Type
/// var @this = new XmlDocument();
///
/// // Exemples
/// string result1 = @this.GetValueOrDefault(x => x.FirstChild.InnerXml, "FizzBuzz"); // return "FizzBuzz";
/// string result2 = @this.GetValueOrDefault(x => x.FirstChild.InnerXml, () => "FizzBuzz"); // return "FizzBuzz"
///
/// // Unit Test
/// Assert.AreEqual("FizzBuzz", result1);
/// Assert.AreEqual("FizzBuzz", result2);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using System.Xml;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_GetValueOrDefault
/// {
/// [TestMethod]
/// public void GetValueOrDefault()
/// {
/// // Type
/// var @this = new XmlDocument();
///
/// // Exemples
/// string result1 = @this.GetValueOrDefault(x => x.FirstChild.InnerXml, "FizzBuzz"); // return "FizzBuzz";
/// string result2 = @this.GetValueOrDefault(x => x.FirstChild.InnerXml, () => "FizzBuzz"); // return "FizzBuzz"
///
/// // Unit Test
/// Assert.AreEqual("FizzBuzz", result1);
/// Assert.AreEqual("FizzBuzz", result2);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using System.Xml;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_GetValueOrDefault
/// {
/// [TestMethod]
/// public void GetValueOrDefault()
/// {
/// // Type
/// var @this = new XmlDocument();
///
/// // Exemples
/// string result1 = @this.GetValueOrDefault(x => x.FirstChild.InnerXml, "FizzBuzz"); // return "FizzBuzz";
/// string result2 = @this.GetValueOrDefault(x => x.FirstChild.InnerXml, () => "FizzBuzz"); // return "FizzBuzz"
///
/// // Unit Test
/// Assert.AreEqual("FizzBuzz", result1);
/// Assert.AreEqual("FizzBuzz", result2);
/// }
/// }
/// }
/// </code>
/// </example>
public static TResult GetValueOrDefault<T, TResult>(this T @this, Func<T, TResult> func, Func<TResult> defaultValueFactory)
{
try
{
return func(@this);
}
catch (Exception)
{
return defaultValueFactory();
}
}
/// <summary>
/// A T extension method that gets value or default.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <typeparam name="TResult">Type of the result.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="func">The function.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The value or default.</returns>
/// <example>
/// <code>
/// using System.Xml;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
///
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_GetValueOrDefault
/// {
/// [TestMethod]
/// public void GetValueOrDefault()
/// {
/// // Type
/// var @this = new XmlDocument();
///
/// // Exemples
/// string result1 = @this.GetValueOrDefault(x => x.FirstChild.InnerXml, "FizzBuzz"); // return "FizzBuzz";
/// string result2 = @this.GetValueOrDefault(x => x.FirstChild.InnerXml, () => "FizzBuzz"); // return "FizzBuzz"
///
/// // Unit Test
/// Assert.AreEqual("FizzBuzz", result1);
/// Assert.AreEqual("FizzBuzz", result2);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using System.Xml;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_GetValueOrDefault
/// {
/// [TestMethod]
/// public void GetValueOrDefault()
/// {
/// // Type
/// var @this = new XmlDocument();
///
/// // Exemples
/// string result1 = @this.GetValueOrDefault(x => x.FirstChild.InnerXml, "FizzBuzz"); // return "FizzBuzz";
/// string result2 = @this.GetValueOrDefault(x => x.FirstChild.InnerXml, () => "FizzBuzz"); // return "FizzBuzz"
///
/// // Unit Test
/// Assert.AreEqual("FizzBuzz", result1);
/// Assert.AreEqual("FizzBuzz", result2);
/// }
/// }
/// }
/// </code>
/// </example>
/// <example>
/// <code>
/// using System.Xml;
/// using Microsoft.VisualStudio.TestTools.UnitTesting;
/// using Z.ExtensionMethods.Object;
///
/// namespace ExtensionMethods.Examples
/// {
/// [TestClass]
/// public class System_Object_GetValueOrDefault
/// {
/// [TestMethod]
/// public void GetValueOrDefault()
/// {
/// // Type
/// var @this = new XmlDocument();
///
/// // Exemples
/// string result1 = @this.GetValueOrDefault(x => x.FirstChild.InnerXml, "FizzBuzz"); // return "FizzBuzz";
/// string result2 = @this.GetValueOrDefault(x => x.FirstChild.InnerXml, () => "FizzBuzz"); // return "FizzBuzz"
///
/// // Unit Test
/// Assert.AreEqual("FizzBuzz", result1);
/// Assert.AreEqual("FizzBuzz", result2);
/// }
/// }
/// }
/// </code>
/// </example>
public static TResult GetValueOrDefault<T, TResult>(this T @this, Func<T, TResult> func, Func<T, TResult> defaultValueFactory)
{
try
{
return func(@this);
}
catch (Exception)
{
return defaultValueFactory(@this);
}
}
#endregion
#region IfNotNull
/// <summary>
/// A T extension method that execute an action when the value is not null.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="action">The action.</param>
public static void IfNotNull<T>(this T @this, Action<T> action) where T : class
{
if (@this != null)
{
action(@this);
}
}
/// <summary>
/// A T extension method that the function result if not null otherwise default value.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <typeparam name="TResult">Type of the result.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="func">The function.</param>
/// <returns>The function result if @this is not null otherwise default value.</returns>
public static TResult IfNotNull<T, TResult>(this T @this, Func<T, TResult> func) where T : class
{
return @this != null ? func(@this) : default(TResult);
}
/// <summary>
/// A T extension method that the function result if not null otherwise default value.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <typeparam name="TResult">Type of the result.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="func">The function.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The function result if @this is not null otherwise default value.</returns>
public static TResult IfNotNull<T, TResult>(this T @this, Func<T, TResult> func, TResult defaultValue) where T : class
{
return @this != null ? func(@this) : defaultValue;
}
/// <summary>
/// A T extension method that the function result if not null otherwise default value.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <typeparam name="TResult">Type of the result.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="func">The function.</param>
/// <param name="defaultValueFactory">The default value factory.</param>
/// <returns>The function result if @this is not null otherwise default value.</returns>
public static TResult IfNotNull<T, TResult>(this T @this, Func<T, TResult> func, Func<TResult> defaultValueFactory) where T : class
{
return @this != null ? func(@this) : defaultValueFactory();
}
#endregion
#region NullIf
/// <summary>
/// A T extension method that null if.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="predicate">The predicate.</param>
/// <returns>A T.</returns>
public static T NullIf<T>(this T @this, Func<T, bool> predicate) where T : class
{
if (predicate(@this))
{
return null;
}
return @this;
}
#endregion
#region NullIfEquals
/// <summary>
/// A T extension method that null if equals.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="value">The value.</param>
/// <returns>A T.</returns>
public static T NullIfEquals<T>(this T @this, T value) where T : class
{
if (@this.Equals(value))
{
return null;
}
return @this;
}
#endregion
#region NullIfEqualsAny
/// <summary>
/// A T extension method that null if equals any.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="values">A variable-length parameters list containing values.</param>
/// <returns>A T.</returns>
public static T NullIfEqualsAny<T>(this T @this, params T[] values) where T : class
{
if (Array.IndexOf(values, @this) != -1)
{
return null;
}
return @this;
}
#endregion
#region ToStringSafe
/// <summary>
/// An object extension method that converts the @this to string or return an empty string if the value is null.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a string or empty if the value is null.</returns>
public static string ToStringSafe(this object @this)
{
return @this == null ? "" : @this.ToString();
}
#endregion
#region Try
/// <summary>
/// A TType extension method that tries.
/// </summary>
/// <typeparam name="TType">Type of the type.</typeparam>
/// <typeparam name="TResult">Type of the result.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="tryFunction">The try function.</param>
/// <returns>A TResult.</returns>
public static TResult Try<TType, TResult>(this TType @this, Func<TType, TResult> tryFunction)
{
try
{
return tryFunction(@this);
}
catch
{
return default(TResult);
}
}
/// <summary>
/// A TType extension method that tries.
/// </summary>
/// <typeparam name="TType">Type of the type.</typeparam>
/// <typeparam name="TResult">Type of the result.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="tryFunction">The try function.</param>
/// <param name="catchValue">The catch value.</param>
/// <returns>A TResult.</returns>
public static TResult Try<TType, TResult>(this TType @this, Func<TType, TResult> tryFunction, TResult catchValue)
{
try
{
return tryFunction(@this);
}
catch
{
return catchValue;
}
}
/// <summary>
/// A TType extension method that tries.
/// </summary>
/// <typeparam name="TType">Type of the type.</typeparam>
/// <typeparam name="TResult">Type of the result.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="tryFunction">The try function.</param>
/// <param name="catchValueFactory">The catch value factory.</param>
/// <returns>A TResult.</returns>
public static TResult Try<TType, TResult>(this TType @this, Func<TType, TResult> tryFunction, Func<TType, TResult> catchValueFactory)
{
try
{
return tryFunction(@this);
}
catch
{
return catchValueFactory(@this);
}
}
/// <summary>
/// A TType extension method that tries.
/// </summary>
/// <typeparam name="TType">Type of the type.</typeparam>
/// <typeparam name="TResult">Type of the result.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="tryFunction">The try function.</param>
/// <param name="result">[out] The result.</param>
/// <returns>A TResult.</returns>
public static bool Try<TType, TResult>(this TType @this, Func<TType, TResult> tryFunction, out TResult result)
{
try
{
result = tryFunction(@this);
return true;
}
catch
{
result = default(TResult);
return false;
}
}
/// <summary>
/// A TType extension method that tries.
/// </summary>
/// <typeparam name="TType">Type of the type.</typeparam>
/// <typeparam name="TResult">Type of the result.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="tryFunction">The try function.</param>
/// <param name="catchValue">The catch value.</param>
/// <param name="result">[out] The result.</param>
/// <returns>A TResult.</returns>
public static bool Try<TType, TResult>(this TType @this, Func<TType, TResult> tryFunction, TResult catchValue, out TResult result)
{
try
{
result = tryFunction(@this);
return true;
}
catch
{
result = catchValue;
return false;
}
}
/// <summary>
/// A TType extension method that tries.
/// </summary>
/// <typeparam name="TType">Type of the type.</typeparam>
/// <typeparam name="TResult">Type of the result.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="tryFunction">The try function.</param>
/// <param name="catchValueFactory">The catch value factory.</param>
/// <param name="result">[out] The result.</param>
/// <returns>A TResult.</returns>
public static bool Try<TType, TResult>(this TType @this, Func<TType, TResult> tryFunction, Func<TType, TResult> catchValueFactory, out TResult result)
{
try
{
result = tryFunction(@this);
return true;
}
catch
{
result = catchValueFactory(@this);
return false;
}
}
/// <summary>
/// A TType extension method that attempts to action from the given data.
/// </summary>
/// <typeparam name="TType">Type of the type.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="tryAction">The try action.</param>
/// <returns>true if it succeeds, false if it fails.</returns>
public static bool Try<TType>(this TType @this, Action<TType> tryAction)
{
try
{
tryAction(@this);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// A TType extension method that attempts to action from the given data.
/// </summary>
/// <typeparam name="TType">Type of the type.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="tryAction">The try action.</param>
/// <param name="catchAction">The catch action.</param>
/// <returns>true if it succeeds, false if it fails.</returns>
public static bool Try<TType>(this TType @this, Action<TType> tryAction, Action<TType> catchAction)
{
try
{
tryAction(@this);
return true;
}
catch
{
catchAction(@this);
return false;
}
}
#endregion
#region Between
/// <summary>
/// A T extension method that check if the value is between (exclusif) the minValue and maxValue.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="minValue">The minimum value.</param>
/// <param name="maxValue">The maximum value.</param>
/// <returns>true if the value is between the minValue and maxValue, otherwise false.</returns>
public static bool Between<T>(this T @this, T minValue, T maxValue) where T : IComparable<T>
{
return minValue.CompareTo(@this) == -1 && @this.CompareTo(maxValue) == -1;
}
#endregion
#region In
/// <summary>
/// A T extension method to determines whether the object is equal to any of the provided values.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The object to be compared.</param>
/// <param name="values">The value list to compare with the object.</param>
/// <returns>true if the values list contains the object, else false.</returns>
public static bool In<T>(this T @this, params T[] values)
{
return Array.IndexOf(values, @this) != -1;
}
#endregion
#region InRange
/// <summary>
/// A T extension method that check if the value is between inclusively the minValue and maxValue.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="minValue">The minimum value.</param>
/// <param name="maxValue">The maximum value.</param>
/// <returns>true if the value is between inclusively the minValue and maxValue, otherwise false.</returns>
public static bool InRange<T>(this T @this, T minValue, T maxValue) where T : IComparable<T>
{
return @this.CompareTo(minValue) >= 0 && @this.CompareTo(maxValue) <= 0;
}
#endregion
#region IsDBNull
/// <summary>
/// Returns an indication whether the specified object is of type .
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">An object.</param>
/// <returns>true if is of type ; otherwise, false.</returns>
public static bool IsDBNull<T>(this T @this) where T : class
{
return Convert.IsDBNull(@this);
}
#endregion
#region IsDefault
/// <summary>
/// A T extension method that query if 'source' is the default value.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The source to act on.</param>
/// <returns>true if default, false if not.</returns>
public static bool IsDefault<T>(this T @this)
{
return @this.Equals(default(T));
}
#endregion
#region IsNotNull
/// <summary>
/// A T extension method that query if '@this' is not null.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <returns>true if not null, false if not.</returns>
public static bool IsNotNull<T>(this T @this) where T : class
{
return @this != null;
}
#endregion
#region IsNull
/// <summary>
/// 是否为空
/// </summary>
/// <param name="this">object对象</param>
/// <returns>bool</returns>
public static bool IsNull(this object @this)
{
return @this == null || @this == DBNull.Value;
}
/// <summary>
/// A T extension method that query if '@this' is null.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <returns>true if null, false if not.</returns>
public static bool IsNull<T>(this T @this) where T : class, new()
{
return @this == null;
}
#endregion
#region NotIn
/// <summary>
/// A T extension method to determines whether the object is not equal to any of the provided values.
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The object to be compared.</param>
/// <param name="values">The value list to compare with the object.</param>
/// <returns>true if the values list doesn't contains the object, else false.</returns>
public static bool NotIn<T>(this T @this, params T[] values)
{
return Array.IndexOf(values, @this) == -1;
}
#endregion
#region ReferenceEquals
/// <summary>
/// Determines whether the specified instances are the same instance.
/// </summary>
/// <param name="this">The first object to compare.</param>
/// <param name="obj">The second object to compare.</param>
/// <returns>true if is the same instance as or if both are null; otherwise, false.</returns>
public new static bool ReferenceEquals(this object @this, object obj)
{
return object.ReferenceEquals(@this, obj);
}
#endregion
#region ToDictionary
/// <summary>
/// 目标匿名参数对象转为字典
/// </summary>
/// <param name="this"></param>
/// <returns></returns>
public static IDictionary<string, object> ToDictionary(this object @this)
{
if (@this is IDictionary<string, object> dic)
return dic;
dic = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
if (@this.IsNotNull())
{
// 修正字符串字典的支持问题
if (@this is IDictionary dic2)
{
foreach (DictionaryEntry item in dic2)
{
dic[item.Key + ""] = item.Value;
}
}
else
{
foreach (var pi in @this.GetType().GetProperties())
{
if (pi.GetIndexParameters().Length > 0)
continue;
if (pi.GetCustomAttribute<XmlIgnoreAttribute>().IsNotNull())
continue;
dic[pi.Name] = @this.GetValue(pi);
}
}
}
return dic;
}
/// <summary>
/// 目标匿名参数对象转为字典
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="this"></param>
/// <returns></returns>
public static IDictionary<TKey, TValue> ToDictionary<TKey, TValue>(this object @this)
{
if (@this is IDictionary<TKey, TValue> dic)
return dic;
dic = new Dictionary<TKey, TValue>();
if (@this.IsNotNull())
{
// 修正字符串字典的支持问题
if (@this is IDictionary dic2)
{
foreach (DictionaryEntry item in dic2)
{
dic[item.Key.To<TKey>()] = item.Value.To<TValue>();
}
}
else
{
foreach (var pi in @this.GetType().GetProperties())
{
if (pi.GetIndexParameters().Length > 0)
continue;
if (pi.GetCustomAttribute<XmlIgnoreAttribute>().IsNotNull())
continue;
dic[pi.Name.To<TKey>()] = pi.GetValue(@this).To<TValue>();
}
}
}
return dic;
}
#endregion
#region IsValid
/// <summary>
/// 验证对象是否有效
/// </summary>
/// <param name="this">要验证的对象</param>
/// <returns></returns>
public static bool IsValid(this object @this)
{
var isValid = true;
if (@this is IEnumerable list)
{
foreach (var item in list)
{
if (!item.IsValid())
{
isValid = false;
break;
}
}
}
else
{
isValid = Validator.TryValidateObject(@this, new ValidationContext(@this, null, null), new Collection<ValidationResult>(), true);
}
return isValid;
}
/// <summary>
/// 验证对象是否有效
/// </summary>
/// <param name="this">要验证的对象</param>
/// <returns></returns>
public static (bool isValid, Collection<ValidationResult> validationResults) IsValidWithResult(this object @this)
{
var isValid = true;
var validationResults = new Collection<ValidationResult>();
if (@this is IEnumerable list)
{
foreach (var item in list)
{
var (r, results) = item.IsValidWithResult();
if (!r && results?.Count > 0)
{
isValid = false;
results.ToList().ForEach(o => validationResults.Add(o));
break;
}
}
}
else
{
isValid = Validator.TryValidateObject(@this, new ValidationContext(@this, null, null), validationResults, true);
}
return (isValid, validationResults);
}
#endregion
#region GetValue
/// <summary>
/// 获取目标对象的成员值
/// </summary>
/// <param name="target">目标对象</param>
/// <param name="member">成员</param>
/// <returns></returns>
public static object GetValue(this object target, MemberInfo member)
{
if (member == null)
{
member = target as MemberInfo;
target = null;
}
if (member is PropertyInfo)
return (member as PropertyInfo)?.GetValue(target, null);
else if (member is FieldInfo)
return (member as FieldInfo)?.GetValue(target);
else
throw new ArgumentOutOfRangeException(nameof(member));
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using CP.i8n;
//------------------------------------------------------------------------------
//
// This code was generated by OzzCodeGen.
//
// Manual changes to this file will be overwritten if the code is regenerated.
//
//------------------------------------------------------------------------------
namespace CriticalPath.Data
{
[MetadataTypeAttribute(typeof(SizingStandardDTO.SizingStandardMetadata))]
public partial class SizingStandardDTO
{
internal sealed partial class SizingStandardMetadata
{
// This metadata class is not intended to be instantiated.
private SizingStandardMetadata() { }
[StringLength(64, ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "MaxLeght")]
[Required(ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "Required")]
[Display(ResourceType = typeof(EntityStrings), Name = "Title")]
public string Title { get; set; }
}
}
} |
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== //
//
// Notes:
//
// ============================================================================ //
namespace EnhancedEditor
{
/// <summary>
/// Used to simulate <see cref="UnityEditor.MessageType"/> without needing to use the UnityEditor namespace.
/// </summary>
public enum MessageType
{
None,
Info,
Warning,
Error
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour {
public Transform obj;//跟随的物体
public Vector3 objoffset = Vector3.zero;//偏移度
public Transform target;
public float distance = 10.0f; //与目标物体的距离
public float mindistance=2f; //最小距离
public float maxDistance = 15f; //最大距离
public float zoomSpeed=1f;
public float xSpeed=250.0f; //视角移动速度
public float ySpeed = 120.0f;
public bool allowYTilt=true; //Y轴视角允许与移动范围
public float yMinLimit=15.0f;
public float yMaxLimit=80.0f;
private float x=0.0f;
private float y=0.0f;
private float targetX=0f;
private float targetY=0f;
private float targetDistance=0f;
private float xVelocity=1f;
private float yVelocity=1f;
private float zoomVelocity=1f;
void Start(){
var angles = transform.eulerAngles;
targetX = x = angles.x;
targetY = y = ClampAngle (angles.y, yMinLimit, yMaxLimit);
targetDistance = distance;
}
void LateUpdate(){
if (obj) {
float scroll = Input.GetAxis ("Mouse ScrollWheel");
if (scroll > 0.0f)
targetDistance -= zoomSpeed;
else if (scroll < 0.0f)
targetDistance += zoomSpeed;
targetDistance = Mathf.Clamp (targetDistance, mindistance, maxDistance);
//按住鼠标右键来控制视角变换或左ctrl和鼠标左键
if (Input.GetMouseButton (1) || (Input.GetMouseButton (0) && (Input.GetKey (KeyCode.LeftControl) || Input.GetKey (KeyCode.RightControl)))) {
targetX+=Input.GetAxis("Mouse X")*xSpeed*0.02f;
if(allowYTilt){
targetY -= Input.GetAxis ("Mouse Y") * ySpeed * 0.02f;
targetY = ClampAngle (targetY, yMinLimit, yMaxLimit);
}
}
x = Mathf.SmoothDampAngle (x, targetX, ref xVelocity, 0.3f);
if (allowYTilt)
y = Mathf.SmoothDampAngle (y, targetY, ref yVelocity, 0.3f);
else
y = targetY;
Quaternion rotation = Quaternion.Euler (y, x, 0);
distance = Mathf.SmoothDamp (distance, targetDistance, ref zoomVelocity, 0.5f);
//视角面对跟随物体
Vector3 position = rotation * new Vector3 (0.0f, 0.0f, -distance) + obj.position + objoffset;
transform.rotation = rotation;
transform.position = position;
}
}
private float ClampAngle(float angle,float min,float max){
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
return Mathf.Clamp (angle, min, max);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.IO;
using System.Text;
using sfShareLib;
using System.Threading.Tasks;
using sfAPIService.Models;
using System.Web.Script.Serialization;
using sfAPIService.Filter;
using Swashbuckle.Swagger.Annotations;
using Newtonsoft.Json;
using CDSShareLib.Helper;
namespace sfAPIService.Controllers
{
[Authorize]
[CustomAuthorizationFilter(ClaimType = "Roles", ClaimValue = "admin")]
[RoutePrefix("admin-api/WidgetCatalog")]
public class WidgetCatalogController : ApiController
{
/// <summary>
/// Client_Id : Admin - OK
/// </summary>
///<param name="level">Company, Factory, Equipment</param>
[HttpGet]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(List<WidgetCatalogModel.Format_Detail>))]
[CustomAuthorizationFilter(ClaimType = "Roles", ClaimValue = "admin")]
public IHttpActionResult GetAllWidgetCatalog([FromUri]string level = "Company")
{
int companyId = Global.GetCompanyIdFromToken();
WidgetCatalogModel model = new WidgetCatalogModel();
switch (level.ToLower().ToString())
{
case "company":
case "factory":
case "equipment":
return Content(HttpStatusCode.OK, model.getAllWidgetCatalogByCompanyId(companyId, level));
}
return Content(HttpStatusCode.BadRequest, "Level should be company or factory or equipment.");
}
/// <summary>
/// Client_Id : Admin - OK
/// </summary>
[HttpGet]
[Route("{id}")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(WidgetCatalogModel.Format_Detail))]
public IHttpActionResult GetWidgetCatalogById(int id)
{
try
{
WidgetCatalogModel model = new WidgetCatalogModel();
return Content(HttpStatusCode.OK, model.GetById(id));
}
catch (CDSException cdsEx)
{
return Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId));
}
catch (Exception ex)
{
return Content(HttpStatusCode.InternalServerError, ex);
}
}
/// <summary>
/// Client_Id : Admin - OK
/// </summary>
[HttpPost]
public IHttpActionResult CreateWidgetCatalog([FromBody]WidgetCatalogModel.Format_Create dataModel)
{
string logForm = "Form : " + JsonConvert.SerializeObject(dataModel);
string logAPI = "[Post] " + Request.RequestUri.ToString();
if (!ModelState.IsValid || dataModel == null)
{
Global._appLogger.Warn(logAPI + " || Input Parameter not expected || " + logForm);
return Content(HttpStatusCode.BadRequest, HttpResponseFormat.InvaildData());
}
try
{
int companyId = Global.GetCompanyIdFromToken();
WidgetCatalogModel model = new WidgetCatalogModel();
int id = model.Create(companyId, dataModel);
return Content(HttpStatusCode.OK, HttpResponseFormat.Success(id));
}
catch (CDSException cdsEx)
{
return Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId));
}
catch (Exception ex)
{
StringBuilder logMessage = LogHelper.BuildExceptionMessage(ex);
logMessage.AppendLine(logForm);
Global._appLogger.Error(logAPI + logMessage);
return Content(HttpStatusCode.InternalServerError, ex);
}
}
/// <summary>
/// Client_Id : Admin - OK
/// </summary>
[HttpPatch]
[Route("{id}")]
public IHttpActionResult UpdateWidgetCatalog(int id, [FromBody]WidgetCatalogModel.Format_Update dataModel)
{
string logForm = "Form : " + JsonConvert.SerializeObject(dataModel);
string logAPI = "[Patch] " + Request.RequestUri.ToString();
if (!ModelState.IsValid || dataModel == null)
{
Global._appLogger.Warn(logAPI + " || Input Parameter not expected || " + logForm);
return Content(HttpStatusCode.BadRequest, HttpResponseFormat.InvaildData());
}
try
{
WidgetCatalogModel model = new WidgetCatalogModel();
model.Update(id, dataModel);
return Content(HttpStatusCode.OK, HttpResponseFormat.Success());
}
catch (CDSException cdsEx)
{
return Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId));
}
catch (Exception ex)
{
StringBuilder logMessage = LogHelper.BuildExceptionMessage(ex);
logMessage.AppendLine(logForm);
Global._appLogger.Error(logAPI + logMessage);
return Content(HttpStatusCode.InternalServerError, ex);
}
}
/// <summary>
/// Client_Id : Admin - OK
/// </summary>
[HttpDelete]
[Route("{id}")]
public IHttpActionResult DeleteWidgetCatalog(int id)
{
try
{
WidgetCatalogModel model = new WidgetCatalogModel();
model.DeleteById(id);
return Content(HttpStatusCode.OK, HttpResponseFormat.Success());
}
catch (CDSException cdsEx)
{
return Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId));
}
catch (Exception ex)
{
string logAPI = "[Delete] " + Request.RequestUri.ToString();
StringBuilder logMessage = LogHelper.BuildExceptionMessage(ex);
Global._appLogger.Error(logAPI + logMessage);
return Content(HttpStatusCode.InternalServerError, ex);
}
}
}
}
|
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using BakerWebApp.Models;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
namespace BakerWebApp.Controllers
{
[Authorize]
public class RegistrosController : Controller
{
private ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
public RegistrosController(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
{
_context = context;
_userManager = userManager;
}
// GET: Registros
public async Task<IActionResult> Index()
{
var usuario = _userManager.FindByNameAsync(User.Identity.Name).Result;
var applicationDbContext = _context.Registros.Where(item => item.Usuario.Id == usuario.Id).Include(r => r.Cliente);
return View(await applicationDbContext.ToListAsync());
}
// GET: Registros/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return HttpNotFound();
}
Registro registro = await _context.Registros.SingleAsync(m => m.RegistroId == id);
if (registro == null)
{
return HttpNotFound();
}
return View(registro);
}
// GET: Registros/Create
public IActionResult Create()
{
ViewBag.Cliente = new SelectList(_context.Clientes, "ClienteId", "Nombre");
return View();
}
// POST: Registros/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Registro registro)
{
registro.Usuario = _userManager.FindByNameAsync(User.Identity.Name).Result;
registro.UsuarioId = registro.Usuario.Id;
if (ModelState.IsValid)
{
_context.Registros.Add(registro);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.Cliente = new SelectList(_context.Clientes, "ClienteId", "Nombre", registro.ClienteId);
return View(registro);
}
// GET: Registros/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return HttpNotFound();
}
Registro registro = await _context.Registros.SingleAsync(m => m.RegistroId == id);
if (registro == null)
{
return HttpNotFound();
}
ViewBag.Cliente = new SelectList(_context.Clientes, "ClienteId", "Nombre", registro.ClienteId);
return View(registro);
}
// POST: Registros/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Registro registro)
{
if (ModelState.IsValid)
{
_context.Update(registro);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.Cliente = new SelectList(_context.Clientes, "ClienteId", "Cliente", registro.ClienteId);
return View(registro);
}
// GET: Registros/Delete/5
[ActionName("Delete")]
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return HttpNotFound();
}
Registro registro = await _context.Registros.SingleAsync(m => m.RegistroId == id);
if (registro == null)
{
return HttpNotFound();
}
return View(registro);
}
// POST: Registros/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
Registro registro = await _context.Registros.SingleAsync(m => m.RegistroId == id);
_context.Registros.Remove(registro);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
}
|
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
#nullable disable
namespace BillSystem.Models
{
public partial class BillContext : DbContext
{
public BillContext()
{
}
public BillContext(DbContextOptions<BillContext> options)
: base(options)
{
}
public virtual DbSet<Bill> Bills { get; set; }
public virtual DbSet<Billdetail> Billdetails { get; set; }
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<Product> Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
optionsBuilder.UseSqlServer("Server=DESKTOP-J3PH7KC\\SQLEXPRESS;Database=Bill;Trusted_Connection=True;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("Relational:Collation", "Chinese_PRC_CI_AS");
modelBuilder.Entity<Bill>(entity =>
{
entity.ToTable("BILL");
entity.Property(e => e.Id).HasColumnName("ID");
entity.Property(e => e.CustId).HasColumnName("CUST_ID");
entity.HasOne(d => d.Cust)
.WithMany(p => p.Bills)
.HasForeignKey(d => d.CustId)
.HasConstraintName("FK__BILL__CUST_ID__59063A47");
});
modelBuilder.Entity<Billdetail>(entity =>
{
entity.ToTable("BILLDETAILS");
entity.Property(e => e.Id).HasColumnName("ID");
entity.Property(e => e.BillId).HasColumnName("BILL_ID");
entity.Property(e => e.ProdId).HasColumnName("PROD_ID");
entity.Property(e => e.Quantity).HasColumnName("QUANTITY");
entity.Property(e => e.UnitPrice).HasColumnName("UNIT_PRICE");
entity.HasOne(d => d.Bill)
.WithMany(p => p.Billdetails)
.HasForeignKey(d => d.BillId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK__BILLDETAI__BILL___619B8048");
entity.HasOne(d => d.Prod)
.WithMany(p => p.Billdetails)
.HasForeignKey(d => d.ProdId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK__BILLDETAI__PROD___628FA481");
});
modelBuilder.Entity<Customer>(entity =>
{
entity.ToTable("CUSTOMER");
entity.Property(e => e.Id).HasColumnName("ID");
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(80)
.IsUnicode(false)
.HasColumnName("NAME");
entity.Property(e => e.Phone)
.IsRequired()
.HasMaxLength(80)
.IsUnicode(false)
.HasColumnName("PHONE");
});
modelBuilder.Entity<Product>(entity =>
{
entity.ToTable("PRODUCT");
entity.Property(e => e.Id).HasColumnName("ID");
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(80)
.IsUnicode(false)
.HasColumnName("NAME");
entity.Property(e => e.Price).HasColumnName("PRICE");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
|
// Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NtApiDotNet.Utilities.Text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace NtApiDotNet.Win32.Security.Authentication.Ntlm
{
internal static class NtlmUtils
{
internal static bool TryParseStringValues(BinaryReader reader, out int length, out int position)
{
length = 0;
position = 0;
if (reader.RemainingLength() < 8)
return false;
length = reader.ReadUInt16();
_ = reader.ReadUInt16();
position = reader.ReadInt32();
return true;
}
internal static bool TryParseAvPairs(BinaryReader reader, out List<NtlmAvPair> av_pairs)
{
av_pairs = new List<NtlmAvPair>();
while (reader.RemainingLength() > 0)
{
if (!NtlmAvPair.TryParse(reader, out NtlmAvPair pair))
{
return false;
}
if (pair.Type == MsAvPairType.EOL)
break;
av_pairs.Add(pair);
}
return true;
}
public static bool ParseString(NtlmNegotiateFlags flags, byte[] data, int length, int position, out string result)
{
result = string.Empty;
if (data.Length < position + length)
return false;
if (flags.HasFlagSet(NtlmNegotiateFlags.Unicode))
{
result = Encoding.Unicode.GetString(data, position, length);
}
else if (flags.HasFlagSet(NtlmNegotiateFlags.Oem))
{
result = BinaryEncoding.Instance.GetString(data, position, length);
}
else
{
return false;
}
return true;
}
public static bool ParseBytes(byte[] data, int length, int position, out byte[] result)
{
result = new byte[0];
if (length == 0)
return true;
if (data.Length < position + length)
return false;
result = new byte[length];
Array.Copy(data, position, result, 0, length);
return true;
}
public static bool ParseString(NtlmNegotiateFlags flags, BinaryReader reader, byte[] data, bool valid, out string result)
{
result = string.Empty;
if (!TryParseStringValues(reader, out int length, out int position))
return false;
if (!valid)
return true;
return ParseString(flags, data, length, position, out result);
}
internal static bool TryParse(BinaryReader reader, out Version version)
{
version = default;
if (reader.RemainingLength() < 8)
return false;
int major = reader.ReadByte();
int minor = reader.ReadByte();
int build = reader.ReadUInt16();
_ = reader.ReadBytes(3);
int revision = reader.ReadByte();
version = new Version(major, minor, build, revision);
return true;
}
}
}
|
using Foundation;
using Kit.Services.Interfaces;
using System.Threading.Tasks;
namespace Kit.iOS.Services
{
public class FolderPermissions : IFolderPermissions
{
public override async Task<bool> CanRead(string directoryInfo)
{
await Task.Yield();
NSFileManager dir = new NSFileManager();
return dir.IsReadableFile(directoryInfo);
}
public override async Task<bool> CanWrite(string directoryInfo)
{
await Task.Yield();
NSFileManager dir = new NSFileManager();
return dir.IsWritableFile(directoryInfo);
}
public override async Task<bool> TryToUnlock(string Path)
{
await Task.Yield();
return true;
}
}
}
|
using PetSharing.Domain.Dtos;
using System;
using System.Collections.Generic;
namespace PetSharing.Domain.Models
{
public class PetProfileDto
{
public string OwnerId { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public string Img { get; set; }
public string Type { get; set; }
public string Breed { get; set; }
public string Gender { get; set; }
public DateTime? DateOfBirth { get; set; }
public string Location { get; set; }
public double AvgLikeCount { get; set; }
public bool IsSale { get; set; }
public bool IsReadyForSex { get; set; }
public bool IsShare { get; set; }
public List<PostDto> Posts { get; set; }
public PetProfileDto()
{
Posts = new List<PostDto>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using SubSonic.Extensions;
namespace Pes.Core
{
public partial class BoardForum
{
public static BoardForum GetForumByGroupID(Int32 GroupID)
{
BoardForum result;
BoardForum forum = (from f in BoardForum.All()
join gf in GroupForum.All() on f.ForumID equals gf.ForumID
where gf.GroupID == GroupID
select f).FirstOrDefault();
result = forum;
return result;
}
public static BoardForum GetForumByID(Int32 ForumID)
{
BoardForum result;
BoardForum forum = BoardForum.All().Where(f => f.ForumID == ForumID).FirstOrDefault();
result = forum;
return result;
}
public static BoardForum GetForumByPageName(string PageName)
{
BoardForum result;
BoardForum forum = BoardForum.All().Where(f => f.PageName == PageName).FirstOrDefault();
result = forum;
return result;
}
public static List<BoardForum> GetForumsByCategoryID(Int32 CategoryID)
{
List<BoardForum> results;
IEnumerable<BoardForum> forums = BoardForum.All().Where(f => f.CategoryID == CategoryID);
results = forums.ToList();
return results;
}
public static List<BoardForum> GetAllForums()
{
List<BoardForum> results;
IEnumerable<BoardForum> forums = BoardForum.All();
results = forums.ToList();
return results;
}
public static Int32 SaveForum(BoardForum boardForum)
{
if (boardForum.ForumID > 0)
{
BoardForum.Update(boardForum);
}
else
{
Add(boardForum);
}
return boardForum.ForumID;
}
public static void DeleteForum(BoardForum boardForum)
{
Delete(boardForum.ForumID);
}
}
} |
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using OmniSharp.Extensions.JsonRpc.Generators.Contexts;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace OmniSharp.Extensions.JsonRpc.Generators.Strategies
{
internal class SendMethodNotificationStrategy : IExtensionMethodContextGeneratorStrategy
{
public IEnumerable<MemberDeclarationSyntax> Apply(SourceProductionContext context, ExtensionMethodContext extensionMethodContext, GeneratorData item)
{
if (item is not NotificationItem notification) yield break;
if (extensionMethodContext is not { IsProxy: true }) yield break;
var method = MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), item.JsonRpcAttributes.RequestMethodName)
.WithModifiers(
TokenList(
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.StaticKeyword)
)
)
.WithExpressionBody(Helpers.GetNotificationInvokeExpression())
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken));
yield return method
.WithParameterList(
ParameterList(
SeparatedList(
new[] {
Parameter(Identifier("mediator"))
.WithType(extensionMethodContext.Item)
.WithModifiers(TokenList(Token(SyntaxKind.ThisKeyword))),
Parameter(Identifier("request"))
.WithType(notification.Request.Syntax)
}
)
)
);
}
}
}
|
using UnityEngine;
using System.Collections;
namespace ProjectV.ItemSystem{
public interface IISQuality {
string Name{ get; set;}
Sprite Icon{get;set;}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MeasurementSymmetrySpatial : Measurement
{
public struct SumElement
{
public int level;
public float delta;
public float weight;
}
public class SpatialElement
{
public int level;
public int stemCount;
public int allCount;
public float stemSize;
public float allSize;
public List<SpatialElement> leftBranches;
public List<SpatialElement> rightBranches;
}
public int level = 2;
private List<SumElement> asymetryList = new List<SumElement> ();
private SpatialElement symmetryNode = null;
int _countParts(LSystemGraph structNode)
{
if (structNode == null)
return 0;
int sum = 1;
foreach (LSystemGraph child in structNode.neighbour)
{
sum += _countParts(child);
}
return sum;
}
float _countSizes(LSystemGraph structNode)
{
if (structNode == null)
return 0;
float sum = structNode.size.magnitude;
foreach (LSystemGraph child in structNode.neighbour)
{
sum += _countSizes(child);
}
return sum;
}
SpatialElement _getSymNode (LSystemGraph structNode, int level)
{
if (structNode == null)
return null;
SpatialElement node = new SpatialElement ();
node.level = level;
node.stemCount = 0;
node.allCount = 0;
node.stemSize = 0;
node.leftBranches = new List<SpatialElement> ();
node.rightBranches = new List<SpatialElement> ();
while (structNode.neighbour.Count != 1 && structNode.neighbour.Count != 0)
{
if(structNode.neighbour.Count != 2)
{
node.stemCount += structNode.neighbour.Count;
foreach(LSystemGraph neighbour in structNode.neighbour)
{
node.stemSize += neighbour.size.magnitude;
}
structNode = structNode.neighbour[2] as LSystemGraph;
}
else
{
if(level > 0)
{
if((structNode.neighbour[0] as LSystemGraph).angle < 0)
{
node.rightBranches.Add(_getSymNode(structNode.neighbour[0] as LSystemGraph, level - 1));
}
else
{
node.leftBranches.Add(_getSymNode(structNode.neighbour[0] as LSystemGraph, level - 1));
}
}
else
{
node.stemCount += _countParts(structNode.neighbour[0] as LSystemGraph);
node.stemSize += _countSizes(structNode.neighbour[0] as LSystemGraph);
}
structNode = structNode.neighbour[1] as LSystemGraph;
}
}
node.stemCount += structNode.neighbour.Count;
node.stemSize += structNode.size.magnitude;
if (structNode.neighbour.Count == 0)
{
node.stemCount++;
}
int leftSum = 0;
for (int i = 0; i < node.leftBranches.Count; i++)
{
leftSum += node.leftBranches[i].allCount;
}
int rightSum = 0;
for (int i = 0; i < node.rightBranches.Count; i++)
{
rightSum += node.rightBranches[i].allCount;
}
node.allCount = node.stemCount + leftSum + rightSum;
float leftSizeSum = 0;
for (int i = 0; i < node.leftBranches.Count; i++)
{
leftSizeSum += node.leftBranches[i].allSize;
}
float rightSizeSum = 0;
for (int i = 0; i < node.rightBranches.Count; i++)
{
rightSizeSum += node.rightBranches[i].allSize;
}
node.allSize = node.stemSize + leftSizeSum + rightSizeSum;
return node;
}
void _fillNodeValues (SpatialElement node)
{
SumElement se = new SumElement ();
se.level = node.level;
float leftSum = 0;
for (int i = 0; i < node.leftBranches.Count; i++)
{
leftSum += node.leftBranches[i].allSize;
}
float rightSum = 0;
for (int i = 0; i < node.rightBranches.Count; i++)
{
rightSum += node.rightBranches[i].allSize;
}
se.delta = (leftSum + rightSum) == 0 ? 0 : (float)Mathf.Abs (leftSum - rightSum) / (float)(node.allCount);
se.weight = (float)node.allSize / (float)symmetryNode.allSize;
asymetryList.Add (se);
for (int i = 0; i < node.leftBranches.Count; i++)
{
_fillNodeValues(node.leftBranches[i]);
}
for (int i = 0; i < node.rightBranches.Count; i++)
{
_fillNodeValues(node.rightBranches[i]);
}
}
public override float Evaluate(Representation representation)
{
RepresentationMesh repre = representation as RepresentationMesh;
if (repre == null)
return 0;
if (repre.structure == null)
return 0;
asymetryList.Clear ();
symmetryNode = null;
symmetryNode = _getSymNode (repre.structure as LSystemGraph, level);
_fillNodeValues (symmetryNode);
float returnValue = 0;
for (int i = 0; i < asymetryList.Count; i++)
{
returnValue += asymetryList[i].delta * asymetryList[i].weight;
}
return returnValue;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VendingMachine.Interfaces;
using VendingMachine.Models;
namespace VendingMachine.Repository
{
public class ProductRepository : IProductRepository
{
private List<Product> _products = new List<Product>
{
new Product(id:1, name:"Coca Cola", price:0.80M, description:"330ml"),
new Product(id:2, name:"Coke Zero", price:0.80M, description:"330ml"),
new Product(id:3, name:"Fanta", price:0.80M, description:"330ml"),
new Product(id:4, name:"Sprite", price:0.80M, description:"330ml"),
new Product(id:5, name:"Coca Cola", price:1.20M, description:"500ml"),
new Product(id:6, name:"Coke Zero", price:1.20M, description:"500ml"),
new Product(id:7, name:"Fanta", price:1.20M, description:"500ml"),
new Product(id:8, name:"Sprite", price:1.20M, description:"500ml"),
new Product(id:9, name:"Water", price:1.00M, description:"500ml"),
};
public Product FindById(int id)
{
return _products.FirstOrDefault(c => c.Id == id);
}
public bool Exists(int id)
{
return _products.Any(c => c.Id == id);
}
public List<Product> GetAll()
{
return _products;
}
}
}
|
using System;
using System.Collections.Generic;
using LoanStreet.LoanServicing.Model;
using Xunit;
namespace LoanStreet.LoanServicing.Examples.Institutions
{
public class CreateInstitution : TestBase
{
public static Institution GetTestInstitution()
{
var name = Guid.NewGuid().ToString();
var ticker = name.Substring(0, 5);
var address = new Address(
"West 30th Street",
"8th Floor",
"New York",
"NY",
"10025"
);
return new Institution(
name,
ticker,
address,
new List<Fund>()
);
}
public static Institution CreateAnInstitution()
{
// 1) Instantiate an Institution
var name = Guid.NewGuid().ToString();
var ticker = name.Substring(0, 5);
var address = new Address(
"West 30th Street",
"8th Floor",
"New York",
"NY",
"10025"
);
var pending = new Institution(
name,
ticker,
address,
new List<Fund>()
);
var client = ClientFactory.GetInstitutionsController();
var institution = client.CreateInstitution(pending);
return institution;
}
[Fact]
public void CreateInstitutionExample()
{
// 1) Set Credentials. You will need to uncomment and set the following line
// ClientFactory.SetCredentials("YourUser", "YourPassword")
// 2) Create an Institution Model Instance
var institution = GetTestInstitution();
// 3) Get the Institutions Client
var client = ClientFactory.GetInstitutionsController();
// 4) Send the Institution model to the Servicing API!
var createdInstitution = client.CreateInstitution(institution);
// 5) The API will respond with an instance of the institution it created. This instance will have
// a populated `institutionId` property, this is the unique identifier the Servicing system has
// assign to the Institution.
//
// When creating or updating, we should always use the instance returned by the client, rather
// than the instance we sent to the API
//
// Strictly for testing purposes, verify that we received a response
Assert.NotNull(createdInstitution);
}
[Fact(Skip = "Pending Permissions Correction")]
public void GetInstitution()
{
// 1) Set Credentials. You will need to uncomment and set the following line
// ClientFactory.SetCredentials("YourUser", "YourPassword");
// 2) Get the institutions client
var client = ClientFactory.GetInstitutionsController();
// 3) Load Your User's Institution
var loadedById = client.GetInstitution(Context.institutionId);
// 5) Strictly for testing purposes, load the institution by id
Assert.NotNull(loadedById);
}
[Fact]
public void ListInstitutions()
{
// 1) Set Credentials. You will need to uncomment and set the following line
// ClientFactory.SetCredentials("YourUser", "YourPassword");
// 2) Get the Institutions client
var client = ClientFactory.GetInstitutionsController();
// 3) List institutions my user is permitted to view
var allInstitutions = client.ListInstitutions();
// 4) Strictly for testing purposes, assert that we received a response.
Assert.NotNull(allInstitutions);
}
}
} |
using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Microsoft.Win32.SafeHandles;
namespace Sample
{
partial class NativeMethods
{
internal partial class NCrypt
{
private const string NCryptLibraryName = "ncrypt.dll";
[DllImport(NCryptLibraryName, CharSet = CharSet.Unicode)]
internal static extern int NCryptCreatePersistedKey(SafeNCryptProviderHandle hProvider,
[Out] out SafeNCryptKeyHandle phKey,
string pszAlgId,
string pszKeyName,
int dwLegacyKeySpec,
CngKeyCreationOptions dwFlags);
[DllImport(NCryptLibraryName, CharSet = CharSet.Unicode)]
internal static extern int NCryptOpenStorageProvider(
[Out] out SafeNCryptProviderHandle phProvider,
[MarshalAs(UnmanagedType.LPWStr)] string pszProviderName,
int dwFlags);
[DllImport(NCryptLibraryName, CharSet = CharSet.Unicode)]
internal static extern int NCryptImportKey(
SafeNCryptProviderHandle hProvider,
IntPtr hImportKey, // NCRYPT_KEY_HANDLE
string pszBlobType,
ref NCryptBufferDesc pParameterList,
[Out] out SafeNCryptKeyHandle phKey,
[MarshalAs(UnmanagedType.LPArray)] byte[] pbData,
int cbData,
int dwFlags);
[DllImport(NCryptLibraryName, CharSet = CharSet.Unicode)]
internal static extern int NCryptImportKey(
SafeNCryptProviderHandle hProvider,
IntPtr hImportKey, // NCRYPT_KEY_HANDLE
string pszBlobType,
IntPtr pParameterList, // NCryptBufferDesc *
[Out] out SafeNCryptKeyHandle phKey,
[MarshalAs(UnmanagedType.LPArray)] byte[] pbData,
int cbData,
int dwFlags);
[DllImport(NCryptLibraryName, CharSet = CharSet.Unicode)]
internal static extern int NCryptFinalizeKey(SafeNCryptKeyHandle hKey, int dwFlags);
[DllImport(NCryptLibraryName, CharSet = CharSet.Unicode)]
internal static extern int NCryptExportKey(
SafeNCryptKeyHandle hKey,
IntPtr hExportKey,
string pszBlobType,
IntPtr pParameterList, // NCryptBufferDesc *
byte[] pbOutput,
int cbOutput,
[Out] out int pcbResult,
int dwFlags);
[DllImport(NCryptLibraryName, CharSet = CharSet.Unicode)]
internal static extern int NCryptExportKey(
SafeNCryptKeyHandle hKey,
IntPtr hExportKey,
string pszBlobType,
ref NCryptBufferDesc pParameterList,
byte[] pbOutput,
int cbOutput,
[Out] out int pcbResult,
int dwFlags);
[DllImport(NCryptLibraryName, CharSet = CharSet.Unicode)]
internal static extern int NCryptSetProperty(
SafeNCryptHandle hObject,
string pszProperty,
[MarshalAs(UnmanagedType.LPArray)] byte[] pbInput,
int cbInput,
CngPropertyOptions dwFlags);
[DllImport(NCryptLibraryName, CharSet = CharSet.Unicode)]
internal static extern int NCryptSetProperty(
SafeNCryptHandle hObject,
string pszProperty,
string pbInput,
int cbInput,
CngPropertyOptions dwFlags);
[DllImport(NCryptLibraryName, CharSet = CharSet.Unicode)]
internal static extern int NCryptSetProperty(
SafeNCryptHandle hObject,
string pszProperty,
IntPtr pbInput,
int cbInput,
CngPropertyOptions dwFlags);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CovidData.Models
{
public class BasicData
{
public int dailyconfirmed { get; set; }
public int dailydeceased { get; set; }
public int dailyrecovered { get; set; }
public string date { get; set; }
public DateTime? dateymd { get; set; }
public int totalconfirmed { get; set; }
public int totaldeceased { get; set; }
public int totalrecovered { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using ExpenseTracker.Model;
using System.ComponentModel;
using System.Collections.ObjectModel;
namespace ExpenseTracker.ViewModels
{
class AddItemViewModel : INotifyPropertyChanged
{
public DataQuery_Mod DataQuery;
private bool _IsBusy = false;
public bool IsBusy { get { return _IsBusy; } set { _IsBusy = value; OnPropertyChanged(nameof(IsBusy)); } }
public int ID { get; set; }
public int User_ID { get; set; }
private bool _InAccVisible;
public bool InAccVisible
{
get { return _InAccVisible; }
set { _InAccVisible = value; OnPropertyChanged(nameof(InAccVisible)); }
}
private string _TransName;
public string TransName
{
get { return _TransName; }
set { _TransName = value; OnPropertyChanged(nameof(TransName)); }
}
private ObservableCollection<string> _IncomeAccountList;
public ObservableCollection<string> IncomeAccountList
{
get { return _IncomeAccountList; }
set { _IncomeAccountList = value; OnPropertyChanged(nameof(IncomeAccountList)); }
}
private string _IncomeAccount;
public string IncomeAccount
{
get { return _IncomeAccount; }
set { _IncomeAccount = value; OnPropertyChanged(nameof(IncomeAccount)); }
}
private string _AccountType;
public string AccountType
{
get { return _AccountType; }
set
{
_AccountType = value;
OnPropertyChanged(nameof(AccountType));
}
}
private string _AccountName;
public string AccountName
{
get { return _AccountName; }
set
{
_AccountName = value;
OnPropertyChanged(nameof(AccountName));
}
}
private string _TransAmount;
public string TransAmount
{
get { return _TransAmount; }
set
{
_TransAmount = value;
OnPropertyChanged(nameof(TransAmount));
}
}
private ObservableCollection<string> _CategoryList;
public ObservableCollection<string> CategoryList
{
get { return _CategoryList; }
set
{
_CategoryList = value;
OnPropertyChanged(nameof(CategoryList));
}
}
private string _Category;
public string Category
{
get { return _Category; }
set
{
_Category = value;
OnPropertyChanged(nameof(Category));
}
}
public AddItemViewModel()
{
DataQuery = new DataQuery_Mod();
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string name = "")
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
}
|
using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using CGCN.Framework;
using Npgsql;
using NpgsqlTypes;
using CGCN.DataAccess;
using HoaDonDataAccess.DataAccess;
namespace HoaDonDataAccess.BusinesLogic
{
/// <summary>
/// Mô tả thông tin cho bảng tienthanhtoanphieunhap
/// Cung cấp các hàm xử lý, thao tác với bảng tienthanhtoanphieunhap
/// Người tạo (C): tuanva
/// Ngày khởi tạo: 03/09/2015
/// </summary>
public class tienthanhtoanphieunhapBL
{
private tienthanhtoanphieunhap objtienthanhtoanphieunhapDA = new tienthanhtoanphieunhap();
public tienthanhtoanphieunhapBL() { objtienthanhtoanphieunhapDA = new tienthanhtoanphieunhap(); }
#region Public Method
private readonly DataAccessLayerBaseClass mDataAccess = new DataAccessLayerBaseClass(Data.ConnectionString);
/// <summary>
/// Lấy toàn bộ dữ liệu từ bảng tienthanhtoanphieunhap
/// </summary>
/// <returns>DataTable</returns>
public DataTable GetAll()
{
return objtienthanhtoanphieunhapDA.GetAll();
}
/// <summary>
/// Hàm lấy object tienthanhtoanphieunhap theo mã
/// </summary>
/// <returns>Trả về objttienthanhtoanphieunhap </returns>
public tienthanhtoanphieunhap GetByID(string strid)
{
return objtienthanhtoanphieunhapDA.GetByID(strid);
}
/// <summary>
/// Hàm lấy objtienthanhtoanphieunhap theo mã phiếu nhập hàng và ngày thanh toán
/// </summary>
/// <param name="sidhd">Mã phiếu nhập hàng kiểu string(Guid)</param>
/// <param name="dtngaytt">Ngày thanh toán kiểu DateTime</param>
/// <returns>object: tienthanhtoanphieunhap</returns>
public tienthanhtoanphieunhap GetByIDPNvsNgayTT(string sidpn, DateTime dtngaytt)
{
return objtienthanhtoanphieunhapDA.GetByIDPNvsNgayTT(sidpn, dtngaytt);
}
/// <summary>
/// Hàm lấy danh sách tiền thanh toán theo mã hóa đơn
/// </summary>
/// <param name="sidpn">Mã phiếu nhập kiểu string(Guid)</param>
/// <returns>DataTable</returns>
public DataTable GetByIDPN(string sidpn)
{
return objtienthanhtoanphieunhapDA.GetByIDPN(sidpn);
}
/// <summary>
/// Hàm tính tổng tiền đã thanh toán theo mã hóa đơn nhập
/// </summary>
/// <param name="sidhd">Mã hóa đơn nhập</param>
/// <returns>Tổng tiền đã thanh toán kiểu double</returns>
public double GetTienDaThanhToan(string sidpn)
{
double tongtien = 0;
try
{
tbltienthanhtoanBL ctr = new tbltienthanhtoanBL();
DataTable dt = new DataTable();
dt = GetByIDPN(sidpn);
for (int i = 0; i < dt.Rows.Count; i++)
{
tongtien = tongtien + Convert.ToDouble(dt.Rows[i]["tientt"].ToString().Trim());
}
return tongtien;
}
catch { return tongtien; }
}
/// <summary>
/// Hàm kiểm tra đã tồn tại bản ghi theo mã phiếu nhập và ngày thanh toán
/// </summary>
/// <param name="sidhd">Mã phiếu nhập kiểu string (Guid)</param>
/// <param name="dtngaytt">Ngày thanh toán kiểu DateTime</param>
/// <returns>bool: False-Không tồn tại;True-Có tồn tại</returns>
public bool CheckExit(string sidpn, DateTime dtngaytt)
{
return objtienthanhtoanphieunhapDA.CheckExit(sidpn, dtngaytt);
}
/// <summary>
/// Thêm mới dữ liệu vào bảng: tienthanhtoanphieunhap
/// </summary>
/// <param name="obj">objtienthanhtoanphieunhap</param>
/// <returns>Trả về trắng: Thêm mới thành công; Trả về khác trắng: Thêm mới không thành công</returns>
public string Insert(tienthanhtoanphieunhap objtienthanhtoanphieunhap)
{
return objtienthanhtoanphieunhapDA.Insert(objtienthanhtoanphieunhap);
}
/// <summary>
/// Cập nhật dữ liệu vào bảng: tienthanhtoanphieunhap
/// </summary>
/// <param name="obj">objtienthanhtoanphieunhap</param>
/// <returns>Trả về trắng: Cập nhật thành công; Trả về khác trắng: Cập nhật không thành công</returns>
public string Update(tienthanhtoanphieunhap objtienthanhtoanphieunhap)
{
return objtienthanhtoanphieunhapDA.Update(objtienthanhtoanphieunhap);
}
/// <summary>
/// Xóa dữ liệu từ bảng tienthanhtoanphieunhap
/// </summary>
/// <returns></returns>
public string Delete(string strid)
{
return objtienthanhtoanphieunhapDA.Delete(strid);
}
/// <summary>
/// Hàm lấy tất cả dữ liệu trong bảng tienthanhtoanphieunhap
/// </summary>
/// <returns>Trả về List<<tienthanhtoanphieunhap>></returns>
public List<tienthanhtoanphieunhap> GetList()
{
return objtienthanhtoanphieunhapDA.GetList();
}
/// <summary>
/// Hàm lấy danh sách objtienthanhtoanphieunhap
/// </summary>
/// <param name="recperpage">Số lượng bản ghi kiểu integer</param>
/// <param name="pageindex">Số trang kiểu integer</param>
/// <returns>Trả về List<<tienthanhtoanphieunhap>></returns>
public List<tienthanhtoanphieunhap> GetListPaged(int recperpage, int pageindex)
{
return objtienthanhtoanphieunhapDA.GetListPaged(recperpage, pageindex);
}
/// <summary>
/// Hàm lấy danh sách objtienthanhtoanphieunhap
/// </summary>
/// <param name="recperpage">Số lượng bản ghi kiểu integer</param>
/// <param name="pageindex">Số trang kiểu integer</param>
/// <returns>Trả về List<<tienthanhtoanphieunhap>></returns>
public DataTable GetDataTablePaged(int recperpage, int pageindex)
{
return objtienthanhtoanphieunhapDA.GetDataTablePaged(recperpage, pageindex);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Ext.Net;
using Ext.Net.Utilities;
public partial class Aspx_DWHViajesCarga : System.Web.UI.Page
{
readonly UoMetodos _zMetodos = new UoMetodos();
private string _perfil = string.Empty;
private string _usuario = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (X.IsAjaxRequest) return;
_perfil = Request.QueryString["param1"];
_usuario = Request.QueryString["param2"];
z_dtnInicial.MinDate = DateTime.Parse("2015-01-01");
z_dtnInicial.MaxDate = DateTime.Now;
z_dtnInicial.SetValue(DateTime.Parse("2015-01-01"));
z_dtnFinal.SetValue(DateTime.Now);
try
{
switch (_perfil)
{
case "NISSAN_USUARIO":
break;
case "NISSAN_EJECUTIVO":
break;
case "NISSAN_USUARIO_REPORTES":
break;
/*default:
Response.Redirect(@"~/AccesoNoAutorizado.html");
break;*/
}
}
catch (Exception ex)
{
X.Msg.Show(new MessageBoxConfig
{
Buttons = MessageBox.Button.OK,
Icon = MessageBox.Icon.ERROR,
Title = "Error",
Message = "No es posible conectarse al servidor, intente de nuevo"
});
ResourceManager.AjaxSuccess = false;
ResourceManager.AjaxErrorMessage = ex.Message;
}
}
[DirectMethod]
public string ZMetViajesCarga(string zparInicio, string zparFinal)
{
var zVarstrresultado = "";
try
{
var zDtsPorcentajeCarga = _zMetodos.ZMetConsultaViajesPorcentajeCarga(zparInicio, zparFinal);
zGrdPnl_PorcCarga.GetStore().DataSource = zDtsPorcentajeCarga.Tables["ViajesPorcCarga"];
zGrdPnl_PorcCarga.GetStore().DataBind();
/*var zDtsPorcentajeCargaResumen = _zMetodos.ZMetConsultaViajesPorcentajeCargaResumen(zparInicio, zparFinal);
zCartChart_PorcCarga.GetStore().RemoveAll();
zCartChart_PorcCarga.GetStore().DataSource = zDtsPorcentajeCargaResumen.Tables["ViajesCargaResumen"];
zCartChart_PorcCarga.GetStore().DataBind();*/
/*---------------------*/
var zDtsViajesCantidad = _zMetodos.ZMetConsultaViajesCantidad(zparInicio, zparFinal);
z_str_ViajesCantidad.DataSource = zDtsViajesCantidad.Tables["ViajesCantidad"];
z_str_ViajesCantidad.DataBind();
/*---------------------*/
var zDtsViajesRebotes = _zMetodos.ZMetConsultaViajesRebotes(zparInicio, zparFinal);
z_str_ViajesRebotes.DataSource = zDtsViajesRebotes.Tables["ViajesRebotes"];
z_str_ViajesRebotes.DataBind();
zVarstrresultado = _zMetodos.JsonResulEjec(1, "SQL_OK", "Embarques", "");
}
catch (Exception ex)
{
zVarstrresultado = _zMetodos.JsonResulEjec(0, "SQL_ERROR", "Embarques", "Error en ejecución SQL...");
}
return zVarstrresultado;
}
private DataTable Transformar(IEnumerable<IGrouping<string, DataRow>> datos)
{
//
// Se define la estructura del DataTable
//
var dt = new DataTable();
dt.Columns.Add("Mes");
dt.Columns.Add("Total");
//
// Se recorre cada valor agruparo por linq y se vuelca el resultado
// en un nuevo registro del datatable
//
foreach (var item in datos)
{
var row2 = dt.NewRow();
row2["Mes"] = item.Key;
row2["CantRegistros"] = item.Count();
row2["Total"] = item.Sum<DataRow>(x => Convert.ToInt32(x["Total"]));
dt.Rows.Add(row2);
}
return dt;
}
} |
namespace ns8
{
using Buddy.Auth;
using Buddy.Auth.Objects;
using Buddy.Auth.SR;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.ServiceModel;
using System.Text;
using System.Threading;
internal class Class40
{
internal readonly AClient aclient_0;
private static byte[] byte_0;
private static EndpointAddress endpointAddress_0;
[CompilerGenerated]
private static Region region_0;
private static Stopwatch stopwatch_0;
public static string string_0;
[CompilerGenerated]
private static string string_1;
[CompilerGenerated]
private static string string_2;
private const string string_3 = "<RSAKeyValue><Modulus>t0aG8IaxqGaPj0mJN8HwD0BDm57mUdEnuiq+ANRH5A+rLoLrHbCfgDaslUckBzzlUqXHncDGARD8tYbVRjFWjbH4oWPLvKfjx/ZmIIvzVxOj5Uo9r95qJdS+DNh7oVP8pFavEtSOurXYrw0uRbj08r1zrrIsrssfXVBw2PI/pCy+gX3WeydXQknczl97bKIOBAFobMpLUBsQcM8Bs8gJC+f81cGw1ndhAwqZYRpR/KlDdEw0vWACpOMBIdeLAK0akx2deWvquAGRmLJBaJInOGpYRa6kVqcXRIG1vB2Zh3x9GhYeoeAQMVcogTvIxgNfiGNNc6CgsyRWoikLYS+1UQ==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
[field: CompilerGenerated]
public static event EventHandler Event_0;
[field: CompilerGenerated]
public static event EventHandler Event_1;
[field: CompilerGenerated]
public static event EventHandler Event_2;
static Class40()
{
smethod_0(Region.BestLatency);
}
public Class40()
{
NetTcpBinding binding1 = new NetTcpBinding(SecurityMode.None) {
PortSharingEnabled = true,
MaxReceivedMessageSize = 0x7fffffffL
};
binding1.ReaderQuotas.MaxArrayLength = 0x7fffffff;
binding1.SendTimeout = new TimeSpan(0, 10, 0);
NetTcpBinding binding = binding1;
this.aclient_0 = new AClient(binding, endpointAddress_0);
}
[Obsolete("Does nothing")]
public void method_0()
{
}
public void method_1()
{
this.aclient_0.Abort();
}
public unsafe r0 method_10(params object[] object_0)
{
byte[] buffer3;
if (!this.method_4() || ((stopwatch_0 != null) && (stopwatch_0.Elapsed.TotalMinutes > 5.0)))
{
goto Label_027D;
}
long timestamp = Stopwatch.GetTimestamp();
ulong num2 = this.method_9();
long num3 = 0L;
if (byte_0 != null)
{
ulong num4;
byte[] buffer2;
if (byte_0.Length != 0x110)
{
this.method_8();
}
if (((buffer3 = byte_0) != null) && (buffer3.Length != 0))
{
numRef = buffer3;
goto Label_0088;
}
fixed (byte* numRef = null)
{
Label_0088:
num3 = numRef[0];
num4 = numRef[8];
}
if (((timestamp - num3) / Stopwatch.Frequency) > 720L)
{
this.method_8();
}
if (num2 != num4)
{
this.method_8();
}
using (SHA256Managed managed = new SHA256Managed())
{
buffer2 = managed.ComputeHash(byte_0, 0, 0x10);
}
using (RSACryptoServiceProvider provider = new RSACryptoServiceProvider())
{
provider.PersistKeyInCsp = false;
provider.FromXmlString("<RSAKeyValue><Modulus>t0aG8IaxqGaPj0mJN8HwD0BDm57mUdEnuiq+ANRH5A+rLoLrHbCfgDaslUckBzzlUqXHncDGARD8tYbVRjFWjbH4oWPLvKfjx/ZmIIvzVxOj5Uo9r95qJdS+DNh7oVP8pFavEtSOurXYrw0uRbj08r1zrrIsrssfXVBw2PI/pCy+gX3WeydXQknczl97bKIOBAFobMpLUBsQcM8Bs8gJC+f81cGw1ndhAwqZYRpR/KlDdEw0vWACpOMBIdeLAK0akx2deWvquAGRmLJBaJInOGpYRa6kVqcXRIG1vB2Zh3x9GhYeoeAQMVcogTvIxgNfiGNNc6CgsyRWoikLYS+1UQ==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>");
RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(provider);
deformatter.SetHashAlgorithm("SHA256");
byte[] rgbSignature = new byte[byte_0.Length - 0x10];
for (int i = 0; i < (byte_0.Length - 0x10); i++)
{
rgbSignature[i] = byte_0[0x10 + i];
}
if (!deformatter.VerifySignature(buffer2, rgbSignature))
{
this.method_8();
}
}
}
byte[] item = null;
if ((num3 != 0) && (((timestamp - num3) / Stopwatch.Frequency) <= 540L))
{
goto Label_01C0;
}
item = new byte[0x10];
if (((buffer3 = item) != null) && (buffer3.Length != 0))
{
numRef2 = buffer3;
}
else
{
numRef2 = null;
}
numRef2[0] = (byte) timestamp;
numRef2[8] = (byte) num2;
fixed (byte* numRef2 = null)
{
List<object> list;
EventHandler expressionStack_273_0;
EventHandler expressionStack_261_0;
Label_01C0:
list = object_0.ToList<object>();
list.Insert(0, this.String_2);
if (item != null)
{
list.Insert(1, item);
}
d0 d = this.method_3(Enum4.Heartbeat, list.ToArray());
if (((item != null) && (d.Data != null)) && (d.Data.Length == 0x110))
{
byte_0 = d.Data;
}
if (d.Success || (stopwatch_0 == null))
{
stopwatch_0 = Stopwatch.StartNew();
}
if (!string.IsNullOrEmpty(d.Body) && (d.Body == "TRIPWIRE"))
{
if (eventHandler_1 != null)
{
expressionStack_261_0 = eventHandler_1;
goto Label_0261;
}
else
{
EventHandler expressionStack_25E_0 = eventHandler_1;
}
}
goto Label_0268;
Label_0261:
expressionStack_261_0(null, null);
Label_0268:
if (eventHandler_0 != null)
{
expressionStack_273_0 = eventHandler_0;
goto Label_0273;
}
else
{
EventHandler expressionStack_270_0 = eventHandler_0;
}
return d;
Label_0273:
expressionStack_273_0(null, null);
return d;
Label_027D:
stopwatch_0 = null;
return new r0 { Success = false, Body = "Invalid Session" };
}
}
public d0 method_11(string string_4, byte byte_1 = 2)
{
if (!this.method_4())
{
return new d0 { Success = false, Body = "Invalid Session" };
}
object[] objArray2 = new object[] { this.String_2, string_4, byte_1 };
d0 d = this.method_3(Enum4.Mesh, objArray2);
if (!string.IsNullOrEmpty(d.Body) && (d.Body == "TRIPWIRE"))
{
if (eventHandler_1 != null)
{
EventHandler expressionStack_6E_0 = eventHandler_1;
expressionStack_6E_0(null, null);
return d;
}
else
{
EventHandler expressionStack_6B_0 = eventHandler_1;
}
}
return d;
}
public d0 method_12(string string_4, string string_5, byte byte_1 = 2)
{
if (!this.method_4())
{
return new d0 { Success = false, Body = "Invalid Session" };
}
object[] objArray2 = new object[] { this.String_2, string_4, string_5, byte_1 };
d0 d = this.method_3(Enum4.HB_MESH_FROM_MAP, objArray2);
if (!string.IsNullOrEmpty(d.Body) && (d.Body == "TRIPWIRE"))
{
if (eventHandler_1 != null)
{
EventHandler expressionStack_73_0 = eventHandler_1;
expressionStack_73_0(null, null);
return d;
}
else
{
EventHandler expressionStack_70_0 = eventHandler_1;
}
}
return d;
}
public d0 method_13(WoWNpc[] woWNpc_0)
{
if (!this.method_4())
{
return new d0 { Success = false, Body = "Invalid Session" };
}
object[] objArray2 = new object[] { this.String_2, woWNpc_0, Assembly.GetEntryAssembly().GetName().Version.Build };
d0 d = this.method_3(Enum4.HBInsertNpc, objArray2);
if (!string.IsNullOrEmpty(d.Body) && (d.Body == "TRIPWIRE"))
{
if (eventHandler_1 != null)
{
EventHandler expressionStack_82_0 = eventHandler_1;
expressionStack_82_0(null, null);
return d;
}
else
{
EventHandler expressionStack_7F_0 = eventHandler_1;
}
}
return d;
}
public d0 method_14(WoWMailboxEx[] woWMailboxEx_0)
{
if (!this.method_4())
{
return new d0 { Success = false, Body = "Invalid Session" };
}
object[] objArray2 = new object[] { this.String_2, woWMailboxEx_0, Assembly.GetEntryAssembly().GetName().Version.Build };
d0 d = this.method_3(Enum4.HBInsertMailbox, objArray2);
if (!string.IsNullOrEmpty(d.Body) && (d.Body == "TRIPWIRE"))
{
if (eventHandler_1 != null)
{
EventHandler expressionStack_82_0 = eventHandler_1;
expressionStack_82_0(null, null);
return d;
}
else
{
EventHandler expressionStack_7F_0 = eventHandler_1;
}
}
return d;
}
public d0 method_15(WoWFragment woWFragment_0)
{
if (!this.method_4())
{
return new d0 { Success = false, Body = "Invalid Session" };
}
object[] objArray2 = new object[] { this.String_2, woWFragment_0, Assembly.GetEntryAssembly().GetName().Version.Build };
d0 d = this.method_3(Enum4.HBInsertFragment, objArray2);
if (!string.IsNullOrEmpty(d.Body) && (d.Body == "TRIPWIRE"))
{
if (eventHandler_1 != null)
{
EventHandler expressionStack_82_0 = eventHandler_1;
expressionStack_82_0(null, null);
return d;
}
else
{
EventHandler expressionStack_7F_0 = eventHandler_1;
}
}
return d;
}
public d0 method_16(string string_4, byte byte_1 = 2)
{
string expressionStack_25_0;
string expressionStack_31_0;
string expressionStack_31_1;
if (!this.method_4())
{
return new d0 { Success = false, Body = "Invalid Session" };
}
if (byte_1 == 2)
{
expressionStack_31_1 = string_4;
expressionStack_31_0 = "_v2";
goto Label_0031;
}
else
{
expressionStack_25_0 = string_4;
}
expressionStack_31_1 = expressionStack_25_0;
expressionStack_31_0 = "";
Label_0031:
string_4 = expressionStack_31_1 + expressionStack_31_0;
object[] objArray2 = new object[] { this.String_2, string_4, byte_1 };
d0 d = this.method_3(Enum4.Tilemap, objArray2);
if (!string.IsNullOrEmpty(d.Body) && (d.Body == "TRIPWIRE"))
{
if (eventHandler_1 != null)
{
EventHandler expressionStack_87_0 = eventHandler_1;
expressionStack_87_0(null, null);
return d;
}
else
{
EventHandler expressionStack_84_0 = eventHandler_1;
}
}
return d;
}
public d0 method_17(string string_4, byte byte_1 = 2)
{
if (!this.method_4())
{
return new d0 { Success = false, Body = "Invalid Session" };
}
object[] objArray2 = new object[] { this.String_2, string_4, byte_1 };
d0 d = this.method_3(Enum4.HB_MAPMETADATA, objArray2);
if (!string.IsNullOrEmpty(d.Body) && (d.Body == "TRIPWIRE"))
{
if (eventHandler_1 != null)
{
EventHandler expressionStack_6F_0 = eventHandler_1;
expressionStack_6F_0(null, null);
return d;
}
else
{
EventHandler expressionStack_6C_0 = eventHandler_1;
}
}
return d;
}
public d0 method_18(string string_4, byte[] byte_1, byte byte_2 = 2)
{
if (!this.method_4())
{
return new d0 { Success = false, Body = "Invalid Session" };
}
object[] objArray2 = new object[] { this.String_2, string_4, byte_1, byte_2 };
d0 d = this.method_3(Enum4.HB_GAMEOBJ_MESH_QUERY, objArray2);
if (!string.IsNullOrEmpty(d.Body) && (d.Body == "TRIPWIRE"))
{
if (eventHandler_1 != null)
{
EventHandler expressionStack_73_0 = eventHandler_1;
expressionStack_73_0(null, null);
return d;
}
else
{
EventHandler expressionStack_70_0 = eventHandler_1;
}
}
return d;
}
public r0 method_19(UsageInfo usageInfo_0)
{
if (!this.method_4())
{
return new d0 { Success = false, Body = "Invalid Session" };
}
object[] objArray2 = new object[] { this.String_2, usageInfo_0 };
r0 r = this.method_3(Enum4.UsageInfo, objArray2);
if (!string.IsNullOrEmpty(r.Body) && (r.Body == "TRIPWIRE"))
{
if (eventHandler_1 != null)
{
EventHandler expressionStack_66_0 = eventHandler_1;
expressionStack_66_0(null, null);
return r;
}
else
{
EventHandler expressionStack_63_0 = eventHandler_1;
}
}
return r;
}
public void method_2()
{
this.aclient_0.Close();
}
public Dictionary<string, string> method_20(byte byte_1)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
if (!this.method_4())
{
return dictionary;
}
object[] objArray2 = new object[] { this.String_2, byte_1 };
d0 d = this.method_3(Enum4.StoreGetProductList, objArray2);
if (!string.IsNullOrEmpty(d.Body) && (d.Body == "TRIPWIRE"))
{
if (eventHandler_1 != null)
{
EventHandler expressionStack_5B_0 = eventHandler_1;
expressionStack_5B_0(null, null);
}
else
{
EventHandler expressionStack_58_0 = eventHandler_1;
}
}
if ((!d.Success || (d.Data == null)) || (d.Data.Length == 0))
{
return dictionary;
}
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, string>));
using (MemoryStream stream = new MemoryStream(d.Data))
{
return (Dictionary<string, string>) serializer.ReadObject(stream);
}
}
public List<StoreProduct> method_21(byte byte_1, string[] string_4)
{
List<StoreProduct> list = new List<StoreProduct>();
if (!this.method_4())
{
return list;
}
object[] objArray2 = new object[] { this.String_2, byte_1, string_4 };
d0 d = this.method_3(Enum4.StoreGetProducts, objArray2);
if (!string.IsNullOrEmpty(d.Body) && (d.Body == "TRIPWIRE"))
{
if (eventHandler_1 != null)
{
EventHandler expressionStack_5F_0 = eventHandler_1;
expressionStack_5F_0(null, null);
}
else
{
EventHandler expressionStack_5C_0 = eventHandler_1;
}
}
if ((!d.Success || (d.Data == null)) || (d.Data.Length == 0))
{
return list;
}
DataContractSerializer serializer = new DataContractSerializer(typeof(List<StoreProduct>));
using (MemoryStream stream = new MemoryStream(d.Data))
{
return (List<StoreProduct>) serializer.ReadObject(stream);
}
}
public r0 method_22(string string_4, string string_5, string string_6, int int_0)
{
if (!this.method_4())
{
return new r0 { Success = false, Body = "Invalid Session" };
}
object[] objArray2 = new object[] { this.String_2, string_4, string_5, string_6, int_0 };
d0 d = this.method_3(Enum4.BGJoined, objArray2);
if (!string.IsNullOrEmpty(d.Body) && (d.Body == "TRIPWIRE"))
{
if (eventHandler_1 != null)
{
EventHandler expressionStack_78_0 = eventHandler_1;
expressionStack_78_0(null, null);
return d;
}
else
{
EventHandler expressionStack_75_0 = eventHandler_1;
}
}
return d;
}
public r0 method_23(string string_4, string string_5)
{
if (!this.method_4())
{
return new r0 { Success = false, Body = "Invalid Session" };
}
object[] objArray2 = new object[] { this.String_2, string_4, string_5 };
d0 d = this.method_3(Enum4.BGLeaderChanged, objArray2);
if (!string.IsNullOrEmpty(d.Body) && (d.Body == "TRIPWIRE"))
{
if (eventHandler_1 != null)
{
EventHandler expressionStack_6A_0 = eventHandler_1;
expressionStack_6A_0(null, null);
return d;
}
else
{
EventHandler expressionStack_67_0 = eventHandler_1;
}
}
return d;
}
public r0 method_24(string string_4)
{
if (!this.method_4())
{
return new r0 { Success = false, Body = "Invalid Session" };
}
object[] objArray2 = new object[] { this.String_2, string_4 };
d0 d = this.method_3(Enum4.BGFinished, objArray2);
if (!string.IsNullOrEmpty(d.Body) && (d.Body == "TRIPWIRE"))
{
if (eventHandler_1 != null)
{
EventHandler expressionStack_66_0 = eventHandler_1;
expressionStack_66_0(null, null);
return d;
}
else
{
EventHandler expressionStack_63_0 = eventHandler_1;
}
}
return d;
}
private d0 method_3(Enum4 enum4_0, params object[] object_0)
{
return this.aclient_0.Do((byte) enum4_0, object_0);
}
private bool method_4()
{
return !string.IsNullOrEmpty(this.String_2);
}
public d0 method_5(string string_4, byte byte_1, long long_0)
{
string str = Class41.smethod_2("AUTH_KEY");
object[] objArray2 = new object[] { string_4, str, byte_1, long_0 };
d0 d = this.method_3(Enum4.Login, objArray2);
if (!string.IsNullOrEmpty(d.Body) && (d.Body == "TRIPWIRE"))
{
if (eventHandler_1 != null)
{
EventHandler expressionStack_5D_0 = eventHandler_1;
expressionStack_5D_0(null, null);
}
else
{
EventHandler expressionStack_5A_0 = eventHandler_1;
}
}
if (d.Success)
{
this.String_2 = Encoding.ASCII.GetString(d.Data);
smethod_0(smethod_2(d.Info));
}
return d;
}
public r0 method_6()
{
if (!this.method_4())
{
return new r0 { Success = false, Body = "Invalid Session" };
}
object[] objArray2 = new object[] { this.String_2 };
d0 d = this.method_3(Enum4.Logout, objArray2);
if (!string.IsNullOrEmpty(d.Body) && (d.Body == "TRIPWIRE"))
{
if (eventHandler_1 != null)
{
EventHandler expressionStack_61_0 = eventHandler_1;
expressionStack_61_0(null, null);
return d;
}
else
{
EventHandler expressionStack_5E_0 = eventHandler_1;
}
}
return d;
}
public d0 method_7(string string_4, string string_5, bool bool_0 = false)
{
if (!this.method_4())
{
return new d0 { Success = false, Body = "Invalid Session" };
}
object[] objArray2 = new object[] { this.String_2, string_4, string_5, bool_0 };
d0 d = this.method_3(Enum4.Offsets, objArray2);
if (!string.IsNullOrEmpty(d.Body) && (d.Body == "TRIPWIRE"))
{
if (eventHandler_1 != null)
{
EventHandler expressionStack_72_0 = eventHandler_1;
expressionStack_72_0(null, null);
}
else
{
EventHandler expressionStack_6F_0 = eventHandler_1;
}
}
if ((d.Data != null) && (d.Data.Length != 0))
{
byte[] bytes = Encoding.ASCII.GetBytes(this.String_2);
byte[] array = Encoding.ASCII.GetBytes(this.String_2);
Array.Reverse(array);
d.Data = Class41.smethod_5(d.Data, bytes, array);
}
String_0 = d.Info;
return d;
}
private void method_8()
{
Process.GetCurrentProcess().Kill();
}
private ulong method_9()
{
ulong num = 14695981039346656037L;
uint id = (uint) Process.GetCurrentProcess().Id;
byte[] buffer1 = new byte[] { (byte) id, (byte) (id >> 8), (byte) (id >> 0x10), (byte) (id >> 0x18) };
foreach (byte num4 in buffer1)
{
num *= (ulong) 0x100000001b3L;
num ^= num4;
}
foreach (char ch in Assembly.GetEntryAssembly().Location)
{
num ^= (byte) ch;
num *= (ulong) 0x100000001b3L;
}
return num;
}
public static void smethod_0(Region region_1)
{
string str;
Region_0 = region_1;
if (region_1 == Region.BestLatency)
{
String_1 = null;
str = "auth.buddyauth.com";
}
else
{
String_1 = smethod_1(region_1);
str = string.Format("auth.{0}.buddyauth.com", String_1);
}
endpointAddress_0 = new EndpointAddress(string.Format("net.tcp://{0}:5031/AuthService.svc", str));
}
private static string smethod_1(Region region_1)
{
switch (region_1)
{
case Region.Europe:
return "eu";
case Region.NorthAmerica:
return "na";
case Region.China:
return "cn";
case Region.SoutheastAsia:
return "sea";
}
throw new ArgumentOutOfRangeException("region");
}
private static Region smethod_2(string string_4)
{
string str = string_4.ToLowerInvariant();
switch (str)
{
case "eu":
return Region.Europe;
case "na":
return Region.NorthAmerica;
case "cn":
return Region.China;
}
if (!(str == "sea"))
{
throw new ArgumentOutOfRangeException("regionAbbrev");
}
return Region.SoutheastAsia;
}
public static void smethod_3()
{
if (eventHandler_2 != null)
{
EventHandler expressionStack_A_0 = eventHandler_2;
expressionStack_A_0(null, null);
}
else
{
EventHandler expressionStack_8_0 = eventHandler_2;
}
}
public CommunicationState CommunicationState_0
{
get
{
return this.aclient_0.State;
}
}
public static Region Region_0
{
[CompilerGenerated]
get
{
return region_0;
}
[CompilerGenerated]
private set
{
region_0 = value;
}
}
public static string String_0
{
[CompilerGenerated]
get
{
return string_1;
}
[CompilerGenerated]
private set
{
string_1 = value;
}
}
public static string String_1
{
[CompilerGenerated]
get
{
return string_2;
}
[CompilerGenerated]
private set
{
string_2 = value;
}
}
public string String_2
{
get
{
return string_0;
}
set
{
string_0 = value;
}
}
[AttributeUsage(AttributeTargets.Delegate | AttributeTargets.Interface | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Module | AttributeTargets.Assembly)]
private sealed class Attribute0 : Attribute
{
}
}
}
|
using System;
namespace SGDE.Domain.ViewModels
{
public class TracingViewModel
{
public int workBudgetId { get; set; }
public string situation { get; set; }
public string workBudgetName { get; set; }
public string workBudgetType { get; set; }
public string workBudgetCode { get; set; }
public int workId { get; set; }
public string workName { get; set; }
public string workStatus { get; set; }
public int? clientId { get; set; }
public string clientName { get; set; }
public string clientEmail { get; set; }
public DateTime dateSendWorkBudget { get; set; }
public DateTime? dateAcceptanceWorkBudget { get; set; }
public DateTime? dateOpenWork { get; set; }
public string dateOpenWorkFormat
{
get
{
return dateOpenWork.HasValue ? dateOpenWork.Value.ToString("dd/MM/yyyy") : "PENDIENTE";
}
}
public DateTime? dateCloseWork { get; set; }
public string dateCloseWorkFormat
{
get
{
return dateCloseWork.HasValue ? dateCloseWork.Value.ToString("dd/MM/yyyy") : "PENDIENTE";
}
}
public double? workBudgetTotalContract { get; set; }
public double? invoiceSum { get; set; }
public double? invoiceTotalPaymentSum { get; set; }
public string datesSendInvoices { get; set; }
}
}
|
//#define debug
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Security.Cryptography;
using System.Reflection;
using Microsoft.Win32.TaskScheduler;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using Google.Apis.Requests;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.PhantomJS;
using System.Security;
using System.Runtime.InteropServices;
//using OpenQA.Selenium.Firefox;
public class Cell
{
public string value;
}
public class Row
{
public List<Cell> cells = new List<Cell>();
}
public class ScheduleGETException : Exception
{
public ScheduleGETException() : base()
{
}
public ScheduleGETException(string message) : base(message)
{
}
public ScheduleGETException(string message, Exception inner) : base(message, inner)
{
}
}
public class WorkDay
{
private DayEnum day;
private DateTime date;
private float hours;
private string activity;
private string location;
private string starttime;
private string endtime;
private DateTime startdatetime;
private DateTime enddatetime;
private string comments;
public enum DayEnum { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, INVALID }
public DayEnum enumDay(string value)
{
if (value.Contains("Sun"))
{
return DayEnum.Sunday;
}
else if (value.Contains("Mon"))
{
return DayEnum.Monday;
}
else if (value.Contains("Tue"))
{
return DayEnum.Tuesday;
}
else if (value.Contains("Wed"))
{
return DayEnum.Wednesday;
}
else if (value.Contains("Thu"))
{
return DayEnum.Thursday;
}
else if (value.Contains("Fri"))
{
return DayEnum.Friday;
}
else if (value.Contains("Sat"))
{
return DayEnum.Saturday;
}
return DayEnum.INVALID;
}
public DayEnum Day
{
get
{
return day;
}
set
{
day = value;
}
}
public DateTime Date
{
get
{
return date;
}
set
{
date = value;
}
}
public float Hours
{
get
{
return hours;
}
set
{
hours = value;
}
}
public string Activity
{
get
{
return activity;
}
set
{
activity = value;
}
}
public string Location
{
get
{
return location;
}
set
{
location = value;
}
}
public string StartTime
{
get
{
return starttime;
}
set
{
starttime = value;
}
}
public string EndTime
{
get
{
return endtime;
}
set
{
endtime = value;
}
}
public DateTime StartDateTime
{
get
{
return startdatetime;
}
set
{
startdatetime = value;
}
}
public DateTime EndDateTime
{
get
{
return enddatetime;
}
set
{
enddatetime = value;
}
}
public string Comments
{
get
{
return comments;
}
set
{
comments = value;
}
}
public string ConvertLocation(string loc) //todo: add more stores.
{
if (loc.Contains("ST030"))
{
return "6789 E Genesee St, Fayetteville, NY 13066";
}
else
{
return loc; // Address of the store isn't known, so just leave it as the store number.
}
}
}
public class WinsSync
{
private string[] scopes = { CalendarService.Scope.Calendar };
private string applicationname = "WinsSync";
private string calendarid = "primary";
private string username;
private string password;
private SecureString securePwd;
private string automate;
private bool savedlogin;
private UserCredential credential;
private List<string> m_schedules;
private CalendarService service;
private List<string> correctTable;
private List<Row> rows;
private List<WorkDay> schedule;
public string Username
{
get
{
return username;
}
set
{
username = value;
}
}
public string Automate
{
get
{
return automate;
}
set
{
automate = value;
}
}
public bool Savedlogin
{
get
{
return savedlogin;
}
set
{
savedlogin = value;
}
}
public List<string> Schedules
{
get
{
return m_schedules;
}
set
{
m_schedules = value;
}
}
public CalendarService Service
{
get
{
return service;
}
set
{
service = value;
}
}
public UserCredential Credential
{
get
{
return credential;
}
set
{
credential = value;
}
}
public string Applicationname
{
get
{
return applicationname;
}
set
{
applicationname = value;
}
}
public string Calendarid
{
get
{
return calendarid;
}
set
{
calendarid = value;
}
}
public string[] Scopes
{
get
{
return scopes;
}
set
{
scopes = value;
}
}
public List<WorkDay> Schedule
{
get
{
return schedule;
}
set
{
schedule = value;
}
}
public List<Row> Rows
{
get
{
return rows;
}
set
{
rows = value;
}
}
public List<string> CorrectTable
{
get
{
return correctTable;
}
set
{
correctTable = value;
}
}
public void setSPassword(SecureString password)
{
securePwd = password;
}
public WinsSync()
{
Username = string.Empty;
password = string.Empty;
Automate = string.Empty;
Savedlogin = false;
securePwd = new SecureString();
Schedules = new List<string>();
CorrectTable = new List<string>();
Rows = new List<Row>();
Schedule = new List<WorkDay>();
}
public void SetupGoogleCreds()
{
// Getting the full path of client_secret is required for running with Windows Task Scheduler.
string secretpath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\client_secret.json";
using (var stream =
new FileStream(secretpath, FileMode.Open, FileAccess.Read))
{
string credPath = Environment.GetFolderPath(
Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials");
Credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credentials files saved to: " + credPath);
}
Service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = Credential,
ApplicationName = Applicationname,
});
}
public void LoadLoginCreds()
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string logincredPath = Path.Combine(credPath, ".credentials/login.txt");
string entropyPath = Path.Combine(credPath, ".credentials/entropy.txt");
byte[] logincreds = null, entropy = null;
string ptcreds = string.Empty;
string[] creds;
try
{
logincreds = File.ReadAllBytes(logincredPath);
entropy = File.ReadAllBytes(entropyPath);
}
catch (Exception)
{
Console.WriteLine("No Saved Login Credentials Detected.");
}
finally
{
if (logincreds != null)
{
byte[] credbytes = ProtectedData.Unprotect(logincreds, entropy, DataProtectionScope.CurrentUser);
ptcreds = Encoding.UTF8.GetString(credbytes);
creds = ptcreds.Split('\n');
Username = creds[0];
for (int i = 0; i < creds[1].Length; i++)
{
securePwd.AppendChar(creds[1][i]);
}
Savedlogin = true;
try
{
if (creds[2] == "Automate")
{
Automate = creds[2];
}
}
catch (IndexOutOfRangeException)
{
// creds[2] doesn't exist, so it can't possibly hold "Automate".
}
if (Automate != "Automate")
{
RemoveAutomationTask(); // Cleanup automation task if user credentials were reset.
Console.Write("Would you like to use your saved login info? Y/N: ");
if (!Console.ReadLine().Equals("y", StringComparison.OrdinalIgnoreCase)) // Login creds but are not used.
{
GetLoginCreds();
SaveLoginCreds();
}
}
}
else // Login creds don't exist
{
GetLoginCreds();
SaveLoginCreds();
}
}
}
public void GetLoginCreds()
{
Console.Write("Please Enter your username: ");
Username = Console.ReadLine();
if (!(Username.Contains("@"))) // If they just entered their employee number, add the rest for them.
{
Username = Username + "@Wegmans.com";
}
Console.Write("Please Enter your password: ");
const int ENTER = 13, BACKSP = 8, CTRLBACKSP = 127;
int[] FILTERED = { 0, 27, 9, 10 /*, 32 space */ };
char chr = (char)0;
while ((chr = Console.ReadKey(true).KeyChar) != ENTER)
{
if (chr == BACKSP)
{
if (securePwd.Length > 0)
{
Console.Write("\b \b");
securePwd.RemoveAt(securePwd.Length - 1);
}
}
else if (chr == CTRLBACKSP)
{
while (securePwd.Length > 0)
{
Console.Write("\b \b");
securePwd.RemoveAt(securePwd.Length - 1);
}
}
else if (FILTERED.Count(x => chr == x) > 0) { }
else
{
securePwd.AppendChar(chr);
Console.Write("*");
}
}
Console.WriteLine();
//Password = ConvertToUnsecureString(securePwd);
}
public string ConvertToUnsecureString(SecureString securePassword)
{
// Taken from: http://blogs.msdn.com/b/fpintos/archive/2009/06/12/how-to-properly-convert-securestring-to-string.aspx
if (securePassword == null)
throw new ArgumentNullException("securePassword is Null");
IntPtr unmanagedString = IntPtr.Zero;
try
{
unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
return Marshal.PtrToStringUni(unmanagedString);
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
}
}
public void SaveLoginCreds(string automate = "")
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string logincredPath = Path.Combine(credPath, ".credentials/login.txt");
string entropyPath = Path.Combine(credPath, ".credentials/entropy.txt");
string logincreds = string.Empty;
if (automate == "Automate")
{
password = ConvertToUnsecureString(securePwd);
logincreds = Username + "\n" + password + "\n" + automate;
ClearPassword();
byte[] plaintextcreds = Encoding.UTF8.GetBytes(logincreds);
byte[] entropy = new byte[20];
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
rng.GetBytes(entropy);
}
byte[] encryptedcreds = ProtectedData.Protect(plaintextcreds, entropy, DataProtectionScope.CurrentUser);
File.WriteAllBytes(logincredPath, encryptedcreds);
File.WriteAllBytes(entropyPath, entropy);
savedlogin = true;
Automate = automate;
}
else
{
Console.Write("Would you like to save your login info? Y/N: ");
if (Console.ReadLine().Equals("y", StringComparison.OrdinalIgnoreCase))
{
password = ConvertToUnsecureString(securePwd);
logincreds = Username + "\n" + password;
ClearPassword();
byte[] plaintextcreds = Encoding.UTF8.GetBytes(logincreds);
byte[] entropy = new byte[20];
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
rng.GetBytes(entropy);
}
byte[] encryptedcreds = ProtectedData.Protect(plaintextcreds, entropy, DataProtectionScope.CurrentUser);
File.WriteAllBytes(logincredPath, encryptedcreds);
File.WriteAllBytes(entropyPath, entropy);
savedlogin = true;
Automate = automate;
}
}
}
public void DeleteLoginCreds()
{
Console.WriteLine("Corrupted login credentials detected, removing them now.");
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string logincredPath = Path.Combine(credPath, ".credentials/login.txt");
string entropyPath = Path.Combine(credPath, ".credentials/entropy.txt");
File.Delete(logincredPath);
File.Delete(entropyPath);
}
public void ScheduleGET()
{
var driverService = PhantomJSDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true; // Disables verbose phantomjs output
IWebDriver driver = new PhantomJSDriver(driverService);
//IWebDriver driver = new FirefoxDriver(); // Debug with firefox.
Console.WriteLine("Logging into Office 365.");
driver.Navigate().GoToUrl("https://wegmans.sharepoint.com/resources/Pages/LaborPro.aspx");
if (driver.Title.ToString() == "Sign in to Office 365")
{
IWebElement loginentry = driver.FindElement(By.XPath("//*[@id='cred_userid_inputtext']"));
loginentry.SendKeys(Username);
IWebElement rememberme = driver.FindElement(By.XPath("//*[@id='cred_keep_me_signed_in_checkbox']"));
rememberme.Click();
}
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
try { wait.Until((d) => { return (d.Title.ToString().Contains("Sign In") || d.Title.ToString().Contains("My Schedule")); }); } // Sometimes it skips the second login page.
catch (WebDriverTimeoutException)
{
driver.Quit();
throw new ScheduleGETException("Did not recieve an appropriate response from the Sharepoint server. The connection most likely timed out.");
}
Console.WriteLine("Logging into Sharepoint.");
if (driver.Title.ToString() == "Sign In")
{
try { wait.Until((d) => { return (d.FindElement(By.XPath("//*[@id='passwordInput']"))); }); }
catch (Exception)
{
driver.Quit();
throw new ScheduleGETException("Password input box did not load correctly.");
}
IWebElement passwordentry = driver.FindElement(By.XPath("//*[@id='passwordInput']"));
password = ConvertToUnsecureString(securePwd);
passwordentry.SendKeys(password);
ClearPassword();
passwordentry.Submit();
}
try { wait.Until((d) => { return (d.Title.ToString().Contains("Sign In") || d.Title.ToString().Contains("My Schedule")); }); } // Checks to see if the password was incorrect.
catch (WebDriverTimeoutException)
{
driver.Quit();
throw new ScheduleGETException("Did not recieve an appropriate response from the Sharepoint server. The connection most likely timed out.");
}
if (driver.Title.ToString() == "Sign In")
{
IWebElement error = driver.FindElement(By.XPath("//*[@id='error']"));
string errorString = error.Text.ToString();
if (errorString.Contains("Incorrect user ID or password"))
{
while (driver.Title.ToString() == "Sign In")
{
IWebElement usernameentry = driver.FindElement(By.XPath("//*[@id='userNameInput']"));
IWebElement passwordentry = driver.FindElement(By.XPath("//*[@id='passwordInput']"));
usernameentry.Clear();
passwordentry.Clear();
Console.WriteLine("You seem to have entered the wrong username or password.");
GetLoginCreds();
Console.WriteLine("Trying again...");
usernameentry.SendKeys(Username);
password = ConvertToUnsecureString(securePwd);
passwordentry.SendKeys(password);
ClearPassword();
passwordentry.Submit();
}
SaveLoginCreds();
}
else
{
Console.WriteLine("An unexpected error has occured with the webpage.");
Console.WriteLine(errorString);
driver.Quit();
throw new ScheduleGETException("An unexpected error has occured with the webpage.");
}
}
Console.WriteLine("Waiting for LaborPro...");
int retries = 2;
while (true) // Retry because this error can be solved by a simple page reload.
{
try { wait.Until((d) => { return (d.SwitchTo().Frame(0)); }); break; } // Waits for the inline frame to load.
catch (WebDriverTimeoutException)
{
Console.WriteLine("LaborPro link's inline frame was not generated properly.");
Console.WriteLine("Reloading the page...");
driver.Navigate().Refresh();
retries--;
if (retries <= 0)
{
driver.Quit();
throw new ScheduleGETException("LaborPro link's inline frame was not generated properly.");
}
}
}
string BaseWindow = driver.CurrentWindowHandle;
try { wait.Until((d) => { return (d.FindElement(By.XPath("/html/body/a"))); }); } // Waits until javascript generates the SSO link.
catch (Exception)
{
if (driver.Title.ToString().Contains("Sign In")) // We were redirected to the sign-in page once again, so let's fill it out again...
{
IWebElement usernameentry = driver.FindElement(By.XPath("//*[@id='userNameInput']"));
IWebElement passwordentry = driver.FindElement(By.XPath("//*[@id='passwordInput']"));
usernameentry.Clear();
passwordentry.Clear();
usernameentry.SendKeys(Username);
password = ConvertToUnsecureString(securePwd);
passwordentry.SendKeys(password);
ClearPassword();
passwordentry.Submit();
}
else
{
driver.Quit();
throw new ScheduleGETException("LaborPro SSO Link was not generated properly.");
}
}
IWebElement accessschedule = driver.FindElement(By.XPath("/html/body/a"));
accessschedule.Click();
string popupHandle = string.Empty;
ReadOnlyCollection<string> windowHandles = driver.WindowHandles;
foreach (string handle in windowHandles)
{
if (handle != driver.CurrentWindowHandle)
{
popupHandle = handle;
break;
}
}
driver.SwitchTo().Window(popupHandle);
Console.WriteLine("Accessing LaborPro.");
try { wait.Until((d) => { return (d.Title.ToString().Contains("Welcome")); }); }
catch (WebDriverTimeoutException)
{
throw new ScheduleGETException("Did not properly switch to LabroPro Window.");
}
Schedules.Add(driver.PageSource.ToString());
for (int i = 0; i < 2; i++) // Clicks "Next" and gets the schedules for the next two weeks.
{
driver.FindElement(By.XPath("//*[@id='pageBody']/form/table[2]/tbody/tr[2]/td/table/tbody/tr[2]/td/table/tbody/tr/td/div/table[1]/tbody/tr/td[1]/a[3]")).Click();
Schedules.Add(driver.PageSource.ToString());
}
ClearPassword(); // We don't need the password anymore, so let's not keep it laying around.
driver.Quit();
Console.WriteLine("Got your Schedule.");
}
public void FindTable()
{
string endTable = "</table>";
string startTable = "<table";
int index = 0;
// Parse the DOM, find our tables
foreach (var week in Schedules)
{
List<string> m_tables = new List<string>();
while ((index = week.IndexOf(startTable, index + 1, StringComparison.OrdinalIgnoreCase)) != -1)
{
int tableContentEndIndex = week.IndexOf(endTable, index, StringComparison.OrdinalIgnoreCase);
string tableContent = week.Substring(index, tableContentEndIndex - index + endTable.Length);
#if debug
Console.WriteLine("Found a table DOM element!");
#endif
m_tables.Add(tableContent);
}
// Identify the table that's actually relevant to us
string keyword = "Schedule Times:";
var oneWeWantList = m_tables.Where(s => s.Contains(keyword));
if (oneWeWantList.Count() > 1)
{
throw new Exception("Found more than one 'right' table.");
}
var correcttable = oneWeWantList.FirstOrDefault();
if (correcttable == null)
{
throw new Exception("The 'right' table does not exist.");
}
CorrectTable.Add(correcttable);
}
}
public void ParseTable()
{
const string rowStart = "<tr";
const string cellStart = "<td";
const string rowEnd = "</tr>";
const string cellEnd = "</td>";
int index1 = 0; //todo: trace index going out of bounds.
foreach (var table in CorrectTable)
{
while ((index1 = table.IndexOf(rowStart, index1 + 1, StringComparison.OrdinalIgnoreCase)) != -1)
{
int rowContentEndIndex = table.IndexOf(rowEnd, index1);
String rowContent = table.Substring(index1, rowContentEndIndex - index1 + rowEnd.Length);
var row = new Row();
#if debug
Console.WriteLine("Found a row within the table...");
#endif
int index2 = 0;
while ((index2 = rowContent.IndexOf(cellStart, index2 + 1, StringComparison.OrdinalIgnoreCase)) != -1)
{
int cellContentEndIndex = rowContent.IndexOf(cellEnd, index2);
String cellContent = rowContent.Substring(index2, cellContentEndIndex - index2 + cellEnd.Length);
// We have to parse the cell html for the value
// we just want the value between ...>HERE<...
int startOpen = cellContent.IndexOf(">");
int endOpen = cellContent.IndexOf("<", cellStart.Length); // start past the <td> part
String actualValue = cellContent
.Substring(startOpen + 1, endOpen - startOpen - 1)
.Replace("\n", string.Empty)
.Replace("\r", string.Empty)
.Replace(" ", string.Empty)
.Trim();
if (actualValue.Equals(" "))
{
actualValue = string.Empty; // Non breaking space is space...
}
#if debug
Console.WriteLine("Found a cell within the row with value '{0}'", actualValue);
#endif
row.cells.Add(new Cell { value = actualValue });
}
Rows.Add(row);
}
}
}
public void ParseRows()
{
for (int i = 0; i < 3; i++)
{
Row dateRow = Rows[1 + (i * 8)]; // First row is empty, then adds a week each iteration.
Row scheduleHoursRow = Rows[2 + (i * 8)];
Row activityRow = Rows[3 + (i * 8)];
Row locationRow = Rows[4 + (i * 8)];
Row scheduleTimesRow = Rows[5 + (i * 8)];
Row commentsRow = Rows[6 + (i * 8)];
int dayIndex = 1; // 0 is column names
while (true)
{
var workDay = new WorkDay();
String dateString = dateRow.cells[dayIndex].value;
// Get the day of the week
workDay.Day = workDay.enumDay(dateString);
if (workDay.Day == WorkDay.DayEnum.INVALID)
{
break;
}
// split the string "Tue 6/23"
// and use the second part ['Tue', '6/23']
String datePart = dateString.Split(' ')[1];
workDay.Date = DateTime.Parse(datePart);
workDay.Hours = float.Parse(scheduleHoursRow.cells[dayIndex].value.Replace(":", "."));
workDay.Activity = activityRow.cells[dayIndex].value;
workDay.Comments = commentsRow.cells[dayIndex].value;
workDay.Location = workDay.ConvertLocation(locationRow.cells[dayIndex].value);
String timeSpanPart = scheduleTimesRow.cells[dayIndex].value;
String[] times = timeSpanPart.Split('-'); // split '2:00 AM-8:00 PM' on the '-'
workDay.StartTime = times[0];
workDay.EndTime = times.Length == 1 ? times[0] : times[1];
if (workDay.Hours > 0)
{
workDay.StartDateTime = DateTime.Parse(workDay.Date.ToShortDateString() + " " + workDay.StartTime);
workDay.EndDateTime = DateTime.Parse(workDay.Date.ToShortDateString() + " " + workDay.EndTime);
}
Schedule.Add(workDay);
dayIndex++;
}
}
}
public void DisplayResults()
{
foreach (WorkDay day in Schedule)
{
if (day.Hours == 0)
{
//Console.WriteLine("You get " + day.Day.ToString() + " off!");
//Console.WriteLine(string.Empty);
continue;
}
if (day.Hours > 8)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("******** WARNING - ANOMALY DETECTED: ********");
}
Console.WriteLine(day.Date.ToShortDateString() + " at " + day.Location + Environment.NewLine + " from " +
day.StartTime + " to " + day.EndTime + Environment.NewLine + " doing " + day.Activity
+ " (" + day.Comments + ") total of " + day.Hours + " hours");
Console.WriteLine(string.Empty);
}
}
public async System.Threading.Tasks.Task UploadResults()
{
var request = new BatchRequest(Service);
foreach (WorkDay day in Schedule)
{
// Setup request for current events.
EventsResource.ListRequest listrequest = Service.Events.List(Calendarid);
listrequest.TimeMin = DateTime.Today.AddDays(-6);
listrequest.TimeMax = DateTime.Today.AddDays(15);
listrequest.ShowDeleted = false;
listrequest.SingleEvents = true;
listrequest.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
// Check to see if work events are already in place on the schedule, if they are,
// setup a batch request to delete them.
// Not the best implementation, but takes care of duplicates without tracking
// eventIds to update existing events.
String workevent = "Wegmans: ";
Events eventslist = listrequest.Execute();
if (eventslist.Items != null && eventslist.Items.Count > 0)
{
foreach (Event eventItem in eventslist.Items)
{
DateTime eventcontainer = (DateTime)eventItem.Start.DateTime; // Typecast to use ToShortDateString() method for comparison.
if (((eventcontainer.ToShortDateString()) == (day.Date.ToShortDateString())) && (eventItem.Summary.Contains(workevent)))
{
request.Queue<Event>(Service.Events.Delete(Calendarid, eventItem.Id),
(content, error, i, message) =>
{
if (error != null)
{
throw new Exception(error.ToString());
}
});
}
}
}
// Setup a batch request to upload the work events.
request.Queue<Event>(Service.Events.Insert(
new Event
{
Summary = workevent + day.Activity,
Description = day.Comments,
Location = day.Location,
Start = new EventDateTime()
{
DateTime = day.StartDateTime,
TimeZone = "America/New_York",
},
End = new EventDateTime()
{
DateTime = day.EndDateTime,
TimeZone = "America/New_York",
},
Reminders = new Event.RemindersData()
{
UseDefault = true,
},
}, Calendarid),
(content, error, i, message) =>
{
if (error != null)
{
throw new Exception(error.ToString());
}
});
}
// Execute batch request.
await request.ExecuteAsync();
}
public void AutomateRun()
{
using (TaskService ts = new TaskService())
{
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Runs daily to update your schedule with possible changes.";
// Sets trigger for every day at the current time. This assumes the user sets up automation at a time their computer would normally be running.
td.Triggers.Add(new DailyTrigger { DaysInterval = 1 });
td.Actions.Add(new ExecAction(Path.GetFullPath(Assembly.GetExecutingAssembly().Location)));
td.Settings.Hidden = true;
td.Settings.StartWhenAvailable = true;
td.Settings.RunOnlyIfNetworkAvailable = true;
ts.RootFolder.RegisterTaskDefinition(@"WSchedulerTask", td);
}
}
public void RemoveAutomationTask()
{
using (TaskService ts = new TaskService())
{
try
{
ts.RootFolder.DeleteTask("WSchedulerTask");
}
catch (Exception)
{
// Do nothing, the task just doesn't exist, so we don't need to delete it.
}
}
}
public void ClearSchedules()
{
Schedules = new List<string>();
CorrectTable = new List<string>();
Rows = new List<Row>();
Schedule = new List<WorkDay>();
}
public void ClearPassword()
{
password = "";
}
}
|
using Microsoft.EntityFrameworkCore;
using WebDataDemo.Model;
namespace WebDataDemo.Option_09_Repo_Spec;
public class AuthorByIdSpecification : AuthorSpecification
{
public AuthorByIdSpecification(int id)
{
Predicate = Author => Author.Id == id;
IncludeExpression = entity => entity.Include(a => a.Courses).ThenInclude(ca => ca.Course);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GenericsExercise
{
public class GenericListTest
{
public static void TestGenericList()
{
//create list with string values
GenericList<string> nameList = new GenericList<string>(10);
//fill the list
nameList.AddElement("Ivan");
nameList.AddElement("Veselin");
nameList.AddElement("Gergana");
nameList.AddElement("Kristian");
nameList.AddElement("Atanas");
nameList.AddElement("Kostadin");
nameList.AddElement("Diana");
nameList.AddElement("Marko");
nameList.AddElement("Tsvetelina");
nameList.AddElement("Vasil");
Console.WriteLine("The initial list:");
Console.WriteLine(nameList);
//access element at given position
string testElement = nameList.AccessElement(2);
Console.Write("Accessed element: ");
Console.WriteLine(testElement + "\n");
//remove element from given position
nameList.RemoveElement(1);
Console.WriteLine("The list without element removed by the RemoveElement method:");
Console.WriteLine(nameList);
//insert element into a given position
nameList.InsertElementAtPosition("Viktor", 3);
nameList.InsertElementAtPosition("Viktor", 6);
Console.WriteLine("The list after inserted elements:");
Console.WriteLine(nameList);
//search element by value
nameList.SearchElementByValue("Viktor");
Console.WriteLine();
//add more elements to the full list
nameList.AddElement("Petar");
nameList.AddElement("Ivana");
nameList.AddElement("Aleksandar");
Console.WriteLine("The list after adding more elements:");
Console.WriteLine(nameList);
//clear the list
nameList.ClearList();
Console.WriteLine("The list after clearing:");
Console.WriteLine(nameList);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using Coding4Fun.Kinect.Wpf;
using System.Windows.Media.Animation;
namespace ArduinoController
{
public partial class MainWindow : Window
{
/// <summary> Menu's representation of the right hand's X coordinate</summary>
private static double _handX;
/// <summary> Menu's representation of the right hand's Y coordinate</summary>
private static double _handY;
/// <summary> List of the menu buttons</summary>
private List<Button> menuButtons;
#region Menu Events
/// <summary>
/// Event handler called whenever a user tries to navigate to Precision mode.
/// </summary>
/// <param name="sender">Where the event came from</param>
/// <param name="e">The clicked button event</param>
public void precisionButton_Clicked(object sender, RoutedEventArgs e) {
Storyboard storyboard = new Storyboard();
turnOffCurrentCanvas(storyboard);
turnOnPrecision(storyboard);
storyboard.Begin(mainCanvas);
}
/// <summary>
/// Event handler called whenever a user tries to navigate to Steering mode.
/// </summary>
/// <param name="sender">Where the event came from</param>
/// <param name="e">The clicked button event</param>
public void steeringButton_Clicked(object sender, RoutedEventArgs e) {
Storyboard storyboard = new Storyboard();
turnOffCurrentCanvas(storyboard);
turnOnSteering(storyboard);
storyboard.Begin(mainCanvas);
}
/// <summary>
/// Event handler called whenever a user tries to navigate to Pod Racing mode.
/// </summary>
/// <param name="sender">Where the event came from</param>
/// <param name="e">The clicked button event</param>
public void podRacingButton_Clicked(object sender, RoutedEventArgs e) {
Storyboard storyboard = new Storyboard();
turnOffCurrentCanvas(storyboard);
turnOnPodRacing(storyboard);
storyboard.Begin(mainCanvas);
}
/// <summary>
/// Event handler called whenever a user tries to navigate to the Menu.
/// </summary>
/// <param name="sender">Where the event came from</param>
/// <param name="e">The clicked button event</param>
public void menuButton_Clicked(object sender, RoutedEventArgs e) {
Storyboard storyboard = new Storyboard();
turnOffCurrentCanvas(storyboard);
turnOnMenu(storyboard);
storyboard.Begin(mainCanvas);
}
#endregion
#region Turn On/Off Menu
/// <summary>
/// Adds fade in animations for turning on the menu to the given storyboard. Used when switching modes.
/// </summary>
/// <param name="storyboard">The storyboard on which the animations for fading out/in will be played</param>
private void turnOnMenu(Storyboard storyboard) {
foreach (Button b in menuButtons) {
b.IsEnabled = true;
storyboard.Children.Add(newAnimation(b, 0, 1, fadeIn, fadeOut));
}
currentMode = Mode.MENU;
storyboard.Children.Add(newAnimation(menuTitle, 0, 1, fadeIn, fadeOut));
storyboard.Children.Add(newBackgroundAnimation(ViewerCanvas, 0, 1, fadeIn, fadeOut));
storyboard.Children.Add(newBackgroundAnimation(mainCanvas, 0.0, 1.0, fadeIn, fadeOut));
ViewerCanvas.Opacity = 0.0;
shiftViewerTo(470, 410);
}
/// <summary>
/// Adds fade out animations for turning off the menu to the given storyboard. Used when switching modes.
/// </summary>
/// <param name="storyboard">The storyboard on which the animations for fading out/in will be played</param>
private void turnOffMenu(Storyboard storyboard) {
foreach (Button b in menuButtons) {
b.IsEnabled = false;
storyboard.Children.Add(newAnimation(b, 1, 0, fadeOut, timeZero));
}
storyboard.Children.Add(newAnimation(menuTitle, 1, 0, fadeOut, timeZero));
storyboard.Children.Add(newBackgroundAnimation(mainCanvas, 0, 0, fadeOut, timeZero));
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Babylips.DB.Interface
{
public interface IUserForm : IBaseEntity
{
[Display(Name = "Adın Soyadın")]
[Required(ErrorMessage = "Ad Soyad gerekli")]
string NameSurname { get; set; }
[Display(Name = "Email Adresin")]
[Required(ErrorMessage = "E-posta adresi gerekli")]
[EmailAddress(ErrorMessage = "Yanlış e-posta adresi")]
string Email { get; set; }
[Display(Name = "Telefon Numaran")]
[Required(ErrorMessage = "Telefon gerekli")]
[Phone(ErrorMessage = "Yanlış telefon numarası")]
string Mobile { get; set; }
[Display(Name = "il")]
[Required(ErrorMessage = "Şehir seçmelisin")]
int CityId { get; set; }
[Display(Name = "ilce")]
[Required(ErrorMessage = "İlçe seçmelisin")]
int CountyId { get; set; }
[Display(Name = "Adres")]
[Required(ErrorMessage = "Adresini yazmalısın")]
string Address { get; set; }
[Display(Name = "Doğum Tarihin")]
string Birthday { get; set; }
}
} |
using System;
using Data.Models;
using Data.Models.Other;
using Microsoft.EntityFrameworkCore;
using Game = Data.Models.Game;
using GameEvent = Data.Models.GameEvent;
using League = Data.Models.League;
using LeagueType = Data.Models.LeagueType;
using Team = Data.Models.Team;
namespace Data
{
internal class WebsiteDbContext : DbContext
{
public DbSet<Settings> Settings { get; set; }
public DbSet<PushSubscription> Subscriptions { get; set; }
public DbSet<League> League { get; set; }
public DbSet<Team> Team { get; set; }
public DbSet<Game> Game { get; set; }
public DbSet<GameEvent> GameEvent { get; set; }
public WebsiteDbContext()
{
}
public WebsiteDbContext(DbContextOptions<WebsiteDbContext> options)
: base(options)
{ }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<League>().HasIndex(g=>g.Type).IsUnique();
modelBuilder.Entity<Game>().HasKey(g=>g.MatchId);
var pushSubscriptionEntityTypeBuilder = modelBuilder.Entity<PushSubscription>();
pushSubscriptionEntityTypeBuilder.Ignore(p => p.Keys);
var leagueTypeBuilder = modelBuilder.Entity<League>();
leagueTypeBuilder.Property(t => t.Type).HasConversion(v => v.ToString(), v => (LeagueType)Enum.Parse(typeof(LeagueType), v));;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CharacterController : FSM
{
public bool CanPlay { set; get; }
// Start is called before the first frame update
void Start()
{
ChooseCharacter();
//if (_scoreData.score == 0) { Loose(); ChangeScene(); } else if (virus == 0) { EndGame(); ChangeScene(); } }
// Update is called once per frame
void Update()
{
}
void ChooseCharacter()
{
//si hay alguno antes eliminarlo
}
void EndGame()
{
}
void Loose()
{
}
void ChangeScene()
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Smy.Math;
public class FadeLoading : MonoBehaviour
{
[SerializeField]
private Text loadingText = null;
[SerializeField]
private Image loadingImage = null;
private Timer timer;
private void Start()
{
timer = new Timer(1.5f);
Initialize(false);
}
public void Initialize(bool enable)
{
loadingText.enabled = enable;
loadingImage.enabled = enable;
timer.Initialize();
}
public void Load()
{
timer.Update();
if (timer.IsTime())
{
timer.Initialize();
}
loadingImage.rectTransform.localEulerAngles =
new Vector3(0.0f, 0.0f, -Easing.QuartInOut(timer.currentTime, timer.limitTime, 0.0f, 360.0f));
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace UCMAService
{
public class UserInfoNew : UserInfo
{
public DateTime ConferenceDeleteDateTime { get; set; }
}
} |
namespace XShare.Data.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using XShare.Data.DataSeed;
using XShare.Data.Models;
public sealed class Configuration : DbMigrationsConfiguration<XShareDbContext>
{
public Configuration()
{
this.AutomaticMigrationsEnabled = true;
this.AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(XShareDbContext context)
{
new AdminSeeder().Seed(context);
new FeaturesSeeder().Seed(context);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Globalization;
using System.Data.SqlTypes;
/// <summary>
/// Summary description for CandidatesBll
/// </summary>
public class CandidatesBll
{
public CandidatesBll()
{
//
// TODO: Add constructor logic here
//
}
#region --- Declared Variables ---
public int Id { set; get; }
public string CandidatesId { set; get; }
public int ElectionId { set; get; }
public string ElectionName { set; get; }
public int DistrictNo { set; get; }
public string Years { set; get; }
public string ClubName { set; get; }
public string Name { set; get; }
public string JoiningDate { set; get; }
public string Classification { set; get; }
public int MembershipNo { set; get; }
public string Email { set; get; }
public string Mobile { set; get; }
public SqlDateTime Birthday { set; get; }
public string Description { set; get; }
public string Photo { set; get; }
public string BioData { set; get; }
public string Ipaddress { set; get; }
#endregion
#region --- Add ---
public int AddCandidate()
{
int i = 0;
DBconnection obj = new DBconnection();
obj.SetCommandSP = "z_AddCandidates";
obj.AddParam("@election_id", this.ElectionId);
obj.AddParam("@district_no", this.DistrictNo);
obj.AddParam("@years", this.Years);
obj.AddParam("@club_name", this.ClubName);
obj.AddParam("@name", this.Name);
obj.AddParam("@joining_date", this.JoiningDate);
obj.AddParam("@classification", this.Classification);
obj.AddParam("@membership_no", this.MembershipNo);
obj.AddParam("@email", this.Email);
obj.AddParam("@mobile", this.Mobile);
obj.AddParam("@birthday", this.Birthday);
obj.AddParam("@description", this.Description);
obj.AddParam("@photo", this.Photo);
obj.AddParam("@biodata", this.BioData);
obj.AddParam("@ipaddress", this.Ipaddress);
i = obj.ExecuteNonQuery();
return i;
}
#endregion
#region --- Update ---
public int UpdateCandidate()
{
int i = 0;
DBconnection obj = new DBconnection();
obj.SetCommandSP = "z_UpdateCandidates";
obj.AddParam("@id", this.Id);
obj.AddParam("@election_id", this.ElectionId);
obj.AddParam("@district_no", this.DistrictNo);
obj.AddParam("@years", this.Years);
obj.AddParam("@club_name", this.ClubName);
obj.AddParam("@name", this.Name);
obj.AddParam("@joining_date", this.JoiningDate);
obj.AddParam("@classification", this.Classification);
obj.AddParam("@membership_no", this.MembershipNo);
obj.AddParam("@email", this.Email);
obj.AddParam("@mobile", this.Mobile);
obj.AddParam("@birthday", this.Birthday);
obj.AddParam("@description", this.Description);
obj.AddParam("@photo", this.Photo);
obj.AddParam("@biodata", this.BioData);
i = obj.ExecuteNonQuery();
return i;
}
#endregion
#region --- Get ---
public DataTable GetCandidateById()
{
DBconnection obj = new DBconnection();
DataTable dt = new DataTable();
obj.SetCommandSP = "z_GetCandidates";
obj.AddParam("@id", this.Id);
dt = obj.ExecuteTable();
return dt;
}
public DataTable GetCandidateByElection()
{
DBconnection obj = new DBconnection();
DataTable dt = new DataTable();
obj.SetCommandSP = "z_GetCandidatesByElection";
obj.AddParam("@election_id", this.ElectionId);
dt = obj.ExecuteTable();
return dt;
}
public DataTable GetCandidateByDistNo()
{
DBconnection obj = new DBconnection();
DataTable dt = new DataTable();
obj.SetCommandSP = "z_GetCandidatesByDistNo";
obj.AddParam("@years", this.Years);
obj.AddParam("@district_no", this.DistrictNo);
dt = obj.ExecuteTable();
return dt;
}
public DataTable GetCandidateList()
{
DBconnection obj = new DBconnection();
DataTable dt = new DataTable();
obj.SetCommandSP = "z_CandidatesList";
dt = obj.ExecuteTable();
return dt;
}
public DataTable GetCandidatesByElectionName()
{
DBconnection obj = new DBconnection();
DataTable dt = new DataTable();
obj.SetCommandSP = "z_GetCandidatesByElectionName";
obj.AddParam("@election_name", this.ElectionName);
dt = obj.ExecuteTable();
return dt;
}
public DataTable GetCandidateInPref()
{
DBconnection obj = new DBconnection();
DataTable dt = new DataTable();
obj.SetCommandSP = "z_GetCandidatesInPref";
obj.AddParam("@district_no", this.DistrictNo);
obj.AddParam("@years", this.Years);
obj.AddParam("@id", this.Id);
dt = obj.ExecuteTable();
return dt;
}
public DataTable GetCandidateInPref2()
{
DBconnection obj = new DBconnection();
DataTable dt = new DataTable();
obj.SetCommandSP = "z_GetCandidatesInPref2";
obj.AddParam("@district_no", this.DistrictNo);
obj.AddParam("@candidate_id", this.CandidatesId);
dt = obj.ExecuteTable();
return dt;
}
#endregion
#region --- Delete ---
public int DeleteCandidate()
{
int i = 0;
DBconnection obj = new DBconnection();
obj.SetCommandSP = "z_DeleteCandidates";
obj.AddParam("@id", this.Id);
i = obj.ExecuteNonQuery();
return i;
}
#endregion
public string ToTitleCase(string str) { return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower()); }
} |
using System;
using System.Runtime.InteropServices;
namespace Siemens.Simatic.RfReader
{
/// <summary>
/// Helper class to allow time measurements with high-resolution timers
/// </summary>
public class PerfTiming
{
/// <summary>
/// Win32 API function to retrieve a high-resolution performance counter
/// value
/// </summary>
/// <param name="nPfCt">The performance counter value retrieved</param>
/// <returns>Returns true on success</returns>
[DllImport("KERNEL32")]
public static extern bool QueryPerformanceCounter(ref Int64 nPfCt);
/// <summary>
/// Win32 API function to get the performance frequency which must be
/// used
/// </summary>
/// <param name="nPfFreq">The performance frequency</param>
/// <returns>Returns true on success</returns>
[DllImport("KERNEL32")]
public static extern bool QueryPerformanceFrequency(ref Int64 nPfFreq);
/// <summary>The machine's performance frequency.</summary>
protected Int64 m_i64Frequency;
/// <summary>The start point of our performance measurement.</summary>
protected Int64 m_i64Start;
/// <summary>
/// Create a new instance for performance measurements
/// and initialize it with the system's performance frequency
/// </summary>
public PerfTiming()
{
QueryPerformanceFrequency(ref m_i64Frequency);
m_i64Start = 0;
}
/// <summary>
/// Start performance measurement by retrieving a first performance counter value
/// </summary>
public void Start()
{
QueryPerformanceCounter(ref m_i64Start);
}
/// <summary>
/// Stop performance measurement. Calculate the time passed since Start() and
/// return the calculated time.
/// </summary>
/// <returns>The time passed between the last call to Start and the call to End in seconds.</returns>
public double End()
{
Int64 i64End = 0;
QueryPerformanceCounter(ref i64End);
return ((i64End - m_i64Start) / (double)m_i64Frequency);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Lab_EDI_3.Services
{
public class Storage
{
private static Storage _instance = null;
public static Storage GetInstance()
{
if (_instance == null) _instance = new Storage();
return _instance;
}
public CustomEstructure.Lista<Medicamento> MiInventario;
public CustomEstructure.Lista<Cliente> MiListadoCliente;
public CustomEstructure.ArbolB MiArbol;
public int CantidadClientes;
public Pedido MiPedido;
public Cliente Nuevo;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CadenciaDeDisparo : MonoBehaviour
{
public float speed = 4;
void Update()
{
transform.position -= transform.forward * speed * Time.deltaTime;
Invoke("destruir", 10);
}
private void OnTriggerEnter(Collider other)
{
if (other.GetComponent<Spawner>())
{
Destroy(gameObject);
if (Spawner.cadencia >= 0.32f)
Spawner.cadencia = Spawner.cadencia - 0.01f;
// Debug.Log(Spawner.cadencia);
}
}
public void destruir()
{
Destroy(gameObject);
}
}
|
using System;
using System.Collections.Generic;
namespace puzzles
{
class Program
{
public static int[] RandomArray()
{
int sum = 0;
int[] arr = new int[10];
Random rand = new Random();
for(int i = 0; i<10; i++)
{
arr[i] = rand.Next(5,25);
sum += arr[i];
}
System.Console.WriteLine("Sum is {0}", sum);
int max = arr[0];
int min = arr[0];
foreach (var item in arr)
{
if(item > max)
{
max = item;
}
else if (item < min)
{
min = item;
}
}
System.Console.WriteLine("Max is {0}, and Min is {1}, ", max, min);
return arr;
}
public static int CoinToss()
{
System.Console.WriteLine("Tossing coing...");
Random rand = new Random();
int coin = rand.Next(1,3);
if(coin == 1)
{
System.Console.WriteLine("Heads!");
}
else
{
System.Console.WriteLine("Tails!");
}
return coin;
}
static double TossMultipleCoins(int num)
{
double result;
int heads = 0;
int coin;
Random rand = new Random();
for(int i = 1; i < num; i++)
{
coin = rand.Next(1,3);
System.Console.WriteLine(coin);
if(coin == 2)
{
heads++;
}
}
result = (double)heads/(double)num;
System.Console.WriteLine("result is {0}", result);
return result;
}
static string[] names()
{
string[] arr = new string[]{"Todd", "Tiffany", "Charlie", "Geneva", "Sydney"};
Random rand = new Random();
int count = 0;
for(int i = 0; i < arr.Length; i++)
{
if(arr[i].Length > 5)
{
count++;
}
int idx = rand.Next(0, arr.Length);
string temp = arr[i];
arr[i] = arr[idx];
arr[idx] = temp;
}
string[] newArr = new string[count];
int newIdx = 0;
foreach(string name in arr)
{
if(name.Length > 5)
{
newArr[newIdx] = name;
newIdx++;
}
}
foreach(string name in newArr)
{
System.Console.WriteLine(name);
}
return newArr;
}
static void Main(string[] args)
{
// RandomArray();
CoinToss();
// TossMultipleCoins(4);
// names();
}
}
}
|
using JIoffe.BIAD.Model;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.AI.QnA;
using Microsoft.Bot.Schema;
using Newtonsoft.Json;
using System.Threading;
using System.Threading.Tasks;
namespace JIoffe.BIAD.Bots
{
public class QnAMakerBot : IBot
{
//Step X) Initialize a private variable of QnAMaker via Dependency Injection
private readonly QnAMaker _qnaMaker;
public QnAMakerBot(QnAMaker qnaMaker)
{
_qnaMaker = qnaMaker;
}
public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
{
//Ignore activities that are not messages
if (turnContext.Activity.Type != "message")
return;
//Invoke GetAnswersAsync from the QnAMaker instance and respond to the user
// - Send a notice if there was no response from the service
// - Send the top answer if there was
var response = await _qnaMaker.GetAnswersAsync(turnContext);
if(response == null || response.Length == 0)
{
await turnContext.SendActivityAsync(Responses.QnA.NoAnswer, cancellationToken: cancellationToken);
}
else
{
var answer = response[0].Answer;
//Step 1) Convert the answer to an instance of RichQnAResult
//TODO - Use JsonConvert.DeserializeObject to convert the answer to a RichQnAResult
//Step 2) Create a hero card based on the content of the richQnaResult
// - Set the title and text to match the rich result's title and text
// - Add a button of type OpenUrl to navigate to the url in the result
// - Add the image based on the img property of the result
//TODO - Create the hero card
//Step 3) Create a new activity that we can attach the hero card to
//TODO - Use MessageFactory.Attachment to create a new activity
//Step 4) Send the activity to the user
//TODO via turnContext.SendActivityAsync, send the activity to the user
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorkOutTracker.workout;
using static WorkOutTracker.Program;
namespace WorkOutTracker
{
class Weightlifting : WorkOut
{
public WeightType LiftType;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Animator))]
[RequireComponent(typeof(Rigidbody))]
public class CampMoveAgent : MonoBehaviour {
int index;
Animator anim;
Rigidbody rb;
Transform[] points;
bool moving = false;
Transform target;
float approachSqr = 0.2f;
float speed;
public void Init(float speed, Transform[] points, int index)
{
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody>();
this.speed = speed;
this.points = points;
this.index = index;
StartMoving(points[index]);
}
void StopMoving()
{
moving = false;
anim.SetBool("moving", false);
}
void StartMoving(Transform target)
{
moving = true;
this.target = target;
transform.LookAt(target);
anim.SetBool("moving", true);
}
IEnumerator NextPointRoutine()
{
StopMoving();
float waitTime = Random.Range(1f, 7f);
yield return new WaitForSeconds(waitTime);
index++;
if (points.Length == index) index = 0;
StartMoving(points[index]);
}
void FixedUpdate()
{
if (!moving) return;
Vector3 dir = target.position - transform.position;
if (dir.sqrMagnitude < approachSqr) StartCoroutine(NextPointRoutine());
else rb.MovePosition(rb.position + dir.normalized * speed * Time.fixedDeltaTime);
}
}
|
using HardwareInventoryManager.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using HardwareInventoryManager.Helpers.User;
namespace HardwareInventoryManager.Helpers.User
{
public class TenantUtility : ITenantUtility
{
private CustomApplicationDbContext _context;
public TenantUtility()
{
_context = new CustomApplicationDbContext();
}
public int GetTenantIdFromEmail(string emailAddress)
{
int tenantContextId = 0;
ApplicationUser uu = _context.Users.Include(x => x.UserTenants).First(u => u.UserName == emailAddress) as ApplicationUser;
if (uu.UserTenants != null && uu.UserTenants.Count > 0)
{
return uu.UserTenants.First().TenantId;
}
return tenantContextId;
}
public int GetTenantIdFromUserId(string userId)
{
int tenantContextId = 0;
ApplicationUser uu = _context.Users.Include(x => x.UserTenants).First(u => u.Id == userId) as ApplicationUser;
if (uu.UserTenants != null && uu.UserTenants.Count > 0)
{
return uu.UserTenants.First().TenantId;
}
return tenantContextId;
}
public IQueryable<Tenant> GetUserTenants(string userName)
{
ApplicationUser uu = _context.Users.Include(x => x.UserTenants).First(u => u.UserName == userName) as ApplicationUser;
if (uu.UserTenants != null && uu.UserTenants.Count > 0)
{
return uu.UserTenants.AsQueryable();
}
return new List<Tenant>().AsQueryable();
}
}
} |
using CRUDXamarin_DAL.Handler;
using CRUDXamarin_Ent;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CRUDXamarin_BL.Handler
{
public class clsGestionPersonasBL
{
/// <summary>
/// Metodo que comprobará la lógica de la empresa y llamará o no al método de insertar persona
/// de la capa DAL
/// </summary>
/// <param name="oPersona">
/// objeto persona que será insertado o no en la base de datos, dependiendo de si lo
/// permiten las reglas de la empresa
/// </param>
/// <returns>
/// entero que sera el n de filas afectadas
/// </returns>
public int insertarPersona(clsPersona oPersona)
{
clsGestionPersonasDAL gestionPersonasDAL = new clsGestionPersonasDAL();
return gestionPersonasDAL.insertarPersona(oPersona); ;
}
/// <summary>
/// Método que llama al eliminar persona de la capa DAL o no, dependiendo de
/// la lógica de la empresa. Si se puede eliminar, se eliminará.
/// </summary>
/// <param name="oPersona">
/// objeto persona que se quiere eliminar
/// </param>
/// <returns>
/// devuelve el numero de filas afectadas o -1 si no se puede eliminar
/// porque la empresa así lo quiere
/// </returns>
public async Task<int> eliminarPersona(clsPersona oPersona)
{
int resultado;
clsGestionPersonasDAL gestionPersonasDAL = new clsGestionPersonasDAL();
resultado = await gestionPersonasDAL.eliminarPersonaAsync(oPersona.idPersona);
//de momento no hay logica de empresa
return resultado;
//return 0;
}
/// <summary>
/// Método que llama al actualizar persona de la capa DAL o no, dependiendo de
/// la lógica de la empresa. Si se puede actualizar, se hará. Si se actualiza lo
/// harán todos sus campos.
/// </summary>
/// <param name="oPersona">
/// objeto persona que se quiere actualizar
/// </param>
/// <returns>
/// devuelve el numero de filas afectadas o -1 si no se puede actualizar
/// porque la empresa así lo quiere
/// </returns>
public int actualizarPersona(clsPersona oPersona)
{
/*
int resultado;
clsGestionPersonasDAL gestionPersonasDAL = new clsGestionPersonasDAL();
resultado = gestionPersonasDAL.actualizarPersona(oPersona);
return resultado;
*/
return 0;
}
}
}
|
namespace GetLabourManager.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class FieldLocationmigra : DbMigration
{
public override void Up()
{
AddColumn("dbo.GangSheetHeaders", "FieldLocation", c => c.Int(nullable: false));
}
public override void Down()
{
DropColumn("dbo.GangSheetHeaders", "FieldLocation");
}
}
}
|
namespace Standard
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode), BestFitMapping(false), SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")]
internal class WIN32_FIND_DATAW
{
public FileAttributes dwFileAttributes;
public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime;
public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime;
public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime;
public int nFileSizeHigh;
public int nFileSizeLow;
public int dwReserved0;
public int dwReserved1;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=260)]
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=14)]
public string cAlternateFileName;
}
}
|
using System;
using System.Windows.Forms;
namespace Game
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
this.Text = "";
if (Form1.win.ToString().Equals("1"))
{
panel2.BackgroundImage = Properties.Resources.cross;
}
else
panel2.BackgroundImage = Properties.Resources.nought;
}
private void button1_Click(object sender, EventArgs e)
{
Home h1 = new Home();
this.Hide();
h1.Show();
this.Close();
}
}
}
|
using UnityEngine;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif
[SLua.CustomLuaClass]
public class GameConfig : ScriptableObject
{
#if UNITY_EDITOR
const string KeyDebugString = "OzGameConfig_connect_server";
[SLua.DoNotToLua]
public static string connectServer
{
get
{
string _debug = EditorPrefs.GetString(KeyDebugString, "");
return _debug;
}
set
{
EditorPrefs.SetString(KeyDebugString, value);
}
}
#endif
private static string m_server;
public static string server
{
get
{
#if UNITY_EDITOR
if(!string.IsNullOrEmpty(connectServer))
{
return connectServer;
}
else
{
return m_server;
}
#else
return m_server;
#endif
}
set
{
m_server = value;
}
}
private static GameConfig m_localConfig;
public static GameConfig localConfig
{
get
{
if (m_localConfig == null)
{
m_localConfig = Resources.Load<GameConfig>("config");
#if UNITY_EDITOR
if (m_localConfig == null)
{
m_localConfig = GameConfig.CreateInstance<GameConfig>();
AssetDatabase.CreateAsset(m_localConfig, "Assets/Resources/config.asset");
}
#endif
}
return m_localConfig;
}
}
public static RemoteGameConfig remoteConfig = new RemoteGameConfig();
public static string LocalSubVersionKey
{
get
{
return string.Concat(PathUtil.GetPlatformFolderForAssetBundles(), CurrentBundleVersion.versionCode, "_subVersion");
}
}
public static string LocalResVersionKey
{
get
{
return string.Concat(PathUtil.GetPlatformFolderForAssetBundles(), CurrentBundleVersion.versionCode, "_resVersion");
}
}
public static void ResetConfig()
{
remoteConfig.subVersion = "0";
remoteConfig.resVersion = "0";
}
public static void SetRemoteConfig(string subVersion, string resVersion)
{
if (string.IsNullOrEmpty(subVersion))
{
subVersion = "0";
}
if (string.IsNullOrEmpty(resVersion))
{
resVersion = "0";
}
remoteConfig.subVersion = subVersion;
remoteConfig.resVersion = resVersion;
}
private SortedList<string, string> configs = new SortedList<string, string>();
[SerializeField]
private string m_subVersion;
[SerializeField]
private string m_resVersion;
[SerializeField]
private string m_assetDomain;
[SerializeField]
private string m_platform = "orig";
public string platform
{
get
{
return m_platform;
}
set
{
m_platform = value;
}
}
//小版本号,热更用
public string subVersion
{
get
{
if (string.IsNullOrEmpty(m_subVersion))
{
m_subVersion = GetConfig("subVersion");
}
return m_subVersion;
}
set
{
m_subVersion = value;
}
}
public string resVersion
{
get
{
if (string.IsNullOrEmpty(m_resVersion))
{
m_resVersion = GetConfig("resVersion");
}
return m_resVersion;
}
set
{
m_resVersion = value;
}
}
public string assetDomain
{
get
{
if (string.IsNullOrEmpty(m_assetDomain))
{
m_assetDomain = GetConfig("assetDomain");
}
#if BANSHU && !UNITY_EDITOR
return m_assetDomain + "/banshu";
#else
return m_assetDomain;
#endif
}
set
{
m_assetDomain = value;
}
}
public string GetConfig(string key)
{
string value = string.Empty;
configs.TryGetValue(key, out value);
return value;
}
}
public class RemoteGameConfig
{
//lua代码版本号
public string subVersion = "0";
//资源版本号
public string resVersion = "0";
}
|
using bot_backEnd.DAL.Interfaces;
using bot_backEnd.Data;
using bot_backEnd.Models.DbModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace bot_backEnd.DAL
{
public class CommentNotificationDAL : ICommentNotificationDAL
{
private readonly AppDbContext _context;
public CommentNotificationDAL(AppDbContext context)
{
_context = context;
}
public async Task<ActionResult<CommentNotification>> AddCommentNotification(CommentNotification notification)
{
_context.CommentNotification.Add(notification);
await _context.SaveChangesAsync();
//_context.Entry(notification).State = EntityState.Detached;
return notification;
}
public async Task<ActionResult<bool>> DeleteCommentNotification(int commentID, int PostID, int userEntityID, int notificationTypeID)
{
var notification = await _context.CommentNotification.
Where(c => c.CommentID == commentID && c.PostID == PostID &&
c.SenderID == userEntityID && c.NotificationTypeID == notificationTypeID)
.FirstOrDefaultAsync();
if (notification == null)
return false;
_context.CommentNotification.Remove(notification);
await _context.SaveChangesAsync();
return true;
}
public async Task<ActionResult<List<CommentNotification>>> GetAllCommentNotificationsByUserID(int userEntityID)
{
return await _context.CommentNotification
.Where(n => n.ReceiverID == userEntityID)
.Include(n => n.Sender.ProfilePhoto)
.Include(n => n.Sender.Gender)
.Include(n => n.Receiver.ProfilePhoto)
.Include(n => n.Comment)
.Include(n => n.Post)
.ToListAsync();
}
public async Task<ActionResult<CommentNotification>> GetCommentNotificationByID(int commentNotificationID)
{
return await _context.CommentNotification
.Where(c => c.Id == commentNotificationID)
.Include(n => n.Sender.ProfilePhoto)
.Include(n => n.Sender.Gender)
.Include(n => n.Receiver.ProfilePhoto)
.Include(n => n.Comment)
.Include(n => n.Post)
.FirstOrDefaultAsync();
}
public async Task<ActionResult<bool>> MakeAllNotificationsRead(int userID)
{
var notifs = GetAllCommentNotificationsByUserID(userID).Result.Value;
foreach (var item in notifs)
item.Read = true;
await _context.SaveChangesAsync();
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hyperspace
{
class Unit : Object
{
public List<Bullet> ListOfBullets { get; set; }
public int Velocity { get; set; }
public int Lives { get; set; }
public Unit(int x, int y)
{
Symbol = "^";
X = x;
Y = y;
Color = ConsoleColor.Yellow;
ListOfBullets = new List<Bullet>();
Lives = 3;
}
public void Fire()
{
ListOfBullets.Add(new Bullet(this));
}
public void Draw()
{
Console.SetCursorPosition(X, Y);
Console.ForegroundColor = Color;
Console.Write(Symbol);
Console.ResetColor();
}
public void ResetPosition(int x, int y)
{
X = x;
Y = y;
}
//public void DestroyBullet()
//{
//}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour
{
public string playGameLevel;
public string theInstruction;
public string mainMenuLevel;
public string aboutScene;
public string theCredits;
public void PlayGame()
{
SceneManager.LoadScene(playGameLevel);
}
public void ViewInstruction()
{
SceneManager.LoadScene(theInstruction);
}
public void BackToMain()
{
SceneManager.LoadScene(mainMenuLevel);
}
public void GameAbout()
{
SceneManager.LoadScene(aboutScene);
}
public void Credits()
{
SceneManager.LoadScene(theCredits);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OpenCloudPrinciple_OCP_.ModelClasses.FilteringComputerMonitor.ImplementOCP
{
public class MonitorFilter : IFilter<ComputerMonitor>
{
public List<ComputerMonitor> Filter(IEnumerable<ComputerMonitor> monitors, ISpecification<ComputerMonitor> specification)
{
return monitors.Where(s => specification.isSatisfied(s)).ToList();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LaserSpowner : MonoBehaviour {
public List<GameObject> laserPrefabList = new List<GameObject>();
[SerializeField]
public AnimationCurve spownRate = AnimationCurve.Linear(0,1.0f,10.0f,2.0f);
private float nextSpawnTS;
private float spownedCount = 0;
// Update is called once per frame
public float speed = 10f;
private void Awake()
{
nextSpawnTS = Time.time;
this.CalculateNextSpownTS();
}
void Update () {
if(Time.time >= this.nextSpawnTS && laserPrefabList.Count!=0)
{
this.Spawn(laserPrefabList[0]);
laserPrefabList.RemoveAt(0);
this.CalculateNextSpownTS();
}
}
private void Spawn(GameObject orignal)
{
GameObject instance= Instantiate(orignal.gameObject, this.transform.position, this.transform.rotation);
this.spownedCount++;
}
private void CalculateNextSpownTS()
{
this.nextSpawnTS =this.nextSpawnTS+ this.spownRate.Evaluate(this.spownedCount);
}
}
|
/***********************
@ author:zlong
@ Date:2015-01-08
@ Desc:办公费用管理逻辑层
* ********************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DriveMgr.BLL
{
public class OfficeBLL
{
private static readonly DriveMgr.IDAL.IOfficeDAL officeDal = DriveMgr.DALFactory.Factory.GetOfficeDAL();
/// <summary>
/// 增加一条数据
/// </summary>
public bool AddOffice(Model.OfficeModel model)
{
return officeDal.AddOffice(model);
}
/// <summary>
/// 更新一条数据
/// </summary>
public bool UpdateOffice(Model.OfficeModel model)
{
return officeDal.UpdateOffice(model);
}
/// <summary>
/// 删除一条数据
/// </summary>
public bool DeleteOffice(int id)
{
return officeDal.DeleteOffice(id);
}
/// <summary>
/// 批量删除数据
/// </summary>
public bool DeleteOfficeList(string idlist)
{
return officeDal.DeleteOfficeList(idlist);
}
/// <summary>
/// 得到一个对象实体
/// </summary>
public Model.OfficeModel GetOfficeModel(int id)
{
return officeDal.GetOfficeModel(id);
}
/// <summary>
/// 获取分页数据
/// </summary>
/// <param name="officeUse">用途</param>
/// <param name="tagPerson">经办人</param>
/// <param name="createStartDate">开始时间</param>
/// <param name="createEndDate">结束时间</param>
/// <param name="order">排序</param>
/// <param name="pageSize">每页大小</param>
/// <param name="pageIndex">当前页</param>
/// <param name="totalCount">总记录数</param>
/// <returns></returns>
public string GetPagerData(string officeUse, string tagPerson, string createStartDate, string createEndDate, string order, int pageSize, int pageIndex, out int totalCount)
{
StringBuilder strSql = new StringBuilder();
strSql.Append(" DeleteMark = 0 ");
if (officeUse.Trim() != string.Empty && !DriveMgr.Common.SqlInjection.GetString(officeUse))
{
strSql.Append(" and OfficeUse like '%" + officeUse + "%'");
}
if (tagPerson.Trim() != string.Empty && !DriveMgr.Common.SqlInjection.GetString(tagPerson))
{
strSql.Append(" and TagPerson like '%" + tagPerson + "%'");
}
if (createStartDate.Trim() != string.Empty)
{
strSql.Append(" and CreateDate > '" + createStartDate + "'");
}
if (createEndDate.Trim() != string.Empty)
{
strSql.Append(" and CreateDate < '" + createEndDate + "'");
}
return officeDal.GetPagerData("tb_Office", "Id,OfficeUse,TagPerson,UseDate,OfficeAmount,Remark,CreatePerson,CreateDate,UpdatePerson,UpdateDate", order, pageSize, pageIndex, strSql.ToString(), out totalCount);
}
}
}
|
using System.Text;
using System.Web;
namespace CloudinaryDotNet
{
/// <summary>
/// Implement platform specific functions
/// </summary>
internal static partial class Utils
{
internal static string EncodedUrl(string url)
{
return HttpUtility.UrlEncode(url, Encoding.UTF8);
}
internal static string Encode(string value)
{
return HttpUtility.UrlEncodeUnicode(value);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Grisaia.Categories;
using Grisaia.Mvvm.Model;
using Grisaia.Mvvm.Services;
namespace Grisaia.Mvvm.ViewModel {
public sealed partial class InstallDirsViewModel : ViewModelWindow {
#region Fields
private IReadOnlyList<InstallDirsGameViewModel> games;
#endregion
#region Properties
/// <summary>
/// Gets the database for all Grisaia databases.
/// </summary>
public GrisaiaModel GrisaiaDatabase { get; }
/// <summary>
/// Gets the database for all Grisaia games.
/// </summary>
public GameDatabase GameDatabase => GrisaiaDatabase.GameDatabase;
/// <summary>
/// Gets the database for all known Grisaia characters.
/// </summary>
public CharacterDatabase CharacterDatabase => GrisaiaDatabase.CharacterDatabase;
/// <summary>
/// Gets the database for all located character sprites.
/// </summary>
public SpriteDatabase SpriteDatabase => GrisaiaDatabase.SpriteDatabase;
/// <summary>
/// Gets the program settings
/// </summary>
public SpriteViewerSettings Settings => GrisaiaDatabase.Settings;
private readonly IRelayCommandFactory relayFactory;
public IGrisaiaDialogService Dialogs { get; }
public UIService UI { get; }
/// <summary>
/// Gets the list of games and their custom install view models.
/// </summary>
public IReadOnlyList<InstallDirsGameViewModel> Games {
get => games;
set => Set(ref games, value);
}
#endregion
#region Constructors
public InstallDirsViewModel(IRelayCommandFactory relayFactory,
GrisaiaModel grisaiaDb,
IGrisaiaDialogService dialogs,
UIService ui)
: base(relayFactory)
{
Title = "Grisaia Extract Sprite Viewer - Game Locations";
GrisaiaDatabase = grisaiaDb;
UI = ui;
Dialogs = dialogs;
this.relayFactory = relayFactory;
var games = GameDatabase.Games.Select(g => new InstallDirsGameViewModel(relayFactory, this, g));
Games = Array.AsReadOnly(games.ToArray());
}
#endregion
public override void Loaded() {
var games = GameDatabase.Games.Select(g => new InstallDirsGameViewModel(relayFactory, this, g));
Games = Array.AsReadOnly(games.ToArray());
}
}
}
|
//Pixel Studios 2016
//Weapon Customisation v1.2
using UnityEngine;
using System.Collections;
public class UI_Button : MonoBehaviour {
[Header("What attachment holder is this linked to?")]
//What customisation menu it should activate
public string attachment_Menu;
[Header("UI helper")]
//UI helper which helps changing the attachment customisation menus
public UI_Menus cs;
//Checks if you can select this button
private bool canSelect;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//Checks if you can click the button
if(canSelect)
{
if(Input.GetMouseButtonDown(0))
{
//Change the menu to this attachment type menu
cs.changeMenu(attachment_Menu);
}
}
}
//Checks if the cursor is on this button
void OnMouseEnter()
{
canSelect = true;
}
//Checks if the cursor is off this button
void OnMouseExit()
{
canSelect = false;
}
}
|
using FluentValidation;
using Publicon.Infrastructure.Commands.Models.User;
namespace Publicon.Api.Validators.User
{
public class RegisterUserCommandValidator : AbstractValidator<RegisterUserCommand>
{
public RegisterUserCommandValidator()
{
RuleFor(p => p.Email)
.EmailAddress();
RuleFor(p => p.FamilyName)
.NotEmpty()
.NotNull()
.Length(3, 200);
RuleFor(p => p.GivenName)
.NotEmpty()
.NotNull()
.Length(3, 200);
RuleFor(p => p.Password)
.NotEmpty()
.NotNull()
.MinimumLength(6);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.SqlTypes;
namespace PROJETOBDDEDE
{
public partial class Form1 : Form
{
frmAddAluno frmAddAluno = new frmAddAluno();
frmAddProf frmAddProf = new frmAddProf();
/* frmExcAluno frmExcAluno = new frmExcAluno();
frmExcProf frmExcProf = new frmExcProf();*/
private void invisibleGroup(GroupBox x)
{
x.Visible = false;
}
public Form1()
{
InitializeComponent();
}
//////// CADASTRAR ///////
private void btnCadastro_Click(object sender, EventArgs e)
{
gp_Cadastro.Visible = true;
invisibleGroup(gp_EXC);
invisibleGroup(gp_Mod);
invisibleGroup(gp_Visu);
}
private void btnCadAluno_Click(object sender, EventArgs e)
{
frmAddAluno.ShowDialog();
}
private void btnCadProf_Click(object sender, EventArgs e)
{
frmAddProf.ShowDialog();
}
/////////////////////////////////////
//////// Excluir ///////
private void btnExcluir_Click(object sender, EventArgs e)
{
gp_EXC.Visible = true;
invisibleGroup(gp_Cadastro);
invisibleGroup(gp_Mod);
invisibleGroup(gp_Visu);
}
private void btn_exc_Aluno_Click(object sender, EventArgs e)
{
// frmExcAluno.ShowDialog();
}
private void btn_exc_Prof_Click(object sender, EventArgs e)
{
// frmExcProf.ShowDialog();
}
private void btnPesquisa_Click(object sender, EventArgs e)
{
new src.forms.frmViewAluno().ShowDialog();
}
/////////////////////////////////////
}
}
|
using System.Windows;
using System.Windows.Input;
namespace PhotoGadget.Views
{
/// <summary>
/// Interaction logic for PhotoGadgetView.xaml
/// </summary>
public partial class PhotoGadgetView : Window
{
public PhotoGadgetView()
{
InitializeComponent();
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
{
try
{
DragMove();
}
catch
{
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CapaEntidades
{
public class E_Venta
{
private int _Id_venta;
private int _Id_empleado;
private DateTime _Fecha;
private string _Tipo_comprobante;
private string _Serie;
private string _Correlativo;
private decimal _Iva;
private string _Cliente;
public int Id_venta { get => _Id_venta; set => _Id_venta = value; }
public int Id_empleado { get => _Id_empleado; set => _Id_empleado = value; }
public DateTime Fecha { get => _Fecha; set => _Fecha = value; }
public string Tipo_comprobante { get => _Tipo_comprobante; set => _Tipo_comprobante = value; }
public string Serie { get => _Serie; set => _Serie = value; }
public string Correlativo { get => _Correlativo; set => _Correlativo = value; }
public decimal Iva { get => _Iva; set => _Iva = value; }
public string Cliente { get => _Cliente; set => _Cliente = value; }
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Medit1.Models
{
public class Image
{
[Key, Column(Order = 1)]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ImageId { get; set; }
[Required]
public String Path { get; set; }
public Cruise Cruise { get; set; }
}
}
|
using System.Text;
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System.Net.Http;
using System.Drawing;
using System.Collections.ObjectModel;
using System.Xml;
using System.ComponentModel;
using System.Reflection;
namespace LinnworksAPI
{
public class PackageType
{
public Guid PackageTypeId;
public Guid PackageGroupId;
public String PackageTitle;
public Double FromGramms;
public Double ToGramms;
public Double PackagingWeight;
public Double PackagingCapacity;
public Guid Rowguid;
public Double Width;
public Double Height;
public Double Depth;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bala : MonoBehaviour
{
public float Velocidad = 20;
void Start()
{
Destroy(gameObject, 3);
}
void OnTriggerEnter(Collider col)
{
Destroy(gameObject);
}
void Update()
{
transform.position += transform.up * Velocidad * Time.deltaTime;
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using DotNetNuke.Entities;
namespace DotNetNuke.Tests.Core.Controllers
{
public class ConfigurationSettingsComparer : EqualityComparer<ConfigurationSetting>
{
public override bool Equals(ConfigurationSetting x, ConfigurationSetting y)
{
if (x.Key == y.Key && x.Value == y.Value && x.IsSecure == y.IsSecure)
{
return true;
}
return false;
}
public override int GetHashCode(ConfigurationSetting obj)
{
throw new NotImplementedException();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using CTCT.Util;
namespace CTCT.Components.EventSpot
{
/// <summary>
/// Registrant class
/// </summary>
[DataContract]
[Serializable]
public class Registrant : Component
{
/// <summary>
/// Constructor
/// </summary>
public Registrant()
{
this.Sections = new List<Section>();
this.PaymentSummary = new PaymentSummary();
this.GuestSections = new List<Guest>();
}
/// <summary>
/// Id
/// </summary>
[DataMember(Name = "id", EmitDefaultValue = false)]
public string Id { get; set; }
/// <summary>
/// Sections
/// </summary>
[DataMember(Name = "sections", EmitDefaultValue = false)]
public IList<Section> Sections { get; set; }
/// <summary>
/// Ticket id
/// </summary>
[DataMember(Name = "ticket_id", EmitDefaultValue = false)]
public string TicketId { get; set; }
/// <summary>
/// String representation of date the registrant registered for the event
/// </summary>
[DataMember(Name = "registration_date", EmitDefaultValue = false)]
private string RegistrationDateString { get; set; }
/// <summary>
/// Date the registrant registered for the event
/// </summary>
public DateTime? RegistrationDate
{
get { return this.RegistrationDateString.FromISO8601String(); }
set { this.RegistrationDateString = value.ToISO8601String(); }
}
/// <summary>
/// Payment summary
/// </summary>
[DataMember(Name = "payment_summary", EmitDefaultValue = false)]
public PaymentSummary PaymentSummary { get; set; }
/// <summary>
/// Email
/// </summary>
[DataMember(Name = "email", EmitDefaultValue = false)]
public string Email { get; set; }
/// <summary>
/// First name
/// </summary>
[DataMember(Name = "first_name", EmitDefaultValue = false)]
public string FirstName { get; set; }
/// <summary>
/// Last name
/// </summary>
[DataMember(Name = "last_name", EmitDefaultValue = false)]
public string LastName { get; set; }
/// <summary>
/// Guest count
/// </summary>
[DataMember(Name = "guest_count", EmitDefaultValue = true)]
public int GuestCount { get; set; }
/// <summary>
/// Payment status
/// </summary>
[DataMember(Name = "payment_status", EmitDefaultValue = false)]
public string PaymentStatus { get; set; }
/// <summary>
/// Registration status
/// </summary>
[DataMember(Name = "registration_status", EmitDefaultValue = false)]
public string RegistrationStatus { get; set; }
/// <summary>
/// String representation of update date
/// </summary>
[DataMember(Name = "updated_date", EmitDefaultValue = false)]
private string UpdatedDateString { get; set; }
/// <summary>
/// Update date
/// </summary>
public DateTime? UpdatedDate
{
get { return this.UpdatedDateString.FromISO8601String(); }
set { this.UpdatedDateString = value.ToISO8601String(); }
}
/// <summary>
/// An array of guest properties
/// </summary>
[DataMember(Name = "guest_sections", EmitDefaultValue = false)]
public IList<Guest> GuestSections { get; set; }
}
}
|
using System.Collections.Generic;
using Asset.DataAccess.Library.AssetModelGetways.AssetSetupGetways;
using Asset.Models.Library.EntityModels.AssetsModels.AssetSetups;
namespace Asset.BisnessLogic.Library.AssetModelManagers.AssetSetupManagers
{
public class AssetLocationManager : IRepositoryManager<AssetLocation>
{
private readonly AssetLocationGetway _assetLocationGetway;
public AssetLocationManager()
{
_assetLocationGetway = new AssetLocationGetway();
}
public bool IsAssetLocationNameExist(string name)
{
bool isName = false;
var assetLocationName = GetAssetLocationByName(name);
if (assetLocationName != null)
{
isName = true;
}
return isName;
}
private AssetLocation GetAssetLocationByName(string name)
{
return _assetLocationGetway.GetAssetLocationByName(name);
}
public bool IsAssetLocatoinShortNameExist(string shortName)
{
bool isShortName = false;
var assetLocationShortName = GetAssetLocationByShortName(shortName);
if (assetLocationShortName != null)
{
isShortName = true;
}
return isShortName;
}
private AssetLocation GetAssetLocationByShortName(string shortName)
{
return _assetLocationGetway.GetAssetLocationByShortName(shortName);
}
public bool IsAssetLocationByCodeExist(string code)
{
bool isCode = false;
var assetLocationCode = GetAssetLocationByCode(code);
if (assetLocationCode != null)
{
isCode = true;
}
return isCode;
}
private AssetLocation GetAssetLocationByCode(string code)
{
return _assetLocationGetway.GetAssetLocationByCode(code);
}
public IEnumerable<AssetLocation> AssetLocationsWithOrganizationAndBranch()
{
return _assetLocationGetway.AssetLocationsWithOrganizationAndBranch();
}
public AssetLocation SingleAssetLocation(int id)
{
return _assetLocationGetway.SingleAssetLocation(id);
}
public IEnumerable<AssetLocation> FindById(int id)
{
return _assetLocationGetway.Find(id);
}
public AssetLocation Get(int id)
{
return _assetLocationGetway.Get(id);
}
public IEnumerable<AssetLocation> GetAll()
{
return _assetLocationGetway.GetAll();
}
public int Add(AssetLocation entity)
{
return _assetLocationGetway.Add(entity);
}
public int AddRange(IEnumerable<AssetLocation> entities)
{
return _assetLocationGetway.AddRange(entities);
}
public int Update(AssetLocation entity)
{
return _assetLocationGetway.Update(entity);
}
public int Remove(AssetLocation entity)
{
return _assetLocationGetway.Remove(entity);
}
public int RemoveRange(IEnumerable<AssetLocation> entities)
{
return _assetLocationGetway.RemoveRange(entities);
}
}
}
|
using System;
using System.ComponentModel;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Zengo.WP8.FAS.Controls;
using Zengo.WP8.FAS.Resources;
namespace Zengo.WP8.FAS.Views
{
public partial class FavouriteLeaguePage : PhoneApplicationPage
{
#region Fields
ListSortDirection sortDirection;
private string searchTerm;
private const int SearchRow = 1;
private const double SearchHeight = 70;
private const int FeedbackRow = 3;
private const double FeedbackHeight = 70;
#endregion
#region Constructor
public FavouriteLeaguePage()
{
InitializeComponent();
sortDirection = ListSortDirection.Ascending;
searchTerm = string.Empty;
PopulateList();
LeagueList.SelectionChanged += LeagueListOnSelectionChanged;
SearchBox.DoSearch += SearchBox_DoSearch;
SearchBoxFeedback.CancelSearch += SearchBoxResults_CancelSearch;
PageHeaderControl.PageTitle = AppResources.FavouriteLeaguePage;
PageHeaderControl.PageName = AppResources.ProductTitle;
BuildApplicationBar();
UpdateAppBarMenu();
}
private void BuildApplicationBar()
{
ApplicationBar = new ApplicationBar();
var button = new ApplicationBarIconButton(new Uri("/Images/AppBar/search.png", UriKind.RelativeOrAbsolute)) { Text = AppResources.AppBarSearch };
button.Click += AppBarButtonSearch_Click;
ApplicationBar.Buttons.Add(button);
var item = new ApplicationBarMenuItem { Text = AppResources.AppBarSortAscending };
item.Click += AppBarMenuItemSortAscending_Click;
ApplicationBar.MenuItems.Add(item);
}
#endregion
#region Event Handlers
private void LeagueListOnSelectionChanged(object sender, LongListLeaguesControl.LeagueSelectionChangedEventArgs e)
{
App.AppConstants.FavLeague = e.League;
NavigationService.GoBack();
}
void SearchBox_DoSearch(object sender, Controls.SearchBoxControl.DoSearchEventArgs e)
{
// Return focus back to screen - get rid of the keyboard
this.Focus();
// grab the search term
searchTerm = e.searchTerm;
// Do the search / sort
PopulateList();
// Disable search box - do this to close the row
EnableSearch(false);
EnableInfo(true, App.ViewModel.DbViewModel.PlayersCount(searchTerm));
}
void SearchBoxResults_CancelSearch(object sender, EventArgs e)
{
// Search term is empty
searchTerm = string.Empty;
// Populate the list
PopulateList();
// Disable search box
EnableSearch(false);
// Disable info box
EnableInfo(false, 0);
}
#endregion
#region AppBarEvents
void AppBarMenuItemSortAscending_Click(object sender, EventArgs e)
{
//Toggle the search direction
sortDirection = sortDirection == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending;
// make sure the app bar menu has the correct text
UpdateAppBarMenu();
// Populate the list
PopulateList();
}
private void AppBarButtonSearch_Click(object sender, System.EventArgs e)
{
EnableSearch(!SearchBox.IsSearchEnabled());
}
#endregion
#region Helpers
internal void EnableSearch(bool enable)
{
if (enable)
{
LayoutRoot.RowDefinitions[SearchRow].Height = new GridLength(SearchHeight);
}
else
{
LayoutRoot.RowDefinitions[SearchRow].Height = new GridLength(0);
Focus();
}
SearchBox.EnableSearch(enable);
}
private void EnableInfo(bool enable, int results)
{
LayoutRoot.RowDefinitions[FeedbackRow].Height = enable ? new GridLength(FeedbackHeight) : new GridLength(0);
SearchBoxFeedback.Enable(enable, results, searchTerm);
}
private void PopulateList()
{
var list = App.FreeEntryViewModel.Leagues(sortDirection, searchTerm);
LeagueList.LeagueLongList.ItemsSource = (System.Collections.IList)list;
}
private void UpdateAppBarMenu()
{
var m = (ApplicationBarMenuItem)ApplicationBar.MenuItems[0];
m.Text = sortDirection == ListSortDirection.Ascending ? AppResources.AppBarSortDescending : AppResources.AppBarSortAscending;
}
#endregion
}
} |
/*
* Copyright (c) 2021 Samsung Electronics Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Alarms.ViewModels;
using System;
using System.Globalization;
using Xamarin.Forms;
namespace Alarms.Converters
{
/// <summary>
/// Class that converts AlarmInfo to description of alarm.
/// </summary>
public class AlarmInfoToDescriptionConverter : IValueConverter
{
#region methods
/// <summary>
/// Converts AlarmInfo to description of alarm.
/// </summary>
/// <param name="value">The value produced by the binding source.</param>
/// <param name="targetType">The type of the binding target property.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>String with description of alarm.</returns>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string retString = string.Empty;
if (value is AlarmInfoViewModel alarm)
{
retString = alarm.Date.Date == DateTime.Today
? alarm.Date.ToString("H:mm")
: alarm.Date.ToString("H:mm, d MMMM yyyy");
if (alarm.DaysFlags.IsAny())
{
retString += "\nrepeated every " + alarm.DaysFlags;
}
return retString;
}
return retString;
}
/// <summary>
/// Does nothing, but it must be defined, because it is in "IValueConverter" interface.
/// </summary>
/// <param name="value">The value produced by the binding source.</param>
/// <param name="targetType">The type of the binding target property.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>Converted value.</returns>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
/// <summary>
/// Private method which generates time period description from number of seconds.
/// </summary>
/// <param name="seconds">Number of seconds.</param>
/// <returns>Text describing number of minutes and seconds.</returns>
private string FormatSeconds(int seconds)
{
if (seconds >= 60)
{
string retVal = $"{seconds / 60} minutes";
if (seconds % 60 > 0)
{
retVal += $" and {seconds % 60} seconds";
}
return retVal;
}
else
{
return $"{seconds} seconds";
}
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace JJTrailerStore.Areas.Admin.Models
{
public class Order
{
//general
public Guid ID { get; set; }
public string InvoiceID { get; set; }
public Guid ShoppingCartID { get; set; }
public Guid PaymentID { get; set; }
public Guid ShippingID { get; set; }
public decimal OrderTotal { get; set; }
public bool Status { get; set; }
public string IPAddress { get; set; }
public string UserBrowser { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace affärslager
{
internal class ExpeditRepository
{
internal List<Expedit> expediter = new List<Expedit>();
internal void LäggTillExpedit(string anställningsNr, string anamn, string användarnamn, string lösen)
{
expediter.Add(new Expedit(anställningsNr, anamn, användarnamn, lösen));
}
internal void LaddaExpediter()
{
if(HämtaExpediter().Count() == 0)
{
LäggTillExpedit("1", "Lisa", "Lisa1", "Lisa1");
LäggTillExpedit("2", "Albert", "Albert2", "Albert2");
}
}
internal List<Expedit> HämtaExpediter()
{
return expediter;
}
internal bool LoggaInExpedit(string användarnamn, string lösen)
{
bool kontroll = false;
for(int i = 0; i < expediter.Count; i++)
{
kontroll = expediter[i].InloggsKontroll(användarnamn, lösen);
if(kontroll == true)
{
kontroll = true;
return kontroll;
}
}
return kontroll;
}
internal string HittaInloggadExpeditNR()
{
string expeditNr = null;
foreach (Expedit expedit in expediter)
{
if (expedit.Inloggad == true)
{
expeditNr = expedit.AnställningsNr;
}
}
return expeditNr;
}
internal void LoggaUtExpedit()
{
foreach (Expedit expedit in expediter)
{
if (expedit.Inloggad == true)
{
expedit.Inloggad = false;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using wcfLogistica;
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (Session["Usuario"] is Empleado)
{
lblMensaje.Text = ((Empleado)Session["Usuario"]).Logueo;
btnCambioContrasena.Visible = true;
}
else
{
btnCambioContrasena.Visible = false;
Response.Redirect("~/Login.aspx");
}
}
catch (Exception)
{
Response.Redirect("~/Login.aspx");
}
}
protected void btnLogout_Click(object sender, EventArgs e)
{
Session.Remove("Usuario");
Session.Remove("Mensaje");
Session.Remove("SolicitudesEmpresa");
Session.Remove("Paquetes");
Session.Remove("PaquetesSeleccionados");
lblMensaje.Text = "Usuario desconectado";
Response.Redirect("~/Default.aspx");
}
protected void btnCambioContrasena_Click(object sender, EventArgs e)
{
Response.Redirect("~/CambioContrasenaEmpleado.aspx");
}
}
|
using Player.Code;
using UnityEngine;
using UnityEngine.UI;
using Zenject;
namespace UI.PowerBar.Code
{
public class PowerBar : ITickable
{
private readonly PlayerFacade _playerFacade;
private readonly RestorePowerBar _restorePowerBar;
private readonly Slider _slider;
private PowerBar(
Slider slider,
PlayerFacade playerFacade,
RestorePowerBar restorePowerBar)
{
_slider = slider;
_playerFacade = playerFacade;
_restorePowerBar = restorePowerBar;
}
public bool IsGameRunning { get; set; }
public void Tick()
{
if (!_restorePowerBar.HasCompleted) return;
if (!IsGameRunning) return;
const float countDownSpeed = 0.01f;
_slider.value -= Time.deltaTime * countDownSpeed;
if (_slider.value <= 0) _playerFacade.Die();
}
// Fill Bar from 0 to 100% at beginning of a new level.
// When bar is full the game is ready to play.
// When player starts moving or does any input action
// the power bar start to gonna deplete.
// If power is depleted the hero dies.
// define Power Units
// define Maximum Power per level
}
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Crypto.Parameters;
using commercio.sdk;
using commercio.sacco.lib;
using KellermanSoftware.CompareNetObjects;
namespace sdk_test
{
[TestClass]
public class InviteUserHelper_Test
{
[TestMethod]
// '"fromWallet()" returns a well-formed "InviteUser" object.'
public void WellFormedInviteUserFromWallet()
{
//This is the comparison class
CompareLogic compareLogic = new CompareLogic();
NetworkInfo networkInfo = new NetworkInfo(bech32Hrp: "did:com:", lcdUrl: "");
String mnemonicString = "gorilla soldier device force cupboard transfer lake series cement another bachelor fatigue royal lens juice game sentence right invite trade perfect town heavy what";
List<String> mnemonic = new List<String>(mnemonicString.Split(" ", StringSplitOptions.RemoveEmptyEntries));
Wallet wallet = Wallet.derive(mnemonic, networkInfo);
String recipientDid = "did:com:id";
InviteUser expectedInviteUser = new InviteUser(recipientDid: recipientDid, senderDid: wallet.bech32Address);
InviteUser inviteUser = InviteUserHelper.fromWallet(wallet, recipientDid);
Assert.AreEqual(compareLogic.Compare(inviteUser.toJson(), expectedInviteUser.toJson()).AreEqual, true);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerRespawnKey : MonoBehaviour
{
[SerializeField] private Transform boxKey = null;
private ResetPosition playerCheckpoint;
void Start()
{
playerCheckpoint = GetComponent<ResetPosition>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.R))
boxKey.position = playerCheckpoint.getCheckpoint();
}
}
|
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using System.Collections.ObjectModel;
using WPF_Uebung.ViewModels;
using System;
using System.Windows.Threading;
using System.Threading;
namespace WPF_Uebung.ViewModel
{
/// <summary>
/// This class contains properties that the main View can data bind to.
/// <para>
/// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
/// </para>
/// <para>
/// You can also use Blend to data bind with the tool's support.
/// </para>
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
public class MainViewModel : ViewModelBase
{
private ObservableCollection<TruckVM> waitingTrucks = new ObservableCollection<TruckVM>();
private ObservableCollection<TruckVM> readyTrucks = new ObservableCollection<TruckVM>();
private TruckVM selectedWaitingTruck;
private TruckVM selectedReadyTruck;
private RelayCommand deleteBtnClicked;
private RelayCommand startGenerationBtnClicked;
private RelayCommand stopGenerationBtnClicked;
private RelayCommand shiftTruck;
private Server server;
public RelayCommand DeleteBtnClicked1
{
get
{
return deleteBtnClicked;
}
set
{
deleteBtnClicked = value;
}
}
public ObservableCollection<TruckVM> WaitingTrucks
{
get
{
return waitingTrucks;
}
set
{
waitingTrucks = value; RaisePropertyChanged();
}
}
public ObservableCollection<TruckVM> ReadyTrucks
{
get
{
return readyTrucks;
}
set
{
readyTrucks = value;
}
}
public RelayCommand StopGenerationBtnClicked
{
get
{
return stopGenerationBtnClicked;
}
set
{
stopGenerationBtnClicked = value;
}
}
public RelayCommand ShiftTruck
{
get
{
return shiftTruck;
}
set
{
shiftTruck = value;
}
}
public TruckVM SelectedReadyTruck
{
get
{
return selectedReadyTruck;
}
set
{
selectedReadyTruck = value; RaisePropertyChanged();
}
}
public RelayCommand StartGenerationBtnClicked
{
get
{
return startGenerationBtnClicked;
}
set
{
startGenerationBtnClicked = value;
}
}
public TruckVM SelectedWaitingTruck
{
get
{
return selectedWaitingTruck;
}
set
{
selectedWaitingTruck = value;
}
}
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
StartGenerationBtnClicked = new RelayCommand(StartGeneration);
stopGenerationBtnClicked = new RelayCommand(StopGeneration);
shiftTruck = new RelayCommand(Shift);
Data();
ThreadPool.QueueUserWorkItem(new WaitCallback((object o) =>
{
int thread2;
while (true)
{
thread2 = Thread.CurrentThread.ManagedThreadId;
Data();
Thread.Sleep(2000);
}
}));
}
private void Shift()
{
readyTrucks.Add(selectedWaitingTruck);
waitingTrucks.Remove(selectedWaitingTruck);
selectedWaitingTruck = null;
}
private void StopGeneration()
{
throw new NotImplementedException();
}
private void StartGeneration()
{
DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Interval = new TimeSpan(0, 0, 3);
Data();
}
private void ClearAllEntries()
{
waitingTrucks.Clear();
readyTrucks.Clear();
}
private void Data()
{
int t = Thread.CurrentThread.ManagedThreadId;
LoadVM loadtest = new LoadVM("test1", 2, 2);
LoadVM loadtest2 = new LoadVM("test2", 3, 3);
LoadVM loadtest3 = new LoadVM("test3", 4, 4);
ObservableCollection<LoadVM> loadlist = new ObservableCollection<LoadVM>();
loadlist.Add(loadtest);
loadlist.Add(loadtest2);
loadlist.Add(loadtest3);
waitingTrucks.Add(new TruckVM("DemoEntry1", 1, loadlist));
waitingTrucks.Add(new TruckVM("DemoEntry2", 3, loadlist));
waitingTrucks.Add(new TruckVM("DemoEntry2", 5, loadlist));
}
}
} |
namespace ReDefNet
{
/// <summary>
/// The initialization status of a component.
/// </summary>
public enum InitializationStatus
{
/// <summary>
/// The component is destroyed.
/// </summary>
Destroyed,
/// <summary>
/// The component is transitioning to the initialized state.
/// </summary>
Initializing,
/// <summary>
/// The component is initialized.
/// </summary>
Initialized,
/// <summary>
/// The component is transitioning to the destroyed state.
/// </summary>
Destroying
}
} |
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System.Web;
using System.Web.Routing;
using DotNetNuke.ComponentModel;
using DotNetNuke.Entities.Modules;
using DotNetNuke.UI.Modules;
namespace DotNetNuke.Web.Mvc.Routing
{
public abstract class ModuleRoutingProvider
{
public static ModuleRoutingProvider Instance()
{
var component = ComponentFactory.GetComponent<ModuleRoutingProvider>();
if (component == null)
{
component = new StandardModuleRoutingProvider();
ComponentFactory.RegisterComponentInstance<ModuleRoutingProvider>(component);
}
return component;
}
public abstract string GenerateUrl(RouteValueDictionary routeValues, ModuleInstanceContext moduleContext);
public abstract RouteData GetRouteData(HttpContextBase httpContext, ModuleControlInfo moduleControl);
}
}
|
using System;
namespace Liides1{
class Inimene{
protected int vanus;
public Inimene(int uvanus){
vanus=uvanus;
}
public virtual void YtleVanus(){
Console.WriteLine("Minu vanus on "+vanus+" aastat");
}
}
interface IViisakas{
void Tervita(String tuttav);
}
class Laps:Inimene, IViisakas {
public Laps(int vanus):base(vanus){}
public void Tervita(String tuttav){
Console.WriteLine("Tere, "+tuttav);
}
}
class Koer: IViisakas{
public void Tervita(String tuttav){
Console.WriteLine("Auh!");
}
}
class InimTest{
static void TuleSynnipaevale(IViisakas v){
v.Tervita("vanaema");
}
public static void Main(string[] arg){
Laps juku=new Laps(6);
juku.YtleVanus();
Koer muki=new Koer();
TuleSynnipaevale(juku);
TuleSynnipaevale(muki);
}
}
}
//* Katseta, mis juhtub, kui Lapse tervita kirjutada väikese tähega. - ei tööta, Laps does not implement interface member |
using OmniSharp.Extensions.JsonRpc;
namespace OmniSharp.Extensions.LanguageServer.Protocol.Client
{
public interface ILanguageClientRegistry : IJsonRpcHandlerRegistry<ILanguageClientRegistry>
{
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using CloneDeploy_ApiCalls;
using CloneDeploy_Common;
using CloneDeploy_Entities;
using log4net;
using Newtonsoft.Json;
namespace CloneDeploy_Services
{
public class OnlineKernelServices
{
private readonly ILog log = LogManager.GetLogger(typeof(OnlineKernelServices));
public bool DownloadKernel(OnlineKernel onlineKernel)
{
if (SettingServices.ServerIsClusterPrimary)
{
foreach (var tftpServer in new SecondaryServerServices().GetAllWithTftpRole())
{
var result = new APICall(new SecondaryServerServices().GetToken(tftpServer.Name))
.ServiceAccountApi.DownloadOnlineKernel(onlineKernel);
if (!result)
return false;
}
}
return WebDownload(onlineKernel);
}
public List<OnlineKernel> GetAllOnlineKernels()
{
var wc = new WebClient();
try
{
var data = wc.DownloadData("http://files.clonedeploy.org/kernels/kernels.json");
var text = Encoding.UTF8.GetString(data);
return JsonConvert.DeserializeObject<List<OnlineKernel>>(text);
}
catch (Exception ex)
{
log.Error(ex.Message);
return null;
}
}
private bool WebDownload(OnlineKernel onlineKernel)
{
var baseUrl = "http://files.clonedeploy.org/kernels/";
using (var wc = new WebClient())
{
try
{
wc.DownloadFile(new Uri(baseUrl + onlineKernel.BaseVersion + "/" + onlineKernel.FileName),
SettingServices.GetSettingValue(SettingStrings.TftpPath) + "kernels" +
Path.DirectorySeparatorChar + onlineKernel.FileName);
return true;
}
catch (Exception ex)
{
log.Error(ex.Message);
return false;
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using StructureMap;
using PESWeb.UserControls.Interfaces;
using Pes.Core;
namespace PESWeb.UserControls.Presenters
{
public class ProfileDisplayPresenter
{
private IProfileDisplay _view;
private IRedirector _redirector;
private IUserSession _userSession;
public ProfileDisplayPresenter()
{
_redirector = ObjectFactory.GetInstance<IRedirector>();
_userSession = ObjectFactory.GetInstance<IUserSession>();
}
public void Init(IProfileDisplay view)
{
_view = view;
}
public void SendFriendRequest(Int32 AccountIdToInvite)
{
_redirector.GoToFriendsInviteFriends(AccountIdToInvite);
}
public void DeleteFriend(Int32 FriendID)
{
if (_userSession.CurrentUser != null)
{
Friend.DeleteFriendByID(_userSession.CurrentUser.AccountID, FriendID);
HttpContext.Current.Response.Redirect(HttpContext.Current.Request.RawUrl);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net;
using System.ServiceModel.Syndication;
using System.Threading.Tasks;
using System.Linq;
using System.Xml;
using Reading_RSS_feed.Models;
using Quartz;
using System.Configuration;
using Quartz.Impl;
namespace Reading_RSS_feed
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Service start. Time: {0}", DateTime.Now.ToString("HH:mm:ss"));
IJobDetail parseJobDetail = JobBuilder.Create<ParseJob>()
.WithIdentity("ParserJob")
.Build();
ITrigger parseTrigger = TriggerBuilder.Create()
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInMinutes(1)
.RepeatForever())
.Build();
IScheduler scheduler = new StdSchedulerFactory().GetScheduler().Result;
scheduler.ScheduleJob(parseJobDetail, parseTrigger);
scheduler.Start();
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace CoreApi.Model
{
[Table("Class")]
public class ClassInfo
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Required, StringLength(32)]
public string Name { get; set; }
[Required, Column("CTime")]
public DateTime CreateTime { get; set; }
[Column(TypeName = "ntext"), MaxLength(20), MinLength(10)]
public string Remark { get; set; }
[NotMapped]
public string NotNeed { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data;
using MySql.Web;
using MySql.Data.MySqlClient;
namespace ProjectMFS
{
public partial class Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (((SiteMaster)this.Master).IsLoggedIn)//Permissions
{
this.LoginPanel.Visible = false;
//Permissions
if (((SiteMaster)this.Master).UserLevel <= 5)
{
this.MainPanel.Visible = true;
}
}
MySqlConnection mycon = new MySql.Data.MySqlClient.MySqlConnection(ConfigurationManager.ConnectionStrings["mfs"].ToString());
mycon.Open();
MySql.Data.MySqlClient.MySqlCommand mycmd = new MySql.Data.MySqlClient.MySqlCommand("SELECT * FROM projectmfs.participant", mycon);
string outstr = "";
using(MySql.Data.MySqlClient.MySqlDataReader reader = mycmd.ExecuteReader())
{
while(reader.Read())
{
outstr += reader.GetValue(0).ToString() + reader.ToString() + "<br />";
}
reader.Close();
}
mycon.Close();
}
protected void Search_Click(object sender, EventArgs e)
{
//MainDataGrid.DataBind();
}
protected void MainGridViewButton_Click(object source, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
// Add logic for addition operation here.
}
else if (e.CommandName == "Edit")
{
}
}
}
} |
using System;
namespace Covid_19_Arkanoid.Controlador
{
public class EnterKeyPressException : Exception
{
public EnterKeyPressException(string message) : base(message)
{
}
}
} |
using Checkout.Payment.Query.Seedwork.Models;
using System.Collections.Generic;
namespace Checkout.Payment.Query.Seedwork.Interfaces
{
public interface IDomainNotification
{
void Publish(IDomainNotificationEvent @event);
void PublishBusinessViolation(string message);
void PublishError(string message);
public bool HasNotificationType(DomainNotificationType type);
public IEnumerable<IDomainNotificationEvent> GetNotifications(DomainNotificationType type);
void PublishNotFound(string message);
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Geometry
{
class Square
{
private string name;
private double a, b, c, d;
public string Name { get { return name; } set { name = value; } }
public double A { get { return a; } set { a = value; } }
public double B { get { return b; } set { b = value; } }
public double C { get { return c; } set { c = value; } }
public double D { get { return d; } set { d = value; } }
public Square() { }
public Square(string nameForFigure, double aSide)//A constructor, that is needed a value, before creation
{
name = nameForFigure;
a = aSide;
b = aSide;
c = aSide;
d = aSide;
}
public double Circumference()//returns the Circumference value
{
return a + b + c + d;
}
public double AreaForSquare()//returns the Area value
{
return Math.Pow(a, 2);
}
}
}
|
using System;
namespace pt.it4noobs.local.Database.UoW.Implementation.Helpers
{
public static class TryParseExtensions
{
private static readonly TimeZoneInfo DatabaseTimeZone = TimeZoneInfo.Local;
public static int TryParseToInt(this object obj)
{
var res = default(int);
if (obj == null) return res;
int.TryParse(obj.ToString(), out res);
return res;
}
public static decimal TryParseToDecimal(this object obj)
{
var res = default(decimal);
if (obj == null) return res;
decimal.TryParse(obj.ToString(), out res);
return res;
}
public static DateTime TryParseToDateTime(this object obj)
{
var res = default(DateTime);
if (obj == null) return res;
DateTime.TryParse(obj.ToString(), out res);
return res;
}
public static DateTimeOffset ParseDateTimeAdjustedWithDefaultOffset(this object obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
var result = DateTime.Parse(obj.ToString());
return new DateTimeOffset(result, DatabaseTimeZone.GetUtcOffset(result));
}
public static bool TryParseActiveInactiveToBoolean(this string strValue)
{
return strValue == "ACTIVO";
}
}
}
|
using aima.core.agent;
using aima.core.environment.eightpuzzle;
using aima.core.search.framework;
using aima.core.search.framework.problem;
using aima.core.search.framework.qsearch;
using System;
using System.Collections;
using System.Collections.Generic;
namespace lab4
{
class Program
{
//static int[] state = new int[] { 4, 1, 3, 7, 2, 6, 0, 5, 8 };
static int[] state = new int[] { 1, 2, 3, 4, 5, 6, 0, 7, 8 };
static EightPuzzleBoard board = new EightPuzzleBoard(state);
static void Main(string[] args)
{
Console.WriteLine("Initial:");
Console.WriteLine("{0} {1} {2}\n{3} {4} {5}\n{6} {7} {8}", state[0], state[1], state[2], state[3], state[4], state[5], state[6], state[7], state[8]);
Console.WriteLine("----");
search(board);
Console.WriteLine("Press any key");
Console.ReadKey();
}
private static void search(EightPuzzleBoard init)
{
Problem problem = new Problem(board, EightPuzzleFunctionFactory
.getActionsFunction(), EightPuzzleFunctionFactory
.getResultFunction(), new MyGoalTest());
Search search = new BreadthFirstSearch(new GraphSearch());
SearchAgent agent = new SearchAgent(problem, search);
printActions(agent.getActions());
printInstrumentation(agent.getInstrumentation());
}
private static void printInstrumentation(Dictionary<string, string> dictionary)
{
foreach (var value in dictionary)
{
Console.WriteLine(value.ToString());
}
}
private static void printActions(List<aima.core.agent.Action> list)
{
for (int i = 0; i < list.Count; i++)
{
var action = list[i].ToString();
Console.WriteLine(action);
}
}
}
}
|
using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Net.Mail;
using Obout.Interface;
using Obout.Ajax.UI.HTMLEditor;
using Obout.Ajax.UI.HTMLEditor.ToolbarButton;
using HSoft.SQL;
using HSoft.ClientManager.Web;
public partial class EmailIndividialLead : System.Web.UI.Page
{
public static DataRow _dr = null;
public static DataRow _de = null;
protected void Page_Load(object sender, EventArgs e)
{
//Page.UICulture = "en";
//Page.UICulture = "auto";
if (!Page.IsPostBack)
{
Tools.devlogincheat();
String sId = "0208773E-F9DF-456B-B0FA-00181B862E0F";
if (!String.IsNullOrEmpty(Request.QueryString["Id"])) { sId = Request.QueryString["Id"]; }
String ssql = String.Empty;
HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString);
ssql = String.Format("SELECT * FROM Lead_Flat WHERE Id = '{0}' AND isdeleted = 0", sId);
_dr = _sql.GetRow(ssql);
ssql = String.Format("SELECT * FROM Employee WHERE Id = '{0}' AND isdeleted = 0", Session["guser"]);
_de = _sql.GetRow(ssql);
_sql.Close();
String scontent = String.Format("Dear {0}" +
"<br/><br/><br/><br/>" +
"regards <a href='mailto:{2}@uncleharry.com?Uncleharry Sales' target='_top'>{1}</a> ", _dr["Name"], _de["DisplayName"], _de["EmailName"]);
editor.EditPanel.Content = scontent;
subject.Text = "Uncleharry Sales";
}
}
protected void Submit_click(object sender, EventArgs e)
{
// ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditorResponse", "alert('Submitted:\\n\\n" + editor.EditPanel.Content.Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'") + "');", true);
MailAddress _smtpfrom = new MailAddress("emailer@uncleharry.biz", "Sales Uncleharry");
MailAddress _from = new MailAddress(String.Format("{0}@uncleharry.biz", _de["EmailName"]), _de["DisplayName"].ToString());
MailAddress _to = new MailAddress(_dr["Email"].ToString(), _dr["Name"].ToString());
// MailAddress _to = new MailAddress("rene.hugentobler@gmail.com", _dr["Name"].ToString());
// MailAddress _to = new MailAddress("harry@rakerappliancerepair.com", _dr["Name"].ToString());
// Tools.sendMail(from, to, subject.Text, editor.EditPanel.Content, true);
Tools.sendMail(_smtpfrom, @"Taurec86@", _from, _to, subject.Text, editor.EditPanel.Content, true);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditorResponse2", "window.close();", true);
}
protected void Close_click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditorResponse", "window.close();", true);
}
}
/*
DataRow _dr = null;
DataRow _de = null;
OboutTextBox tbSubject = new OboutTextBox();
protected void Page_Load(object sender, EventArgs e)
{
Tools.devlogincheat();
if (!Page.IsPostBack)
{
String sId = "0208773E-F9DF-456B-B0FA-00181B862E0F";
if (!String.IsNullOrEmpty(Request.QueryString["Id"])) { sId = Request.QueryString["Id"]; }
String ssql = String.Empty;
HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString);
ssql = String.Format("SELECT * FROM Lead_Flat WHERE Id = '{0}' AND isdeleted = 0", sId);
_dr = _sql.GetRow(ssql);
ssql = String.Format("SELECT * FROM Employee WHERE Id = '{0}' AND isdeleted = 0", Session["guser"]);
_de = _sql.GetRow(ssql);
String scontent = String.Format("Dear {0}" +
"<br/><br/><br/><br/>" +
"regards <a href='mailto:{2}@uncleharry.com?Uncleharry Sales' target='_top'>{1}</a> ", _dr["Name"],_de["DisplayName"], _de["EmailName"]);
editor.EditPanel.Content = scontent;
_sql.Close();
}
tbSubject.ID = "subject";
tbSubject.Width = Unit.Pixel(400);
tbSubject.AutoCompleteType = AutoCompleteType.None;
// tbSubject.FolderStyle = "styles/premiere_blue/interface/OboutTextBox";
Subject.Controls.Add(tbSubject);
}
protected void Editable_click(object sender, EventArgs e)
{
editor.Enabled = !editor.Enabled;
Submit.Enabled = editor.Enabled;
}
protected void Submit_click(object sender, EventArgs e)
{
// ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditorResponse", "alert('Submitted:\\n\\n" + editor.EditPanel.Content.Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'") + "');", true);
MailAddress from = new MailAddress(String.Format("{0}@uncleharry.biz", _de["EmailName"]), _de["DisplayName"].ToString());
// MailAddress to = new MailAddress(_dr["Email"].ToString(), _de["Name"].ToString());
MailAddress to = new MailAddress("rene.hugentobler@gmail.com", _de["Name"].ToString());
Tools.sendMail(from, to, tbSubject.Text, editor.EditPanel.Content, true);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditorResponse2", "window.close();", true);
}
protected void Close_click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditorResponse", "window.close();", true);
}
}
*/ |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ISP._2_after
{
interface IProduct
{
decimal Price { get; set; }
int Stock { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : AttachableObject, IDamageable
{
const float LIFETIME = 500f;
[SerializeField]
public float lifetime;
[SerializeField]
private int hitpoint = 100;
public int Hitpoint { get; set; }
private bool IsDead;
private Rigidbody2D rigidbody;
[SerializeField]
private float torqueSpeed = 10f;
[SerializeField]
private float jumpForce = 800f;
[SerializeField]
private Image lifeImage;
private float turn;
private bool isFacingRight = true;
private const int MAX_GROUNED_COLLIDER_CHECK = 20;
private Collider2D[] colliders = new Collider2D[20];
private bool isAirSpinning = false;
[SerializeField]
private float airSpinningSpeed = 100f;
//[SerializeField]
//private float airSpinningDuration = 1.5f;
void Start() {
rigidbody = GetComponent<Rigidbody2D>();
colliders = new Collider2D[MAX_GROUNED_COLLIDER_CHECK];
lifetime = LIFETIME;
}
void Update() {
UpdateHorizontalMove();
UpdateJumpState();
UpdateLifetime();
UpdateAirSpinning();
}
void FixedUpdate() {
if (IsGrounded()) {
rigidbody.AddTorque(torqueSpeed * turn * -1 * GameManager.GetInstance().GetSpeedMultipier());
}
if (isAirSpinning) {
//rigidbody.AddTorque(torqueFastSpeed * turn * -1 * GameManager.GetInstance().GetSpeedMultipier());
if (isFacingRight) {
transform.Rotate(0, 0, -airSpinningSpeed);
} else {
transform.Rotate(0, 0, airSpinningSpeed);
}
}
}
void UpdateAirSpinning() {
//if (Input.GetKeyDown(KeyCode.Q) && !IsGrounded() && !isAirSpinning) {
// isAirSpinning = true;
// StartCoroutine(AirSpin());
//}
if (Input.GetKeyDown(KeyCode.Q) && !IsGrounded()) {
isAirSpinning = true;
}
}
//IEnumerator AirSpin() {
// yield return new WaitForSeconds(airSpinningDuration);
// isAirSpinning = false;
//}
bool IsGrounded() {
int groundLayer = 8;
colliders = new Collider2D[MAX_GROUNED_COLLIDER_CHECK];
PhysicsScene2D.OverlapCollider(GetComponent<Collider2D>(), colliders, Physics2D.DefaultRaycastLayers);
for (int i = 0; i < colliders.Length; i++) {
if (colliders[i]) {
if (colliders[i].gameObject.layer.Equals(groundLayer)) {
isAirSpinning = false;
return true;
}
}
}
return false;
}
void UpdateHorizontalMove() {
if (IsGrounded()) {
float newHorizontal = Input.GetAxis("Horizontal");
if (newHorizontal > 0 && !isFacingRight) {
ChangeMoveDirection();
} else if (newHorizontal < 0 && isFacingRight) {
ChangeMoveDirection();
}
turn = newHorizontal;
}
}
void ChangeMoveDirection() {
rigidbody.velocity = new Vector2(0f, 0f);
rigidbody.angularVelocity = 0f;
isFacingRight = !isFacingRight;
}
void UpdateJumpState() {
if (Input.GetButtonDown("Jump") && IsGrounded()) {
GameObject planet = GameManager.GetInstance().GetPlanet();
Vector3 jumpDirection = new Vector2((transform.position.x - planet.transform.position.x), (transform.position.y - planet.transform.position.y));
rigidbody.AddForce(jumpDirection * jumpForce);
}
}
void UpdateLifetime() {
if (attachers.Count > 0) return;
lifetime -= Time.deltaTime;
float frac = lifetime / LIFETIME;
lifeImage.fillAmount = frac;
lifeImage.color = new Color(1f - frac, (frac) + 0f * (1f - frac), (frac) + 0f * (1f - frac));
if (lifetime <= 0f) {
Dead();
}
}
public int Hit(int damage) {
// int remainingHP = this.hitpoint - damage;
// this.hitpoint = remainingHP;
// if (remainingHP <= 0)
// {
if (attachers.Count > 0) {
float minLifetime = float.MaxValue;
Attacher oldestAttacher = null;
foreach (var item in attachers) {
GameObject obj = item.Key;
Attacher attacher = obj.GetComponent<Attacher>();
if (attacher.lifetime < minLifetime) {
minLifetime = attacher.lifetime;
oldestAttacher = attacher;
}
}
if (oldestAttacher != null) {
oldestAttacher.Detach();
}
return 1;
}
this.Dead();
return 0;
// }
// return remainingHP;
}
public void Dead() {
if (!IsDead) {
IsDead = true;
GameManager.GetInstance().DoPlayerDead();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace PO.DataService
{
// ConnectionStringlerin tutulma yerine, Db authentication yontemine gore degisebilir.
// Varsayilan => config file da connection string elemanında bulunan PersonelOrganizerDB key'i.
public class PODataObjectFactory
{
private static string mDefaultConnectionString;
static PODataObjectFactory()
{
mDefaultConnectionString = ConfigurationManager.ConnectionStrings["PersonelOrganizerDB"].ConnectionString;
}
public static IPODataObject GetDataObject(string pDefaultDB, bool pIsTransactional)
{
IPODataObject oDataObject = null;
oDataObject = new PODataObject(mDefaultConnectionString, pDefaultDB , pIsTransactional);
return oDataObject;
}
public static IPODataObject GetAnotherDataObject(string pConnectionStringName, string pDefaultDB, bool pIsTransactional)
{
string connectionString = ConfigurationManager.ConnectionStrings[pConnectionStringName].ConnectionString;
IPODataObject oDataObject = null;
oDataObject = new PODataObject(connectionString, pDefaultDB, pIsTransactional);
return oDataObject;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.