// Returns true if the expected result is right // Returns false if the expected result is wrong public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Create a new instance of NotSupportedException."); try { string expectValue = "HELLO"; NotSupportedException myException = new NotSupportedException(expectValue); if (myException == null) { TestLibrary.TestFramework.LogError("001.1", "NotSupportedException instance can not create correctly."); retVal = false; } if (myException.Message != expectValue) { TestLibrary.TestFramework.LogError("001.2", "the Message should return " + expectValue); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e); retVal = false; } return retVal; }
public static int Main () { var ex = new ApplicationException (); try { TestRethrow (ex).Wait (); } catch (AggregateException e) { if (e.InnerException != ex) return 1; } if (counter != 3) return 2; var ex2 = new NotSupportedException (); try { TestRethrow (ex2).Wait (); } catch (AggregateException e) { if (e.InnerException != ex2) return 3; } if (counter != 9) return 4; Console.WriteLine ("ok"); return 0; }
// Returns true if the expected result is right // Returns false if the expected result is wrong public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: the parameter string is null."); try { string expectValue = null; NotSupportedException myException = new NotSupportedException(expectValue); if (myException == null) { TestLibrary.TestFramework.LogError("002.1", "NotSupportedException instance can not create correctly."); retVal = false; } if (myException.Message == expectValue) { TestLibrary.TestFramework.LogError("002.2", "the Message should return the default value."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e); retVal = false; } return retVal; }
public virtual void TestShouldGenerateCorrectDetailedMessageForChainedBaseExceptions() { BaseException e1 = new BaseException("ONE"); BaseException e2 = new UnsupportedTagException("TWO", e1); BaseException e3 = new NotSupportedException("THREE", e2); BaseException e4 = new NoSuchTagException("FOUR", e3); BaseException e5 = new InvalidDataException("FIVE", e4); Assert.AreEqual("FIVE", e5.Message); Assert.AreEqual("[Mp3net.InvalidDataException: FIVE] caused by [Mp3net.NoSuchTagException: FOUR] caused by [Mp3net.NotSupportedException: THREE] caused by [Mp3net.UnsupportedTagException: TWO] caused by [Mp3net.BaseException: ONE]", e5.GetDetailedMessage()); }
// Returns true if the expected result is right // Returns false if the expected result is wrong public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Create a new instance of NotSupportedException."); try { NotSupportedException myException = new NotSupportedException(); if (myException == null) { TestLibrary.TestFramework.LogError("001.1", "NotSupportedException instance can not create correctly."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e); retVal = false; } return retVal; }
private static PartitionId ResolvePartitionId(AccountPartitionIdParameter accountPartitionIdParameter, Task.TaskErrorLoggingDelegate errorLogger) { PartitionId result = null; LocalizedString?localizedString; IEnumerable <AccountPartition> objects = accountPartitionIdParameter.GetObjects <AccountPartition>(null, DirectorySessionFactory.Default.CreateTopologyConfigurationSession(ConsistencyMode.PartiallyConsistent, ADSessionSettings.SessionSettingsFactory.Default.FromRootOrgScopeSet(), 548, "ResolvePartitionId", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\Deployment\\NewOrganizationTask.cs"), null, out localizedString); Exception ex = null; using (IEnumerator <AccountPartition> enumerator = objects.GetEnumerator()) { if (enumerator.MoveNext()) { AccountPartition accountPartition = enumerator.Current; if (!accountPartition.TryGetPartitionId(out result)) { ex = new NotSupportedException(Strings.ErrorCorruptedPartition(accountPartitionIdParameter.ToString())); } else if (enumerator.MoveNext()) { ex = new ManagementObjectAmbiguousException(Strings.ErrorObjectNotUnique(accountPartitionIdParameter.ToString())); } if (accountPartition.IsSecondary) { ex = new ArgumentException(Strings.ErrorSecondaryPartitionNotEnabledForProvisioning(accountPartitionIdParameter.RawIdentity)); } } else { ex = new ManagementObjectNotFoundException(localizedString ?? Strings.ErrorObjectNotFound(accountPartitionIdParameter.ToString())); } } if (ex != null) { errorLogger(ex, ErrorCategory.InvalidArgument, accountPartitionIdParameter); } return(result); }
internal static Exception CreateException(DeviceError err, string msg) { Exception exp; switch (err) { case DeviceError.InvalidParameter: case DeviceError.NotInitialized: //fall through exp = new ArgumentException(msg); break; case DeviceError.NotSupported: exp = new NotSupportedException(msg + " : Device does not support the Operation."); break; case DeviceError.AlreadyInProgress: //fall through case DeviceError.ResourceBusy: //fall through case DeviceError.OperationFailed: //fall through case DeviceError.InvalidOperation: exp = new InvalidOperationException(msg); break; case DeviceError.PermissionDenied: exp = new UnauthorizedAccessException(msg); break; default: exp = new InvalidOperationException("Unknown error occured."); break; } return(exp); }
public async Task Deserialize_WithExceptionErrorsAsync() { var flurlHttpException = await CreateFlurlHttpExceptionAsync().ConfigureAwait(false); var notSupportedException = new NotSupportedException(); var result1 = new MockCommandResult() { Result = new MockCommandEntity(), Errors = new List <Exception>() { flurlHttpException, notSupportedException } }; var json1 = JsonConvert.SerializeObject(result1); var result2 = JsonConvert.DeserializeObject <ICommandResult>(json1); var json2 = JsonConvert.SerializeObject(result2); Assert.Equal(json1, json2); }
// // Attempts to persist the security descriptor onto the object // private void Persist(string name, SafeHandle handle, AccessControlSections includeSections, object exceptionContext) { WriteLock(); try { int error; SecurityInfos securityInfo = 0; SecurityIdentifier owner = null, group = null; SystemAcl sacl = null; DiscretionaryAcl dacl = null; if ((includeSections & AccessControlSections.Owner) != 0 && _securityDescriptor.Owner != null) { securityInfo |= SecurityInfos.Owner; owner = _securityDescriptor.Owner; } if ((includeSections & AccessControlSections.Group) != 0 && _securityDescriptor.Group != null) { securityInfo |= SecurityInfos.Group; group = _securityDescriptor.Group; } if ((includeSections & AccessControlSections.Audit) != 0) { securityInfo |= SecurityInfos.SystemAcl; if (_securityDescriptor.IsSystemAclPresent && _securityDescriptor.SystemAcl != null && _securityDescriptor.SystemAcl.Count > 0) { sacl = _securityDescriptor.SystemAcl; } else { sacl = null; } if ((_securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected) != 0) { securityInfo = (SecurityInfos)((uint)securityInfo | ProtectedSystemAcl); } else { securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedSystemAcl); } } if ((includeSections & AccessControlSections.Access) != 0 && _securityDescriptor.IsDiscretionaryAclPresent) { securityInfo |= SecurityInfos.DiscretionaryAcl; // if the DACL is in fact a crafted replaced for NULL replacement, then we will persist it as NULL if (_securityDescriptor.DiscretionaryAcl.EveryOneFullAccessForNullDacl) { dacl = null; } else { dacl = _securityDescriptor.DiscretionaryAcl; } if ((_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected) != 0) { securityInfo = unchecked ((SecurityInfos)((uint)securityInfo | ProtectedDiscretionaryAcl)); } else { securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedDiscretionaryAcl); } } if (securityInfo == 0) { // // Nothing to persist // return; } error = Win32.SetSecurityInfo(_resourceType, name, handle, securityInfo, owner, group, sacl, dacl); if (error != Interop.Errors.ERROR_SUCCESS) { System.Exception exception = null; if (_exceptionFromErrorCode != null) { exception = _exceptionFromErrorCode(error, name, handle, exceptionContext); } if (exception == null) { if (error == Interop.Errors.ERROR_ACCESS_DENIED) { exception = new UnauthorizedAccessException(); } else if (error == Interop.Errors.ERROR_INVALID_OWNER) { exception = new InvalidOperationException(SR.AccessControl_InvalidOwner); } else if (error == Interop.Errors.ERROR_INVALID_PRIMARY_GROUP) { exception = new InvalidOperationException(SR.AccessControl_InvalidGroup); } else if (error == Interop.Errors.ERROR_INVALID_NAME) { exception = new ArgumentException(SR.Argument_InvalidName, nameof(name)); } else if (error == Interop.Errors.ERROR_INVALID_HANDLE) { exception = new NotSupportedException(SR.AccessControl_InvalidHandle); } else if (error == Interop.Errors.ERROR_FILE_NOT_FOUND) { exception = new FileNotFoundException(); } else if (error == Interop.Errors.ERROR_NO_SECURITY_ON_OBJECT) { exception = new NotSupportedException(SR.AccessControl_NoAssociatedSecurity); } else { Debug.Fail($"Unexpected error code {error}"); exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error)); } } throw exception; } // // Everything goes well, let us clean the modified flags. // We are in proper write lock, so just go ahead // this.OwnerModified = false; this.GroupModified = false; this.AccessRulesModified = false; this.AuditRulesModified = false; } finally { WriteUnlock(); } }
public WebSocketReceiveResult Receive() { try { // we may receive control frames so reading needs to happen in an infinite loop while (true) { // allow this operation to be cancelled from iniside OR outside this instance WebSocketFrame frame = null; try { frame = WebSocketFrameReader.Read(_stream, _receiveBuffer); _logger(LogLevel.Debug, "websocket.ReceivedFrame: " + frame.OpCode + ", " + frame.IsFinBitSet + ", " + frame.Count); } catch (InternalBufferOverflowException ex) { CloseOutputAutoTimeout(WebSocketCloseStatus.MessageTooBig, "Frame too large to fit in buffer. Use message fragmentation", ex); throw; } catch (ArgumentOutOfRangeException ex) { CloseOutputAutoTimeout(WebSocketCloseStatus.ProtocolError, "Payload length out of range", ex); throw; } catch (EndOfStreamException ex) { CloseOutputAutoTimeout(WebSocketCloseStatus.InvalidPayloadData, "Unexpected end of stream encountered", ex); throw; } catch (OperationCanceledException ex) { CloseOutputAutoTimeout(WebSocketCloseStatus.EndpointUnavailable, "Operation cancelled", ex); throw; } catch (Exception ex) { CloseOutputAutoTimeout(WebSocketCloseStatus.InternalServerError, "Error reading WebSocket frame", ex); throw; } switch (frame.OpCode) { case WebSocketOpCode.ConnectionClose: return(RespondToCloseFrame(frame, _receiveBuffer)); case WebSocketOpCode.Ping: ArraySegment <byte> pingPayload = new ArraySegment <byte>(_receiveBuffer.Array, _receiveBuffer.Offset, frame.Count); SendPong(pingPayload); break; case WebSocketOpCode.Pong: ArraySegment <byte> pongBuffer = new ArraySegment <byte>(_receiveBuffer.Array, frame.Count, _receiveBuffer.Offset); if (pongBuffer.Array.SequenceEqual(_pingPayload)) { } LastPingPong = DateTime.UtcNow; NeedsPing = true; break; case WebSocketOpCode.TextFrame: if (!frame.IsFinBitSet) { // continuation frames will follow, record the message type Text _continuationFrameMessageType = WebSocketMessageType.Text; } return(new WebSocketReceiveResult(frame.Count, WebSocketMessageType.Text, frame.IsFinBitSet, _receiveBuffer)); case WebSocketOpCode.BinaryFrame: if (!frame.IsFinBitSet) { // continuation frames will follow, record the message type Binary _continuationFrameMessageType = WebSocketMessageType.Binary; } return(new WebSocketReceiveResult(frame.Count, WebSocketMessageType.Binary, frame.IsFinBitSet, _receiveBuffer)); case WebSocketOpCode.ContinuationFrame: return(new WebSocketReceiveResult(frame.Count, _continuationFrameMessageType, frame.IsFinBitSet, _receiveBuffer)); default: Exception ex = new NotSupportedException($"Unknown WebSocket opcode {frame.OpCode}"); CloseOutputAutoTimeout(WebSocketCloseStatus.ProtocolError, ex.Message, ex); throw ex; } } } catch (Exception catchAll) { // Most exceptions will be caught closer to their source to send an appropriate close message (and set the WebSocketState) // However, if an unhandled exception is encountered and a close message not sent then send one here if (_state == WebSocketState.Open) { CloseOutputAutoTimeout(WebSocketCloseStatus.InternalServerError, "Unexpected error reading from WebSocket", catchAll); } throw; } }
public static void ReadSimpleTestClass_NonGenericWrappers_NoAddMethod_Throws(Type type, string json, Type exceptionMessageType) { NotSupportedException ex = Assert.Throws <NotSupportedException>(() => JsonSerializer.Deserialize(json, type)); Assert.Contains(exceptionMessageType.ToString(), ex.Message); }
public static void SeedAllGenres(AppDbContext db) { //check to see if all the languages have already been added if (db.Genres.Count() == 13) { //exit the program - we don't need to do any of this NotSupportedException ex = new NotSupportedException("Genre record count is already 13!"); throw ex; } Int32 intGenresAdded = 0; try { //Create a list of languages List <Genre> Genres = new List <Genre>(); Genre g1 = new Genre { GenreName = "Adventure" }; Genres.Add(g1); Genre g2 = new Genre { GenreName = "Contemporary Fiction" }; Genres.Add(g2); Genre g3 = new Genre { GenreName = "Fantasy" }; Genres.Add(g3); Genre g4 = new Genre { GenreName = "Historical Fiction" }; Genres.Add(g4); Genre g5 = new Genre { GenreName = "Horror" }; Genres.Add(g5); Genre g6 = new Genre { GenreName = "Humor" }; Genres.Add(g6); Genre g7 = new Genre { GenreName = "Mystery" }; Genres.Add(g7); Genre g8 = new Genre { GenreName = "Poetry" }; Genres.Add(g8); Genre g9 = new Genre { GenreName = "Romance" }; Genres.Add(g9); Genre g10 = new Genre { GenreName = "Science Fiction" }; Genres.Add(g10); Genre g11 = new Genre { GenreName = "Shakespeare" }; Genres.Add(g11); Genre g12 = new Genre { GenreName = "Suspense" }; Genres.Add(g12); Genre g13 = new Genre { GenreName = "Thriller" }; Genres.Add(g13); Genre l; //loop through the list and see which (if any) need to be added foreach (Genre gen in Genres) { //see if the language already exists in the database l = db.Genres.FirstOrDefault(x => x.GenreName == gen.GenreName); //language was not found if (l == null) { //Add the language db.Genres.Add(gen); db.SaveChanges(); intGenresAdded += 1; } } } catch { String msg = "Genres Added: " + intGenresAdded.ToString(); throw new InvalidOperationException(msg); } }
public async Task Routine_ReturnsFaultedTask_LogsFaultedTask() { // Arrange using IJobManager jobManager = TestHelper.CreateJobManager(true); var job = jobManager.Create("my-job"); var start = "2000-01-01Z".ToUtcDateOffset(); var timeMachine = ShiftedTimeProvider.CreateTimeMachine(start); TimeProvider.Override(timeMachine); var output = new StringWriterWithEncoding(Encoding.UTF8); job.Output = output; var exception = new NotSupportedException("Bye baby!"); JobDelegate routine = (parameter, tracker, writer, token) => { writer.WriteLine("Hi there!"); return(Task.FromException(exception)); }; job.Schedule = new ConcreteSchedule( start.AddSeconds(1)); job.IsEnabled = true; // Act job.Routine = routine; var updatedRoutine = job.Routine; await timeMachine.WaitUntilSecondsElapse(start, 1.5); // will fail by this time var outputResult = output.ToString(); var info = job.GetInfo(null); // Assert try { Assert.That(updatedRoutine, Is.SameAs(routine)); Assert.That(outputResult, Does.Contain("Hi there!")); Assert.That(outputResult, Does.Contain(exception.ToString())); Assert.That(info.CurrentRun, Is.Null); Assert.That(info.RunCount, Is.EqualTo(1)); var run = info.Runs.Single(); Assert.That(run.Status, Is.EqualTo(JobRunStatus.Faulted)); Assert.That(run.Exception, Is.SameAs(exception)); Assert.That(run.Output, Does.Contain(exception.ToString())); var log = _logWriter.ToString(); Assert.That(log, Does.Contain($"Job 'my-job' completed synchronously. Reason of start was 'ScheduleDueTime'.")); } catch (Exception ex) { var sb = new StringBuilder(); sb.AppendLine("*** Test Failed ***"); sb.AppendLine(ex.ToString()); sb.AppendLine("*** Log: ***"); var log = _logWriter.ToString(); sb.AppendLine(log); Assert.Fail(sb.ToString()); } }
// We do not want to support the cloning-related operation for now. // They appear to mainly target corner-case scenarios in Windows itself, // and are (mainly) a historical artefact of abandoned early designs // for IRandonAccessStream. // Cloning can be added in future, however, it would be quite complex // to support it correctly for generic streams. private static void ThrowCloningNotSuported(String methodName) { NotSupportedException nse = new NotSupportedException(SR.Format(SR.NotSupported_CloningNotSupported, methodName)); nse.SetErrorCode(HResults.E_NOTIMPL); throw nse; }
public CannotFetchDataException(NotSupportedException ex, string serviceName) { cause = ex; this.serviceName = serviceName; }
public static Exception ToIotHubClientContract(Error error) { Exception retException; if (error == null) { retException = new IotHubException("Unknown error."); return(retException); } string message = error.Description; string trackingId = null; if (error.Info != null && error.Info.TryGetValue(TrackingId, out trackingId)) { message = "{0}{1}{2}".FormatInvariant(message, Environment.NewLine, "Tracking Id:" + trackingId); } if (error.Condition.Equals(TimeoutError)) { retException = new TimeoutException(message); } else if (error.Condition.Equals(AmqpErrorCode.NotFound)) { retException = new DeviceNotFoundException(message, (Exception)null); } else if (error.Condition.Equals(AmqpErrorCode.NotImplemented)) { retException = new NotSupportedException(message); } else if (error.Condition.Equals(MessageLockLostError)) { retException = new DeviceMessageLockLostException(message); } else if (error.Condition.Equals(AmqpErrorCode.NotAllowed)) { retException = new InvalidOperationException(message); } else if (error.Condition.Equals(AmqpErrorCode.UnauthorizedAccess)) { retException = new UnauthorizedException(message); } else if (error.Condition.Equals(ArgumentError)) { retException = new ArgumentException(message); } else if (error.Condition.Equals(ArgumentOutOfRangeError)) { retException = new ArgumentOutOfRangeException(message); } else if (error.Condition.Equals(AmqpErrorCode.MessageSizeExceeded)) { retException = new MessageTooLargeException(message); } else if (error.Condition.Equals(AmqpErrorCode.ResourceLimitExceeded)) { retException = new DeviceMaximumQueueDepthExceededException(message); } else if (error.Condition.Equals(DeviceAlreadyExists)) { retException = new DeviceAlreadyExistsException(message, null); } else if (error.Condition.Equals(DeviceContainerThrottled)) { retException = new IotHubThrottledException(message, null); } else if (error.Condition.Equals(IotHubSuspended)) { retException = new IotHubSuspendedException(message); } else { retException = new IotHubException(message); } if (trackingId != null && retException is IotHubException) { IotHubException iotHubException = (IotHubException)retException; iotHubException.TrackingId = trackingId; } return(retException); }
internal static NotSupportedException NotSupported(string error) { NotSupportedException e = new NotSupportedException(error); return(e); }
public static void ThrowsNotSupported(Action action, string expectedMessage) { NotSupportedException exception = Assert.Throws <NotSupportedException>(() => action.Invoke()); Assert.Equal(expectedMessage, exception.Message); }
internal override void Decompile(CodeExpression expression, StringBuilder stringBuilder, CodeExpression parentExpression) { bool mustParenthesize = false; CodeBinaryOperatorExpression binaryExpr = (CodeBinaryOperatorExpression)expression; if (binaryExpr.Left == null) { string message = string.Format(CultureInfo.CurrentCulture, Messages.NullBinaryOpLHS, binaryExpr.Operator.ToString()); RuleEvaluationException exception = new RuleEvaluationException(message); exception.Data[RuleUserDataKeys.ErrorObject] = binaryExpr; throw exception; } if (binaryExpr.Right == null) { string message = string.Format(CultureInfo.CurrentCulture, Messages.NullBinaryOpRHS, binaryExpr.Operator.ToString()); RuleEvaluationException exception = new RuleEvaluationException(message); exception.Data[RuleUserDataKeys.ErrorObject] = binaryExpr; throw exception; } string opString; switch (binaryExpr.Operator) { case CodeBinaryOperatorType.Modulus: opString = " % "; break; case CodeBinaryOperatorType.Multiply: opString = " * "; break; case CodeBinaryOperatorType.Divide: opString = " / "; break; case CodeBinaryOperatorType.Subtract: opString = " - "; break; case CodeBinaryOperatorType.Add: opString = " + "; break; case CodeBinaryOperatorType.LessThan: opString = " < "; break; case CodeBinaryOperatorType.LessThanOrEqual: opString = " <= "; break; case CodeBinaryOperatorType.GreaterThan: opString = " > "; break; case CodeBinaryOperatorType.GreaterThanOrEqual: opString = " >= "; break; case CodeBinaryOperatorType.IdentityEquality: case CodeBinaryOperatorType.ValueEquality: opString = " == "; break; case CodeBinaryOperatorType.IdentityInequality: opString = " != "; break; case CodeBinaryOperatorType.BitwiseAnd: opString = " & "; break; case CodeBinaryOperatorType.BitwiseOr: opString = " | "; break; case CodeBinaryOperatorType.BooleanAnd: opString = " && "; break; case CodeBinaryOperatorType.BooleanOr: opString = " || "; break; default: string message = string.Format(CultureInfo.CurrentCulture, Messages.BinaryOpNotSupported, binaryExpr.Operator.ToString()); NotSupportedException exception = new NotSupportedException(message); exception.Data[RuleUserDataKeys.ErrorObject] = binaryExpr; throw exception; } CodeExpression leftExpr = binaryExpr.Left; CodeExpression rightExpr = binaryExpr.Right; if (binaryExpr.Operator == CodeBinaryOperatorType.ValueEquality) { // Look for special cases: // LHS == false --> ! LHS // or // (LHS == expr) == false --> LHS != expr CodePrimitiveExpression rhsPrimitive = rightExpr as CodePrimitiveExpression; if (rhsPrimitive != null) { object rhsValue = rhsPrimitive.Value; if (rhsValue != null) { // we don't have the comparison "==null" if (rhsValue.GetType() == typeof(bool) && (bool)rhsValue == false) { // We have comparison "== false". CodeBinaryOperatorExpression lhsBinary = leftExpr as CodeBinaryOperatorExpression; if (lhsBinary != null && lhsBinary.Operator == CodeBinaryOperatorType.ValueEquality) { // We have the pattern // (expr1 == expr2) == false // Treat this as: // expr1 != expr2 opString = " != "; leftExpr = lhsBinary.Left; rightExpr = lhsBinary.Right; } else { // We have the pattern // LHS == false // Treat this as: // ! LHS mustParenthesize = RuleDecompiler.MustParenthesize(leftExpr, parentExpression); if (mustParenthesize) stringBuilder.Append("("); // Note the "parentExpression" passed to the child decompile... cast is the only // built-in operation that has "unary" precedence, so pass that as the parent // to get the parenthesization right. . stringBuilder.Append("!"); RuleExpressionWalker.Decompile(stringBuilder, leftExpr, new CodeCastExpression()); if (mustParenthesize) stringBuilder.Append(")"); return; } } } } } else if (binaryExpr.Operator == CodeBinaryOperatorType.Subtract) { // Look for the special case: // 0 - RHS --> - RHS CodePrimitiveExpression lhsPrimitive = leftExpr as CodePrimitiveExpression; if (lhsPrimitive != null && lhsPrimitive.Value != null) { object lhsValue = lhsPrimitive.Value; // Check if the LHS is zero. We'll only check a few types (decimal, // double, float, int, long), since these occur most often (and the // unsigned types are all illegal). TypeCode tc = Type.GetTypeCode(lhsValue.GetType()); bool isZero = false; switch (tc) { case TypeCode.Decimal: isZero = ((decimal)lhsValue) == 0; break; case TypeCode.Double: isZero = ((double)lhsValue) == 0; break; case TypeCode.Single: isZero = ((float)lhsValue) == 0; break; case TypeCode.Int32: isZero = ((int)lhsValue) == 0; break; case TypeCode.Int64: isZero = ((long)lhsValue) == 0; break; } if (isZero) { mustParenthesize = RuleDecompiler.MustParenthesize(rightExpr, parentExpression); if (mustParenthesize) stringBuilder.Append("("); // Note the "parentExpression" passed to the child decompile... cast is the only // built-in operation that has "unary" precedence, so pass that as the parent // to get the parenthesization right. stringBuilder.Append("-"); RuleExpressionWalker.Decompile(stringBuilder, rightExpr, new CodeCastExpression()); if (mustParenthesize) stringBuilder.Append(")"); return; } } } mustParenthesize = RuleDecompiler.MustParenthesize(binaryExpr, parentExpression); if (mustParenthesize) stringBuilder.Append("("); RuleExpressionWalker.Decompile(stringBuilder, leftExpr, binaryExpr); stringBuilder.Append(opString); RuleExpressionWalker.Decompile(stringBuilder, rightExpr, binaryExpr); if (mustParenthesize) stringBuilder.Append(")"); }
// // FindServicePoint - Query using an Uri for a given server point // /// <include file='doc\ServicePointManager.uex' path='docs/doc[@for="ServicePointManager.FindServicePoint2"]/*' /> /// <devdoc> /// <para>Findes an existing <see cref='System.Net.ServicePoint'/> or creates a new <see cref='System.Net.ServicePoint'/> to manage communications to the specified <see cref='System.Uri'/> /// instance.</para> /// </devdoc> public static ServicePoint FindServicePoint(Uri address, IWebProxy proxy) { if (address==null) { throw new ArgumentNullException("address"); } GlobalLog.Enter("ServicePointManager::FindServicePoint() address:" + address.ToString()); string tempEntry; bool isProxyServicePoint = false; ScavengeIdleServicePoints(); // // find proxy info, and then switch on proxy // if (proxy!=null && !proxy.IsBypassed(address)) { // use proxy support // rework address Uri proxyAddress = proxy.GetProxy(address); if (proxyAddress.Scheme != Uri.UriSchemeHttps && proxyAddress.Scheme != Uri.UriSchemeHttp) { Exception exception = new NotSupportedException(SR.GetString(SR.net_proxyschemenotsupported, proxyAddress.Scheme)); GlobalLog.LeaveException("ServicePointManager::FindServicePoint() proxy has unsupported scheme:" + proxyAddress.Scheme.ToString(), exception); throw exception; } address = proxyAddress; isProxyServicePoint = true; // // Search for the correct proxy host, // then match its acutal host by using ConnectionGroups // which are located on the actual ServicePoint. // tempEntry = MakeQueryString(proxyAddress); } else { // // Typical Host lookup // tempEntry = MakeQueryString(address); } // // lookup service point in the table // ServicePoint servicePoint = null; lock (s_ServicePointTable) { // // once we grab the lock, check if it wasn't already added // WeakReference servicePointReference = (WeakReference) s_ServicePointTable[tempEntry]; if ( servicePointReference != null ) { servicePoint = (ServicePoint)servicePointReference.Target; } if (servicePoint == null) { // // lookup failure or timeout, we need to create a new ServicePoint // if (s_MaxServicePoints<=0 || s_ServicePointTable.Count<s_MaxServicePoints) { // // Determine Connection Limit // int connectionLimit = InternalConnectionLimit; string schemeHostPort = MakeQueryString(address); if (ConfigTable.ContainsKey(schemeHostPort) ) { connectionLimit = (int) ConfigTable[schemeHostPort]; } // Note: we don't check permissions to access proxy. // Rather, we should protect proxy property from being changed servicePoint = new ServicePoint(address, s_MaxServicePointIdleTime, connectionLimit); servicePointReference = new WeakReference(servicePoint); // only set this when created, donates a proxy, statt Server servicePoint.InternalProxyServicePoint = isProxyServicePoint; s_ServicePointTable[tempEntry] = servicePointReference; } else { Exception exception = new InvalidOperationException(SR.GetString(SR.net_maxsrvpoints)); GlobalLog.LeaveException("ServicePointManager::FindServicePoint() reached the limit count:" + s_ServicePointTable.Count.ToString() + " limit:" + s_MaxServicePoints.ToString(), exception); throw exception; } } } // lock GlobalLog.Leave("ServicePointManager::FindServicePoint() servicePoint#" + ValidationHelper.HashString(servicePoint)); return servicePoint; }
private void OpenBackground_DoWork(object sender, DoWorkEventArgs e) { try { using (FileStream stream = new FileStream(ProjectSavePath, FileMode.Open)) { ZipFile zippy = new ZipFile(stream); //File (*.depro) Version int Fileversion = Convert.ToInt32(zippy.ZipFileComment); if (Fileversion == 2) { OpenProjectV2(zippy); } else { ThreadException = new NotSupportedException("This fileversion is not supported! Sorry!"); e.Result = false; return; } } //checking for missing files: (make option to search for it later) bool filenotfound = false; for (int i = 0; i < AllFiles.Count; i++) { if (File.Exists(AllFiles[i].FilePath) == false){ filenotfound = true; break; } } if (filenotfound == true) { ThreadException = new FileNotFoundException(); e.Result = false; return; } e.Result = true; } catch (Exception ex) { e.Result = false; ThreadException = ex; } }
/// <summary> /// Initializes the Level. /// </summary> /// <param name="randomSeed">Randomizer Seed</param> /// <param name="slots">List of Slots</param> public void Init(int randomSeed, params LevelSlot[] slots) { // Init only allowed in Uninit-Mode. if (Mode != LevelMode.Uninit) { throw new NotSupportedException("Level is not ready for init"); } // Initialize the Randomizer. RandomSeed = (int)DateTime.Now.Ticks; if (randomSeed != 0) { RandomSeed = randomSeed; } // Generate the Simulation Context for this Level. Context = new SimulationContext( Context.Resolver, Context.Settings, new Random(RandomSeed)); // Check for the right number of Slots. if (slots.Length > MAX_SLOTS) { var exception = new ArgumentOutOfRangeException("There are too many Slots"); SetMode(LevelMode.InitFailed, exception); throw exception; } // Generate Engine engine = new Engine(Context.Resolver); // Generate Map and validate. Map map = GetMap(); if (map == null) { var exception = new NotSupportedException("No Map was created"); SetMode(LevelMode.InitFailed, exception); throw exception; } map.CheckMap(); int minPlayer = LevelDescription.MinPlayerCount; int maxPlayer = LevelDescription.MaxPlayerCount; // TODO: Ermitteln der Filter Attribute //object[] levelFilters = GetType().GetCustomAttributes(typeof(FactionFilterAttribute), false); //var filters = new Dictionary<int, List<FactionFilterAttribute>>(); //foreach (FactionFilterAttribute item in levelFilters) //{ // if (!filters.ContainsKey(item.SlotIndex)) // filters.Add(item.SlotIndex, new List<FactionFilterAttribute>()); // filters[item.SlotIndex].Add(item); //} // Check for Color Collisions. var colors = new List <PlayerColor>(); foreach (var slot in slots) { if (slot != null) { if (colors.Contains(slot.Color)) { var exception = new NotSupportedException("There are two Players with the same color"); SetMode(LevelMode.InitFailed, exception); throw exception; } colors.Add(slot.Color); } } // Gegencheck mit Level-Attributen int playerCount = 0; int highestSlot = 0; for (int i = 0; i < slots.Length; i++) { if (slots[i] != null) { // Counter playerCount++; highestSlot = i; // TODO: Filter //if (filters.ContainsKey(i) && filters[i].Count > 0) //{ // if (filters[i].Any(item => item.FactionType == slots[i].GetType())) // continue; // Mode = LevelMode.InitFailed; // Factions = null; // throw new NotSupportedException(string.Format( // "Faction '{0}' is not allowed in Slot {1}", // slots[i].GetType(), i)); //} } } // Faction Counts mit Map- und Level-Requirements gegenchecken if (playerCount < minPlayer) { var exception = new NotSupportedException(string.Format("Not enought player. Requires {0} Player", minPlayer)); SetMode(LevelMode.InitFailed, exception); throw exception; } if (playerCount > maxPlayer) { var exception = new NotSupportedException(string.Format("Too many player. Requires a Maximum of {0} Player", maxPlayer)); SetMode(LevelMode.InitFailed, exception); throw exception; } if (highestSlot > map.GetPlayerCount()) { var exception = new NotSupportedException(string.Format("Too many Slots used. Map has only {0} Slots", map.GetPlayerCount())); SetMode(LevelMode.InitFailed, exception); throw exception; } // Factions erzeugen Factions = new Faction[MAX_SLOTS]; for (int i = 0; i < slots.Length; i++) { if (slots[i] == null) { continue; } SimulationContext factionContext = new SimulationContext(Context.Resolver, slotSettings[i]); // Identify and generate Faction try { Factions[i] = Context.Resolver.CreateFaction(factionContext, slots[i].FactoryType, this); } catch (Exception ex) { SetMode(LevelMode.InitFailed, ex); throw; } // In Case the Faction could not be found... if (Factions[i] == null) { var exception = new Exception(string.Format("Cound not identify Faction for player {0}.", slots[i].Name)); SetMode(LevelMode.InitFailed, exception); throw exception; } } // State erzeugen mapState = new MapState(); mapState.BlockBorder = map.BlockBorder; mapState.Tiles = (MapTile[, ])map.Tiles.Clone(); engine.Init(map); engine.OnInsertItem += engine_OnInsertItem; engine.OnRemoveItem += engine_OnRemoveItem; // Fraktionen ins Spiel einbetten for (byte i = 0; i < Factions.Length; i++) { try { InitFaction(i, slots[i], Factions[i]); } catch (Exception ex) { SetMode(LevelMode.PlayerException, ex, i); Factions = null; throw; } } // Initialisierung des Levels try { OnInit(); } catch (Exception ex) { SetMode(LevelMode.InitFailed, ex); Factions = null; throw; } SetMode(LevelMode.Running); }
private static RuleCodeDomStatement GetStatement(CodeStatement statement) { Type statementType = statement.GetType(); RuleCodeDomStatement wrapper = null; if (statementType == typeof(CodeExpressionStatement)) { wrapper = ExpressionStatement.Create(statement); } else if (statementType == typeof(CodeAssignStatement)) { wrapper = AssignmentStatement.Create(statement); } else { string message = string.Format(CultureInfo.CurrentCulture, Messages.CodeStatementNotHandled, statement.GetType().FullName); NotSupportedException exception = new NotSupportedException(message); exception.Data[RuleUserDataKeys.ErrorObject] = statement; throw exception; } return wrapper; }
internal static NotSupportedException NotSupported() { NotSupportedException e = new NotSupportedException(); return(e); }
private static ServicePoint FindServicePointHelper(Uri address, bool isProxyServicePoint) { GlobalLog.Enter("ServicePointManager::FindServicePointHelper() address:" + address.ToString()); if (isProxyServicePoint) { if (address.Scheme != Uri.UriSchemeHttp) { // < Exception exception = new NotSupportedException(SR.GetString(SR.net_proxyschemenotsupported, address.Scheme)); GlobalLog.LeaveException("ServicePointManager::FindServicePointHelper() proxy has unsupported scheme:" + address.Scheme.ToString(), exception); throw exception; } } // // Search for the correct proxy host, // then match its acutal host by using ConnectionGroups // which are located on the actual ServicePoint. // string tempEntry = MakeQueryString(address, isProxyServicePoint); // lookup service point in the table ServicePoint servicePoint = null; GlobalLog.Print("ServicePointManager::FindServicePointHelper() locking and looking up tempEntry:[" + tempEntry.ToString() + "]"); lock (s_ServicePointTable) { // once we grab the lock, check if it wasn't already added WeakReference servicePointReference = s_ServicePointTable[tempEntry] as WeakReference; GlobalLog.Print("ServicePointManager::FindServicePointHelper() lookup returned WeakReference#" + ValidationHelper.HashString(servicePointReference)); if ( servicePointReference != null ) { servicePoint = (ServicePoint)servicePointReference.Target; GlobalLog.Print("ServicePointManager::FindServicePointHelper() successful lookup returned ServicePoint#" + ValidationHelper.HashString(servicePoint)); } if (servicePoint==null) { // lookup failure or timeout, we need to create a new ServicePoint if (s_MaxServicePoints<=0 || s_ServicePointTable.Count<s_MaxServicePoints) { // Determine Connection Limit int connectionLimit = InternalConnectionLimit; string schemeHostPort = MakeQueryString(address); bool userDefined = s_UserChangedLimit; if (ConfigTable.ContainsKey(schemeHostPort) ) { connectionLimit = (int) ConfigTable[schemeHostPort]; userDefined = true; } servicePoint = new ServicePoint(address, s_ServicePointIdlingQueue, connectionLimit, tempEntry, userDefined, isProxyServicePoint); GlobalLog.Print("ServicePointManager::FindServicePointHelper() created ServicePoint#" + ValidationHelper.HashString(servicePoint)); servicePointReference = new WeakReference(servicePoint); s_ServicePointTable[tempEntry] = servicePointReference; GlobalLog.Print("ServicePointManager::FindServicePointHelper() adding entry WeakReference#" + ValidationHelper.HashString(servicePointReference) + " key:[" + tempEntry + "]"); } else { Exception exception = new InvalidOperationException(SR.GetString(SR.net_maxsrvpoints)); GlobalLog.LeaveException("ServicePointManager::FindServicePointHelper() reached the limit count:" + s_ServicePointTable.Count.ToString() + " limit:" + s_MaxServicePoints.ToString(), exception); throw exception; } } } GlobalLog.Leave("ServicePointManager::FindServicePointHelper() servicePoint#" + ValidationHelper.HashString(servicePoint)); return servicePoint; }
[InlineData(typeof(ConcurrentBag <string>), @"[""1""]")] // Not supported. Not IList, and we don't detect the add method for this collection. public static void Read_ConcurrentCollection_Throws(Type type, string json) { NotSupportedException ex = Assert.Throws <NotSupportedException>(() => JsonSerializer.Deserialize(json, type)); Assert.Contains(type.ToString(), ex.Message); }
static internal NotSupportedException NotSupported() { NotSupportedException e = new NotSupportedException(); return e; }
public static Exception ToIotHubClientContract(Error error) { Exception retException; if (error == null) { retException = new IotHubException("Unknown error."); return(retException); } string message = error.Description; string trackingId = null; if (error.Info != null && error.Info.TryGetValue(AmqpIotConstants.TrackingId, out trackingId)) { message = "{0}{1}{2}".FormatInvariant(message, Environment.NewLine, "Tracking Id:" + trackingId); } if (error.Condition.Equals(TimeoutError)) { retException = new TimeoutException(message); } else if (error.Condition.Equals(AmqpErrorCode.NotFound)) { retException = new DeviceNotFoundException(message, (Exception)null); } else if (error.Condition.Equals(AmqpErrorCode.NotImplemented)) { retException = new NotSupportedException(message); } else if (error.Condition.Equals(MessageLockLostError)) { retException = new DeviceMessageLockLostException(message); } else if (error.Condition.Equals(AmqpErrorCode.NotAllowed)) { retException = new InvalidOperationException(message); } else if (error.Condition.Equals(AmqpErrorCode.UnauthorizedAccess)) { retException = new UnauthorizedException(message); } else if (error.Condition.Equals(ArgumentError)) { retException = new ArgumentException(message); } else if (error.Condition.Equals(ArgumentOutOfRangeError)) { retException = new ArgumentOutOfRangeException(message); } else if (error.Condition.Equals(AmqpErrorCode.MessageSizeExceeded)) { retException = new MessageTooLargeException(message); } else if (error.Condition.Equals(AmqpErrorCode.ResourceLimitExceeded)) { // Note: The DeviceMaximumQueueDepthExceededException is not supposed to be thrown here as it is being mapped to the incorrect error code // Error code 403004 is only applicable to C2D (Service client); see https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-troubleshoot-error-403004-devicemaximumqueuedepthexceeded // Error code 403002 is applicable to D2C (Device client); see https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-troubleshoot-error-403002-iothubquotaexceeded // We have opted not to change the exception type thrown here since it will be a breaking change, alternatively, we are adding the correct exception type // as the inner exception. retException = new DeviceMaximumQueueDepthExceededException( $"Please check the inner exception for more information.\n " + $"The correct exception type is `{nameof(QuotaExceededException)}` " + $"but since that is a breaking change to the current behavior in the SDK, you can refer to the inner exception " + $"for more information. Exception message: {message}", new QuotaExceededException(message)); } else if (error.Condition.Equals(DeviceContainerThrottled)) { retException = new IotHubThrottledException(message, null); } else if (error.Condition.Equals(IotHubSuspended)) { retException = new IotHubSuspendedException(message); } else { retException = new IotHubException(message); } if (trackingId != null && retException is IotHubException) { var iotHubException = (IotHubException)retException; iotHubException.TrackingId = trackingId; } return(retException); }
static internal NotSupportedException NotSupported(string error) { NotSupportedException e = new NotSupportedException(error); return e; }
/// <summary> /// The main processing loop of the command. /// </summary> protected override void ProcessRecord() { string path = GetFilePath(); if (path == null) { return; } if (!File.Exists(path)) { InvalidOperationException ioe = PSTraceSource.NewInvalidOperationException( ImportLocalizedDataStrings.FileNotExist, path); WriteError(new ErrorRecord(ioe, "ImportLocalizedData", ErrorCategory.ObjectNotFound, path)); return; } // Prevent additional commands in ConstrainedLanguage mode if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) { if (_setSupportedCommand) { NotSupportedException nse = PSTraceSource.NewNotSupportedException( ImportLocalizedDataStrings.CannotDefineSupportedCommand); ThrowTerminatingError( new ErrorRecord(nse, "CannotDefineSupportedCommand", ErrorCategory.PermissionDenied, null)); } } string script = GetScript(path); if (script == null) { return; } try { var scriptBlock = Context.Engine.ParseScriptBlock(script, false); scriptBlock.CheckRestrictedLanguage(SupportedCommand, null, false); object result; PSLanguageMode oldLanguageMode = Context.LanguageMode; Context.LanguageMode = PSLanguageMode.RestrictedLanguage; try { result = scriptBlock.InvokeReturnAsIs(); if (result == AutomationNull.Value) { result = null; } } finally { Context.LanguageMode = oldLanguageMode; } if (_bindingVariable != null) { VariablePath variablePath = new(_bindingVariable); if (variablePath.IsUnscopedVariable) { variablePath = variablePath.CloneAndSetLocal(); } if (string.IsNullOrEmpty(variablePath.UnqualifiedPath)) { InvalidOperationException ioe = PSTraceSource.NewInvalidOperationException( ImportLocalizedDataStrings.IncorrectVariableName, _bindingVariable); WriteError(new ErrorRecord(ioe, "ImportLocalizedData", ErrorCategory.InvalidArgument, _bindingVariable)); return; } SessionStateScope scope = null; PSVariable variable = SessionState.Internal.GetVariableItem(variablePath, out scope); if (variable == null) { variable = new PSVariable(variablePath.UnqualifiedPath, result, ScopedItemOptions.None); Context.EngineSessionState.SetVariable(variablePath, variable, false, CommandOrigin.Internal); } else { variable.Value = result; if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) { // Mark untrusted values for assignments to 'Global:' variables, and 'Script:' variables in // a module scope, if it's necessary. ExecutionContext.MarkObjectAsUntrustedForVariableAssignment(variable, scope, Context.EngineSessionState); } } } // If binding variable is null, write the object to stream else { WriteObject(result); } } catch (RuntimeException e) { PSInvalidOperationException ioe = PSTraceSource.NewInvalidOperationException(e, ImportLocalizedDataStrings.ErrorLoadingDataFile, path, e.Message); throw ioe; } return; }
public static void SeedAllPositions(AppDbContext db) { if (db.Positions.Count() == 16) { NotSupportedException ex = new NotSupportedException("Already 16 Positions"); throw ex; } Int32 intPositionsAdded = 0; List <Position> Positions = new List <Position>(); List <MajorDetail> majorDetails = new List <MajorDetail>(); try { Position p1 = new Position() { Title = "Supply Chain Internship", Description = "", PositionType = PositionType.Internship, Location = "Houston, Texas", Deadline = new DateTime(2019, 05, 05) }; p1.Company = db.Companies.FirstOrDefault(c => c.Name == "Shell"); MajorDetail mj1 = new MajorDetail() { Position = p1, Major = db.Majors.FirstOrDefault(m => m.Name == "Supply Chain Management") }; majorDetails.Add(mj1); Positions.Add(p1); Position p2 = new Position() { Title = "Accounting Intern", Description = "Work in our audit group", PositionType = PositionType.Internship, Location = "Austin, Texas", Deadline = new DateTime(2019, 05, 01) }; p2.Company = db.Companies.FirstOrDefault(c => c.Name == "Deloitte"); MajorDetail mj2 = new MajorDetail() { Position = p2, Major = db.Majors.FirstOrDefault(m => m.Name == "Accounting") }; majorDetails.Add(mj2); Positions.Add(p2); Position p3 = new Position() { Title = "Web Development", Description = "Developing a great new website for customer portfolio management", PositionType = PositionType.FullTime, Location = "Richmond, Virginia", Deadline = new DateTime(2019, 03, 14) }; p3.Company = db.Companies.FirstOrDefault(c => c.Name == "Capital One"); MajorDetail mj3 = new MajorDetail() { Position = p3, Major = db.Majors.FirstOrDefault(m => m.Name == "MIS") }; majorDetails.Add(mj3); Positions.Add(p3); Position p4 = new Position() { Title = "Sales Associate", Description = "", PositionType = PositionType.FullTime, Location = "Los Angeles, California", Deadline = new DateTime(2019, 04, 01) }; p4.Company = db.Companies.FirstOrDefault(c => c.Name == "Aon"); MajorDetail mj4 = new MajorDetail() { Position = p4, Major = db.Majors.FirstOrDefault(m => m.Name == "Accounting") }; majorDetails.Add(mj4); MajorDetail mj5 = new MajorDetail() { Position = p4, Major = db.Majors.FirstOrDefault(m => m.Name == "Marketing") }; majorDetails.Add(mj5); MajorDetail mj6 = new MajorDetail() { Position = p4, Major = db.Majors.FirstOrDefault(m => m.Name == "Finance") }; majorDetails.Add(mj6); Positions.Add(p4); Position p5 = new Position() { Title = "Amenities Analytics Intern", Description = "Help analyze our amenities and customer rewards programs", PositionType = PositionType.Internship, Location = "New York, New York", Deadline = new DateTime(2019, 03, 30) }; p5.Company = db.Companies.FirstOrDefault(c => c.Name == "Hilton Worldwide"); MajorDetail mj7 = new MajorDetail() { Position = p5, Major = db.Majors.FirstOrDefault(m => m.Name == "Finance") }; majorDetails.Add(mj7); MajorDetail mj8 = new MajorDetail() { Position = p5, Major = db.Majors.FirstOrDefault(m => m.Name == "MIS") }; majorDetails.Add(mj8); MajorDetail mj9 = new MajorDetail() { Position = p5, Major = db.Majors.FirstOrDefault(m => m.Name == "Marketing") }; majorDetails.Add(mj9); MajorDetail mj10 = new MajorDetail() { Position = p5, Major = db.Majors.FirstOrDefault(m => m.Name == "Business Honors") }; majorDetails.Add(mj10); Positions.Add(p5); Position p6 = new Position() { Title = "Junior Programmer", Description = "", PositionType = PositionType.Internship, Location = "Redmond, Washington", Deadline = new DateTime(2019, 04, 03) }; p6.Company = db.Companies.FirstOrDefault(c => c.Name == "Microsoft"); MajorDetail mj11 = new MajorDetail() { Position = p6, Major = db.Majors.FirstOrDefault(m => m.Name == "MIS") }; majorDetails.Add(mj11); Positions.Add(p6); Position p7 = new Position() { Title = "Consultant ", Description = "Full-time consultant position", PositionType = PositionType.FullTime, Location = "Houston, Texas", Deadline = new DateTime(2019, 04, 15) }; p7.Company = db.Companies.FirstOrDefault(c => c.Name == "Accenture"); MajorDetail mj12 = new MajorDetail() { Position = p7, Major = db.Majors.FirstOrDefault(m => m.Name == "MIS") }; majorDetails.Add(mj12); MajorDetail mj13 = new MajorDetail() { Position = p7, Major = db.Majors.FirstOrDefault(m => m.Name == "Accounting") }; majorDetails.Add(mj13); MajorDetail mj14 = new MajorDetail() { Position = p7, Major = db.Majors.FirstOrDefault(m => m.Name == "Business Honors") }; majorDetails.Add(mj14); Positions.Add(p7); Position p8 = new Position() { Title = "Project Manager", Description = "", PositionType = PositionType.FullTime, Location = "Chicago, Illinois", Deadline = new DateTime(2019, 06, 01) }; p8.Company = db.Companies.FirstOrDefault(c => c.Name == "Aon"); MajorDetail mj15 = new MajorDetail() { Position = p8, Major = db.Majors.FirstOrDefault(m => m.Name == "MIS") }; majorDetails.Add(mj15); MajorDetail mj16 = new MajorDetail() { Position = p8, Major = db.Majors.FirstOrDefault(m => m.Name == "Supply Chain Management") }; majorDetails.Add(mj16); MajorDetail mj17 = new MajorDetail() { Position = p8, Major = db.Majors.FirstOrDefault(m => m.Name == "Accounting") }; majorDetails.Add(mj17); MajorDetail mj18 = new MajorDetail() { Position = p8, Major = db.Majors.FirstOrDefault(m => m.Name == "Marketing") }; majorDetails.Add(mj18); MajorDetail mj19 = new MajorDetail() { Position = p8, Major = db.Majors.FirstOrDefault(m => m.Name == "Finance") }; majorDetails.Add(mj19); MajorDetail mj20 = new MajorDetail() { Position = p8, Major = db.Majors.FirstOrDefault(m => m.Name == "International Business") }; majorDetails.Add(mj20); MajorDetail mj21 = new MajorDetail() { Position = p8, Major = db.Majors.FirstOrDefault(m => m.Name == "Business Honors") }; majorDetails.Add(mj21); Positions.Add(p8); Position p9 = new Position() { Title = "Account Manager", Description = "", PositionType = PositionType.FullTime, Location = "Dallas, Texas", Deadline = new DateTime(2019, 02, 28) }; p9.Company = db.Companies.FirstOrDefault(c => c.Name == "Deloitte"); MajorDetail mj23 = new MajorDetail() { Position = p9, Major = db.Majors.FirstOrDefault(m => m.Name == "Accounting") }; majorDetails.Add(mj23); MajorDetail mj24 = new MajorDetail() { Position = p9, Major = db.Majors.FirstOrDefault(m => m.Name == "Business Honors") }; majorDetails.Add(mj24); Positions.Add(p9); Position p10 = new Position() { Title = "Marketing Intern", Description = "Help our marketing team develop new advertising strategies for local Austin businesses", PositionType = PositionType.Internship, Location = "Austin, Texas", Deadline = new DateTime(2019, 04, 30) }; p10.Company = db.Companies.FirstOrDefault(c => c.Name == "Adlucent"); MajorDetail mj25 = new MajorDetail() { Position = p10, Major = db.Majors.FirstOrDefault(m => m.Name == "Marketing") }; majorDetails.Add(mj25); Positions.Add(p10); Position p11 = new Position() { Title = "Financial Analyst", Description = "", PositionType = PositionType.FullTime, Location = "Richmond, Virginia", Deadline = new DateTime(2019, 04, 15) }; p11.Company = db.Companies.FirstOrDefault(c => c.Name == "Capital One"); MajorDetail mj26 = new MajorDetail() { Position = p11, Major = db.Majors.FirstOrDefault(m => m.Name == "Finance") }; majorDetails.Add(mj26); Positions.Add(p11); Position p12 = new Position() { Title = "Pilot", Description = "", PositionType = PositionType.FullTime, Location = "Ft. Worth, Texas", Deadline = new DateTime(2019, 10, 08) }; p12.Company = db.Companies.FirstOrDefault(c => c.Name == "United Airlines"); MajorDetail mj27 = new MajorDetail() { Position = p12, Major = db.Majors.FirstOrDefault(m => m.Name == "MIS") }; majorDetails.Add(mj27); MajorDetail mj28 = new MajorDetail() { Position = p12, Major = db.Majors.FirstOrDefault(m => m.Name == "Supply Chain Management") }; majorDetails.Add(mj28); MajorDetail mj29 = new MajorDetail() { Position = p12, Major = db.Majors.FirstOrDefault(m => m.Name == "Accounting") }; majorDetails.Add(mj29); MajorDetail mj30 = new MajorDetail() { Position = p12, Major = db.Majors.FirstOrDefault(m => m.Name == "Marketing") }; majorDetails.Add(mj30); MajorDetail mj31 = new MajorDetail() { Position = p12, Major = db.Majors.FirstOrDefault(m => m.Name == "Finance") }; majorDetails.Add(mj31); MajorDetail mj32 = new MajorDetail() { Position = p12, Major = db.Majors.FirstOrDefault(m => m.Name == "International Business") }; majorDetails.Add(mj32); MajorDetail mj33 = new MajorDetail() { Position = p12, Major = db.Majors.FirstOrDefault(m => m.Name == "Business Honors") }; majorDetails.Add(mj33); Positions.Add(p12); Position p13 = new Position() { Title = "Corporate Recruiting Intern", Description = "", PositionType = PositionType.Internship, Location = "Redmond, Washington", Deadline = new DateTime(2019, 04, 30) }; p13.Company = db.Companies.FirstOrDefault(c => c.Name == "Microsoft"); MajorDetail mj35 = new MajorDetail() { Position = p13, Major = db.Majors.FirstOrDefault(m => m.Name == "Management") }; majorDetails.Add(mj35); Positions.Add(p13); Position p14 = new Position() { Title = "Business Analyst", Description = "", PositionType = PositionType.FullTime, Location = "Austin, Texas", Deadline = new DateTime(2019, 05, 31) }; p14.Company = db.Companies.FirstOrDefault(c => c.Name == "Microsoft"); MajorDetail mj36 = new MajorDetail() { Position = p14, Major = db.Majors.FirstOrDefault(m => m.Name == "MIS") }; majorDetails.Add(mj36); Positions.Add(p14); Position p15 = new Position() { Title = "Programmer Analyst", Description = "", PositionType = PositionType.FullTime, Location = "Minneapolis, Minnesota", Deadline = new DateTime(2019, 05, 15) }; p15.Company = db.Companies.FirstOrDefault(c => c.Name == "Target"); MajorDetail mj37 = new MajorDetail() { Position = p15, Major = db.Majors.FirstOrDefault(m => m.Name == "MIS") }; majorDetails.Add(mj37); Positions.Add(p15); Position p16 = new Position() { Title = "Intern", Description = "", PositionType = PositionType.Internship, Location = "Minneapolis, Minnesota", Deadline = new DateTime(2019, 05, 15) }; p16.Company = db.Companies.FirstOrDefault(c => c.Name == "Target"); MajorDetail mj38 = new MajorDetail() { Position = p16, Major = db.Majors.FirstOrDefault(m => m.Name == "Finance") }; majorDetails.Add(mj38); MajorDetail mj66 = new MajorDetail() { Position = p16, Major = db.Majors.FirstOrDefault(m => m.Name == "MIS") }; majorDetails.Add(mj66); MajorDetail mj67 = new MajorDetail() { Position = p16, Major = db.Majors.FirstOrDefault(m => m.Name == "Accounting") }; majorDetails.Add(mj67); MajorDetail mj68 = new MajorDetail() { Position = p16, Major = db.Majors.FirstOrDefault(m => m.Name == "International Business") }; majorDetails.Add(mj68); MajorDetail mj69 = new MajorDetail() { Position = p16, Major = db.Majors.FirstOrDefault(m => m.Name == "Business Honors") }; majorDetails.Add(mj69); MajorDetail mj70 = new MajorDetail() { Position = p16, Major = db.Majors.FirstOrDefault(m => m.Name == "Supply Chain Management") }; majorDetails.Add(mj70); MajorDetail mj71 = new MajorDetail() { Position = p16, Major = db.Majors.FirstOrDefault(m => m.Name == "Science and Technology Management") }; majorDetails.Add(mj71); MajorDetail mj72 = new MajorDetail() { Position = p16, Major = db.Majors.FirstOrDefault(m => m.Name == "Management") }; majorDetails.Add(mj72); MajorDetail mj73 = new MajorDetail() { Position = p16, Major = db.Majors.FirstOrDefault(m => m.Name == "Marketing") }; majorDetails.Add(mj73); Positions.Add(p16); Position p17 = new Position() { Title = "Digital Intern", Description = "", PositionType = PositionType.Internship, Location = "Dallas, Texas", Deadline = new DateTime(2019, 05, 20) }; p17.Company = db.Companies.FirstOrDefault(c => c.Name == "Accenture"); MajorDetail mj39 = new MajorDetail() { Position = p17, Major = db.Majors.FirstOrDefault(m => m.Name == "MIS") }; majorDetails.Add(mj39); MajorDetail mj40 = new MajorDetail() { Position = p17, Major = db.Majors.FirstOrDefault(m => m.Name == "Marketing") }; majorDetails.Add(mj40); Positions.Add(p17); Position p18 = new Position() { Title = "Analyst Development Program", Description = "", PositionType = PositionType.Internship, Location = "Plano, Texas", Deadline = new DateTime(2019, 05, 20) }; p18.Company = db.Companies.FirstOrDefault(c => c.Name == "Capital One"); MajorDetail mj41 = new MajorDetail() { Position = p18, Major = db.Majors.FirstOrDefault(m => m.Name == "Finance") }; majorDetails.Add(mj41); MajorDetail mj42 = new MajorDetail() { Position = p18, Major = db.Majors.FirstOrDefault(m => m.Name == "MIS") }; majorDetails.Add(mj42); MajorDetail mj43 = new MajorDetail() { Position = p18, Major = db.Majors.FirstOrDefault(m => m.Name == "Business Honors") }; majorDetails.Add(mj43); Positions.Add(p18); Position p19 = new Position() { Title = "Procurements Associate", Description = "Handle procurement and vendor accounts", PositionType = PositionType.FullTime, Location = "Houston, Texas", Deadline = new DateTime(2019, 05, 30) }; p19.Company = db.Companies.FirstOrDefault(c => c.Name == "Shell"); MajorDetail mj44 = new MajorDetail() { Position = p19, Major = db.Majors.FirstOrDefault(m => m.Name == "Supply Chain Management") }; majorDetails.Add(mj44); Positions.Add(p19); Position p20 = new Position() { Title = "IT Rotational Program", Description = "", PositionType = PositionType.FullTime, Location = "Dallas, Texas", Deadline = new DateTime(2019, 05, 30) }; p20.Company = db.Companies.FirstOrDefault(c => c.Name == "Texas Instruments"); MajorDetail mj45 = new MajorDetail() { Position = p20, Major = db.Majors.FirstOrDefault(m => m.Name == "MIS") }; majorDetails.Add(mj45); Positions.Add(p20); Position p21 = new Position() { Title = "Sales Rotational Program", Description = "", PositionType = PositionType.FullTime, Location = "Dallas, Texas", Deadline = new DateTime(2019, 05, 30) }; p21.Company = db.Companies.FirstOrDefault(c => c.Name == "Texas Instruments"); MajorDetail mj46 = new MajorDetail() { Position = p21, Major = db.Majors.FirstOrDefault(m => m.Name == "Marketing") }; majorDetails.Add(mj46); MajorDetail mj47 = new MajorDetail() { Position = p21, Major = db.Majors.FirstOrDefault(m => m.Name == "Management") }; majorDetails.Add(mj47); MajorDetail mj48 = new MajorDetail() { Position = p21, Major = db.Majors.FirstOrDefault(m => m.Name == "Finance") }; majorDetails.Add(mj48); MajorDetail mj49 = new MajorDetail() { Position = p21, Major = db.Majors.FirstOrDefault(m => m.Name == "Accounting") }; majorDetails.Add(mj49); Positions.Add(p21); Position p22 = new Position() { Title = "Accounting Rotational Program", Description = "", PositionType = PositionType.FullTime, Location = "Austin, Texas", Deadline = new DateTime(2019, 05, 30) }; p22.Company = db.Companies.FirstOrDefault(c => c.Name == "Texas Instruments"); MajorDetail mj50 = new MajorDetail() { Position = p22, Major = db.Majors.FirstOrDefault(m => m.Name == "Accounting") }; majorDetails.Add(mj50); Positions.Add(p22); Position p23 = new Position() { Title = "Financial Planning Intern", Description = "", PositionType = PositionType.Internship, Location = "Orlando, Florida", Deadline = new DateTime(2019, 06, 01) }; p23.Company = db.Companies.FirstOrDefault(c => c.Name == "Academy Sports & Outdoors"); MajorDetail mj51 = new MajorDetail() { Position = p23, Major = db.Majors.FirstOrDefault(m => m.Name == "Finance") }; majorDetails.Add(mj51); MajorDetail mj52 = new MajorDetail() { Position = p23, Major = db.Majors.FirstOrDefault(m => m.Name == "Accounting") }; majorDetails.Add(mj52); MajorDetail mj53 = new MajorDetail() { Position = p23, Major = db.Majors.FirstOrDefault(m => m.Name == "Business Honors") }; majorDetails.Add(mj53); Positions.Add(p23); Position p24 = new Position() { Title = "Digital Product Manager", Description = "", PositionType = PositionType.FullTime, Location = "Houston, Texas", Deadline = new DateTime(2019, 06, 01) }; p24.Company = db.Companies.FirstOrDefault(c => c.Name == "Academy Sports & Outdoors"); MajorDetail mj54 = new MajorDetail() { Position = p24, Major = db.Majors.FirstOrDefault(m => m.Name == "MIS") }; majorDetails.Add(mj54); MajorDetail mj55 = new MajorDetail() { Position = p24, Major = db.Majors.FirstOrDefault(m => m.Name == "Marketing") }; majorDetails.Add(mj55); MajorDetail mj56 = new MajorDetail() { Position = p24, Major = db.Majors.FirstOrDefault(m => m.Name == "Business Honors") }; majorDetails.Add(mj56); MajorDetail mj57 = new MajorDetail() { Position = p24, Major = db.Majors.FirstOrDefault(m => m.Name == "Management") }; majorDetails.Add(mj57); Positions.Add(p24); Position p25 = new Position() { Title = "Product Marketing Intern", Description = "", PositionType = PositionType.Internship, Location = "Redmond, Washington", Deadline = new DateTime(2019, 06, 01) }; p25.Company = db.Companies.FirstOrDefault(c => c.Name == "Microsoft"); MajorDetail mj58 = new MajorDetail() { Position = p25, Major = db.Majors.FirstOrDefault(m => m.Name == "Marketing") }; majorDetails.Add(mj58); MajorDetail mj59 = new MajorDetail() { Position = p25, Major = db.Majors.FirstOrDefault(m => m.Name == "MIS") }; majorDetails.Add(mj59); Positions.Add(p25); Position p26 = new Position() { Title = "Program Manager", Description = "", PositionType = PositionType.FullTime, Location = "Redmond, Washington", Deadline = new DateTime(2019, 06, 01) }; p26.Company = db.Companies.FirstOrDefault(c => c.Name == "Microsoft"); MajorDetail mj60 = new MajorDetail() { Position = p26, Major = db.Majors.FirstOrDefault(m => m.Name == "Marketing") }; majorDetails.Add(mj60); MajorDetail mj61 = new MajorDetail() { Position = p26, Major = db.Majors.FirstOrDefault(m => m.Name == "MIS") }; majorDetails.Add(mj61); Positions.Add(p26); Position p27 = new Position() { Title = "Security Analyst", Description = "", PositionType = PositionType.FullTime, Location = "Redmond, Washington", Deadline = new DateTime(2019, 06, 01) }; p27.Company = db.Companies.FirstOrDefault(c => c.Name == "Microsoft"); MajorDetail mj62 = new MajorDetail() { Position = p27, Major = db.Majors.FirstOrDefault(m => m.Name == "MIS") }; majorDetails.Add(mj62); Positions.Add(p27); Position p28 = new Position() { Title = "Big Data Analyst", Description = "", PositionType = PositionType.FullTime, Location = "Dallas, Texas", Deadline = new DateTime(2019, 05, 09) }; p28.Company = db.Companies.FirstOrDefault(c => c.Name == "United Airlines"); MajorDetail mj63 = new MajorDetail() { Position = p28, Major = db.Majors.FirstOrDefault(m => m.Name == "MIS") }; majorDetails.Add(mj63); MajorDetail mj64 = new MajorDetail() { Position = p28, Major = db.Majors.FirstOrDefault(m => m.Name == "Finance") }; majorDetails.Add(mj64); Positions.Add(p28); try { foreach (Position positionToAdd in Positions) { Position dbPosition = db.Positions.FirstOrDefault(m => m.Title == positionToAdd.Title); if (dbPosition == null) { db.Positions.Add(positionToAdd); db.SaveChanges(); intPositionsAdded += 1; } else { dbPosition.Title = positionToAdd.Title; dbPosition.Description = positionToAdd.Description; dbPosition.PositionType = positionToAdd.PositionType; dbPosition.Location = positionToAdd.Location; dbPosition.Company = positionToAdd.Company; dbPosition.Deadline = positionToAdd.Deadline; dbPosition.MajorDetails = positionToAdd.MajorDetails; db.Update(dbPosition); db.SaveChanges(); intPositionsAdded += 1; } } foreach (MajorDetail mdToAdd in majorDetails) { MajorDetail dbMD = db.MajorDetails.FirstOrDefault(m => m.MajorDetailID == mdToAdd.MajorDetailID); if (dbMD == null) { db.MajorDetails.Add(mdToAdd); db.SaveChanges(); } else { dbMD.Position = mdToAdd.Position; dbMD.Major = mdToAdd.Major; db.Update(dbMD); db.SaveChanges(); } } } catch (Exception ex) { String msg = " Repositories added:" + intPositionsAdded + "; "; throw new InvalidOperationException(ex.Message + msg); } } catch (Exception e) { throw new InvalidOperationException(e.Message); } }
/// <summary> /// Receive web socket result /// </summary> /// <param name="buffer">The buffer to copy data into</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns>The web socket result details</returns> public override async Task <WebSocketReceiveResult> ReceiveAsync(ArraySegment <byte> buffer, CancellationToken cancellationToken) { try { // we may receive control frames so reading needs to happen in an infinite loop while (true) { // allow this operation to be cancelled from iniside OR outside this instance using (CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_internalReadCts.Token, cancellationToken)) { WebSocketFrame frame = null; try { frame = await WebSocketFrameReader.ReadAsync(_stream, buffer, linkedCts.Token); Events.Log.ReceivedFrame(_guid, frame.OpCode, frame.IsFinBitSet, frame.Count); } catch (SocketException) { // do nothing, the socket has been disconnected } catch (InternalBufferOverflowException ex) { await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.MessageTooBig, "Frame too large to fit in buffer. Use message fragmentation", ex); throw; } catch (ArgumentOutOfRangeException ex) { await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.ProtocolError, "Payload length out of range", ex); throw; } catch (EndOfStreamException ex) { await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.InvalidPayloadData, "Unexpected end of stream encountered", ex); throw; } catch (OperationCanceledException ex) { await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.EndpointUnavailable, "Operation cancelled", ex); throw; } catch (Exception ex) { await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.InternalServerError, "Error reading WebSocket frame", ex); throw; } switch (frame.OpCode) { case WebSocketOpCode.ConnectionClose: return(await RespondToCloseFrame(frame, buffer, linkedCts.Token)); case WebSocketOpCode.Ping: ArraySegment <byte> pingPayload = new ArraySegment <byte>(buffer.Array, buffer.Offset, frame.Count); await SendPongAsync(pingPayload, linkedCts.Token); break; case WebSocketOpCode.Pong: ArraySegment <byte> pongBuffer = new ArraySegment <byte>(buffer.Array, frame.Count, buffer.Offset); Pong?.Invoke(this, new PongEventArgs(pongBuffer)); break; case WebSocketOpCode.TextFrame: if (!frame.IsFinBitSet) { // continuation frames will follow, record the message type Text _continuationFrameMessageType = WebSocketMessageType.Text; } return(new WebSocketReceiveResult(frame.Count, WebSocketMessageType.Text, frame.IsFinBitSet)); case WebSocketOpCode.BinaryFrame: if (!frame.IsFinBitSet) { // continuation frames will follow, record the message type Binary _continuationFrameMessageType = WebSocketMessageType.Binary; } return(new WebSocketReceiveResult(frame.Count, WebSocketMessageType.Binary, frame.IsFinBitSet)); case WebSocketOpCode.ContinuationFrame: return(new WebSocketReceiveResult(frame.Count, _continuationFrameMessageType, frame.IsFinBitSet)); default: Exception ex = new NotSupportedException($"Unknown WebSocket opcode {frame.OpCode}"); await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.ProtocolError, ex.Message, ex); throw ex; } } } } catch (Exception catchAll) { // Most exceptions will be caught closer to their source to send an appropriate close message (and set the WebSocketState) // However, if an unhandled exception is encountered and a close message not sent then send one here if (_state == WebSocketState.Open) { await CloseOutputAutoTimeoutAsync(WebSocketCloseStatus.InternalServerError, "Unexpected error reading from WebSocket", catchAll); } throw; } }
internal override void Decompile(CodeExpression expression, StringBuilder stringBuilder, CodeExpression parentExpression) { string str3; bool flag = false; CodeBinaryOperatorExpression childExpr = (CodeBinaryOperatorExpression)expression; if (childExpr.Left == null) { RuleEvaluationException exception = new RuleEvaluationException(string.Format(CultureInfo.CurrentCulture, Messages.NullBinaryOpLHS, new object[] { childExpr.Operator.ToString() })); exception.Data["ErrorObject"] = childExpr; throw exception; } if (childExpr.Right == null) { RuleEvaluationException exception2 = new RuleEvaluationException(string.Format(CultureInfo.CurrentCulture, Messages.NullBinaryOpRHS, new object[] { childExpr.Operator.ToString() })); exception2.Data["ErrorObject"] = childExpr; throw exception2; } switch (childExpr.Operator) { case CodeBinaryOperatorType.Add: str3 = " + "; break; case CodeBinaryOperatorType.Subtract: str3 = " - "; break; case CodeBinaryOperatorType.Multiply: str3 = " * "; break; case CodeBinaryOperatorType.Divide: str3 = " / "; break; case CodeBinaryOperatorType.Modulus: str3 = " % "; break; case CodeBinaryOperatorType.IdentityInequality: str3 = " != "; break; case CodeBinaryOperatorType.IdentityEquality: case CodeBinaryOperatorType.ValueEquality: str3 = " == "; break; case CodeBinaryOperatorType.BitwiseOr: str3 = " | "; break; case CodeBinaryOperatorType.BitwiseAnd: str3 = " & "; break; case CodeBinaryOperatorType.BooleanOr: str3 = " || "; break; case CodeBinaryOperatorType.BooleanAnd: str3 = " && "; break; case CodeBinaryOperatorType.LessThan: str3 = " < "; break; case CodeBinaryOperatorType.LessThanOrEqual: str3 = " <= "; break; case CodeBinaryOperatorType.GreaterThan: str3 = " > "; break; case CodeBinaryOperatorType.GreaterThanOrEqual: str3 = " >= "; break; default: { NotSupportedException exception3 = new NotSupportedException(string.Format(CultureInfo.CurrentCulture, Messages.BinaryOpNotSupported, new object[] { childExpr.Operator.ToString() })); exception3.Data["ErrorObject"] = childExpr; throw exception3; } } CodeExpression left = childExpr.Left; CodeExpression right = childExpr.Right; if (childExpr.Operator == CodeBinaryOperatorType.ValueEquality) { CodePrimitiveExpression expression5 = right as CodePrimitiveExpression; if (expression5 != null) { object obj2 = expression5.Value; if (((obj2 != null) && (obj2.GetType() == typeof(bool))) && !((bool)obj2)) { CodeBinaryOperatorExpression expression6 = left as CodeBinaryOperatorExpression; if ((expression6 == null) || (expression6.Operator != CodeBinaryOperatorType.ValueEquality)) { flag = RuleDecompiler.MustParenthesize(left, parentExpression); if (flag) { stringBuilder.Append("("); } stringBuilder.Append("!"); RuleExpressionWalker.Decompile(stringBuilder, left, new CodeCastExpression()); if (flag) { stringBuilder.Append(")"); } return; } str3 = " != "; left = expression6.Left; right = expression6.Right; } } } else if (childExpr.Operator == CodeBinaryOperatorType.Subtract) { CodePrimitiveExpression expression7 = left as CodePrimitiveExpression; if ((expression7 != null) && (expression7.Value != null)) { object obj3 = expression7.Value; TypeCode typeCode = Type.GetTypeCode(obj3.GetType()); bool flag2 = false; switch (typeCode) { case TypeCode.Int32: flag2 = ((int)obj3) == 0; break; case TypeCode.Int64: flag2 = ((long)obj3) == 0L; break; case TypeCode.Single: flag2 = ((float)obj3) == 0f; break; case TypeCode.Double: flag2 = ((double)obj3) == 0.0; break; case TypeCode.Decimal: flag2 = ((decimal)obj3) == 0M; break; } if (flag2) { flag = RuleDecompiler.MustParenthesize(right, parentExpression); if (flag) { stringBuilder.Append("("); } stringBuilder.Append("-"); RuleExpressionWalker.Decompile(stringBuilder, right, new CodeCastExpression()); if (flag) { stringBuilder.Append(")"); } return; } } } flag = RuleDecompiler.MustParenthesize(childExpr, parentExpression); if (flag) { stringBuilder.Append("("); } RuleExpressionWalker.Decompile(stringBuilder, left, childExpr); stringBuilder.Append(str3); RuleExpressionWalker.Decompile(stringBuilder, right, childExpr); if (flag) { stringBuilder.Append(")"); } }
private static ServicePoint FindServicePointHelper(Uri address, bool isProxyServicePoint) { GlobalLog.Enter("ServicePointManager::FindServicePointHelper() address:" + address.ToString()); if (isProxyServicePoint) { if (address.Scheme != Uri.UriSchemeHttp) { // < Exception exception = new NotSupportedException(SR.GetString(SR.net_proxyschemenotsupported, address.Scheme)); GlobalLog.LeaveException("ServicePointManager::FindServicePointHelper() proxy has unsupported scheme:" + address.Scheme.ToString(), exception); throw exception; } } // // Search for the correct proxy host, // then match its acutal host by using ConnectionGroups // which are located on the actual ServicePoint. // string tempEntry = MakeQueryString(address, isProxyServicePoint); // lookup service point in the table ServicePoint servicePoint = null; GlobalLog.Print("ServicePointManager::FindServicePointHelper() locking and looking up tempEntry:[" + tempEntry.ToString() + "]"); lock (s_ServicePointTable) { // once we grab the lock, check if it wasn't already added WeakReference servicePointReference = s_ServicePointTable[tempEntry] as WeakReference; GlobalLog.Print("ServicePointManager::FindServicePointHelper() lookup returned WeakReference#" + ValidationHelper.HashString(servicePointReference)); if (servicePointReference != null) { servicePoint = (ServicePoint)servicePointReference.Target; GlobalLog.Print("ServicePointManager::FindServicePointHelper() successful lookup returned ServicePoint#" + ValidationHelper.HashString(servicePoint)); } if (servicePoint == null) { // lookup failure or timeout, we need to create a new ServicePoint if (s_MaxServicePoints <= 0 || s_ServicePointTable.Count < s_MaxServicePoints) { // Determine Connection Limit int connectionLimit = InternalConnectionLimit; string schemeHostPort = MakeQueryString(address); bool userDefined = s_UserChangedLimit; if (ConfigTable.ContainsKey(schemeHostPort)) { connectionLimit = (int)ConfigTable[schemeHostPort]; userDefined = true; } servicePoint = new ServicePoint(address, s_ServicePointIdlingQueue, connectionLimit, tempEntry, userDefined, isProxyServicePoint); GlobalLog.Print("ServicePointManager::FindServicePointHelper() created ServicePoint#" + ValidationHelper.HashString(servicePoint)); servicePointReference = new WeakReference(servicePoint); s_ServicePointTable[tempEntry] = servicePointReference; GlobalLog.Print("ServicePointManager::FindServicePointHelper() adding entry WeakReference#" + ValidationHelper.HashString(servicePointReference) + " key:[" + tempEntry + "]"); } else { Exception exception = new InvalidOperationException(SR.GetString(SR.net_maxsrvpoints)); GlobalLog.LeaveException("ServicePointManager::FindServicePointHelper() reached the limit count:" + s_ServicePointTable.Count.ToString() + " limit:" + s_MaxServicePoints.ToString(), exception); throw exception; } } } GlobalLog.Leave("ServicePointManager::FindServicePointHelper() servicePoint#" + ValidationHelper.HashString(servicePoint)); return(servicePoint); }
private void LogExceptionAgain(NotSupportedException ex) { throw new NotImplementedException(); }
/// <summary> /// Throw a 'NotSupportedException' /// </summary> /// <param name="message">Unused parameter</param> private void _NotImpl(string message) { NotSupportedException ex = new NotSupportedException(); throw ex; }
private async Task <ActionResult <ResultSinnerPostSIN> > PostSINnerInternal(UploadInfoObject uploadInfo) { ResultSinnerPostSIN res; _logger.LogTrace("Post SINnerInternalt: " + uploadInfo + "."); ApplicationUser user = null; SINner sinner = null; try { if (!ModelState.IsValid) { var errors = ModelState.Select(x => x.Value.Errors) .Where(y => y.Count > 0) .ToList(); string msg = "ModelState is invalid: "; foreach (var err in errors) { foreach (var singleerr in err) { msg += Environment.NewLine + "\t" + singleerr.ToString(); } } var e = new HubException(msg); res = new ResultSinnerPostSIN(e); return(BadRequest(res)); } if (uploadInfo.UploadDateTime == null) { uploadInfo.UploadDateTime = DateTime.Now; } if (uploadInfo.Client != null) { if (!UploadClientExists(uploadInfo.Client.Id)) { _context.UploadClients.Add(uploadInfo.Client); } else { _context.UploadClients.Attach(uploadInfo.Client); _context.Entry(uploadInfo.Client).State = EntityState.Modified; _context.Entry(uploadInfo.Client).CurrentValues.SetValues(uploadInfo.Client); } } var returncode = HttpStatusCode.OK; user = await _signInManager.UserManager.FindByNameAsync(User.Identity.Name); foreach (var tempsinner in uploadInfo.SINners) { sinner = tempsinner; if (sinner.Id.ToString() == "string") { sinner.Id = Guid.Empty; } if (String.IsNullOrEmpty(sinner.MyExtendedAttributes.JsonSummary)) { var e = new ArgumentException("sinner " + sinner.Id + ": JsonSummary == null"); res = new ResultSinnerPostSIN(e); return(BadRequest(res)); } if (sinner.LastChange == null) { var e = new ArgumentException("Sinner " + sinner.Id + ": LastChange not set!"); res = new ResultSinnerPostSIN(e); return(BadRequest(res)); } if ((sinner.SINnerMetaData.Visibility.Id == null) || (sinner.SINnerMetaData.Visibility.Id == Guid.Empty)) { sinner.SINnerMetaData.Visibility.Id = Guid.NewGuid(); } if ((sinner.MyExtendedAttributes.Id == null) || (sinner.MyExtendedAttributes.Id == Guid.Empty)) { sinner.MyExtendedAttributes.Id = Guid.NewGuid(); } var oldsinner = (from a in _context.SINners .Include(a => a.MyExtendedAttributes) .Include(a => a.SINnerMetaData) .Include(a => a.SINnerMetaData.Visibility) .Include(a => a.SINnerMetaData.Visibility.UserRights) .Include(b => b.MyGroup) where a.Id == sinner.Id select a).FirstOrDefault(); if (oldsinner != null) { var canedit = await CheckIfUpdateSINnerFile(oldsinner.Id.Value, user); if (canedit == null) { string msg = "SINner " + sinner.Id + " is not editable for user " + user.Email + "."; var e = new NoUserRightException(msg); res = new ResultSinnerPostSIN(e); return(BadRequest(res)); } var olduserrights = oldsinner.SINnerMetaData.Visibility.UserRights.ToList(); oldsinner.SINnerMetaData.Visibility.UserRights.Clear(); _context.UserRights.RemoveRange(olduserrights); //check if ANY visibility-data was uploaded if (sinner.SINnerMetaData.Visibility.UserRights.Any()) { bool userfound = false; foreach (var ur in sinner.SINnerMetaData.Visibility.UserRights) { if (ur.EMail.ToLowerInvariant() == user.Email.ToLowerInvariant()) { ur.CanEdit = true; userfound = true; } ur.Id = Guid.NewGuid(); ur.SINnerId = sinner.Id; _context.UserRights.Add(ur); } if (!userfound) { SINnerUserRight ownUser = new SINnerUserRight(); ownUser.Id = Guid.NewGuid(); ownUser.SINnerId = sinner.Id; ownUser.CanEdit = true; ownUser.EMail = user.Email; sinner.SINnerMetaData.Visibility.UserRights.Add(ownUser); _context.UserRights.Add(ownUser); } } else { //no userrights where uploaded. sinner.SINnerMetaData.Visibility.UserRights = olduserrights; } } else { var ownuserfound = false; var list = sinner.SINnerMetaData.Visibility.UserRights.ToList(); foreach (var ur in list) { ur.SINnerId = sinner.Id; if (ur.EMail.ToLowerInvariant() == "*****@*****.**".ToLowerInvariant()) { sinner.SINnerMetaData.Visibility.UserRights.Remove(ur); } if (ur.EMail.ToLowerInvariant() == user.Email.ToLowerInvariant()) { ownuserfound = true; } } if (!ownuserfound) { SINnerUserRight ownright = new SINnerUserRight(); ownright.CanEdit = true; ownright.EMail = user.Email; ownright.SINnerId = sinner.Id; ownright.Id = Guid.NewGuid(); sinner.SINnerMetaData.Visibility.UserRights.Add(ownright); } } foreach (var tag in sinner.SINnerMetaData.Tags) { tag.SetSinnerIdRecursive(sinner.Id); } sinner.UploadClientId = uploadInfo.Client.Id; SINner dbsinner = await CheckIfUpdateSINnerFile(sinner.Id.Value, user, true); SINnerGroup oldgroup = null; if (dbsinner != null) { oldgroup = dbsinner.MyGroup; //_context.SINners.Attach(dbsinner); if (String.IsNullOrEmpty(sinner.GoogleDriveFileId)) { sinner.GoogleDriveFileId = dbsinner.GoogleDriveFileId; } if (String.IsNullOrEmpty(sinner.DownloadUrl)) { sinner.DownloadUrl = dbsinner.DownloadUrl; } var alltags = await _context.Tags.Where(a => a.SINnerId == dbsinner.Id).Select(a => a.Id).ToListAsync(); foreach (var id in alltags) { var tag = from a in _context.Tags where a.Id == id select a; if (tag.Any()) { _context.Tags.Remove(tag.FirstOrDefault()); } } _context.UserRights.RemoveRange(dbsinner.SINnerMetaData.Visibility.UserRights); _context.SINnerVisibility.Remove(dbsinner.SINnerMetaData.Visibility); _context.SINnerExtendedMetaData.Remove(dbsinner.MyExtendedAttributes); _context.SINnerMetaData.Remove(dbsinner.SINnerMetaData); _context.SINners.Remove(dbsinner); dbsinner.SINnerMetaData.Visibility.UserRights.Clear(); dbsinner.SINnerMetaData.Visibility.UserRights = null; dbsinner.SINnerMetaData.Visibility = null; dbsinner.SINnerMetaData.Tags = null; dbsinner.SINnerMetaData = null; dbsinner.MyExtendedAttributes = null; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException ex) { foreach (var entry in ex.Entries) { if (entry.Entity is SINner || entry.Entity is Tag || entry.Entity is SINnerExtended || entry.Entity is SINnerGroup || entry.Entity is SINnerUserRight || entry.Entity is SINnerMetaData) { try { Utils.DbUpdateConcurrencyExceptionHandler(entry, _logger); } catch (Exception e) { res = new ResultSinnerPostSIN(e); return(BadRequest(res)); } } else { var e = new NotSupportedException( "(Codepoint 1) Don't know how to handle concurrency conflicts for " + entry.Metadata.Name); res = new ResultSinnerPostSIN(e); return(BadRequest(res)); } } } catch (DbUpdateException ex) { res = new ResultSinnerPostSIN(ex); return(BadRequest(res)); } await _context.SINners.AddAsync(sinner); string msg = "Sinner " + sinner.Id + " updated: " + _context.Entry(dbsinner).State.ToString(); msg += Environment.NewLine + Environment.NewLine + "LastChange: " + dbsinner.LastChange; _logger.LogError(msg); List <Tag> taglist = sinner.SINnerMetaData.Tags; UpdateEntityEntries(taglist); } else { returncode = HttpStatusCode.Created; sinner.MyGroup = null; _context.SINners.Add(sinner); } try { await _context.SaveChangesAsync(); if (oldgroup != null) { var roles = await _userManager.GetRolesAsync(user); await SINnerGroupController.PutSiNerInGroupInternal(oldgroup.Id.Value, sinner.Id.Value, user, _context, _logger, oldgroup.PasswordHash, roles); } } catch (DbUpdateConcurrencyException ex) { foreach (var entry in ex.Entries) { if (entry.Entity is SINner || entry.Entity is Tag) { try { Utils.DbUpdateConcurrencyExceptionHandler(entry, _logger); } catch (Exception e) { res = new ResultSinnerPostSIN(e); return(BadRequest(res)); } } else { var e = new NotSupportedException( "Don't know how to handle concurrency conflicts for " + entry.Metadata.Name); res = new ResultSinnerPostSIN(e); return(BadRequest(res)); } } } catch (DbUpdateException ex) { res = new ResultSinnerPostSIN(ex); return(BadRequest(res)); } catch (Exception e) { try { var tc = new Microsoft.ApplicationInsights.TelemetryClient(); Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e); telemetry.Properties.Add("User", user?.Email); telemetry.Properties.Add("SINnerId", sinner?.Id?.ToString()); tc.TrackException(telemetry); } catch (Exception ex) { _logger.LogError(ex.ToString()); } res = new ResultSinnerPostSIN(e); return(Conflict(res)); } } List <Guid> myids = (from a in uploadInfo.SINners select a.Id.Value).ToList(); List <SINner> sinlist = new List <SINner>(); foreach (var id in myids) { var sin = from a in _context.SINners where a.Id == id select a; if (sin.Any()) { sinlist.Add(sin.FirstOrDefault()); } } res = new ResultSinnerPostSIN(sinlist); switch (returncode) { case HttpStatusCode.OK: return(Accepted(res)); case HttpStatusCode.Created: return(Created("SINnerPostSIN", res)); default: return(Ok(res)); } } catch (Exception e) { try { var tc = new Microsoft.ApplicationInsights.TelemetryClient(); Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e); telemetry.Properties.Add("User", user?.Email); telemetry.Properties.Add("SINnerId", sinner?.Id?.ToString()); tc.TrackException(telemetry); } catch (Exception ex) { _logger.LogError(ex.ToString()); } res = new ResultSinnerPostSIN(e); return(BadRequest(res)); } }
public static void Read_NonGeneric_NoPublicConstructor_Throws(Type type, string json) { NotSupportedException ex = Assert.Throws <NotSupportedException>(() => JsonSerializer.Deserialize(json, type)); Assert.Contains(type.ToString(), ex.Message); }
internal static Exception Create <T>(string message, DataGridControl dataGridControl, string argument = "") { Exception exception; var exceptionType = typeof(T); if (typeof(ArgumentException) == exceptionType) { exception = new ArgumentException(message, argument); } else if (typeof(ArgumentNullException) == exceptionType) { exception = new ArgumentNullException(message); } else if (typeof(ArgumentOutOfRangeException) == exceptionType) { exception = new ArgumentOutOfRangeException(argument, message); } else if (typeof(IndexOutOfRangeException) == exceptionType) { exception = new IndexOutOfRangeException(message); } else if (typeof(InvalidOperationException) == exceptionType) { exception = new InvalidOperationException(message); } else if (typeof(NotSupportedException) == exceptionType) { exception = new NotSupportedException(message); } else if (typeof(DataGridException) == exceptionType) { return(new DataGridException(message, dataGridControl)); } else if (typeof(DataGridInternalException) == exceptionType) { return(new DataGridInternalException(message, dataGridControl)); } else { exception = new Exception(message); } if (dataGridControl != null) { var name = dataGridControl.GridUniqueName; if (string.IsNullOrEmpty(name)) { name = dataGridControl.Name; } if (!string.IsNullOrEmpty(name)) { exception.Source = name; } } Debug.Assert(exception != null); return(exception); }
private object GenerateObjectFromDataNodeInfo(DataNodeInfo dataNodeInfo, ITypeResolutionService typeResolver) { object result = null; string mimeTypeName = dataNodeInfo.MimeType; // default behavior: if we dont have a type name, it's a string string typeName = string.IsNullOrEmpty(dataNodeInfo.TypeName) ? MultitargetUtil.GetAssemblyQualifiedName(typeof(string), typeNameConverter) : dataNodeInfo.TypeName; if (!string.IsNullOrEmpty(mimeTypeName)) { if (string.Equals(mimeTypeName, ResXResourceWriter.BinSerializedObjectMimeType) || string.Equals(mimeTypeName, ResXResourceWriter.Beta2CompatSerializedObjectMimeType) || string.Equals(mimeTypeName, ResXResourceWriter.CompatBinSerializedObjectMimeType)) { string text = dataNodeInfo.ValueData; byte[] serializedData = FromBase64WrappedString(text); if (binaryFormatter == null) { binaryFormatter = new BinaryFormatter { Binder = new ResXSerializationBinder(typeResolver) }; } IFormatter formatter = binaryFormatter; if (serializedData != null && serializedData.Length > 0) { result = formatter.Deserialize(new MemoryStream(serializedData)); if (result is ResXNullRef) { result = null; } } } else if (string.Equals(mimeTypeName, ResXResourceWriter.ByteArraySerializedObjectMimeType)) { if (!string.IsNullOrEmpty(typeName)) { Type type = ResolveType(typeName, typeResolver); if (type != null) { TypeConverter tc = TypeDescriptor.GetConverter(type); if (tc.CanConvertFrom(typeof(byte[]))) { string text = dataNodeInfo.ValueData; byte[] serializedData = FromBase64WrappedString(text); if (serializedData != null) { result = tc.ConvertFrom(serializedData); } } } else { string newMessage = string.Format(SR.TypeLoadException, typeName, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); XmlException xml = new XmlException(newMessage, null, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); TypeLoadException newTle = new TypeLoadException(newMessage, xml); throw newTle; } } } } else if (!string.IsNullOrEmpty(typeName)) { Type type = ResolveType(typeName, typeResolver); if (type != null) { if (type == typeof(ResXNullRef)) { result = null; } else if (typeName.IndexOf("System.Byte[]") != -1 && typeName.IndexOf("mscorlib") != -1) { // Handle byte[]'s, which are stored as base-64 encoded strings. // We can't hard-code byte[] type name due to version number // updates & potential whitespace issues with ResX files. result = FromBase64WrappedString(dataNodeInfo.ValueData); } else { TypeConverter tc = TypeDescriptor.GetConverter(type); if (tc.CanConvertFrom(typeof(string))) { string text = dataNodeInfo.ValueData; try { result = tc.ConvertFromInvariantString(text); } catch (NotSupportedException nse) { string newMessage = string.Format(SR.NotSupported, typeName, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X, nse.Message); XmlException xml = new XmlException(newMessage, nse, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); NotSupportedException newNse = new NotSupportedException(newMessage, xml); throw newNse; } } else { Debug.WriteLine("Converter for " + type.FullName + " doesn't support string conversion"); } } } else { string newMessage = string.Format(SR.TypeLoadException, typeName, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); XmlException xml = new XmlException(newMessage, null, dataNodeInfo.ReaderPosition.Y, dataNodeInfo.ReaderPosition.X); TypeLoadException newTle = new TypeLoadException(newMessage, xml); throw newTle; } } else { // if mimeTypeName and typeName are not filled in, the value must be a string Debug.Assert(value is string, "Resource entries with no Type or MimeType must be encoded as strings"); } return(result); }
public static bool TryConvertFromString <T>( [NotNull] TypeConverter converter, bool throwTypeConversionExceptions, [NotNull] string s, out T result) where T : struct { Contract.Requires <ArgumentNullException>(converter != null); Contract.Requires <ArgumentException>(!IsNullOrWhiteSpace(s)); // This produces a compiler warning due to CodeContracts issue. // See workaround above for https://github.com/Microsoft/CodeContracts/issues/339 //// Contract.Requires<ArgumentException>(!string.IsNullOrWhiteSpace(s)); result = default(T); try { object converted = converter.ConvertFrom(s); if (converted == null) { return(false); } result = (T)converted; return(true); } catch (FormatException) { if (throwTypeConversionExceptions) { throw; } return(false); } catch (NotSupportedException) { if (throwTypeConversionExceptions) { throw; } return(false); } catch (Exception e) { if (!throwTypeConversionExceptions) { return(false); } FormatException formatException = e.InnerException as FormatException; if (formatException != null) { throw formatException; } NotSupportedException notSupportedException = e.InnerException as NotSupportedException; if (notSupportedException != null) { throw notSupportedException; } throw; } }
private static CommonSecurityDescriptor CreateInternal(ResourceType resourceType, bool isContainer, string name, SafeHandle handle, AccessControlSections includeSections, bool createByName, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) { int error; RawSecurityDescriptor rawSD; if (createByName && name == null) { throw new ArgumentNullException(nameof(name)); } else if (!createByName && handle == null) { throw new ArgumentNullException(nameof(handle)); } error = Win32.GetSecurityInfo(resourceType, name, handle, includeSections, out rawSD); if (error != Interop.Errors.ERROR_SUCCESS) { System.Exception exception = null; if (exceptionFromErrorCode != null) { exception = exceptionFromErrorCode(error, name, handle, exceptionContext); } if (exception == null) { if (error == Interop.Errors.ERROR_ACCESS_DENIED) { exception = new UnauthorizedAccessException(); } else if (error == Interop.Errors.ERROR_INVALID_OWNER) { exception = new InvalidOperationException(SR.AccessControl_InvalidOwner); } else if (error == Interop.Errors.ERROR_INVALID_PRIMARY_GROUP) { exception = new InvalidOperationException(SR.AccessControl_InvalidGroup); } else if (error == Interop.Errors.ERROR_INVALID_PARAMETER) { exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error)); } else if (error == Interop.Errors.ERROR_INVALID_NAME) { exception = new ArgumentException(SR.Argument_InvalidName, nameof(name)); } else if (error == Interop.Errors.ERROR_FILE_NOT_FOUND) { exception = (name == null ? new FileNotFoundException() : new FileNotFoundException(name)); } else if (error == Interop.Errors.ERROR_NO_SECURITY_ON_OBJECT) { exception = new NotSupportedException(SR.AccessControl_NoAssociatedSecurity); } else if (error == Interop.Errors.ERROR_PIPE_NOT_CONNECTED) { exception = new InvalidOperationException(SR.InvalidOperation_DisconnectedPipe); } else { Debug.Fail($"Win32GetSecurityInfo() failed with unexpected error code {error}"); exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error)); } } throw exception; } return(new CommonSecurityDescriptor(isContainer, false /* isDS */, rawSD, true)); }
internal static Exception CreateException(SttError err) { Tizen.Log.Error(LogTag, "Error " + err); Exception exp; switch (err) { case SttError.OutOfMemory: { exp = new OutOfMemoryException("Out Of Memory"); break; } case SttError.IoError: { exp = new InvalidOperationException("I/O Error Occurred"); break; } case SttError.InvalidParameter: { exp = new ArgumentException("Invalid Parameters Provided"); break; } case SttError.TimedOut: { exp = new TimeoutException("No answer from the STT service"); break; } case SttError.OutOfNetwork: { exp = new InvalidOperationException("Network is down"); break; } case SttError.PermissionDenied: { exp = new UnauthorizedAccessException("Permission Denied"); break; } case SttError.NotSupported: { exp = new NotSupportedException("STT NOT supported"); break; } case SttError.InvalidState: { exp = new InvalidOperationException("Invalid state"); break; } case SttError.InvalidLanguage: { exp = new InvalidOperationException("Invalid language"); break; } case SttError.EngineNotFound: { exp = new InvalidOperationException("No available engine"); break; } case SttError.OperationFailed: { exp = new InvalidOperationException("Operation Failed"); break; } case SttError.NotSupportedFeature: { exp = new InvalidOperationException("Not supported feature of current engine"); break; } case SttError.RecordingTimedOut: { exp = new InvalidOperationException("Recording timed out"); break; } case SttError.NoSpeech: { exp = new InvalidOperationException("No speech while recording"); break; } case SttError.InProgressToReady: { exp = new InvalidOperationException("Progress to ready is not finished"); break; } case SttError.InProgressToRecording: { exp = new InvalidOperationException("Progress to recording is not finished"); break; } case SttError.InProgressToProcessing: { exp = new InvalidOperationException("Progress to processing is not finished"); break; } case SttError.ServiceReset: { exp = new InvalidOperationException("Service reset"); break; } default: { exp = new Exception(""); break; } } return(exp); }