Inheritance: IExceptionHandler
 /// <summary>
 /// 移除处理类
 /// </summary>
 /// <param name="handler"></param>
 private static void DelHandler(ExceptionHandler handler)
 {
     if (handlers.ContainsKey(handler.ToString()))
     {
         handlers.Remove(handler.ToString());
     }
 }
示例#2
0
		private static ValueOrError<CrontabSchedule> TryParse(string expression, ExceptionHandler onError)
		{
			if (expression == null)
				throw new ArgumentNullException("expression");

			var tokens = expression.Split(_separators, StringSplitOptions.RemoveEmptyEntries);

			if (tokens.Length != 5)
			{
				return ErrorHandling.OnError(() => new CrontabException(string.Format(
						   "'{0}' is not a valid crontab expression. It must contain at least 5 components of a schedule "
						   + "(in the sequence of minutes, hours, days, months, days of week).",
						   expression)), onError);
			}

			var fields = new CrontabField[5];

			for (var i = 0; i < fields.Length; i++)
			{
				var field = CrontabField.TryParse((CrontabFieldKind)i, tokens[i], onError);
				if (field.IsError)
					return field.ErrorProvider;

				fields[i] = field.Value;
			}

			return new CrontabSchedule(fields[0], fields[1], fields[2], fields[3], fields[4]);
		}
 /// <summary>
 /// 添加处理类
 /// </summary>
 /// <param name="handler"></param>
 private static void AddHandler(ExceptionHandler handler)
 {
     if (!handlers.ContainsKey(handler.ToString()))
     {
         handlers.Add(handler.ToString(), handler);
     }
 }
 public ExceptionHandlerTreeNode( ExceptionHandler handler ) :
     base( TreeViewImage.Method, handler )
 {
     this.handler = handler;
     this.Text = handler.Options.ToString();
     this.EnableLatePopulate();
 }
示例#5
0
 static void Main()
 {
     ExceptionHandler EH = new ExceptionHandler();
         AppDomain.CurrentDomain.UnhandledException += EH.ThreadExceptionHandle;
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         _LoginForm = new LoginForm();
         Application.Run(_LoginForm); // spawn
 }
示例#6
0
		internal static ExceptionProvider OnError(ExceptionProvider provider, ExceptionHandler handler)
		{
			Debug.Assert(provider != null);

			if (handler != null)
				handler(provider());

			return provider;
		}
        public void Handle_ExceptionWhichNoSpecificHandlerCanHandle_RepositoryViolationExceptionThrown()
        {
            ExceptionHandler handler = new ExceptionHandler();
            Exception e = new Exception();

            Action act = () => handler.Handle(e);

            act.ShouldThrow<RepositoryViolationException>(actual => ReferenceEquals(actual.InnerException, e));
        }
示例#8
0
文件: Program.cs 项目: se4598/huggle
 static void Main()
 {
     ExceptionHandler EH = new ExceptionHandler();
     AppDomain.CurrentDomain.UnhandledException += EH.ThreadExceptionHandle;
     Application.Init ();
     LoginForm = new Forms.LoginForm();
     LoginForm.Show ();
     Application.Run ();
 }
示例#9
0
        public void When_rethrows_if_no_handler()
        {
            var exceptions = new Dictionary<Type, Action>();
            var exception = new ExceptionHandler(exceptions);
            int invoke = 0;
            Action action = () => invoke++;

            Assert.Throws<NotImplementedException>(() => exception.On<AbandonedMutexException>(action).When(() => { throw new NotImplementedException(); }));
        }
示例#10
0
        public void When_invokes_target()
        {
            var exceptions = new Dictionary<Type, Action>();
            var exception = new ExceptionHandler(exceptions);
            int invoke = 0;
            Action action = () => Console.WriteLine("caught");

            exception.On<Exception>(action).When(() => invoke++);
            invoke.ShouldBe(1);
        }
示例#11
0
 private bool Throw(ExceptionHandler handler)
 {
     try
     {
         throw new Exception("ExceptionHandlerTests");
     }
     catch (Exception e)
     {
         return handler.HandleException(e);
     }
 }
		public static void InstallExceptionHandler(this Application application, ExceptionHandler exceptionHandler)
		{
			const string WarningFormat =
				"If the TaskScheduler used does not implements the {0} interface," +
				" it could not intercept exceptions thrown in secondary threads.";

			Debug.WriteLine(string.Format(WarningFormat, typeof(ILoggerTaskScheduler).Name));

			singletonExceptionHandler.Set(exceptionHandler);
			exceptionHandler.Install();
		}
示例#13
0
        public void When_invokes_exception_handler_on_exception()
        {
            var exceptions = new Dictionary<Type, Action>();
            var exception = new ExceptionHandler(exceptions);
            int invoke = 0;
            Action action = () => invoke++;

            exception.On<NotImplementedException>(action).When(() => { throw new NotImplementedException(); });

            invoke.ShouldBe(1);
        }
示例#14
0
        public void On_Exception_adds_exception_and_target_invocation()
        {
            var exceptions = new Dictionary<Type, Action>();
            var exception = new ExceptionHandler(exceptions);
            Action action = () => Console.WriteLine("caught");

            exception.On<Exception>(action);

            exceptions.ContainsKey(typeof(Exception));
            exceptions.ContainsValue(action);
            exceptions.Count.ShouldBe(1);
        }
示例#15
0
        public void Run(Proc procediment)
        {
            ExceptionHandler eh = new ExceptionHandler();

            AppDomain.CurrentDomain.UnhandledException += eh.OnThreadException;

            procediment.Invoke();

            AppDomain.CurrentDomain.UnhandledException -= eh.OnThreadException;

            if (eh.Count > 0)
                Assert.Fail("Engine Validator concurrent issues. Concurrent issues count {0}", eh.Count);
        }
示例#16
0
文件: Program.cs 项目: robertfall/LAD
        static void handleException(Exception e)
        {
            var handler = new ExceptionHandler
            {
                Exception = e,
                LoggedOnUser = GlobalProperties.loggedOnUser,
                Mode = Mode.Online
            };

            handler.handleException();
            MessageBox.Show("An error was detected. An email has been sent to Development. LAD will now close.", "Error");
            Application.Exit();
        }
示例#17
0
        private static void handleException(Exception ex)
        {
            var handler = new ExceptionHandler
            {
                Exception = ex,
                LoggedOnUser = Global.loggedOnUser,
                Mode = Global.systemMode

            };

            handler.handleException();
            MessageBox.Show("An error was detected. An email has been sent to Development. LAD will now close.", "Error");
            Application.Exit();
        }
    void ContinueProcessing()
    {
        body = Method.Body;

        body.SimplifyMacros();

        var ilProcessor = body.GetILProcessor();

        var returnFixer = new ReturnFixer
        {
            Method = Method
        };
        returnFixer.MakeLastStatementReturn();

        exceptionVariable = new VariableDefinition(ModuleWeaver.ExceptionType);
        body.Variables.Add(exceptionVariable);
        messageVariable = new VariableDefinition(ModuleWeaver.ModuleDefinition.TypeSystem.String);
        body.Variables.Add(messageVariable);
        paramsArrayVariable = new VariableDefinition(ModuleWeaver.ObjectArray);
        body.Variables.Add(paramsArrayVariable);


        var tryCatchLeaveInstructions = Instruction.Create(OpCodes.Leave, returnFixer.NopBeforeReturn);

        var methodBodyFirstInstruction = GetMethodBodyFirstInstruction();

        var catchInstructions = GetCatchInstructions().ToList();

        ilProcessor.InsertBefore(returnFixer.NopBeforeReturn, tryCatchLeaveInstructions);

        ilProcessor.InsertBefore(returnFixer.NopBeforeReturn, catchInstructions);

        var handler = new ExceptionHandler(ExceptionHandlerType.Catch)
        {
            CatchType = ModuleWeaver.ExceptionType,
            TryStart = methodBodyFirstInstruction,
            TryEnd = tryCatchLeaveInstructions.Next,
            HandlerStart = catchInstructions.First(),
            HandlerEnd = catchInstructions.Last().Next
        };

        body.ExceptionHandlers.Add(handler);

        body.InitLocals = true;
        body.OptimizeMacros();
    }
示例#19
0
		internal static void Implementation( Action action, ExceptionHandler canHandle, ICircuitBreakerState breaker )
		{
			if( breaker.IsBroken )
				throw breaker.LastException;

			try
			{
				action();
				breaker.Reset();
			}
			catch( Exception ex )
			{
				if( !canHandle( ex ) )
					throw;
				breaker.TryBreak( ex );
				throw;
			}
		}
示例#20
0
		internal static async Task ImplementationAsync( Func< Task > action, ExceptionHandler canHandle, ICircuitBreakerState breaker )
		{
			if( breaker.IsBroken )
				throw breaker.LastException;

			try
			{
				await action().ConfigureAwait( false );
				breaker.Reset();
			}
			catch( Exception ex )
			{
				if( !canHandle( ex ) )
					throw;
				breaker.TryBreak( ex );
				throw;
			}
		}
示例#21
0
        private static Func<Exception, bool> RetryImmediately(ExceptionHandler isHandled, int retryCount, Action<Exception, int> retryAction)
        {
            int failureCount = 0;

            return x =>
                {
                    failureCount++;

                    if (!isHandled(x))
                        return false;

                    if (failureCount > retryCount)
                        return false;

                    retryAction(x, failureCount);

                    return true;
                };
        }
示例#22
0
文件: RetryPolicy.cs 项目: slav/Netco
		internal static void Implementation( Action action, ExceptionHandler canRetry, Func< IRetryState > stateBuilder )
		{
			var state = stateBuilder();
			while( true )
			{
				try
				{
					action();
					return;
				}
				catch( Exception ex )
				{
					if( !canRetry( ex ) )
						throw;

					if( !state.CanRetry( ex ) )
						throw;
				}
			}
		}
示例#23
0
        private static void ImplementPolicy(Action action, ExceptionHandler isHandled, CircuitBreaker breaker)
        {
            if (breaker.IsBroken)
                throw breaker.LastException;

            try
            {
                action();
                breaker.Reset();
                return;
            }
            catch (Exception ex)
            {
                if (!isHandled(ex))
                    throw;

                breaker.TryBreak(ex);
                throw;
            }
        }
示例#24
0
文件: RetryPolicy.cs 项目: slav/Netco
		internal static async Task ImplementationAsync( Func< Task > action, ExceptionHandler canRetry, Func< IRetryStateAsync > stateBuilder )
		{
			var state = stateBuilder();
			while( true )
			{
				try
				{
					await action().ConfigureAwait( false );
					return;
				}
				catch( Exception ex )
				{
					if( !canRetry( ex ) )
						throw;

					if( !state.CanRetry( ex ).Result )
						throw;
				}
			}
		}
        public static GuardResult RunGuarded(Action actionToExecute, params ExceptionProcessor[] exceptionProcessors)
        {
            {
                Debug.Assert(actionToExecute != null, "The application method should not be null.");
            }

            var processor = new ExceptionHandler(exceptionProcessors);
            var result = GuardResult.None;
            ExceptionFilter.ExecuteWithFilter(
                () =>
                {
                    actionToExecute();
                    result = GuardResult.Success;
                },
                e =>
                {
                    processor.OnException(e);
                    result = GuardResult.Failure;
                });

            return result;
        }
 void CopyExceptionHandlers(MethodDefinition templateMethod, MethodDefinition newMethod)
 {
     if (!templateMethod.Body.HasExceptionHandlers)
     {
         return;
     }
     foreach (var exceptionHandler in templateMethod.Body.ExceptionHandlers)
     {
         var handler = new ExceptionHandler(exceptionHandler.HandlerType);
         var templateInstructions = templateMethod.Body.Instructions;
         var targetInstructions = newMethod.Body.Instructions;
         if (exceptionHandler.TryStart != null)
         {
             handler.TryStart = targetInstructions[templateInstructions.IndexOf(exceptionHandler.TryStart)];
         }
         if (exceptionHandler.TryEnd != null)
         {
             handler.TryEnd = targetInstructions[templateInstructions.IndexOf(exceptionHandler.TryEnd)];
         }
         if (exceptionHandler.HandlerStart != null)
         {
             handler.HandlerStart = targetInstructions[templateInstructions.IndexOf(exceptionHandler.HandlerStart)];
         }
         if (exceptionHandler.HandlerEnd != null)
         {
             handler.HandlerEnd = targetInstructions[templateInstructions.IndexOf(exceptionHandler.HandlerEnd)];
         }
         if (exceptionHandler.FilterStart != null)
         {
             handler.FilterStart = targetInstructions[templateInstructions.IndexOf(exceptionHandler.FilterStart)];
         }
         if (exceptionHandler.CatchType != null)
         {
             handler.CatchType = Resolve(exceptionHandler.CatchType);
         }
         newMethod.Body.ExceptionHandlers.Add(handler);
     }
 }
 public static Action Wrap(Action x, ExceptionHandler exceptionHandler=null, FinishingHandler finishingHandler=null)
 {
     return () =>
     {
         try
         {
             x();
         }
         /*catch (ThreadAbortException)
         {
         }*/
         catch (Exception e)
         {
             if (exceptionHandler != null)
                 exceptionHandler(e);
         }
         finally
         {
             if (finishingHandler != null)
                 finishingHandler();
         }
     };
 }
示例#28
0
    public void AddFinalizer(MethodDefinition disposeBoolMethod)
    {
        if (TargetType.Methods.Any(x => !x.IsStatic && x.IsMatch("Finalize")))
        {
            //TODO: should support injecting into existing finalizer
            return;
        }
        var finalizeMethod = new MethodDefinition("Finalize", MethodAttributes.HideBySig | MethodAttributes.Family | MethodAttributes.Virtual, typeSystem.Void);
        var instructions = finalizeMethod.Body.Instructions;

        var ret = Instruction.Create(OpCodes.Ret);

        var tryStart = Instruction.Create(OpCodes.Ldarg_0);
        instructions.Add(tryStart);
        if (disposeBoolMethod.Parameters.Count == 1)
        {
            instructions.Add(Instruction.Create(OpCodes.Ldc_I4_0));
        }
        instructions.Add(Instruction.Create(OpCodes.Call, disposeBoolMethod));
        instructions.Add(Instruction.Create(OpCodes.Leave, ret));
        var tryEnd = Instruction.Create(OpCodes.Ldarg_0);
        instructions.Add(tryEnd);
        instructions.Add(Instruction.Create(OpCodes.Call, ModuleWeaver.ObjectFinalizeReference));
        instructions.Add(Instruction.Create(OpCodes.Endfinally));
        instructions.Add(ret);

        var finallyHandler = new ExceptionHandler(ExceptionHandlerType.Finally)
                             {
                                 TryStart = tryStart,
                                 TryEnd = tryEnd,
                                 HandlerStart = tryEnd,
                                 HandlerEnd = ret
                             };

        finalizeMethod.Body.ExceptionHandlers.Add(finallyHandler);
        TargetType.Methods.Add(finalizeMethod);
    }
示例#29
0
 public static void HandleException(Exception ex)
 {
     ExceptionHandler.HandleException(ex, true);
 }
        public void TestThrowFormatException()
        {
            ExceptionHandler eh = new ExceptionHandler("123KB", false);

            eh.FormatExceptionMethod();
        }
示例#31
0
        private void CallEntryPoint(IntPtr baseAddress, IntPtr entryPoint)
        {
            // Initialize shellcode to call the entry of the dll in the process

            var shellcodeBytes = _properties.IsWow64 ? Shellcode.CallDllMainx86(baseAddress, entryPoint) : Shellcode.CallDllMainx64(baseAddress, entryPoint);

            // Allocate memory for the shellcode in the process

            var shellcodeAddress = IntPtr.Zero;

            try
            {
                shellcodeAddress = _properties.MemoryModule.AllocateMemory(_properties.ProcessId, shellcodeBytes.Length);
            }

            catch (Win32Exception)
            {
                ExceptionHandler.ThrowWin32Exception("Failed to allocate memory for the shellcode in the process");
            }

            // Write the shellcode into the memory of the process

            try
            {
                _properties.MemoryModule.WriteMemory(_properties.ProcessId, shellcodeAddress, shellcodeBytes);
            }

            catch (Win32Exception)
            {
                ExceptionHandler.ThrowWin32Exception("Failed to write the shellcode into the memory of the process");
            }

            // Create a remote thread to call the entry point in the process

            Native.NtCreateThreadEx(out var remoteThreadHandle, Native.AccessMask.SpecificRightsAll | Native.AccessMask.StandardRightsAll, IntPtr.Zero, _properties.ProcessHandle, shellcodeAddress, IntPtr.Zero, Native.CreationFlags.HideFromDebugger, 0, 0, 0, IntPtr.Zero);

            if (remoteThreadHandle is null)
            {
                ExceptionHandler.ThrowWin32Exception("Failed to create a remote thread to call the entry point in the process");
            }

            // Wait for the remote thread to finish its task

            Native.WaitForSingleObject(remoteThreadHandle, int.MaxValue);

            // Free the memory previously allocated for the shellcode

            try
            {
                _properties.MemoryModule.FreeMemory(_properties.ProcessId, shellcodeAddress);
            }

            catch (Win32Exception)
            {
                ExceptionHandler.ThrowWin32Exception("Failed to free the memory allocated for the shellcode in the process");
            }

            // Close the handle opened to the remote thread

            remoteThreadHandle?.Close();
        }
示例#32
0
 /// <summary>
 /// Visits the specified <see cref="ExceptionHandler"/> inside the body of the <see cref="MethodDefinition"/>
 /// that was visited by the last <see cref="VisitMethod"/>.
 /// </summary>
 /// <remarks>
 /// In the case of nested try/catch blocks the inner block is visited first before the outer block.
 /// </remarks>
 internal virtual void VisitExceptionHandler(ExceptionHandler handler)
 {
 }
示例#33
0
        public async Task NavigateAsync(MenuType id, bool backPressed = false)
        {
            try
            {
                Page newPage;
                if (!Pages.ContainsKey(id))
                {
                    switch (id)
                    {
                    case MenuType.MyProfile:
                        var page = new XNavigationPage(new ProfileEnhanced(this)
                        {
                            Title = TextResources.MainTabs_MyProfile,
                            Icon  = new FileImageSource {
                                File = TextResources.MainTabs_MyProfile_Icon
                            }
                        });
                        SetDetailIfNull(page);
                        Pages.Add(id, page);
                        break;

                    case MenuType.LatestNews:
                        page = new XNavigationPage(new BlogPage(this)     //NewsPage(this)
                        {
                            Title = TextResources.MainTabs_LatestNews,
                            Icon  = new FileImageSource {
                                File = TextResources.MainTabs_LatestNews_Icon
                            }
                        });
                        SetDetailIfNull(page);
                        Pages.Add(id, page);
                        break;

                    case MenuType.HowItWorks:
                        page = new XNavigationPage(new HowItWorksPage(this)
                        {
                            Title = TextResources.MainTabs_HowItWorks,
                            Icon  = new FileImageSource {
                                File = TextResources.MainTabs_HowItWorks_Icon
                            }
                        });
                        SetDetailIfNull(page);
                        Pages.Add(id, page);
                        break;

                    case MenuType.OgxSystem:
                        page = new XNavigationPage(new OgxSystemPage(this)
                        {
                            Title = TextResources.MainTabs_OGX_System,
                            Icon  = new FileImageSource {
                                File = TextResources.MainTabs_OGX_System_Icon
                            }
                        });
                        SetDetailIfNull(page);
                        Pages.Add(id, page);
                        break;

                    case MenuType.Rewards:
                        page = new XNavigationPage(new RewardsPage(this)
                        {
                            Title = TextResources.MainTabs_Rewards,
                            Icon  = new FileImageSource {
                                File = TextResources.MainTabs_Rewards_Icon
                            }
                        });
                        SetDetailIfNull(page);
                        Pages.Add(id, page);
                        break;

                    case MenuType.MealOptions:
                        page = new XNavigationPage(new MealPlanPage(this)
                        {
                            Title = TextResources.MainTabs_Meal_Options,
                            Icon  = new FileImageSource {
                                File = TextResources.MainTabs_Meal_Options_Icon
                            }
                        });
                        SetDetailIfNull(page);
                        Pages.Add(id, page);
                        break;

                    case MenuType.Testimonials:
                        page = new XNavigationPage(new YoutubeTestimonialPage(this)
                        {
                            Title = TextResources.MainTabs_Testimonials,
                            Icon  = new FileImageSource {
                                File = TextResources.MainTabs_Testimonials_Icon
                            }
                        });
                        SetDetailIfNull(page);
                        Pages.Add(id, page);
                        break;

                    case MenuType.WorkoutVideos:
                        page = new XNavigationPage(new PlaylistPage(this)
                        {
                            Title = TextResources.MainTabs_WorkoutVideos,
                            Icon  = new FileImageSource {
                                File = TextResources.MainTabs_WorkoutVideos_Icon
                            }
                        });
                        SetDetailIfNull(page);
                        Pages.Add(id, page);
                        break;

                    case MenuType.MyMusic:
                        page = new XNavigationPage(new AudioPlayerPage(this)
                        {
                            Title = TextResources.MainTabs_MyMusic,
                            Icon  = new FileImageSource {
                                File = TextResources.MainTabs_MyMusic_Icon
                            }
                        });
                        SetDetailIfNull(page);
                        Pages.Add(id, page);
                        break;

                    case MenuType.Community:
                        page = new XNavigationPage(new CommunityPage(this)
                        {
                            Title = TextResources.MainTabs_Community,
                            Icon  = new FileImageSource {
                                File = TextResources.MainTabs_Community_Icon
                            }
                        });
                        SetDetailIfNull(page);
                        Pages.Add(id, page);
                        break;

                    case MenuType.Settings:
                        page = new XNavigationPage(new Settings(this)
                        {
                            Title = TextResources.MainTabs_Settings,
                            Icon  = new FileImageSource {
                                File = TextResources.MainTabs_Settings_Icon
                            }
                        });
                        SetDetailIfNull(page);
                        Pages.Add(id, page);
                        break;

                    case MenuType.More:
                        page = new XNavigationPage(new MiscContentPage(this)
                        {
                            Title = TextResources.MainTabs_More,
                            Icon  = new FileImageSource {
                                File = TextResources.MainTabs_More_Icon
                            }
                        });
                        SetDetailIfNull(page);
                        Pages.Add(id, page);
                        break;

                    case MenuType.Logout:
                        await App.LogoutAsync();

                        App.GoToAccountPage();
                        return;
                    }
                }

                newPage = Pages[id];
                if (newPage == null)
                {
                    return;
                }

                // Remove page from root page loaded list
                if (id == MenuType.MyMusic ||
                    id == MenuType.WorkoutVideos ||
                    id == MenuType.Settings ||
                    id == MenuType.OgxSystem ||
                    id == MenuType.More)
                {
                    Pages.Remove(id);
                }

                //pop to root for Windows Phone
                // if (Detail != null && Device.RuntimePlatform == Device.WinPhone)
                // {
                // await Detail.Navigation.PopToRootAsync();
                // }

                Detail = new Page();
                Detail = newPage;
                if (!backPressed)
                {
                    VisitedPages.Add(id, true);
                }
                MasterBehavior = MasterBehavior.Popover;
                if (Device.Idiom == TargetIdiom.Phone)
                {
                    IsPresented    = false;
                    MasterBehavior = MasterBehavior.Popover;
                }
                else if (Device.Idiom == TargetIdiom.Tablet)
                {
                    IsPresented    = false;
                    MasterBehavior = MasterBehavior.SplitOnLandscape;
                }
            }
            catch (Exception ex)
            {
                var exceptionHandler = new ExceptionHandler(typeof(RootPage).FullName, ex);
            }
        }
示例#34
0
        private void tbtnSave_ItemClick(object sender, TileItemEventArgs e)
        {
            ExceptionHandler.HandleException(() =>
            {
                if (frmMain.customerIdx != 0)
                {
                    #region Update
                    var updateCustomer = new Customer
                    {
                        CustomerId             = customerInfo.CustomerId,
                        CustomerCode           = txtCode.Text,
                        CustomerName           = txtName.Text,
                        CustomerTaxNo          = txtTaxNo.Text,
                        CustomerTaxDepartment  = txtTaxDepart.Text,
                        CustomerAddress        = txtAddress.Text,
                        CustomerActive         = chbActive.Checked,
                        CustomerDebated        = chbDebate.Checked,
                        CustomerGotAppointment = chbAppointment.Checked,
                        CustomerEnvoyId        = Convert.ToInt32(cmbEnvoy.EditValue)
                    };

                    var updateDirector = new CustomerDirector
                    {
                        DirectorId    = customerDirector.DirectorId,
                        DirectorName  = txtDirectorName.Text,
                        DirectorTitle = txtDirectorTitle.Text,
                        DirectorGsm   = txtDirectorGsm.Text,
                        DirectorMail  = txtDirectorMail.Text,
                        DirectorPhone = txtDirectorPhone.Text,
                        CustomerId    = updateCustomer.CustomerId
                    };
                    var updatePurchasingStaff = new CustomerPurchasingStaff
                    {
                        PurchaseStaffId    = customerPurchStaff.PurchaseStaffId,
                        PurchaseStaffName  = txtPurchasingDirector.Text,
                        PurchaseStaffGsm   = txtPurchasingGsm.Text,
                        PurchaseStaffMail  = txtPurchasingMail.Text,
                        PurchaseStaffPhone = txtPurchasingPhone.Text,
                        CustomerId         = updateCustomer.CustomerId
                    };
                    var updateAccountant = new CustomerAccountant
                    {
                        AccountantId     = customerAccountant.AccountantId,
                        CustomerId       = updateCustomer.CustomerId,
                        AccountantName   = txtAccountantName.Text,
                        AccountantGsm    = txtAccountantGsm.Text,
                        AccountantMail   = txtAccountantMail.Text,
                        AccountantPhone  = txtAccountantPhone.Text,
                        AccountantExpiry = dtpAccountantExpiry.DateTime
                    };
                    _customerService.UpdateWithTransaction(updateCustomer, updateAccountant, updateDirector, updatePurchasingStaff);
                    FillCustomerInfo();
                    XtraMessageBox.Show("Güncellendi.");

                    #endregion
                }
                else
                {
                    #region NewRecord
                    var newCustomerRec = new Customer
                    {
                        CustomerCode           = txtCode.Text,
                        CustomerName           = txtName.Text,
                        CustomerTaxNo          = txtTaxNo.Text,
                        CustomerTaxDepartment  = txtTaxDepart.Text,
                        CustomerAddress        = txtAddress.Text,
                        CustomerActive         = chbActive.Checked,
                        CustomerDebated        = chbDebate.Checked,
                        CustomerGotAppointment = chbAppointment.Checked,
                        CustomerEnvoyId        = Convert.ToInt32(cmbEnvoy.EditValue)
                    };

                    var newDirectorRec = new CustomerDirector
                    {
                        DirectorName  = txtDirectorName.Text,
                        DirectorTitle = txtDirectorTitle.Text,
                        DirectorGsm   = txtDirectorGsm.Text,
                        DirectorMail  = txtDirectorMail.Text,
                        DirectorPhone = txtDirectorPhone.Text,
                    };

                    var newPurchasingStaffRec = new CustomerPurchasingStaff
                    {
                        PurchaseStaffName  = txtPurchasingDirector.Text,
                        PurchaseStaffGsm   = txtPurchasingGsm.Text,
                        PurchaseStaffMail  = txtPurchasingMail.Text,
                        PurchaseStaffPhone = txtPurchasingPhone.Text,
                    };

                    var newAccountantRec = new CustomerAccountant
                    {
                        AccountantName   = txtAccountantName.Text,
                        AccountantGsm    = txtAccountantGsm.Text,
                        AccountantMail   = txtAccountantMail.Text,
                        AccountantPhone  = txtAccountantPhone.Text,
                        AccountantExpiry = dtpAccountantExpiry.DateTime
                    };
                    _customerService.AddWithTransaction(newCustomerRec, newAccountantRec, newDirectorRec, newPurchasingStaffRec);
                    frmMain.customerIdx = newCustomerRec.CustomerId;
                    FillCustomerInfo();
                    tbarDetails.Visible = true;
                    XtraMessageBox.Show("Başarıyla Oluşturuldu.");
                    #endregion
                }
            });
        }
示例#35
0
 private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
 {
     ExceptionHandler.LogException(unhandledExceptionEventArgs.ExceptionObject as Exception);
 }
        public List <SuburbEntity> SelectAll()
        {
            _errorCode    = 0;
            _rowsAffected = 0;

            var returnedEntities = new List <SuburbEntity>();

            try
            {
                var sb = new StringBuilder();
                sb.Append("SELECT ");
                sb.Append("[SuburbId], ");
                sb.Append("[SuburbName], ");
                sb.Append("sb.[StateId], ");
                sb.Append("[StateName] ");
                sb.Append("FROM [dbo].[Suburb] sb ,  [dbo].[State] st ");
                sb.Append("WHERE sb.StateId =st.StateId ");
                sb.Append("SELECT @intErrorCode=@@ERROR; ");
                var commandText = sb.ToString();
                sb.Clear();

                using (var dbConnection = _dbProviderFactory.CreateConnection())
                {
                    if (dbConnection == null)
                    {
                        throw new ArgumentNullException("dbConnection", "The db connection can't be null.");
                    }

                    dbConnection.ConnectionString = _connectionString;

                    using (var dbCommand = _dbProviderFactory.CreateCommand())
                    {
                        if (dbCommand == null)
                        {
                            throw new ArgumentNullException("dbCommand" + " The db command for entity [Suburb] can't be null. ");
                        }

                        dbCommand.Connection  = dbConnection;
                        dbCommand.CommandText = commandText;

                        //Input Parameters - None

                        //Output Parameters
                        _dataHandler.AddParameterToCommand(dbCommand, "@intErrorCode", CsType.Int, ParameterDirection.Output, null);

                        //Open Connection
                        if (dbConnection.State != ConnectionState.Open)
                        {
                            dbConnection.Open();
                        }

                        //Execute query.
                        using (var reader = dbCommand.ExecuteReader())
                        {
                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    var entity = new SuburbEntity();
                                    entity.SuburbId   = reader.GetInt32(0);
                                    entity.SuburbName = reader.GetString(1);
                                    entity.StateId    = reader.GetInt32(2);
                                    entity.StateName  = reader.GetString(3);
                                    returnedEntities.Add(entity);
                                }
                            }
                        }

                        _errorCode = int.Parse(dbCommand.Parameters["@intErrorCode"].Value.ToString());

                        if (_errorCode != 0)
                        {
                            // Throw error.
                            throw new Exception("The SelectAll method for entity [Suburb] reported the Database ErrorCode: " + _errorCode);
                        }
                    }
                }

                return(returnedEntities);
            }
            catch (Exception ex)
            {
                //Log exception error
                _loggingHandler.LogEntry(ExceptionHandler.GetExceptionMessageFormatted(ex), true);

                //Bubble error to caller and encapsulate Exception object
                throw new Exception("SuburbRepository::SelectAll::Error occured.", ex);
            }
        }
示例#37
0
        public override Method VisitMethod(Method method)
        {
            // body might not have been materialized, so make sure we do that first!
            Block body = method.Body;

            if (method == null)
            {
                return(null);
            }
            BlockSorter blockSorter  = new BlockSorter();
            BlockList   sortedBlocks = blockSorter.SortedBlocks;

            this.SucessorBlock      = blockSorter.SuccessorBlock;
            this.StackLocalsAtEntry = new TrivialHashtable();
            this.localsStack        = new LocalsStack();
            ExceptionHandlerList ehandlers = method.ExceptionHandlers;

            for (int i = 0, n = ehandlers == null ? 0 : ehandlers.Count; i < n; i++)
            {
                ExceptionHandler ehandler = ehandlers[i];
                if (ehandler == null)
                {
                    continue;
                }
                Block handlerStart = ehandler.HandlerStartBlock;
                if (handlerStart == null)
                {
                    continue;
                }
                LocalsStack lstack = new LocalsStack();
                this.StackLocalsAtEntry[handlerStart.UniqueKey] = lstack;
                if (ehandler.HandlerType == NodeType.Catch)
                {
                    lstack.exceptionHandlerType = CoreSystemTypes.Object;
                    if (ehandler.FilterType != null)
                    {
                        lstack.exceptionHandlerType = ehandler.FilterType;
                    }
                }
                else if (ehandler.HandlerType == NodeType.Filter)
                {
                    lstack.exceptionHandlerType = CoreSystemTypes.Object;
                    if (ehandler.FilterExpression != null)
                    {
                        lstack = new LocalsStack();
                        lstack.exceptionHandlerType = CoreSystemTypes.Object;
                        this.StackLocalsAtEntry[ehandler.FilterExpression.UniqueKey] = lstack;
                    }
                }
            }
            blockSorter.VisitMethodBody(body);
            for (int i = 0, n = sortedBlocks.Count; i < n; i++)
            {
                Block b = sortedBlocks[i];
                if (b == null)
                {
                    Debug.Assert(false); continue;
                }
                this.VisitBlock(b);
            }
            return(method);
        }
示例#38
0
    void InnerProcess()
    {
        body = Method.Body;
        body.SimplifyMacros();

        var firstInstruction = FirstInstructionSkipCtor();

        var indexOf = body.Instructions.IndexOf(firstInstruction);

        var returnInstruction = FixReturns();

        stopwatchVar = ModuleWeaver.InjectStopwatch(body, indexOf);

        var beforeReturn = Instruction.Create(OpCodes.Nop);
        body.InsertBefore(returnInstruction, beforeReturn);

        InjectIlForFinally(returnInstruction);

        var handler = new ExceptionHandler(ExceptionHandlerType.Finally)
        {
            TryStart = firstInstruction,
            TryEnd = beforeReturn,
            HandlerStart = beforeReturn,
            HandlerEnd = returnInstruction,
        };

        body.ExceptionHandlers.Add(handler);
        body.InitLocals = true;
        body.OptimizeMacros();
    }
示例#39
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string userid   = Request.Form["userid"];
                string suppid   = Request.Form["suppid"];
                string orderid  = Request.Form["orderid"];
                string orderAmt = Request.Form["orderAmt"];
                string bankcode = Request.Form["bankcode"];
                string time     = Request.Form["time"];
                string sign     = Request.Form["sign"];

                bool success = false;

                #region

                if (!string.IsNullOrEmpty(userid) && !string.IsNullOrEmpty(time))
                {
                    DateTime sumTime;

                    if (DateTime.TryParse(time, out sumTime))
                    {
                        if (DateTime.Now.Subtract(sumTime).TotalSeconds <= 10)
                        {
                            int intUserid = 0;

                            if (int.TryParse(userid, out intUserid))
                            {
                                var userinfo = viviapi.BLL.User.Factory.GetCacheUserBaseInfo(intUserid);

                                if (userinfo != null)
                                {
                                    string thisSign =
                                        string.Format(
                                            "userid={0}&suppid={1}&orderid={2}&orderAmt={3}&bankcode={4}&time={5}{6}"
                                            , userid
                                            , suppid
                                            , orderid
                                            , orderAmt
                                            , bankcode
                                            , time
                                            , userinfo.APIKey);

                                    thisSign = viviLib.Security.Cryptography.MD5(thisSign);

                                    if (thisSign == sign)
                                    {
                                        success = true;
                                    }
                                }
                            }
                        }
                    }
                }

                #endregion

                if (success == true)
                {
                    string payform = string.Empty;
                    bool   isdcode = (bankcode == "1003") || (bankcode == "1004");
                    if (isdcode)
                    {
                        viviapi.Model.User.UserInfo user = viviapi.BLL.User.Factory.GetCacheUserBaseInfo(int.Parse(userid));

                        if (user != null)
                        {
                            payform = viviapi.ETAPI.Common.SellFactory.GetDCodeForm(int.Parse(userid)
                                                                                    , user.APIKey
                                                                                    , int.Parse(suppid)
                                                                                    , orderid
                                                                                    , decimal.Parse(orderAmt)
                                                                                    , bankcode);
                        }
                    }
                    else
                    {
                        payform = viviapi.ETAPI.Common.SellFactory.GetPayForm(int.Parse(suppid), orderid,
                                                                              decimal.Parse(orderAmt), bankcode, false);
                    }


                    this.litpayform.Text = payform;
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandleException(ex);
                Response.Write("error");
                Response.End();
            }
        }
 internal async Task InvokeBeforeTunnelConnectRequest(ProxyServer proxyServer,
                                                      TunnelConnectSessionEventArgs connectArgs, ExceptionHandler exceptionFunc)
 {
     if (BeforeTunnelConnectRequest != null)
     {
         await BeforeTunnelConnectRequest.InvokeAsync(proxyServer, connectArgs, exceptionFunc);
     }
 }
 public override DialogResult ShowDialog(MethodDefinition mdef, ExceptionHandler selected)
 {
     FillControls(mdef);
     return(base.ShowDialog(mdef, selected));
 }
示例#42
0
        /// <summary>
        /// 保存按钮事件
        /// </summary>
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (!FrmMainDAO.QueryUserButtonPower(this.Name, this.Text, sender, true))
                {
                    return;
                }

                if (btnSave.Text != "保存")
                {
                    DataRow headRow            = ((DataRowView)bindingSource_BaseInfo.Current).Row;
                    string  autoQuotationNoStr = DataTypeConvert.GetString(headRow["AutoQuotationNo"]);
                    if (quoDAO.CheckQuotationInfo_IsSalesOrder(null, autoQuotationNoStr))
                    {
                        return;
                    }

                    Set_ButtonEditGrid_State(false);
                    textRFQNO.Focus();
                }
                else
                {
                    bindingSource_BaseInfo.EndEdit();
                    DataRow headRow = ((DataRowView)bindingSource_BaseInfo.Current).Row;

                    if (textRFQNO.Text.Trim() == "")
                    {
                        MessageHandler.ShowMessageBox("手工单号不能为空,请重新操作。");
                        textRFQNO.Focus();
                        return;
                    }
                    if (textProjectName.Text.Trim() == "")
                    {
                        MessageHandler.ShowMessageBox("项目名称不能为空,请重新操作。");
                        textProjectName.Focus();
                        return;
                    }
                    if (searchBussinessBaseNo.Text.Trim() == "")
                    {
                        MessageHandler.ShowMessageBox("客户不能为空,请重新操作。");
                        searchBussinessBaseNo.Focus();
                        return;
                    }
                    if (textRequester.Text.Trim() == "")
                    {
                        MessageHandler.ShowMessageBox("客户需求人不能为空,请重新操作。");
                        textRequester.Focus();
                        return;
                    }

                    for (int i = gridViewQuotationPriceInfo.DataRowCount - 1; i >= 0; i--)
                    {
                        DataRow listRow = gridViewQuotationPriceInfo.GetDataRow(i);
                        if (DataTypeConvert.GetString(listRow["CurrencyCate"]) == "")
                        {
                            gridViewQuotationPriceInfo.DeleteRow(i);
                            continue;
                        }
                        if (DataTypeConvert.GetString(listRow["Amount"]) == "" || DataTypeConvert.GetDecimal(listRow["Amount"]) == 0)
                        {
                            MessageHandler.ShowMessageBox("金额不能为空,请填写后再进行保存。");
                            FocusedListView(true, "Amount", i);
                            return;
                        }
                        if (DataTypeConvert.GetString(listRow["Tax"]) == "")
                        {
                            MessageHandler.ShowMessageBox("税率不能为空,请填写后再进行保存。");
                            FocusedListView(true, "Tax", i);
                            return;
                        }
                        if (DataTypeConvert.GetString(listRow["Versions"]) == "")
                        {
                            MessageHandler.ShowMessageBox("版本不能为空,请填写后再进行保存。");
                            FocusedListView(true, "Versions", i);
                            return;
                        }
                        if (DataTypeConvert.GetString(listRow["Offerer"]) == "")
                        {
                            MessageHandler.ShowMessageBox("报价人不能为空,请填写后再进行保存。");
                            FocusedListView(true, "Offerer", i);
                            return;
                        }
                        if (DataTypeConvert.GetString(listRow["QuotationDate"]) == "")
                        {
                            MessageHandler.ShowMessageBox("报价日期不能为空,请填写后再进行保存。");
                            FocusedListView(true, "QuotationDate", i);
                            return;
                        }

                        string versionsStr = DataTypeConvert.GetString(listRow["Versions"]);
                        if (TableQuotationPriceInfo.Select(string.Format("Versions = '{0}'", versionsStr)).Length > 1)
                        {
                            MessageHandler.ShowMessageBox("版本号有重复,请重新填写后再进行保存。");
                            FocusedListView(true, "Versions", i);
                            return;
                        }
                    }

                    int ret = quoDAO.SaveQuotationInfo(headRow, TableQuotationPriceInfo);
                    switch (ret)
                    {
                    case -1:

                        break;

                    case 1:

                        break;

                    case 0:
                        return;
                    }

                    currentAutoQuotationNoStr = DataTypeConvert.GetString(headRow["AutoQuotationNo"]);
                    btnRefresh_Click(null, null);
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandleException(this.Text + "--保存按钮事件错误。", ex);
            }
        }
示例#43
0
 private static void TaskSchedulerOnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
 {
     ExceptionHandler.LogException(unobservedTaskExceptionEventArgs.Exception);
     unobservedTaskExceptionEventArgs.SetObserved();
 }
示例#44
0
        /// <summary>
        ///     Saves all changes which have been made to entities in the repository
        /// </summary>
        public void Save()
        {
            lock (_repositoryLock)
            {
                try
                {
                    using (var ts = new TransactionScope())
                    {
                        bool concurrencyIssueResolved = true;
                        while (concurrencyIssueResolved)
                        {
                            try
                            {
                                concurrencyIssueResolved = false;
                                _context.ChangeTracker.DetectChanges();
                                _context.SaveChanges();
                                if (_eventAggregator != null && _changesInProgress.Any())
                                {
                                    using (var auditRepo = new Repository(_eventAggregator))
                                    {
                                        _eventAggregator.GetEvent <AuditEntityChangesEvent>()
                                        .Publish(
                                            new AuditData
                                        {
                                            Repository = auditRepo,
                                            Changes    = _changesInProgress
                                        });
                                        auditRepo.Save();
                                    }
                                }
                            }
                            catch (DbUpdateConcurrencyException duce)
                            {
                                concurrencyIssueResolved = TryResolveConcurrencyException(duce);
                            }
                        }
                        ts.Complete();
                    }
                }
                catch (DbEntityValidationException validationException)
                {
                    var message = new StringBuilder();
                    foreach (var validationResult in validationException.EntityValidationErrors)
                    {
                        foreach (var validationError in validationResult.ValidationErrors)
                        {
                            message.AppendFormat("{0}: {1}", validationError.PropertyName, validationError.ErrorMessage);
                            message.AppendLine();
                        }
                    }

                    throw ExceptionHandler.HandleException <DataAccessException>(
                              "Database error",
                              string.Format("Saving changes to the repository failed. Validation error: {0}", message),
                              validationException);
                }
                catch (Exception ex)
                {
                    throw ExceptionHandler.HandleException <DataAccessException>(
                              "Database error",
                              "Saving changes to the repository failed.  See InnerException for details.",
                              ex);
                }
            }
        }
        /// <summary>
        /// Loads the XML files from the "Web/Bf2Stats" folder.
        /// These XML files are used for displaying certain information
        /// on some of the Bf2Stats pages
        /// </summary>
        public static void Load()
        {
            try
            {
                // Reset all incase of file changes
                Armies    = new Dictionary <int, string>();
                Maps      = new Dictionary <int, string>();
                ModMapIds = new Dictionary <string, List <int> >()
                {
                    { "bf", new List <int>() },
                    { "sf", new List <int>() },
                    { "ef", new List <int>() },
                    { "af", new List <int>() }
                };
                TheatreMapIds = new Dictionary <string, int[]>();

                // Enumerate through each .XML file in the data directory
                string      DataDir = Path.Combine(Program.RootPath, "Web", "Bf2Stats");
                FileStream  file;
                XmlDocument Doc = new XmlDocument();

                // Load Army Data, Creating file if it doesnt exist already
                using (file = new FileStream(Path.Combine(DataDir, "ArmyData.xml"), FileMode.OpenOrCreate))
                {
                    if (file.Length == 0)
                    {
                        using (StreamWriter writer = new StreamWriter(file, Encoding.UTF8, 1024, true))
                            writer.Write(Program.GetResourceAsString("BF2Statistics.Web.Bf2Stats.ArmyData.xml"));

                        file.Flush();
                        file.Seek(0, SeekOrigin.Begin);
                    }

                    // Load the xml data
                    Doc.Load(file);
                    foreach (XmlNode Node in Doc.GetElementsByTagName("army"))
                    {
                        Armies.Add(Int32.Parse(Node.Attributes["id"].Value), Node.InnerText);
                    }
                }

                // Load Map Data, Creating file if it doesnt exist already
                using (file = new FileStream(Path.Combine(DataDir, "MapData.xml"), FileMode.OpenOrCreate))
                {
                    if (file.Length == 0)
                    {
                        using (StreamWriter writer = new StreamWriter(file, Encoding.UTF8, 1024, true))
                            writer.Write(Program.GetResourceAsString("BF2Statistics.Web.Bf2Stats.MapData.xml"));

                        file.Flush();
                        file.Seek(0, SeekOrigin.Begin);
                    }

                    // Load the xml data
                    Doc.Load(file);
                    foreach (XmlNode Node in Doc.GetElementsByTagName("map"))
                    {
                        int    mid = Int32.Parse(Node.Attributes["id"].Value);
                        string mod = Node.Attributes["mod"].Value;
                        Maps[mid] = Node.InnerText;

                        // Add map to mod map ids if mod is not empty
                        if (!String.IsNullOrWhiteSpace(mod) && ModMapIds.ContainsKey(mod))
                        {
                            ModMapIds[mod].Add(mid);
                        }
                    }
                }

                // Load Theater Data, Creating file if it doesnt exist already
                using (file = new FileStream(Path.Combine(DataDir, "TheaterData.xml"), FileMode.OpenOrCreate))
                {
                    if (file.Length == 0)
                    {
                        using (StreamWriter writer = new StreamWriter(file, Encoding.UTF8, 1024, true))
                            writer.Write(Program.GetResourceAsString("BF2Statistics.Web.Bf2Stats.TheaterData.xml"));

                        file.Flush();
                        file.Seek(0, SeekOrigin.Begin);
                    }

                    // Load the xml data
                    Doc.Load(file);
                    foreach (XmlNode Node in Doc.GetElementsByTagName("theater"))
                    {
                        string   name = Node.Attributes["name"].Value;
                        string[] arr  = Node.Attributes["maps"].Value.Split(',');
                        TheatreMapIds.Add(name, Array.ConvertAll(arr, Int32.Parse));
                    }
                }

                // Load Rank Data
                Rank[] Ranks = new Rank[22];
                int    i     = 0;

                // Load Rank Data, Creating file if it doesnt exist already
                using (file = new FileStream(Path.Combine(DataDir, "RankData.xml"), FileMode.OpenOrCreate))
                {
                    if (file.Length == 0)
                    {
                        using (StreamWriter writer = new StreamWriter(file, Encoding.UTF8, 1024, true))
                            writer.Write(Program.GetResourceAsString("BF2Statistics.Web.Bf2Stats.RankData.xml"));

                        file.Flush();
                        file.Seek(0, SeekOrigin.Begin);
                    }

                    // Load the xml data
                    Doc.Load(file);
                    foreach (XmlNode Node in Doc.GetElementsByTagName("rank"))
                    {
                        Dictionary <string, int> Awards = new Dictionary <string, int>();
                        XmlNode AwardsNode = Node.SelectSingleNode("reqAwards");
                        if (AwardsNode != null && AwardsNode.HasChildNodes)
                        {
                            foreach (XmlNode E in AwardsNode.ChildNodes)
                            {
                                Awards.Add(E.Attributes["id"].Value, Int32.Parse(E.Attributes["level"].Value));
                            }
                        }
                        string[] arr = Node.SelectSingleNode("reqRank").InnerText.Split(',');

                        Ranks[i] = new Rank
                        {
                            Id        = i,
                            MinPoints = Int32.Parse(Node.SelectSingleNode("reqPoints").InnerText),
                            ReqRank   = Array.ConvertAll(arr, Int32.Parse),
                            ReqAwards = Awards
                        };
                        i++;
                    }

                    RankCalculator.SetRankData(Ranks);
                }
            }
            catch (Exception e)
            {
                ExceptionHandler.GenerateExceptionLog(e);
                throw;
            }
        }
示例#46
0
 private static void appDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     ExceptionHandler.Handle(e.ExceptionObject as Exception, e.IsTerminating, null);
 }
示例#47
0
        /// <summary>
        /// Generate a new DynamicMethod with which you can invoke the previous state.
        /// If the NativeDetour holds a reference to a managed method, a copy of the original method is returned.
        /// If the NativeDetour holds a reference to a native function, an "undo-call-redo" trampoline with a matching signature is returned.
        /// </summary>
        public MethodBase GenerateTrampoline(MethodBase signature = null)
        {
            MethodBase remoteTrampoline = OnGenerateTrampoline?.InvokeWhileNull <MethodBase>(this, signature);

            if (remoteTrampoline != null)
            {
                return(remoteTrampoline);
            }

            if (!IsValid)
            {
                throw new ObjectDisposedException(nameof(NativeDetour));
            }

            if (_BackupMethod != null)
            {
                // If we're detouring an IL method and have an IL copy, invoke the IL copy.
                // Note that this ignores the passed signature.
                return(_BackupMethod);
            }

            /*
             * if (signature == null)
             *  signature = _BackupMethod;
             */
            if (signature == null)
            {
                throw new ArgumentNullException("A signature must be given if the NativeDetour doesn't hold a reference to a managed method.");
            }

            // Otherwise, undo the detour, call the method and reapply the detour.

            MethodBase methodCallable = Method;

            if (methodCallable == null)
            {
                methodCallable = DetourHelper.GenerateNativeProxy(Data.Method, signature);
            }

            Type returnType = (signature as MethodInfo)?.ReturnType ?? typeof(void);

            ParameterInfo[] args     = signature.GetParameters();
            Type[]          argTypes = new Type[args.Length];
            for (int i = 0; i < args.Length; i++)
            {
                argTypes[i] = args[i].ParameterType;
            }

            using (DynamicMethodDefinition dmd = new DynamicMethodDefinition(
                       $"Trampoline:Native<{Method?.GetFindableID(simple: true) ?? ((long) Data.Method).ToString("X16")}>?{GetHashCode()}",
                       returnType, argTypes
                       )) {
                ILProcessor il = dmd.GetILProcessor();

                ExceptionHandler eh = new ExceptionHandler(ExceptionHandlerType.Finally);
                il.Body.ExceptionHandlers.Add(eh);

                il.EmitDetourCopy(_BackupNative, Data.Method, Data.Type);

                // Store the return value in a local as we can't preserve the stack across exception block boundaries.
                VariableDefinition localResult = null;
                if (returnType != typeof(void))
                {
                    il.Body.Variables.Add(localResult = new VariableDefinition(il.Import(returnType)));
                }

                // Label blockTry = il.BeginExceptionBlock();
                int instriTryStart = il.Body.Instructions.Count;

                for (int i = 0; i < argTypes.Length; i++)
                {
                    il.Emit(OpCodes.Ldarg, i);
                }

                if (methodCallable is MethodInfo)
                {
                    il.Emit(OpCodes.Call, (MethodInfo)methodCallable);
                }
                else if (methodCallable is ConstructorInfo)
                {
                    il.Emit(OpCodes.Call, (ConstructorInfo)methodCallable);
                }
                else
                {
                    throw new NotSupportedException($"Method type {methodCallable.GetType().FullName} not supported.");
                }

                if (localResult != null)
                {
                    il.Emit(OpCodes.Stloc, localResult);
                }

                il.Emit(OpCodes.Leave, (object)null);
                Instruction instrLeave = il.Body.Instructions[il.Body.Instructions.Count - 1];

                // il.BeginFinallyBlock();
                int instriTryEnd       = il.Body.Instructions.Count;
                int instriFinallyStart = il.Body.Instructions.Count;

                // Reapply the detour even if the method threw an exception.
                il.EmitDetourApply(Data);

                // il.EndExceptionBlock();
                int instriFinallyEnd = il.Body.Instructions.Count;

                Instruction instrLeaveTarget = null;

                if (localResult != null)
                {
                    il.Emit(OpCodes.Ldloc, localResult);
                    instrLeaveTarget = il.Body.Instructions[il.Body.Instructions.Count - 1];
                }

                il.Emit(OpCodes.Ret);
                instrLeaveTarget   = instrLeaveTarget ?? il.Body.Instructions[il.Body.Instructions.Count - 1];
                instrLeave.Operand = instrLeaveTarget;

                // TODO: Are the exception handler indices correct?
                eh.TryStart     = il.Body.Instructions[instriTryStart];
                eh.TryEnd       = il.Body.Instructions[instriTryEnd];
                eh.HandlerStart = il.Body.Instructions[instriTryEnd];
                eh.HandlerEnd   = il.Body.Instructions[instriFinallyEnd];

                return(dmd.Generate());
            }
        }
示例#48
0
        public void Write()
        {
            uint codeSize = InitializeInstructionOffsets();

            jitBody.MaxStack = keepMaxStack ? body.MaxStack : GetMaxStack();

            jitBody.Options = 0;
            if (body.InitLocals)
            {
                jitBody.Options |= 0x10;
            }

            if (body.Variables.Count > 0)
            {
                var local = new LocalSig(body.Variables.Select(var => var.Type).ToList());
                jitBody.LocalVars = SignatureWriter.Write(metadata, local);
            }
            else
            {
                jitBody.LocalVars = new byte[0];
            }

            using (var ms = new MemoryStream()) {
                uint _codeSize = WriteInstructions(new BinaryWriter(ms));
                Debug.Assert(codeSize == _codeSize);
                jitBody.ILCode = ms.ToArray();
            }

            jitBody.EHs = new JITEHClause[exceptionHandlers.Count];
            if (exceptionHandlers.Count > 0)
            {
                jitBody.Options |= 8;
                for (int i = 0; i < exceptionHandlers.Count; i++)
                {
                    ExceptionHandler eh = exceptionHandlers[i];
                    jitBody.EHs[i].Flags = (uint)eh.HandlerType;

                    uint tryStart = GetOffset(eh.TryStart);
                    uint tryEnd   = GetOffset(eh.TryEnd);
                    jitBody.EHs[i].TryOffset = tryStart;
                    jitBody.EHs[i].TryLength = tryEnd - tryStart;

                    uint handlerStart = GetOffset(eh.HandlerStart);
                    uint handlerEnd   = GetOffset(eh.HandlerEnd);
                    jitBody.EHs[i].HandlerOffset = handlerStart;
                    jitBody.EHs[i].HandlerLength = handlerEnd - handlerStart;

                    if (eh.HandlerType == ExceptionHandlerType.Catch)
                    {
                        uint token = metadata.GetToken(eh.CatchType).Raw;
                        if ((token & 0xff000000) == 0x1b000000)
                        {
                            jitBody.Options |= 0x80;
                        }

                        jitBody.EHs[i].ClassTokenOrFilterOffset = token;
                    }
                    else if (eh.HandlerType == ExceptionHandlerType.Filter)
                    {
                        jitBody.EHs[i].ClassTokenOrFilterOffset = GetOffset(eh.FilterStart);
                    }
                }
            }
        }
示例#49
0
        public void OnEditSelected()
        {
            if (!EditEnabled)
            {
                return;
            }

            if (this.SelectedPresetVoiLut == null)
            {
                this.Host.DesktopWindow.ShowMessageBox(SR.MessagePleaseSelectAnItemToEdit, MessageBoxActions.Ok);
                return;
            }

            try
            {
                PresetVoiLutConfiguration       configuration = this.SelectedPresetOperation.GetConfiguration();
                IPresetVoiLutOperationComponent editComponent = this.SelectedPresetOperation.SourceFactory.GetEditComponent(configuration);
                editComponent.EditContext = EditContext.Edit;
                PresetVoiLutOperationsComponentContainer container = new PresetVoiLutOperationsComponentContainer(GetUnusedKeyStrokes(this.SelectedPresetVoiLut), editComponent);
                container.SelectedKeyStroke = this.SelectedPresetVoiLut.KeyStroke;

                if (ApplicationComponentExitCode.Accepted != ApplicationComponent.LaunchAsDialog(this.Host.DesktopWindow, container, SR.TitleEditPreset))
                {
                    return;
                }

                PresetVoiLut preset = container.GetPresetVoiLut();
                Platform.CheckForNullReference(preset, "preset");

                List <PresetVoiLut> conflictingItems = CollectionUtils.Select <PresetVoiLut>(_voiLutPresets.Items,
                                                                                             delegate(PresetVoiLut test){ return(preset.Equals(test)); });

                if (conflictingItems.Count == 0 ||
                    (conflictingItems.Count == 1 && conflictingItems[0].Equals(this.SelectedPresetVoiLut)))
                {
                    PresetVoiLut selected = this.SelectedPresetVoiLut;

                    int index = _voiLutPresets.Items.IndexOf(selected);
                    _voiLutPresets.Items.Remove(selected);

                    if (index < _voiLutPresets.Items.Count)
                    {
                        _voiLutPresets.Items.Insert(index, preset);
                    }
                    else
                    {
                        _voiLutPresets.Items.Add(preset);
                    }

                    Selection = null;

                    this.Modified = true;
                }
                else
                {
                    this.Host.DesktopWindow.ShowMessageBox(SR.MessageNameOrKeystrokeConflictsWithExistingPreset, MessageBoxActions.Ok);
                }
            }
            catch (Exception e)
            {
                ExceptionHandler.Report(e, SR.MessageFailedToEditPreset, this.Host.DesktopWindow);
            }
        }
示例#50
0
        public ActionResult ListAll(string Sorting_Order, int?page)
        {
            try
            {
                ViewBag.CurrentSort          = Sorting_Order;
                ViewBag.SortingSitterName    = String.IsNullOrEmpty(Sorting_Order) ? "SitterNameDESC" : "";
                ViewBag.SortingSitterName    = Sorting_Order == "SitterNameDESC" ? "SitterNameASC" : "SitterNameDESC";
                ViewBag.SortingFee           = Sorting_Order == "FeeDESC" ? "FeeASC" : "FeeDESC";
                ViewBag.SortingAge           = Sorting_Order == "AgeDESC" ? "AgeASC" : "AgeDESC";
                ViewBag.SortingHiringDate    = Sorting_Order == "HiringDateDESC" ? "HiringDateASC" : "HiringDateDESC";
                ViewBag.SortingGrossSalary   = Sorting_Order == "GrossSalaryDESC" ? "GrossSalaryASC" : "GrossSalaryDESC";
                ViewBag.SortingNetSalary     = Sorting_Order == "NetSalaryDESC" ? "NetSalaryASC" : "NetSalaryDESC";
                ViewBag.SortingModifiedDate  = Sorting_Order == "ModifiedDateDESC" ? "ModifiedDateASC" : "ModifiedDateDESC";
                ViewBag.SortingTotalSales    = Sorting_Order == "TotalSalesDESC" ? "TotalSalesASC" : "TotalSalesDESC";
                ViewBag.SortingSessionsCount = Sorting_Order == "SessionsCountDESC" ? "SessionsCountASC" : "SessionsCountDESC";
                var sitters = from e in ListAllSitters() select e;
                switch (Sorting_Order)
                {
                case "TotalSalesASC":
                    sitters = sitters.OrderBy(e => e.TotalSales);
                    break;

                case "TotalSalesDESC":
                    sitters = sitters.OrderByDescending(e => e.TotalSales);
                    break;

                case "SessionsCountASC":
                    sitters = sitters.OrderBy(e => e.SessionsCount);
                    break;

                case "SessionsCountDESC":
                    sitters = sitters.OrderByDescending(e => e.SessionsCount);
                    break;

                case "SitterNameASC":
                    sitters = sitters.OrderBy(e => e.Name);
                    break;

                case "SitterNameDESC":
                    sitters = sitters.OrderByDescending(e => e.Name);
                    break;

                case "FeeASC":
                    sitters = sitters.OrderBy(e => e.Fee);
                    break;

                case "FeeDESC":
                    sitters = sitters.OrderByDescending(e => e.Fee);
                    break;

                case "AgeASC":
                    sitters = sitters.OrderBy(e => e.Age);
                    break;

                case "AgeDESC":
                    sitters = sitters.OrderByDescending(e => e.Age);
                    break;

                case "HiringDateASC":
                    sitters = sitters.OrderBy(e => e.HiringDate);
                    break;

                case "HiringDateDESC":
                    sitters = sitters.OrderByDescending(e => e.HiringDate);
                    break;

                case "GrossSalaryASC":
                    sitters = sitters.OrderBy(e => e.GrossSalary);
                    break;

                case "GrossSalaryDESC":
                    sitters = sitters.OrderByDescending(e => e.GrossSalary);
                    break;

                case "NetSalaryASC":
                    sitters = sitters.OrderBy(e => e.NetSalary);
                    break;

                case "NetSalaryDESC":
                    sitters = sitters.OrderByDescending(e => e.NetSalary);
                    break;

                case "ModifiedDateASC":
                    sitters = sitters.OrderBy(e => e.ModifiedDate);
                    break;

                case "ModifiedDateDESC":
                    sitters = sitters.OrderByDescending(e => e.ModifiedDate);
                    break;

                default:
                    sitters = sitters.OrderBy(e => e.SitterID);
                    break;
                }
                int pageSize   = 10;
                int pageNumber = (page ?? 1);
                return(View(sitters.ToPagedList(pageNumber, pageSize)));
            }
            catch (Exception ex)
            {
                //Log exception error
                _loggingHandler.LogEntry(ExceptionHandler.GetExceptionMessageFormatted(ex), true);
                ViewBag.Message = Server.HtmlEncode(ex.Message);
                return(View("Error"));
            }
        }
示例#51
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="response"></param>
        public static bool Finish(CardOrderSupplierResponse response)
        {
            string cacheKey = "OrderBankComplete" + response.SysOrderNo + response.SupplierId.ToString(CultureInfo.InvariantCulture);

            object flag = Cache.WebCache.GetCacheService().RetrieveObject(cacheKey);

            if (flag != null)
            {
                return(true);
            }

            var orderInfo = Cache.WebCache.GetCacheService().RetrieveObject(response.SysOrderNo) as OrderCardInfo;

            if (orderInfo == null)
            {
                orderInfo = BLL.Order.Card.Factory.Instance.GetModelByOrderId(response.SysOrderNo);
            }
            if (orderInfo == null)
            {
                return(false);
            }

            try
            {
                byte continueSubmit = 0;

                int seq = 1, continueSupp = 0;

                bool processFlag = true;

                if (response.Method == 1)
                {
                    if (response.OrderStatus != 2)
                    {
                        #region 继续提交
                        var suppInfo = BLL.Supplier.Factory.GetCacheModel(response.SupplierId);
                        if (suppInfo != null)
                        {
                            if (!string.IsNullOrEmpty(suppInfo.AsynsRetCode))
                            {
                                string[] arr = suppInfo.AsynsRetCode.Split(',');
                                if (arr.Any(s => s == response.SuppErrorCode))
                                {
                                    continueSubmit = 1;
                                }
                            }
                        }
                        #endregion
                    }

                    DataRow resultRow = BLL.Order.Card.Factory.Instance.CallbackInsert(response.SysOrderNo
                                                                                       , response.SupplierId
                                                                                       , response.OrderStatus
                                                                                       , response.SuppErrorCode
                                                                                       , response.SuppErrorMsg
                                                                                       , continueSubmit);

                    if (resultRow != null)
                    {
                        seq          = Convert.ToInt32(resultRow["seq"]);
                        continueSupp = Convert.ToInt32(resultRow["suppId"]);
                    }

                    if (continueSubmit == 1 && continueSupp > 0)
                    {
                        #region 再次提交
                        try
                        {
                            if (resultRow != null)
                            {
                                var o = new CardOrderSummitArgs()
                                {
                                    SysOrderNo = response.SysOrderNo,
                                    CardTypeId = Convert.ToInt32(resultRow["typeid"]),
                                    CardNo     = resultRow["cardno"].ToString(),
                                    CardPass   = resultRow["cardpass"].ToString(),
                                    FaceValue  = decimal.ToInt32(Convert.ToDecimal(resultRow["facevalue"])),
                                    Attach     = "",
                                    Source     = 2
                                };
                                var callBack = SendCard((SupplierCode)continueSupp, o);
                                if (callBack.SummitStatus == 1)
                                {
                                    processFlag = false;
                                }
                            }
                        }
                        catch
                        {
                        }
                        #endregion
                    }
                    else
                    {
                        processFlag = (seq == 1) || ((seq > 1) && (response.OrderStatus == 2));
                    }
                }

                if (processFlag)
                {
                    orderInfo = UpdateOrder(seq, orderInfo, response);

                    if (seq == 1 && orderInfo != null)
                    {
                        //APINotification.DoAsynchronousNotify(orderInfo);

                        APINotification.SynchronousNotifyX(orderInfo);
                    }
                }
                Cache.WebCache.GetCacheService().AddObject(cacheKey, response.OrderStatus, 5);

                return(true);
            }
            catch (Exception exception)
            {
                ExceptionHandler.HandleException(exception);

                return(false);
            }
        }
示例#52
0
        public static void process(AssemblyDef asm)
        {
            ModuleDef manifestModule = asm.ManifestModule;

            manifestModule.Mvid = null;
            manifestModule.Name = "";
            asm.ManifestModule.Import(new FieldDefUser(""));
            foreach (TypeDef typeDef in manifestModule.Types)
            {
                TypeDef typeDef2 = new TypeDefUser("");
                typeDef2.Methods.Add(new MethodDefUser());
                typeDef2.NestedTypes.Add(new TypeDefUser(""));
                MethodDef item = new MethodDefUser();
                typeDef2.Methods.Add(item);
                typeDef.NestedTypes.Add(typeDef2);
                typeDef.Events.Add(new EventDefUser());
                MethodDef methodDef = new MethodDefUser();
                methodDef.MethodSig = new MethodSig();
                foreach (MethodDef methodDef2 in typeDef.Methods)
                {
                    if (methodDef2.Body != null)
                    {
                        methodDef2.Body.SimplifyBranches();
                        if (!(methodDef2.ReturnType.FullName != "System.Void") && methodDef2.HasBody && methodDef2.Body.Instructions.Count != 0)
                        {
                            TypeSig typeSig  = asm.ManifestModule.Import(typeof(int)).ToTypeSig();
                            Local   local    = new Local(typeSig);
                            TypeSig typeSig2 = asm.ManifestModule.Import(typeof(bool)).ToTypeSig();
                            Local   local2   = new Local(typeSig2);
                            methodDef2.Body.Variables.Add(local);
                            methodDef2.Body.Variables.Add(local2);
                            Instruction operand      = methodDef2.Body.Instructions[methodDef2.Body.Instructions.Count - 1];
                            Instruction instruction  = new Instruction(OpCodes.Ret);
                            Instruction instruction2 = new Instruction(OpCodes.Ldc_I4_1);
                            methodDef2.Body.Instructions.Insert(0, new Instruction(OpCodes.Ldc_I4_0));
                            methodDef2.Body.Instructions.Insert(1, new Instruction(OpCodes.Stloc, local));
                            methodDef2.Body.Instructions.Insert(2, new Instruction(OpCodes.Br, instruction2));
                            Instruction instruction3 = new Instruction(OpCodes.Ldloc, local);
                            methodDef2.Body.Instructions.Insert(3, instruction3);
                            methodDef2.Body.Instructions.Insert(4, new Instruction(OpCodes.Ldc_I4_0));
                            methodDef2.Body.Instructions.Insert(5, new Instruction(OpCodes.Ceq));
                            methodDef2.Body.Instructions.Insert(6, new Instruction(OpCodes.Ldc_I4_1));
                            methodDef2.Body.Instructions.Insert(7, new Instruction(OpCodes.Ceq));
                            methodDef2.Body.Instructions.Insert(8, new Instruction(OpCodes.Stloc, local2));
                            methodDef2.Body.Instructions.Insert(9, new Instruction(OpCodes.Ldloc, local2));
                            methodDef2.Body.Instructions.Insert(10, new Instruction(OpCodes.Brtrue, methodDef2.Body.Instructions[10]));
                            methodDef2.Body.Instructions.Insert(11, new Instruction(OpCodes.Ret));
                            methodDef2.Body.Instructions.Insert(12, new Instruction(OpCodes.Calli));
                            methodDef2.Body.Instructions.Insert(13, new Instruction(OpCodes.Sizeof, operand));
                            methodDef2.Body.Instructions.Insert(methodDef2.Body.Instructions.Count, instruction2);
                            methodDef2.Body.Instructions.Insert(methodDef2.Body.Instructions.Count, new Instruction(OpCodes.Stloc, local2));
                            methodDef2.Body.Instructions.Insert(methodDef2.Body.Instructions.Count, new Instruction(OpCodes.Br, instruction3));
                            methodDef2.Body.Instructions.Insert(methodDef2.Body.Instructions.Count, instruction);
                            ExceptionHandler exceptionHandler = new ExceptionHandler(ExceptionHandlerType.Finally);
                            exceptionHandler.HandlerStart = methodDef2.Body.Instructions[10];
                            exceptionHandler.HandlerEnd   = methodDef2.Body.Instructions[11];
                            exceptionHandler.TryEnd       = methodDef2.Body.Instructions[14];
                            exceptionHandler.TryStart     = methodDef2.Body.Instructions[12];
                            if (!methodDef2.Body.HasExceptionHandlers)
                            {
                                methodDef2.Body.ExceptionHandlers.Add(exceptionHandler);
                            }
                            operand = new Instruction(OpCodes.Br, instruction);
                            methodDef2.Body.OptimizeBranches();
                            methodDef2.Body.OptimizeMacros();
                        }
                    }
                }
            }
            TypeDef  typeDef3 = new TypeDefUser(controlflow.generate(-1));
            FieldDef item2    = new FieldDefUser(controlflow.generate(-1), new FieldSig(manifestModule.Import(typeof(Isolated_png)).ToTypeSig()));

            typeDef3.Fields.Add(item2);
            typeDef3.BaseType = manifestModule.Import(typeof(Isolated_png));
            manifestModule.Types.Add(typeDef3);
            TypeDef typeDef4 = new TypeDefUser("");

            typeDef4.IsInterface = true;
            typeDef4.IsSealed    = true;
            manifestModule.Types.Add(typeDef4);
            manifestModule.TablesHeaderVersion = new ushort?(257);
        }
示例#53
0
        /// <summary>
        /// 通过接口查询订单
        /// </summary>
        /// <param name="supplierId"></param>
        /// <param name="facevalue"></param>
        /// <param name="orderid"></param>
        public static void QueryOrder(int supplierId, int facevalue, string orderid)
        {
            if (supplierId > 0 && facevalue > 0 && !string.IsNullOrEmpty(orderid))
            {
                try
                {
                    //int supplierId = Convert.ToInt32(row["supplierID"]);
                    //int facevalue = Convert.ToInt32(row["facevalue"]);
                    //string orderid = row["orderid"].ToString();

                    switch (supplierId)
                    {
                    case 80:
                    {
                        #region
                        string callback = OfCard.Card.Default.Query(orderid);

                        if (!string.IsNullOrEmpty(callback))
                        {
                            OfCard.Card.Default.Finish(callback);
                        }
                        #endregion
                    }
                    break;

                    case 70:
                    {
                        #region
                        string callback = viviapi.ETAPI.Cared70.Card.Default.Query(orderid);

                        if (!string.IsNullOrEmpty(callback))
                        {
                            Cared70.Card.Default.Finish(orderid, callback);
                        }
                        #endregion
                    }
                    break;
                        //case 51:
                        //    {
                        //        #region
                        //        QueryResponse response = Card.Default.Query(orderid, facevalue);
                        //        if (response != null)
                        //        {
                        //            Card.Default.Finish(response);
                        //        }
                        //        #endregion
                        //    }
                        //    break;
                        //case 85:
                        //    {
                        #region HuiYuan
                        //        string callback = HuiYuan.Card.Default.Query(orderid);

                        //        if (!string.IsNullOrEmpty(callback))
                        //        {
                        //            HuiYuan.Card.Default.Finish(callback);
                        //        }
                        #endregion
                        //    }
                        //    break;
                        //case 851:
                        //    {
                        //        #region
                        //        string callback = HuiSu.Card.Default.Query(orderid);

                        //        if (!string.IsNullOrEmpty(callback))
                        //        {
                        //            HuiSu.Card.Default.Finish(callback);
                        //        }
                        //        #endregion
                        //    }
                        //    break;
                        //case 60866:
                        //    {
                        //        #region 60866
                        //        string callback = Card60866.Card.Default.Query(orderid);

                        //        if (!string.IsNullOrEmpty(callback))
                        //        {
                        //            Card60866.Card.Default.Finish(orderid, callback);
                        //        }
                        //        #endregion
                        //    }
                        //    break;
                    }
                }
                catch (Exception exception)
                {
                    ExceptionHandler.HandleException(exception);
                }
            }
        }
        public void TestThrowIndexOutOfRangeException()
        {
            ExceptionHandler eh = new ExceptionHandler("1", false);

            eh.IndexOutOfRangeExceptionMethod();
        }
示例#55
0
        public static EntityCollection RetrieveSolutionsFromCrm(CrmServiceClient client, bool getManaged)
        {
            try
            {
                QueryExpression query = new QueryExpression
                {
                    EntityName = "solution",
                    ColumnSet  = new ColumnSet("friendlyname", "solutionid", "uniquename", "version"),
                    Criteria   = new FilterExpression
                    {
                        Conditions =
                        {
                            new ConditionExpression
                            {
                                AttributeName = "isvisible",
                                Operator      = ConditionOperator.Equal,
                                Values        = { true }
                            }
                        }
                    },
                    LinkEntities =
                    {
                        new LinkEntity
                        {
                            LinkFromEntityName    = "solution",
                            LinkFromAttributeName = "publisherid",
                            LinkToEntityName      = "publisher",
                            LinkToAttributeName   = "publisherid",
                            Columns     = new ColumnSet("customizationprefix"),
                            EntityAlias = "publisher"
                        }
                    },
                    Distinct = true,
                    Orders   =
                    {
                        new OrderExpression
                        {
                            AttributeName = "friendlyname",
                            OrderType     = OrderType.Ascending
                        }
                    }
                };

                if (!getManaged)
                {
                    ConditionExpression noManaged = new ConditionExpression
                    {
                        AttributeName = "ismanaged",
                        Operator      = ConditionOperator.Equal,
                        Values        = { false }
                    };

                    query.Criteria.Conditions.Add(noManaged);
                }

                EntityCollection solutions = client.RetrieveMultiple(query);

                OutputLogger.WriteToOutputWindow(Resource.Message_RetrievedSolutions, MessageType.Info);

                return(solutions);
            }
            catch (Exception ex)
            {
                ExceptionHandler.LogException(Logger, Resource.ErrorMessage_ErrorRetrievingSolutions, ex);

                return(null);
            }
        }
示例#56
0
        public RestResponse Process(string clusterName, string strUrl, string reqdata, string encoding, Method method)
        {
            DateTime start = DateTime.Now;

            var    result      = new RestResponse();
            string responseStr = string.Empty;
            string url         = null;

            try
            {
                if (!strUrl.StartsWith("/"))
                {
                    strUrl = "/" + strUrl;
                }
                url = ESNodeManager.Instance.GetHttpNode(clusterName) + strUrl;
                WebRequest request = WebRequest.Create(url);
                request.Method = method.ToString();
                if (reqdata != null)
                {
                    byte[] buf = Encoding.GetEncoding(encoding).GetBytes(reqdata);
                    request.ContentType   = "application/json; charset=" + encoding;
                    request.ContentLength = buf.Length;

                    if (method != Method.GET || reqdata.Length > 0)
                    {
                        Stream s = request.GetRequestStream();
                        s.Write(buf, 0, buf.Length);
                        s.Close();
                    }
                }

                WebResponse response = request.GetResponse();
                var         reader   = new StreamReader(response.GetResponseStream(),
                                                        Encoding.GetEncoding(encoding));
                responseStr = reader.ReadToEnd();
                result.SetBody(responseStr);
                result.Status = Status.OK;
                reader.Close();
                reader.Dispose();
                response.Close();

                DateTime endtime = DateTime.Now;
                _logger.InfoFormat("Request Success,Method:{2},Url:{0},Body:{1},Time:{3}", url, reqdata, method, endtime - start);
            }
            catch (WebException e)
            {
                DateTime endtime = DateTime.Now;
                if (e.Response != null)
                {
                    var stream = e.Response.GetResponseStream();
                    if (stream != null)
                    {
                        var reader = new StreamReader(stream,
                                                      Encoding.GetEncoding(encoding));
                        responseStr = reader.ReadToEnd();
                        result.SetBody(responseStr);
                    }
                }
                var msg = string.Format("Method:{2}, Url: {0},Body:{1},Encoding:{3},Time:{5},Response:{4}", url,
                                        reqdata,
                                        method, encoding, responseStr, endtime - start);
                result.Status = Status.INTERNAL_SERVER_ERROR;
                ExceptionHandler.HandleExceptionResponse(responseStr, msg);
            }
            return(result);
        }
示例#57
0
 override protected void ParseExceptionHandlerEntry(bool smallSection){
   int dataSize = this.reader.tables.GetByte();
   int n = (int)(ushort)this.reader.tables.GetInt16();
   if (smallSection)
     n = dataSize / 12;
   else
     n = (dataSize + (n << 8)) / 24;
   if (n < 0) n = 0;
   this.method.ExceptionHandlers = new ExceptionHandlerList(n);
   for (int i = 0; i < n; i++){
     int flags, tryOffset, tryLength, handlerOffset, handlerLength, tokenOrOffset;
     if (smallSection){
       flags = this.reader.tables.GetInt16();
       tryOffset = this.reader.tables.GetUInt16();
       tryLength = this.reader.tables.GetByte();
       handlerOffset = this.reader.tables.GetUInt16();
       handlerLength = this.reader.tables.GetByte();
     }else{
       flags = this.reader.tables.GetInt32();
       tryOffset = this.reader.tables.GetInt32();
       tryLength = this.reader.tables.GetInt32();
       handlerOffset = this.reader.tables.GetInt32();
       handlerLength = this.reader.tables.GetInt32();
     }
     tokenOrOffset = this.reader.tables.GetInt32();
     ExceptionHandler eh = new ExceptionHandler();
     switch(flags){
       case 0x00: 
         eh.HandlerType = NodeType.Catch;
         int pos = this.reader.tables.GetCurrentPosition();
         eh.FilterType = (TypeNode)this.reader.GetMemberFromToken(tokenOrOffset);
         this.reader.tables.SetCurrentPosition(pos);
         break;
       case 0x01: 
         eh.HandlerType = NodeType.Filter; 
         eh.FilterExpression = Reader.GetOrCreateBlock(blockMap, tokenOrOffset);
         break;
       case 0x02: eh.HandlerType = NodeType.Finally; break;
       case 0x04: eh.HandlerType = NodeType.FaultHandler; break;
       default: throw new InvalidMetadataException(ExceptionStrings.BadExceptionHandlerType);
     }
     eh.TryStartBlock = Reader.GetOrCreateBlock(this.blockMap, tryOffset);
     eh.BlockAfterTryEnd = Reader.GetOrCreateBlock(this.blockMap, tryOffset+tryLength);
     eh.HandlerStartBlock = Reader.GetOrCreateBlock(this.blockMap, handlerOffset);
     eh.BlockAfterHandlerEnd = Reader.GetOrCreateBlock(this.blockMap, handlerOffset+handlerLength);
     this.method.ExceptionHandlers.Add(eh);
   }
 }
示例#58
0
 public virtual DialogResult ShowDialog(MethodDefinition mdef, ExceptionHandler selected)
 {
     MethodDefinition         = mdef;
     SelectedExceptionHandler = selected;
     return(ShowDialog());
 }
 internal async Task InvokeBeforeTunnectConnectResponse(ProxyServer proxyServer,
                                                        TunnelConnectSessionEventArgs connectArgs, ExceptionHandler exceptionFunc, bool isClientHello = false)
 {
     if (BeforeTunnelConnectResponse != null)
     {
         connectArgs.IsHttpsConnect = isClientHello;
         await BeforeTunnelConnectResponse.InvokeAsync(proxyServer, connectArgs, exceptionFunc);
     }
 }
        public bool Insert(SuburbEntity entity)
        {
            try
            {
                var sb = new StringBuilder();
                sb.Append("INSERT [dbo].[Suburb] ");
                sb.Append("( ");
                sb.Append("[SuburbName],");
                sb.Append("[StateId]");
                sb.Append(") ");
                sb.Append("VALUES ");
                sb.Append("( ");
                sb.Append(" @SuburbName,");
                sb.Append(" @StateId");
                sb.Append(") ");
                sb.Append("SELECT @intErrorCode=@@ERROR; ");


                var commandText = sb.ToString();
                sb.Clear();

                using (var dbConnection = _dbProviderFactory.CreateConnection())
                {
                    if (dbConnection == null)
                    {
                        throw new ArgumentNullException("dbConnection", "The db connection can't be null.");
                    }

                    dbConnection.ConnectionString = _connectionString;

                    using (var dbCommand = _dbProviderFactory.CreateCommand())
                    {
                        if (dbCommand == null)
                        {
                            throw new ArgumentNullException("dbCommand" + " The db Insert command for entity [Suburb] can't be null. ");
                        }

                        dbCommand.Connection  = dbConnection;
                        dbCommand.CommandText = commandText;

                        //Input Parameters
                        _dataHandler.AddParameterToCommand(dbCommand, "@SuburbName", CsType.String, ParameterDirection.Input, entity.SuburbName);
                        _dataHandler.AddParameterToCommand(dbCommand, "@StateId", CsType.String, ParameterDirection.Input, entity.StateId);

                        //Output Parameters
                        _dataHandler.AddParameterToCommand(dbCommand, "@intErrorCode", CsType.Int, ParameterDirection.Output, null);

                        //Open Connection
                        if (dbConnection.State != ConnectionState.Open)
                        {
                            dbConnection.Open();
                        }

                        //Execute query.
                        _rowsAffected = dbCommand.ExecuteNonQuery();
                        _errorCode    = int.Parse(dbCommand.Parameters["@intErrorCode"].Value.ToString());

                        if (_errorCode != 0)
                        {
                            // Throw error.
                            throw new Exception("The Insert method for entity [Suburb] reported the Database ErrorCode: " + _errorCode);
                        }
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                //Log exception error
                _loggingHandler.LogEntry(ExceptionHandler.GetExceptionMessageFormatted(ex), true);

                //Bubble error to caller and encapsulate Exception object
                throw new Exception("SuburbRepository::Insert::Error occured.", ex);
            }
        }