private static void Main(string[] args) { if (args.Length < 1) { return; } var logger = LogUtil.GetLogger(); var exceptionHelper = new ExceptionHelper(logger, false, true); AppDomain.CurrentDomain.UnhandledException += exceptionHelper.UnhandledExceptionHandler; Application.ThreadException += exceptionHelper.UnhandledThreadExceptionHandler; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var svcName = args[0]; var service = GetService(svcName, logger); if (service == null) { logger.Warn("Invalid service name: " + svcName); return; } // Get arguments and ignore the first argument string[] svcArgs = new string[args.Length - 1]; for (int i = 1; i < args.Length; i++) { svcArgs[i - 1] = args[i]; } service.Logger = logger; service.Initialize(); service.RunService(svcArgs); }
public ChildActionExceptionFilter(ILog log, ExceptionHelper helper) { Ensure.That(() => log).IsNotNull(); Ensure.That(() => helper).IsNotNull(); this.log = log; this.helper = helper; }
public void TestMethod1() { var logger = LogUtil.GetLogger("Test"); var target = new ExceptionHelper(logger, true, false); Application.ThreadException += target.UnhandledThreadExceptionHandler; AppDomain.CurrentDomain.UnhandledException += target.UnhandledExceptionHandler; throw new ApplicationException("TEST"); }
public LocalizedArgumentOutOfRangeException(string argument, object min, object max, string key = "Exceptions.ArgumentOutOfRangeException", string defaultMessage = null, object parameters = null, Exception innerException = null) : base(defaultMessage, innerException) { if (defaultMessage == null) { defaultMessage = "Value must be in the range {0} to {1}"; } Localization = new ExceptionHelper(this, key, defaultMessage, parameters); Localization.AddParameter("Minimum", min).AddParameter("Maximum", max); }
public ChildActionExceptionFilter(ILog log, ExceptionHelper helper) { if (log == null) { throw new ArgumentNullException("log"); } if (helper == null) { throw new ArgumentNullException("helper"); } this.log = log; this.helper = helper; }
public HttpApplicationErrorHander(HttpApplication application, ExceptionHelper helper) { if (application == null) { throw new ArgumentNullException("application"); } if (helper == null) { throw new ArgumentNullException("helper"); } this.application = application; this.helper = helper; }
private static void Main(string[] args) { AppUtil.NameCurrentThread(string.Format("{0}_{1}_{2}_Main", AppUtil.CompanyName, AppUtil.ProductName, AppUtil.ProductVersion)); var logger = LogUtil.GetLogger(); var exceptionHelper = new ExceptionHelper(logger, true, false); Application.ThreadException += exceptionHelper.UnhandledThreadExceptionHandler; AppDomain.CurrentDomain.UnhandledException += exceptionHelper.UnhandledExceptionHandler; AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var bootStrap = new BootStrap(logger); bootStrap.Run(args); }
public override StreamUpgradeInitiator CreateUpgradeInitiator(EndpointAddress remoteAddress, Uri via) { throw ExceptionHelper.PlatformNotSupported("WindowsStreamSecurityUpgradeProvider.CreateUpgradeInitiator is not supported."); }
public B_TargetPlanAction GetTargetPlanAction(Guid bTargetPlanActionID) { ExceptionHelper.TrueThrow <ArgumentNullException>(bTargetPlanActionID == null, "Argument bTargetPlanActionID is Empty"); return(base.GetModelObject(bTargetPlanActionID)); }
public FacilityException(string message) : base(message) { ExceptionHelper.SetUp(this); }
public FacilityException(SerializationInfo info, StreamingContext context) : base(info, context) { ExceptionHelper.SetUp(this); }
/// <summary> /// Converts to database value. If value is null convert it to DBNull.Value or if property is decorated with a serializable attribute /// then convert the value to its serialize self /// </summary> /// <param name="member">The member.</param> /// <param name="value">The value.</param> /// <param name="csvSerializer"></param> /// <param name="xmlSerializer"></param> /// <returns>System.Object.</returns> public object ConvertToDatabaseValue(MemberWrapper member, object value, Func <object, string> xmlSerializer, Func <object, string> jsonSerializer, Func <object, string> csvSerializer) { if (value == null) { return(DBNull.Value); } //if (member.Type == typeof(DateTime) && (DateTime)value == DateTime.MinValue || member.Type == typeof(DateTime?) && (DateTime)value == DateTime.MinValue) //{ // if(DatabaseType == DataBaseType.SqlServer) // return new DateTime(1753, 01, 01); //} if (member.GetCustomAttribute <SqlColumnAttribute>()?.SerializableType != SerializableType.None) { switch (member.GetCustomAttribute <SqlColumnAttribute>()?.SerializableType) { case SerializableType.Xml: xmlSerializer.IsNullThrow(nameof(xmlSerializer), new ArgumentNullException(nameof(xmlSerializer), $"{ExceptionHelper.NullSerializer(member, SerializableType.Xml)}")); return(xmlSerializer.Invoke(value)); case SerializableType.Json: jsonSerializer.IsNullThrow(nameof(jsonSerializer), new ArgumentNullException(nameof(jsonSerializer), $"{ExceptionHelper.NullSerializer(member, SerializableType.Json)}")); return(jsonSerializer.Invoke(value)); case SerializableType.Csv: csvSerializer.IsNullThrow(nameof(csvSerializer), new ArgumentNullException(nameof(csvSerializer), $"{ExceptionHelper.NullSerializer(member, SerializableType.Csv)}")); return(csvSerializer.Invoke(value)); case SerializableType.None: case null: break; default: throw new ArgumentOutOfRangeException(); } } return(value); }
public override JSValue Evaluate(Context context) { var temp = _left.Evaluate(context); JSValue targetObject = context._objectSource; ICallable callable = null; Function func = null; if (temp._valueType >= JSValueType.Object) { if (temp._valueType == JSValueType.Function) { func = temp._oValue as Function; callable = func; } if (func == null) { callable = temp._oValue as ICallable ?? temp.Value as ICallable; if (callable == null) { if (temp.Value is Proxy typeProxy) { callable = typeProxy.PrototypeInstance as ICallable; } } } } if (callable == null) { for (int i = 0; i < Arguments.Length; i++) { context._objectSource = null; Arguments[i].Evaluate(context); } context._objectSource = null; // Аргументы должны быть вычислены даже если функция не существует. ExceptionHelper.ThrowTypeError(_left + " is not a function"); return(null); } if (func == null) { checkStack(); Context.CurrentGlobalContext._callDepth++; try { switch (_callMode) { case CallMode.Construct: { return(callable.Construct(Tools.CreateArguments(Arguments, context))); } case CallMode.Super: { return(callable.Construct(targetObject, Tools.CreateArguments(Arguments, context))); } default: return(callable.Call(targetObject, Tools.CreateArguments(Arguments, context))); } } finally { Context.CurrentGlobalContext._callDepth--; } } if (allowTCO && _callMode == 0 && (func.FunctionDefinition.Kind != FunctionKind.Generator) && (func.FunctionDefinition.Kind != FunctionKind.MethodGenerator) && (func.FunctionDefinition.Kind != FunctionKind.AnonymousGenerator) && context._owner != null && func == context._owner._oValue) { tailCall(context, func); context._objectSource = targetObject; return(JSValue.undefined); } context._objectSource = null; checkStack(); Context.CurrentGlobalContext._callDepth++; try { if (_callMode == CallMode.Construct) { targetObject = null; } if ((temp._attributes & JsValueAttributesInternal.Eval) != 0) { return(callEval(context)); } return(func.InternalInvoke(targetObject, Arguments, context, withSpread, _callMode != 0)); } finally { Context.CurrentGlobalContext._callDepth--; } }
/// <summary> /// Suggests the CLR equivalent of the given type. /// </summary> /// <param name="dbType"></param> /// <returns></returns> public static object GetClrLegalDBNullEquivalent(DbType dbType) { switch (dbType) { case DbType.Object: case DbType.Guid: return(null); case DbType.Boolean: return(false); case DbType.Byte: return(byte.MinValue); case DbType.SByte: return((sbyte)0); case DbType.Int16: return((short)0); case DbType.Int32: return((int)0); case DbType.Int64: return((long)0); case DbType.Single: return((float)0); case DbType.Double: return((double)0); case DbType.UInt16: return(ushort.MinValue); case DbType.UInt32: return(uint.MinValue); case DbType.UInt64: return(ulong.MinValue); case DbType.Currency: case DbType.VarNumeric: case DbType.Decimal: return((decimal)0); case DbType.String: case DbType.StringFixedLength: case DbType.AnsiString: case DbType.AnsiStringFixedLength: case DbType.Binary: return(null); case DbType.Date: case DbType.Time: case DbType.DateTime: return(DateTime.MinValue); default: throw ExceptionHelper.CreateCannotHandleException(dbType); } }
internal unsafe void Read(Stream stream) { // For the complete documentation for this section see: // http://tools.ietf.org/html/rfc6455#section-5.2 this.Header = ReadByte(stream); // The first byte is the Final Bit and the type of the frame IsFinal = (this.Header & 0x80) != 0; Type = (WebSocketFrameTypes)(this.Header & 0xF); byte maskAndLength = ReadByte(stream); // The second byte is the Mask Bit and the length of the payload data HasMask = (maskAndLength & 0x80) != 0; // if 0-125, that is the payload length. Length = (UInt64)(maskAndLength & 127); // If 126, the following 2 bytes interpreted as a 16-bit unsigned integer are the payload length. if (Length == 126) { byte[] rawLen = BufferPool.Get(2, true); stream.ReadBuffer(rawLen, 2); if (BitConverter.IsLittleEndian) { Array.Reverse(rawLen, 0, 2); } Length = (UInt64)BitConverter.ToUInt16(rawLen, 0); BufferPool.Release(rawLen); } else if (Length == 127) { // If 127, the following 8 bytes interpreted as a 64-bit unsigned integer (the // most significant bit MUST be 0) are the payload length. byte[] rawLen = BufferPool.Get(8, true); stream.ReadBuffer(rawLen, 8); if (BitConverter.IsLittleEndian) { Array.Reverse(rawLen, 0, 8); } Length = (UInt64)BitConverter.ToUInt64(rawLen, 0); BufferPool.Release(rawLen); } // The sent byte array as a mask to decode the data. byte[] mask = null; // Read the Mask, if has any if (HasMask) { mask = BufferPool.Get(4, true); if (stream.Read(mask, 0, 4) < mask.Length) { throw ExceptionHelper.ServerClosedTCPStream(); } } if (Type == WebSocketFrameTypes.Text || Type == WebSocketFrameTypes.Continuation) { Data = BufferPool.Get((long)Length, true); } else if (Length == 0) { Data = BufferPool.NoData; } else { Data = new byte[Length]; } //Data = Type == WebSocketFrameTypes.Text ? VariableSizedBufferPool.Get((long)Length, true) : new byte[Length]; if (Length == 0L) { return; } uint readLength = 0; do { int read = stream.Read(Data, (int)readLength, (int)(Length - readLength)); if (read <= 0) { throw ExceptionHelper.ServerClosedTCPStream(); } readLength += (uint)read; } while (readLength < Length); if (HasMask) { fixed(byte *pData = Data, pmask = mask) { // Here, instead of byte by byte, we reinterpret cast the data as uints and apply the masking so. // This way, we can mask 4 bytes in one cycle, instead of just 1 ulong localLength = this.Length / 4; if (localLength > 0) { uint *upData = (uint *)pData; uint umask = *(uint *)pmask; unchecked { for (ulong i = 0; i < localLength; ++i) { upData[i] = upData[i] ^ umask; } } } // Because data might not be exactly dividable by 4, we have to mask the remaining 0..3 too. ulong from = localLength * 4; localLength = from + this.Length % 4; for (ulong i = from; i < localLength; ++i) { pData[i] = (byte)(pData[i] ^ pmask[i % 4]); } } BufferPool.Release(mask); } }
public LocalizedFileNotFoundException(string filename, string key = "Exceptions.FileNotFoundException", string defaultMessage = null, object parameters = null, Exception innerException = null) : base(defaultMessage, innerException) { Localization = new ExceptionHelper(this, key, defaultMessage, parameters); Localization.AddParameter("FileName", filename); }
/// <summary> /// Gets the <c>DbType</c> for the given CLR type. /// </summary> /// <param name="type"></param> /// <returns></returns> public static Type GetClrTypeForDBType(DbType type) { switch (type) { case DbType.Object: return(typeof(object)); case DbType.Byte: return(typeof(byte)); case DbType.SByte: return(typeof(sbyte)); case DbType.Boolean: return(typeof(bool)); case DbType.Int16: return(typeof(short)); case DbType.Int32: return(typeof(int)); case DbType.Int64: return(typeof(long)); case DbType.UInt16: return(typeof(ushort)); case DbType.UInt32: return(typeof(uint)); case DbType.UInt64: return(typeof(ulong)); case DbType.Single: return(typeof(float)); case DbType.Double: return(typeof(double)); case DbType.Decimal: case DbType.Currency: case DbType.VarNumeric: return(typeof(decimal)); case DbType.AnsiString: case DbType.String: case DbType.AnsiStringFixedLength: case DbType.StringFixedLength: return(typeof(string)); case DbType.Date: case DbType.Time: case DbType.DateTime: return(typeof(DateTime)); case DbType.Binary: return(typeof(byte[])); case DbType.Guid: return(typeof(Guid)); default: throw ExceptionHelper.CreateCannotHandleException(type); } }
public S_InterfaceInstance GetInterfaceinstance(Guid sInterfaceinstanceID) { ExceptionHelper.TrueThrow <ArgumentNullException>(sInterfaceinstanceID == null, "Argument sInterfaceinstanceID is Empty"); return(base.GetModelObject(sInterfaceinstanceID)); }
protected void upload_Click(object sender, EventArgs e) { if (fileread.HasFile) { try { if (fileread.PostedFile.ContentType == "text/plain") { if (fileread.PostedFile.ContentLength < 512000) { string filename = Path.GetFileName(fileread.FileName); } } //process file Stream fileStream = fileread.PostedFile.InputStream; using (StreamReader fsr = new StreamReader(fileStream)) { ArrayList stockItems = new ArrayList(); string line; while ((line = fsr.ReadLine()) != null) { string[] tmpArray = line.Split(Convert.ToChar(",")); StockItem stockItem = new StockItem(tmpArray[0], tmpArray[1], tmpArray[2], tmpArray[3]); stockItems.Add(stockItem); } lblStockItemsCount.Text = stockItems.Count.ToString(); IFormatter formatterSerialize = new BinaryFormatter(); Stream streamSerialize = new FileStream(Server.MapPath("stockItems.xml"), FileMode.Create, FileAccess.Write, FileShare.None); formatterSerialize.Serialize(streamSerialize, stockItems); streamSerialize.Close(); TableRow trow; TableCell tcellStockItemName, tcellSupplierName, tcellPackageType, tcellUnitPrice; foreach (StockItem item in stockItems) { trow = new TableRow(); tcellStockItemName = new TableCell(); tcellStockItemName.Controls.Add(RenderTextBox("StockItemName" + item.StockItemName.ToString(), item.StockItemName)); tcellSupplierName = new TableCell(); tcellSupplierName.Controls.Add(RenderTextBox("SupplierName" + item.SupplierName.ToString(), item.SupplierName)); tcellPackageType = new TableCell(); tcellPackageType.Controls.Add(RenderTextBoxSmall("PackageTypeName" + item.UnitPackage.ToString(), item.UnitPackage)); tcellUnitPrice = new TableCell(); tcellUnitPrice.Controls.Add(RenderTextBoxSmall("UnitPrice" + item.UnitPrice.ToString(), item.UnitPrice)); trow.Cells.Add(tcellStockItemName); trow.Cells.Add(tcellSupplierName); trow.Cells.Add(tcellPackageType); trow.Cells.Add(tcellUnitPrice); tblStoskItem.Rows.Add(trow); } //Session.Clear(); //Response.Redirect("EditDataBeforSave.aspx"); } } catch (FileNotFoundException ex) { Label1.Text = ExceptionHelper.GetFileNotFoundExplanation(ex); } catch (SerializationException ex) { Label1.Text = ExceptionHelper.GetSerializationExplanation(ex); } catch (IOException ex) { Label1.Text = ExceptionHelper.GetFileReadExplanation(ex); } catch (Exception ex) { // something else went wrong } } }
private JsValue ToPrecision(JsValue thisObj, JsValue[] arguments) { if (!thisObj.IsNumber() && ReferenceEquals(thisObj.TryCast <NumberInstance>(), null)) { ExceptionHelper.ThrowTypeError(_realm); } var x = TypeConverter.ToNumber(thisObj); var precisionArgument = arguments.At(0); if (precisionArgument.IsUndefined()) { return(TypeConverter.ToString(x)); } var p = (int)TypeConverter.ToInteger(precisionArgument); if (double.IsNaN(x)) { return("NaN"); } if (double.IsInfinity(x)) { return(thisObj.ToString()); } if (p < 1 || p > 100) { ExceptionHelper.ThrowRangeError(_realm, "precision must be between 1 and 100"); } var dtoaBuilder = new DtoaBuilder(101); DtoaNumberFormatter.DoubleToAscii( dtoaBuilder, x, DtoaMode.Precision, p, out var negative, out var decimalPoint); int exponent = decimalPoint - 1; if (exponent < -6 || exponent >= p) { return(CreateExponentialRepresentation(dtoaBuilder, exponent, negative, p)); } using (var builder = StringBuilderPool.Rent()) { // Use fixed notation. if (negative) { builder.Builder.Append('-'); } if (decimalPoint <= 0) { builder.Builder.Append("0."); builder.Builder.Append('0', -decimalPoint); builder.Builder.Append(dtoaBuilder._chars, 0, dtoaBuilder.Length); builder.Builder.Append('0', p - dtoaBuilder.Length); } else { int m = System.Math.Min(dtoaBuilder.Length, decimalPoint); builder.Builder.Append(dtoaBuilder._chars, 0, m); builder.Builder.Append('0', System.Math.Max(0, decimalPoint - dtoaBuilder.Length)); if (decimalPoint < p) { builder.Builder.Append('.'); var extra = negative ? 2 : 1; if (dtoaBuilder.Length > decimalPoint) { int len = dtoaBuilder.Length - decimalPoint; int n = System.Math.Min(len, p - (builder.Builder.Length - extra)); builder.Builder.Append(dtoaBuilder._chars, decimalPoint, n); } builder.Builder.Append('0', System.Math.Max(0, extra + (p - builder.Builder.Length))); } } return(builder.ToString()); } }
public PatternException(string key, string defaultMessage, object parameters, Exception innerException = null) : base(defaultMessage, innerException) { Localization = new ExceptionHelper(this, key, defaultMessage, parameters); }
private void raiseErrorValue() { ExceptionHelper.Throw(new TypeError("Can not decrement readonly \"" + (_left) + "\"")); }
/// <summary> /// https://www.ecma-international.org/ecma-262/6.0/#sec-number.prototype.toexponential /// </summary> private JsValue ToExponential(JsValue thisObj, JsValue[] arguments) { if (!thisObj.IsNumber() && ReferenceEquals(thisObj.TryCast <NumberInstance>(), null)) { ExceptionHelper.ThrowTypeError(_realm); } var x = TypeConverter.ToNumber(thisObj); var fractionDigits = arguments.At(0); if (fractionDigits.IsUndefined()) { fractionDigits = JsNumber.PositiveZero; } var f = (int)TypeConverter.ToInteger(fractionDigits); if (double.IsNaN(x)) { return("NaN"); } if (double.IsInfinity(x)) { return(thisObj.ToString()); } if (f < 0 || f > 100) { ExceptionHelper.ThrowRangeError(_realm, "fractionDigits argument must be between 0 and 100"); } if (arguments.At(0).IsUndefined()) { f = -1; } bool negative = false; if (x < 0) { x = -x; negative = true; } int decimalPoint; DtoaBuilder dtoaBuilder; if (f == -1) { dtoaBuilder = new DtoaBuilder(); DtoaNumberFormatter.DoubleToAscii( dtoaBuilder, x, DtoaMode.Shortest, requested_digits: 0, out _, out decimalPoint); f = dtoaBuilder.Length - 1; } else { dtoaBuilder = new DtoaBuilder(101); DtoaNumberFormatter.DoubleToAscii( dtoaBuilder, x, DtoaMode.Precision, requested_digits: f + 1, out _, out decimalPoint); } Debug.Assert(dtoaBuilder.Length > 0); Debug.Assert(dtoaBuilder.Length <= f + 1); int exponent = decimalPoint - 1; var result = CreateExponentialRepresentation(dtoaBuilder, exponent, negative, f + 1); return(result); }
private void raiseErrorProp() { ExceptionHelper.Throw(new TypeError("Can not decrement property \"" + (_left) + "\" without setter.")); }
private void ShowErrors(IEnumerable <string> errors) { lStatus.Text = ExceptionHelper.GetErrorList(errors); lStatus.Visible = true; }
public override JSValue Evaluate(Context context) { bool post = _type == DecrimentType.Postdecriment; Function setter = null; JSValue res = null; var val = _left.EvaluateForWrite(context); if (val._valueType == JSValueType.Property) { var ppair = val._oValue as Core.PropertyPair; setter = ppair.setter; if (context._strict && setter == null) { raiseErrorProp(); } if (ppair.getter == null) { val = JSValue.undefined.CloneImpl(unchecked ((JSValueAttributesInternal)(-1))); } else { val = ppair.getter.Call(context._objectSource, null).CloneImpl(unchecked ((JSValueAttributesInternal)(-1))); } } else if ((val._attributes & JSValueAttributesInternal.ReadOnly) != 0) { if (context._strict) { raiseErrorValue(); } val = val.CloneImpl(false); } switch (val._valueType) { case JSValueType.Boolean: { val._valueType = JSValueType.Integer; break; } case JSValueType.String: { Tools.JSObjectToNumber(val, val); break; } case JSValueType.Object: case JSValueType.Date: case JSValueType.Function: { val.Assign(val.ToPrimitiveValue_Value_String()); switch (val._valueType) { case JSValueType.Boolean: { val._valueType = JSValueType.Integer; break; } case JSValueType.String: { Tools.JSObjectToNumber(val, val); break; } case JSValueType.Date: case JSValueType.Function: case JSValueType.Object: // null { val._valueType = JSValueType.Integer; val._iValue = 0; break; } } break; } case JSValueType.NotExists: { ExceptionHelper.ThrowIfNotExists(val, _left); break; } } if (post && val.Defined) { res = _tempContainer; res.Assign(val); } else { res = val; } switch (val._valueType) { case JSValueType.Integer: { if (val._iValue == int.MinValue) { val._valueType = JSValueType.Double; val._dValue = val._iValue - 1.0; } else { val._iValue--; } break; } case JSValueType.Double: { val._dValue--; break; } case JSValueType.Undefined: case JSValueType.NotExistsInObject: { val._valueType = JSValueType.Double; val._dValue = double.NaN; break; } } if (setter != null) { var args = new Arguments(context); args.length = 1; args[0] = val; setter.Call(context._objectSource, args); } else if ((val._attributes & JSValueAttributesInternal.Reassign) != 0) { val.Assign(val); } return(res); }
protected override void Execute(NativeActivityContext context) { const string isnullerrorformat = "Свойство '{0}' должно быть задано."; var gridFieldsStr = GridFields.Get(context); if (string.IsNullOrEmpty(gridFieldsStr)) { throw new DeveloperException(isnullerrorformat, GridFieldsDisplayName); } _objNameGrid = new List <string>(gridFieldsStr.Split(new [] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries)); var productList = ProductList.Get(context); var operationCode = OperationCode.Get(context); var needShowGreed = NeedShowSelectGrid.Get(context); try { var productsList = new List <Tuple <string, Product> >(); var userGrpPrd = new List <Product>(); //получим настройки менеджера товара using (var mgr = IoC.Instance.Resolve <IPMConfigManager>()) { foreach (var prd in productList) { var groupKeys = new StringBuilder(); //обязательная группировка по skuid groupKeys.AppendFormat("{0}={1}_", Product.SKUIDPropertyName, prd.SKUID); var confs = mgr.GetPMConfigByParamListByProductId(prd.ProductId, operationCode, null).ToArray(); //формируем группы по товару и настройке менеджера товара foreach (var pmConfig in confs.OrderBy(x => x.ObjectName_r)) { var prdprop = prd.GetProperty(pmConfig.ObjectName_r) ?? string.Empty; _objNameGrid.Add(pmConfig.ObjectName_r); groupKeys.AppendFormat("{0}={1}_", pmConfig.ObjectName_r, prdprop); } productsList.Add(new Tuple <string, Product>(groupKeys.ToString(), prd)); } } //формируем коллекцию товара для отображения + сумма по группам var grpPoductsList = productsList.GroupBy(p => p.Item1, v => v.Item2).ToArray(); foreach (var gr in grpPoductsList) { var product = (Product)gr.First().Clone(); product.ProductCountSKU = gr.Sum(p => p.ProductCountSKU); userGrpPrd.Add(product); } //если всего 1 группа и needShowGreed == false, грид не показываем if (grpPoductsList.Length == 1 && !needShowGreed) { OutGroupProductList.Set(context, userGrpPrd); OutProductList.Set(context, grpPoductsList[0].ToList()); return; } var dialogRet = ShowMain(userGrpPrd); //выбираем товар, в соответствии с выбором пользователя var outGroupProductList = new List <Product>(); var outProductList = new List <Product>(); if (dialogRet && _selectedPrd != null) { outGroupProductList = userGrpPrd.Where(p => p.GetKey <decimal>() == _selectedPrd).ToList(); var grkey = (from gr in grpPoductsList where gr.Any(p => p.GetKey <decimal>() == _selectedPrd) select gr.Key).FirstOrDefault(); outProductList = grpPoductsList.Where(g => g.Key == grkey).SelectMany(p => p).ToList(); } OutGroupProductList.Set(context, outGroupProductList); OutProductList.Set(context, outProductList); DialogResult.Set(context, dialogRet); } catch (Exception ex) { var message = "Ошибка при получении настроек менеджера товара. " + ExceptionHelper.GetErrorMessage(ex, false); ShowWarning(message); } }
internal JSValue proxyMember(bool forWrite, IList <MemberInfo> m) { JSValue r = null; if (m.Count > 1) { for (int i = 0; i < m.Count; i++) { if (!(m[i] is MethodBase)) { ExceptionHelper.Throw(_context.ProxyValue(new TypeError("Incompatible fields types."))); } } var cache = new MethodProxy[m.Count]; for (int i = 0; i < m.Count; i++) { cache[i] = new MethodProxy(_context, m[i] as MethodBase); } r = new MethodGroup(cache); } else { #if PORTABLE || NETCORE switch (m[0].GetMemberType()) #else switch (m[0].MemberType) #endif { case MemberTypes.Method: { var method = (MethodInfo)m[0]; r = new MethodProxy(_context, method); r._attributes &= ~(JSValueAttributesInternal.ReadOnly | JSValueAttributesInternal.DoNotDelete | JSValueAttributesInternal.NonConfigurable | JSValueAttributesInternal.DoNotEnumerate); break; } case MemberTypes.Field: { var field = (m[0] as FieldInfo); if ((field.Attributes & (FieldAttributes.Literal | FieldAttributes.InitOnly)) != 0 && (field.Attributes & FieldAttributes.Static) != 0) { r = _context.ProxyValue(field.GetValue(null)); r._attributes |= JSValueAttributesInternal.ReadOnly; } else { r = new JSValue() { _valueType = JSValueType.Property, _oValue = new PropertyPair ( new ExternalFunction((thisBind, a) => _context.ProxyValue(field.GetValue(field.IsStatic ? null : thisBind.Value))), !m[0].IsDefined(typeof(ReadOnlyAttribute), false) ? new ExternalFunction((thisBind, a) => { field.SetValue(field.IsStatic ? null : thisBind.Value, a[0].Value); return(null); }) : null ) }; r._attributes = JSValueAttributesInternal.Immutable | JSValueAttributesInternal.Field; if ((r._oValue as PropertyPair).setter == null) { r._attributes |= JSValueAttributesInternal.ReadOnly; } } break; } case MemberTypes.Property: { var pinfo = (PropertyInfo)m[0]; r = new JSValue() { _valueType = JSValueType.Property, _oValue = new PropertyPair ( #if (PORTABLE || NETCORE) pinfo.CanRead && pinfo.GetMethod != null ? new MethodProxy(_context, pinfo.GetMethod) : null, pinfo.CanWrite && pinfo.SetMethod != null && !pinfo.IsDefined(typeof(ReadOnlyAttribute), false) ? new MethodProxy(_context, pinfo.SetMethod) : null #else pinfo.CanRead&& pinfo.GetGetMethod(false) != null ? new MethodProxy(_context, pinfo.GetGetMethod(false)) : null, pinfo.CanWrite && pinfo.GetSetMethod(false) != null && !pinfo.IsDefined(typeof(ReadOnlyAttribute), false) ? new MethodProxy(_context, pinfo.GetSetMethod(false)) : null #endif ) }; r._attributes = JSValueAttributesInternal.Immutable; if ((r._oValue as PropertyPair).setter == null) { r._attributes |= JSValueAttributesInternal.ReadOnly; } if (pinfo.IsDefined(typeof(FieldAttribute), false)) { r._attributes |= JSValueAttributesInternal.Field; } break; } case MemberTypes.Event: { var pinfo = (EventInfo)m[0]; r = new JSValue() { _valueType = JSValueType.Property, _oValue = new PropertyPair ( null, #if (PORTABLE || NETCORE) new MethodProxy(_context, pinfo.AddMethod) #else new MethodProxy(_context, pinfo.GetAddMethod()) #endif ) }; break; } case MemberTypes.TypeInfo: #if (PORTABLE || NETCORE) { r = GetConstructor((m[0] as TypeInfo).AsType()); break; } #else case MemberTypes.NestedType: { r = _context.GetConstructor((Type)m[0]); break; } default: throw new NotImplementedException("Convertion from " + m[0].MemberType + " not implemented"); #endif } } if (m[0].IsDefined(typeof(DoNotEnumerateAttribute), false)) { r._attributes |= JSValueAttributesInternal.DoNotEnumerate; } if (forWrite && r.NeedClone) { r = r.CloneImpl(false); } for (var i = m.Count; i-- > 0;) { if (!m[i].IsDefined(typeof(DoNotEnumerateAttribute), false)) { r._attributes &= ~JSValueAttributesInternal.DoNotEnumerate; } if (m[i].IsDefined(typeof(ReadOnlyAttribute), false)) { r._attributes |= JSValueAttributesInternal.ReadOnly; } if (m[i].IsDefined(typeof(NotConfigurable), false)) { r._attributes |= JSValueAttributesInternal.NonConfigurable; } if (m[i].IsDefined(typeof(DoNotDeleteAttribute), false)) { r._attributes |= JSValueAttributesInternal.DoNotDelete; } } return(r); }
public bool Start() { log.Info("Agent starting"); // Open the TCP channel so we can activate an ITestAgency instance from _agencyUrl _channel = TcpChannelUtils.GetTcpChannel(_currentMessageCounter); log.Info("Connecting to TestAgency at {0}", _agencyUrl); try { // Direct cast, not safe cast. If the cast fails we need a clear InvalidCastException message, not a null _agency. _agency = (ITestAgency)Activator.GetObject(typeof(ITestAgency), _agencyUrl); } catch (Exception ex) { log.Error("Unable to connect: {0}", ExceptionHelper.BuildMessageAndStackTrace(ex)); } try { _agency.Register(_agentId, this); log.Debug("Registered with TestAgency"); } catch (Exception ex) { log.Error("RemoteTestAgent: Failed to register with TestAgency. {0}", ExceptionHelper.BuildMessageAndStackTrace(ex)); return(false); } return(true); }
internal void Read(Stream stream) { // For the complete documentation for this section see: // http://tools.ietf.org/html/rfc6455#section-5.2 this.Header = ReadByte(stream); // The first byte is the Final Bit and the type of the frame IsFinal = (this.Header & 0x80) != 0; Type = (WebSocketFrameTypes)(this.Header & 0xF); byte maskAndLength = ReadByte(stream); // The second byte is the Mask Bit and the length of the payload data HasMask = (maskAndLength & 0x80) != 0; // if 0-125, that is the payload length. Length = (UInt64)(maskAndLength & 127); // If 126, the following 2 bytes interpreted as a 16-bit unsigned integer are the payload length. if (Length == 126) { byte[] rawLen = VariableSizedBufferPool.Get(2, true); stream.ReadBuffer(rawLen, 2); if (BitConverter.IsLittleEndian) { Array.Reverse(rawLen, 0, 2); } Length = (UInt64)BitConverter.ToUInt16(rawLen, 0); VariableSizedBufferPool.Release(rawLen); } else if (Length == 127) { // If 127, the following 8 bytes interpreted as a 64-bit unsigned integer (the // most significant bit MUST be 0) are the payload length. byte[] rawLen = VariableSizedBufferPool.Get(8, true); stream.ReadBuffer(rawLen, 8); if (BitConverter.IsLittleEndian) { Array.Reverse(rawLen, 0, 8); } Length = (UInt64)BitConverter.ToUInt64(rawLen, 0); VariableSizedBufferPool.Release(rawLen); } // The sent byte array as a mask to decode the data. byte[] mask = null; // Read the Mask, if has any if (HasMask) { mask = VariableSizedBufferPool.Get(4, true); if (stream.Read(mask, 0, 4) < mask.Length) { throw ExceptionHelper.ServerClosedTCPStream(); } } if (Type == WebSocketFrameTypes.Text || Type == WebSocketFrameTypes.Continuation) { Data = VariableSizedBufferPool.Get((long)Length, true); } else if (Length == 0) { Data = VariableSizedBufferPool.NoData; } else { Data = new byte[Length]; } //Data = Type == WebSocketFrameTypes.Text ? VariableSizedBufferPool.Get((long)Length, true) : new byte[Length]; if (Length == 0L) { return; } uint readLength = 0; do { int read = stream.Read(Data, (int)readLength, (int)(Length - readLength)); if (read <= 0) { throw ExceptionHelper.ServerClosedTCPStream(); } readLength += (uint)read; } while (readLength < Length); if (HasMask) { for (uint i = 0; i < Length; ++i) { Data[i] = (byte)(Data[i] ^ mask[i % 4]); } VariableSizedBufferPool.Release(mask); } }
public FacilityException(string message, Exception innerException) : base(message, innerException) { ExceptionHelper.SetUp(this); }
public LocalizedInvalidOperationException(string key = "Exceptions.InvalidOperationException", string defaultMessage = null, object parameters = null, Exception innerException = null) : base(defaultMessage, innerException) { Localization = new ExceptionHelper(this, key, defaultMessage, parameters); }
public override StreamUpgradeAcceptor CreateUpgradeAcceptor() { throw ExceptionHelper.PlatformNotSupported("WindowsStreamSecurityUpgradeProvider.CreateUpgradeAcceptor is not supported."); }
public void Index_Action_HappyPath() { try { const string testUSI = "370100037230"; // Field IT Test account var testSubscriber = BusinessFacadeforTests.LoadCompositeSubscriber(testUSI, "NW", RosettianUser); Assert.IsNotNull(testSubscriber, "Index_Action_HappyPath - Loaded subscriber is null."); Assert.IsNotNull(testSubscriber.SubscriberDpi, "The LoadCompositeSubscriber call did not bring back any DPI-related data. Check the settings in the App.config file to verify that you are using the correct endpoints"); string strSubscriberID = testSubscriber.SubscriberTriad.ID; Assert.IsNotNull(strSubscriberID, "The test USI of {0} does not appear to be loaded in the Triad environment you are pointing to", testUSI); const string strExpectedViewName = "Index2"; var expectedSubscriberModel = testSubscriber.MapToSubscriberModel(); // Act var actualViewResult = SubscriberControllerForTests.Index(strSubscriberID,"", "WA") as ViewResult; // Assert Assert.IsNotNull(actualViewResult, "Actual View Result is null"); var actualSubscriberModel = actualViewResult.Model as SubscriberModel; Assert.IsNotNull(actualSubscriberModel, "Index_Action_HappyPath - unexpected model type"); var successCode = "200"; Assert.AreEqual(successCode, actualSubscriberModel.ActionResponse.Code, "Code was expected to be {0} but was {1} - error message was {2}", successCode, actualSubscriberModel.ActionResponse.Code, actualSubscriberModel.ActionResponse.Message); var jss = new JavaScriptSerializer(); Assert.AreEqual(strExpectedViewName, actualViewResult.ViewName); Assert.AreEqual(jss.Serialize(expectedSubscriberModel.SubDetailsModel), jss.Serialize(actualSubscriberModel.SubDetailsModel)); } catch (System.Exception ex) { var exceptionHelper = new ExceptionHelper(); Assert.Fail(exceptionHelper.GetAllInnerExceptionMessagesAndStackTraceForTests(ex)); } }
public void AuthorizationAttribute_FormatErrorMessage() { // Default attr with no error message generates default TestAuthorizationAttribute attr = new TestAuthorizationAttribute(); string expectedMessage = string.Format(CultureInfo.CurrentCulture, Resource.AuthorizationAttribute_Default_Message, "testOp"); string message = attr.InternalFormatErrorMessage("testOp"); Assert.AreEqual(expectedMessage, message, "Default FormatErrorMessage was not correct"); // Literal error message (no resource type) generates formatted message attr = new TestAuthorizationAttribute() { ErrorMessage = "testMessage: {0}" }; expectedMessage = string.Format(CultureInfo.CurrentCulture, "testMessage: {0}", "testOp"); message = attr.InternalFormatErrorMessage("testOp"); Assert.AreEqual(expectedMessage, message, "Default FormatErrorMessage with literal error message was not correct"); // ResourceType + legal message formats correctly attr = new TestAuthorizationAttribute() { ErrorMessage = "Message", ResourceType = typeof(AuthorizationResources) }; expectedMessage = string.Format(CultureInfo.CurrentCulture, AuthorizationResources.Message, "testOp"); message = attr.InternalFormatErrorMessage("testOp"); Assert.AreEqual(expectedMessage, message, "FormatErrorMessage with type + error message was not correct"); // Negative tests // ResourceType with empty message throws attr = new TestAuthorizationAttribute() { ResourceType = typeof(AuthorizationResources) }; expectedMessage = string.Format(CultureInfo.CurrentCulture, Resource.AuthorizationAttribute_Requires_ErrorMessage, attr.GetType().FullName, typeof(AuthorizationResources).FullName); ExceptionHelper.ExpectInvalidOperationException(() => attr.InternalFormatErrorMessage("testOp"), expectedMessage); // ResourceType with non-resourced message throws attr = new TestAuthorizationAttribute() { ResourceType = typeof(AuthorizationResources), ErrorMessage = "NotAProperty" }; expectedMessage = string.Format(CultureInfo.CurrentCulture, Resource.AuthorizationAttribute_Requires_Valid_Property, typeof(AuthorizationResources).FullName, "NotAProperty"); ExceptionHelper.ExpectInvalidOperationException(() => attr.InternalFormatErrorMessage("testOp"), expectedMessage); // ResourceType with non-static message throws attr = new TestAuthorizationAttribute() { ResourceType = typeof(AuthorizationResources), ErrorMessage = "NotStaticMessage" }; expectedMessage = string.Format(CultureInfo.CurrentCulture, Resource.AuthorizationAttribute_Requires_Valid_Property, typeof(AuthorizationResources).FullName, "NotStaticMessage"); ExceptionHelper.ExpectInvalidOperationException(() => attr.InternalFormatErrorMessage("testOp"), expectedMessage); // ResourceType with non-string message throws attr = new TestAuthorizationAttribute() { ResourceType = typeof(AuthorizationResources), ErrorMessage = "NotStringMessage" }; expectedMessage = string.Format(CultureInfo.CurrentCulture, Resource.AuthorizationAttribute_Requires_Valid_Property, typeof(AuthorizationResources).FullName, "NotStringMessage"); ExceptionHelper.ExpectInvalidOperationException(() => attr.InternalFormatErrorMessage("testOp"), expectedMessage); // ResourceType with non-public message throws attr = new TestAuthorizationAttribute() { ResourceType = typeof(AuthorizationResources), ErrorMessage = "NotPublicMessage" }; expectedMessage = string.Format(CultureInfo.CurrentCulture, Resource.AuthorizationAttribute_Requires_Valid_Property, typeof(AuthorizationResources).FullName, "NotPublicMessage"); ExceptionHelper.ExpectInvalidOperationException(() => attr.InternalFormatErrorMessage("testOp"), expectedMessage); }
public void Index_Billing_Only_Subscriber() { try { CurrentUser.SetInstance("uitestuser"); const string BillingUSI = "610017386752"; var testSubscriber = BusinessFacadeforTests.LoadCompositeSubscriber("610017386752", "PA", RosettianUser); Assert.IsNotNull(testSubscriber, string.Format("Billing Subscriber {0} returned a null CompositeSubscriber", BillingUSI)); Assert.IsNotNull(testSubscriber.DpiServices, "No Billing Data was returned."); var expectedSubscriberModel = testSubscriber.MapToSubscriberModel(); expectedSubscriberModel.SubDetailsModel.ShouldHideProvisioning = true; ViewResult actualViewResult = SubscriberControllerForTests.Index(BillingUSI, "", "", "PA") as ViewResult; Assert.IsNotNull(actualViewResult); var actualSubscriberModel = actualViewResult.Model as SubscriberModel; Assert.IsNotNull(actualSubscriberModel, "Index_Action_HappyPath - unexpected model type"); var successCode = "200"; Assert.AreEqual(successCode, actualSubscriberModel.ActionResponse.Code, "Code was expected to be {0} but was {1} - error message was {2}", successCode, actualSubscriberModel.ActionResponse.Code, actualSubscriberModel.ActionResponse.Message); var jss = new JavaScriptSerializer(); var expectedJss = jss.Serialize(expectedSubscriberModel.SubDetailsModel); var actualJss = jss.Serialize(actualSubscriberModel.SubDetailsModel); Assert.AreEqual(expectedJss, actualJss, string.Format("Model returned unexpected data: Actual-{0} {2} Expected-{1}", actualJss, expectedJss, System.Environment.NewLine)); } catch (Exception ex) { ExceptionHelper exceptionHelper = new ExceptionHelper(); Assert.Fail(exceptionHelper.GetAllInnerExceptionMessagesAndStackTraceForTests(ex)); } }
public ExceptionFilter() { _exceptionHelper = new ExceptionHelper(); }
public void When_editing_subscriber_provisioning_information_the_services_are_not_changed() { // Given a user // And a known subscriber // And the subscriber is billed // And the subscriber is provisioned const string testUSI = "370100037230"; // Field IT Test account var subscriber = BusinessFacadeforTests.LoadCompositeSubscriber(testUSI, "WA", RosettianUser); Assert.IsNotNull(subscriber, "Loaded subscriber is null."); Assert.IsNotNull(subscriber.SubscriberDpi, "The LoadCompositeSubscriber call did not bring back any DPI-related data. Check the settings in the App.config file to verify that you are using the correct endpoints"); // And the subscriber has provisioned services var originalSubscriberServices = subscriber.SubscriberTriad.Accounts[0].Services; // And the cbr needs to be changed on the provisioned account var model = subscriber.MapToSubscriberModel(); var originalCBR = model.SubDetailsModel.CBR; CurrentSubscriber.SetInstance(subscriber, model); model.SubDetailsModel.CBR = "2189123456"; // When editing the subscriber var actualResult = SubscriberControllerForTests.UpdateSubscriber(model.SubDetailsModel) as JsonResult; // Then the user receives a response Assert.IsNotNull(actualResult, "The result from the update subscriber was null"); // And the response is successful var expectedJson = new { status = "valid", returnedPartial = "" }.ToJSON(); Assert.AreEqual(expectedJson, actualResult.Data.ToJSON()); // And the subscriber cbr is modified var updateSubscriber = BusinessFacadeforTests.LoadCompositeSubscriber(testUSI, "WA", RosettianUser); Assert.IsNotNull(updateSubscriber.SubscriberDpi, "The LoadCompositeSubscriber call did not bring back any DPI-related data. Check the settings in the App.config file to verify that you are using the correct endpoints"); Assert.AreEqual("2189123456", updateSubscriber.SubscriberTriad.SubContactPhone, "The CBR was not updated."); // And the provisioned services remain unchanged var newServices = updateSubscriber.SubscriberTriad.Accounts[0].Services; Assert.IsTrue(newServices.SequenceEqual(originalSubscriberServices, new ServiceComparer()), "The service list is not the same"); //Cleanup subscriber.SubscriberTriad.SubContactPhone = originalCBR; try { using (var client = new RosettianClient()) { client.UpdateSubscriber(subscriber.SubscriberTriad, true, CurrentUser.AsUserDto()); } } catch (System.Exception ex) { var exceptionHelper = new ExceptionHelper(); Assert.Fail(exceptionHelper.GetAllInnerExceptionMessagesAndStackTraceForTests(ex)); } }
protected internal virtual JSValue EvaluateForWrite(Context context) { ExceptionHelper.ThrowReferenceError(Strings.InvalidLefthandSideInAssignment); return(null); }
protected override void GetHeadersFromMessage(Message message, MessageDescription messageDescription, object[] parameters, bool isRequest) { MessageInfo messageInfo = isRequest ? requestMessageInfo : replyMessageInfo; if (!messageInfo.AnyHeaders) { return; } MessageHeaders headers = message.Headers; KeyValuePair <Type, ArrayList>[] multipleHeaderValues = null; ArrayList elementList = null; if (messageInfo.UnknownHeaderDescription != null) { elementList = new ArrayList(); } for (int i = 0; i < headers.Count; i++) { MessageHeaderInfo header = headers[i]; MessageHeaderDescription headerDescription = messageInfo.HeaderDescriptionTable.Get(header.Name, header.Namespace); if (headerDescription != null) { if (header.MustUnderstand) { headers.UnderstoodHeaders.Add(header); } object item = null; XmlDictionaryReader headerReader = headers.GetReaderAtHeader(i); try { object dataValue = DeserializeHeaderContents(headerReader, messageDescription, headerDescription); if (headerDescription.TypedHeader) { item = TypedHeaderManager.Create(headerDescription.Type, dataValue, headers[i].MustUnderstand, headers[i].Relay, headers[i].Actor); } else { item = dataValue; } } finally { headerReader.Dispose(); } if (headerDescription.Multiple) { if (multipleHeaderValues == null) { multipleHeaderValues = new KeyValuePair <Type, ArrayList> [parameters.Length]; } if (multipleHeaderValues[headerDescription.Index].Key == null) { multipleHeaderValues[headerDescription.Index] = new KeyValuePair <System.Type, System.Collections.ArrayList>(headerDescription.TypedHeader ? TypedHeaderManager.GetMessageHeaderType(headerDescription.Type) : headerDescription.Type, new ArrayList()); } multipleHeaderValues[headerDescription.Index].Value.Add(item); } else { parameters[headerDescription.Index] = item; } } else if (messageInfo.UnknownHeaderDescription != null) { #if FEATURE_CORECLR MessageHeaderDescription unknownHeaderDescription = messageInfo.UnknownHeaderDescription; XmlDictionaryReader headerReader = headers.GetReaderAtHeader(i); try { XmlDocument doc = new XmlDocument(); object dataValue = doc.ReadNode(headerReader); if (dataValue != null && unknownHeaderDescription.TypedHeader) { dataValue = TypedHeaderManager.Create(unknownHeaderDescription.Type, dataValue, headers[i].MustUnderstand, headers[i].Relay, headers[i].Actor); } elementList.Add(dataValue); } finally { headerReader.Dispose(); } #else throw ExceptionHelper.PlatformNotSupported(); // XmlDocument not available in native #endif } } if (multipleHeaderValues != null) { for (int i = 0; i < parameters.Length; i++) { if (multipleHeaderValues[i].Key != null) { parameters[i] = multipleHeaderValues[i].Value.ToArray(multipleHeaderValues[i].Key); } } } }
public void Dispose() { _items.ForEach(i => ExceptionHelper.ExceptionCatcher(i.Dispose, where : MethodBase.GetCurrentMethod().ToString())); _items.Clear(); }
private async void ChangeDetailPicture(GalleryImageDetail galleryImageDetail) { //clean. DetailImageBox.ImageSource = null; if (galleryImageDetail == null) { return; } RefreshButton.IsBusy = true; const string notify_content = "加载图片中......"; using (var notify = LoadingStatus.BeginBusy(notify_content)) { var(pick_download, is_new) = await PickSuitableImageURL(galleryImageDetail.DownloadableImageLinks); if (pick_download == null) { //notice error; ExceptionHelper.DebugThrow(new Exception("No image.")); Toast.ShowMessage("没图片可显示"); return; } if (is_new) { //force update var d = DownloadList.DataContext; DownloadList.DataContext = this; DownloadList.DataContext = d; } var downloader = Container.Default.GetExportedValue <ImageFetchDownloadScheduler>(); System.Drawing.Image image; do { image = await ImageResourceManager.RequestImageAsync(pick_download.FullFileName, async() => { return(await downloader.GetImageAsync(pick_download.DownloadLink, null, d => { (long cur, long total) = d; notify.Description = $"({cur * 1.0 / total * 100:F2}%) {notify_content}"; })); }); } while (image == null); var source = image.ConvertToBitmapImage(); RefreshButton.IsBusy = false; if (PictureDetailInfo == galleryImageDetail) { DetailImageBox.ImageSource = source; } else { Log <PictureDetailViewPage> .Debug($"Picture info mismatch."); } };
public void Index_Action_HappyPath_With_Minimal_Subscriber_And_Location() { // Arrange var loc = new LocationDto(); var sub = new SubscriberDto(); try { // new sub data loc = DataHelper.NewLocationData(); sub = DataHelper.NewSubscriberData(); sub.Accounts[0].Location = loc; sub.CustomFields = DataHelper.DefaultCustomFields_Sub(); sub.Accounts[0].ServiceEnabled = true; sub.Accounts[0].AccountType = AccountTypeDto.Residential; DataHelper.RestoreLocation1(loc, false); DataHelper.RestoreSubscriber1(sub, false); // set current subscriber CurrentSubscriber.SetInstance(sub); var subscriber = BusinessFacadeforTests.LoadCompositeSubscriber(sub.ID, string.Empty, RosettianUser); // Deliberately not checking to see if subscriber.SubscriberDpi is null as this test doesn't use that data const string strExpectedViewName = "Index2"; var expectedSubscriberModel = subscriber.MapToSubscriberModel(); // Act var actualViewResult = SubscriberControllerForTests.Index(sub.ID) as ViewResult; // Assert Assert.IsNotNull(actualViewResult, "SubscriberControllerForTests.Index returned null"); Assert.AreEqual(strExpectedViewName, actualViewResult.ViewName, "ViewName"); // 2nd Act var actualSubscriberModel = (SubscriberModel) actualViewResult.Model; // 2nd Assert Assert.IsNotNull(actualSubscriberModel, "Index_Action_HappyPath_With_Minimal_Subscriber_And_Location - unexpected model type"); const string successCode = "200"; Assert.AreEqual(successCode, actualSubscriberModel.ActionResponse.Code, "Code was expected to be {0} but was {1} - error message was {2}", successCode, actualSubscriberModel.ActionResponse.Code, actualSubscriberModel.ActionResponse.Message); var jss = new JavaScriptSerializer(); var expectedJssSerialization = jss.Serialize(expectedSubscriberModel.SubDetailsModel); var actualJssSerialization = jss.Serialize(actualSubscriberModel.SubDetailsModel); Assert.AreEqual(expectedJssSerialization, actualJssSerialization); } catch (System.Exception ex) { var exceptionHelper = new ExceptionHelper(); Assert.Fail(exceptionHelper.GetAllInnerExceptionMessagesAndStackTraceForTests(ex)); } finally { DataHelper.DeleteSubscriber(sub.ID); DataHelper.DeleteLocation(loc.ID); } }
/// <summary> /// Sends a http request with the given object. All headers should be set manually here e.g. content type=application/json /// </summary> /// <param name="request"></param> /// <returns></returns> private Task <HttpResponse <T> > SendRequest <T>(HttpRequestMessage request) { Task <HttpResponse <T> > response = null; HttpResponseMessage responseMessage = null; string responseAsString = null; string responseCode = null; try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; responseMessage = this.httpClient.SendAsync(request).Result; responseCode = responseMessage.StatusCode.ToString(); var responseContent = responseMessage.Content.ReadAsByteArrayAsync().Result; if (responseContent != null && responseContent.Length > 0) { responseAsString = Encoding.UTF8.GetString(responseContent); if (AppSettings.DebugMode) { Console.WriteLine(string.Format("\n** HttpResponse - Status {0}**\n {1}\n", responseMessage.StatusCode, responseAsString)); } } response = Task.FromResult(this.CreateHttpResponse <T>(responseAsString, responseMessage.StatusCode)); } catch (Exception ex) { if (AppSettings.DebugMode) { Console.WriteLine(string.Format(@"\n** Exception - HttpStatuscode:\n{0}**\n\n ** ResponseString {1}\n ** Exception Messages{2}\n ", (responseMessage != null ? responseMessage.StatusCode.ToString() : string.Empty), responseAsString, ExceptionHelper.FlattenExceptionMessages(ex))); } responseCode = "Exception" + ex.Message; throw; } finally { request.Dispose(); this.ResetHandler(); } return(response); }
public void LoadLocationInvalidLocationId() { SubscriberHelper sh = new SubscriberHelper(); SubscriberDto subscriber = null; try { // Arrange subscriber = sh.CreateMinimalSubscriberWithLocation(); subscriber.Accounts[0].Location.ID = "4001.0001999"; //Act PartialViewResult actionResult = SubscriberControllerForTests.LoadLocation(subscriber.Accounts[0].Location.ID) as PartialViewResult; //Assert Assert.IsNotNull(actionResult); Assert.AreEqual("Error", actionResult.ViewName); } catch (System.Exception ex) { ExceptionHelper exceptionHelper = new ExceptionHelper(); Assert.Fail(exceptionHelper.GetAllInnerExceptionMessagesAndStackTraceForTests(ex)); } }
public void Error(Exception ex) { Log(LogLevel.Error, LogType.系统异常, ExceptionHelper.GetExceptionAllMsg(ex)); }
public LocalizedArgumentNullException(string paramName, string key = "Exceptions.ArgumentNullException", string defaultMessage = null, object parameters = null, Exception innerException = null) : base(paramName, defaultMessage) { Localization = new ExceptionHelper(this, key, defaultMessage, parameters); Localization.AddParameter("ParamName", paramName); }
public LocalizedNotSupportedException(string key = "Exception.NotSupportedException", string defaultMessage = null, object parameters = null, Exception innerException = null) : base(defaultMessage, innerException) { Localization = new ExceptionHelper(this, key, defaultMessage, parameters); }