Expression IContractDeserializer.ParseContract (MethodContract mc, string text, ErrorNodeList errs) { Expression expression = null; currentMethodContract = mc; currentMethod = null; currentType = null; if (mc != null){ currentMethod = mc.DeclaringMethod; currentType = currentMethod.DeclaringType; } try{ Parser.ParseContract(this.assembly, text, out expression); }catch (Exception e){ ErrorNodeList eList = errs != null ? errs : this.ErrorList; if (eList != null){ #if OLDERRORS ErrorHandler eh = new ErrorHandler(eList); eh.HandleError(mc,System.Compiler.Error.GenericError,"Deserializer error: " + e.Message); #else this.assembly.MetadataImportErrors.Add(e); #endif } throw e; } return expression; }
public static Thread StartTry(MethodInvoker code, ErrorHandler on_error = null, MethodInvoker on_finally = null, bool background = true) { Thread t = new Thread( () => { try { code.Invoke(); } catch (ThreadAbortException e) { Thread.ResetAbort(); } catch (Exception e) { if (on_error != null) on_error.Invoke(e); else Message.Error(e); } finally { on_finally?.Invoke(); } } ); t.IsBackground = background; t.Start(); return t; }
/// <summary> /// Constructor for client support /// </summary> /// <param name="sizeOfRawBuffer"> The size of the raw buffer </param> /// <param name="userArg"> A Reference to the Users arguments </param> /// <param name="messageHandler"> Reference to the user defined message handler method </param> /// <param name="closeHandler"> Reference to the user defined close handler method </param> /// <param name="errorHandler"> Reference to the user defined error handler method </param> public SocketClient(int sizeOfRawBuffer, object userArg, MessageHandler messageHandler, CloseHandler closeHandler, ErrorHandler errorHandler, ConnectHandler connectHandler) { // Create the raw buffer this.SizeOfRawBuffer = sizeOfRawBuffer; this.RawBuffer = new Byte[this.SizeOfRawBuffer]; // Save the user argument this.userArg = userArg; // Set the handler methods this.messageHandler = messageHandler; this.closeHandler = closeHandler; this.errorHandler = errorHandler; this.connectHandler = connectHandler; // Set the async socket method handlers this.callbackReadMethod = new AsyncCallback(ReceiveComplete); this.callbackWriteMethod = new AsyncCallback(SendComplete); this.callbackWriteHeadMethod = new AsyncCallback(SendHead); this.m_Connected = true; // Init the dispose flag this.disposed = false; }
/// <summary> /// Loads data. /// </summary> /// <param name="success">Callback triggers on successful data load.</param> /// <param name="error">Callback triggers on error.</param> public static Coroutine LoadData(SuccessHandler success, ErrorHandler error) { drWWW www = new drWWW(drAPI.loadData); www.OnSuccess += delegate { Hashtable result = www.result as Hashtable; if (result["data"] == null) { drDebug.LogWarning("No data exists in the data store to load"); return; } if (data == null) { data = new Dictionary<string, object>(); } StoreReturnData(result["data"] as Hashtable); drDebug.Log("Loaded data"); }; www.OnSuccess += success; www.OnError += delegate (string errorMessage) { drDebug.LogError("Error loading data: " + errorMessage); }; www.OnError += error; return www.Fetch(); }
public override void DoSemanticChecks(ErrorHandler errs, Scope currentScope) { foreach (AstNode astNode in _content) { astNode.DoSemanticChecks(errs, currentScope); } }
public override Microsoft.VisualStudio.Package.AuthoringScope ParseSource(ParseRequest req) { Babel.Source source = (Babel.Source)this.GetSource(req.FileName); bool yyparseResult = false; // req.DirtySpan seems to be set even though no changes have occurred // source.IsDirty also behaves strangely // might be possible to use source.ChangeCount to sync instead if (req.DirtySpan.iStartIndex != req.DirtySpan.iEndIndex || req.DirtySpan.iStartLine != req.DirtySpan.iEndLine) { ErrorHandler handler = new ErrorHandler(); Scanner scanner = new Scanner(); // string interface Parser parser = new Parser(); // use noarg constructor parser.scanner = scanner; scanner.Handler = handler; parser.SetHandler(handler); scanner.SetSource(req.Text, 0); parser.MBWInit(req); yyparseResult = parser.Parse(); // store the parse results // source.ParseResult = aast; source.ParseResult = null; source.Braces = parser.Braces; // for the time being, just pull errors back from the error handler if (handler.ErrNum > 0) { foreach (Babel.Parser.Error error in handler.SortedErrorList()) { TextSpan span = new TextSpan(); span.iStartLine = span.iEndLine = error.line - 1; span.iStartIndex = error.column; span.iEndIndex = error.column + error.length; req.Sink.AddError(req.FileName, error.message, span, Severity.Error); } } } switch (req.Reason) { case ParseReason.Check: case ParseReason.HighlightBraces: case ParseReason.MatchBraces: case ParseReason.MemberSelectAndHighlightBraces: // send matches to sink // this should (probably?) be filtered on req.Line / col if (source.Braces != null) { foreach (TextSpan[] brace in source.Braces) { if (brace.Length == 2) req.Sink.MatchPair(brace[0], brace[1], 1); else if (brace.Length >= 3) req.Sink.MatchTriple(brace[0], brace[1], brace[2], 1); } } break; default: break; } return new AuthoringScope(req.Text); }
public static void rankingTops(String token, String list_id, int count, int start_row, String time_type, String relation_type, YebobHandler handler, ErrorHandler onError) { String url = String.Format("{0}/ranking/tops?list_id={1}&count={2}&start_row={3}&time_type={4}&relation_type={5}", URL_PREFIX, list_id, count, start_row, time_type, relation_type); getWithToken(token, url, handler, onError); }
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase) { IErrorHandler handler = new ErrorHandler(); foreach (ChannelDispatcher chDisp in serviceHostBase.ChannelDispatchers) { if (chDisp.BindingName.Contains("WebHttpBinding")) { chDisp.ErrorHandlers.Add(handler); foreach (EndpointDispatcher epDisp in chDisp.Endpoints) { epDisp.DispatchRuntime.MessageInspectors.Add(new Authenticator()); } } } foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints) { if (endpoint.Binding.GetType() == typeof(WebHttpBinding)) { foreach (OperationDescription operation in endpoint.Contract.Operations) { operation.Behaviors.Add(new CustomMessageFormatter.Behavior()); } } } }
new void Awake() { base.Awake(); if(smartFox.IsConnected) { CharacterList = new CharacterListHandler(); CharacterSelected = new CharacterSelectedHandler(); errorHandler = new ErrorHandler(); // Register callback delegate smartFox.AddEventListener(SFSEvent.CONNECTION_LOST, OnConnectionLost); smartFox.AddEventListener(SFSEvent.LOGOUT, OnLogout); smartFox.AddLogListener(LogLevel.DEBUG, OnDebugMessage); // Personal message handlers handlers.Add("characterlist", CharacterList); handlers.Add("characterSelected", CharacterSelected); handlers.Add("error", errorHandler); CharacterList.afterMessageRecieved += AfterCharacterList; CharacterSelected.afterMessageRecieved += AfterCharacterSelected; // We are ready to get the character list new GetCharactersMessage(smartFox, false).Send(); } else { Application.LoadLevel("Lobby"); } }
public Parser(Scanner scanner, ErrorHandler errors) { _scanner = scanner; _scanner.GetToken(); _errors = errors; }
public XmlParserInput (TextReader reader, XmlNameTable nameTable, ErrorHandler error) : this(reader, nameTable, null, error) { }
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { var eh=new ErrorHandler(); foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers) ((ChannelDispatcher)cdb).ErrorHandlers.Insert(0, eh); }
public PublishFolderPicker(string destinationName, ErrorHandler errorCallback, string rootPath) { // This call is required by the Windows Form Designer. InitializeComponent(); destinationTree.RightToLeftLayout = true; this.buttonOK.Text = Res.Get(StringId.OKButtonText); this.buttonCancel.Text = Res.Get(StringId.CancelButton); this.label1.Text = Res.Get(StringId.PublishFolderPickerCaption); this.buttonNewFolder.ButtonText = Res.Get(StringId.NewFolder); this.buttonNewFolder.AccessibleName = Res.Get(StringId.NewFolder); this.buttonNewFolder.ToolTip = Res.Get(StringId.NewFolderTooltip); this.Text = Res.Get(StringId.PublishFolderPickerTitle); //set the error handler. errorHandler = errorCallback; //Root Node RootNode = new TreeNode(); // configure tree RootNode.Text = destinationName; RootNode.Tag = rootPath; destinationTree.Nodes.Add(RootNode); destinationTree.SelectedNode = RootNode; destinationTree.SelectedNode.ImageIndex = 0; }
/// <summary> /// Awards an achievement. /// </summary> /// <param name="achievementName">The name of the achievement to award.</param> /// <param name="success">Callback triggers on successful award.</param> /// <param name="error">Callback triggers on error.</param> public static Coroutine AwardAchievement(string achievementName, SuccessHandler success, ErrorHandler error) { drWWW www = new drWWW(drAPI.awardAchievement); www.AddField("name", achievementName); www.OnSuccess += delegate { if (!(bool)www.result) { // This should never occur, but the check is here just in case drDebug.LogWarning("Did not award achievement \"" + achievementName + "\""); return; } if (!_awardedAchievements.Contains(achievementName)) { _awardedAchievements.Add(achievementName); } drClient.RefreshCanvasComponent(drClient.CanvasComponent.Achievements); drDebug.Log("Awarded achievement " + achievementName); }; www.OnSuccess += success; www.OnError += delegate (string errorMessage) { drDebug.LogError("Error awarding achievement \"" + achievementName + "\": " + errorMessage); }; www.OnError += error; return www.Fetch(); }
public virtual void SetUp() { RcvBuffer = new UnsafeBuffer(new byte[ALIGNED_FRAME_LENGTH]); DataHeader = new DataHeaderFlyweight(); MockFragmentHandler = A.Fake<FragmentHandler>(); MockControlledFragmentHandler = A.Fake<IControlledFragmentHandler>(); Position = A.Fake<IPosition>(options => options.Wrapping(new AtomicLongPosition())); LogBuffers = A.Fake<LogBuffers>(); ErrorHandler = A.Fake<ErrorHandler>(); Subscription = A.Fake<Subscription>(); AtomicBuffers = new UnsafeBuffer[(LogBufferDescriptor.PARTITION_COUNT * 2) + 1]; TermBuffers = new UnsafeBuffer[LogBufferDescriptor.PARTITION_COUNT]; DataHeader.Wrap(RcvBuffer); for (var i = 0; i < LogBufferDescriptor.PARTITION_COUNT; i++) { AtomicBuffers[i] = new UnsafeBuffer(new byte[TERM_BUFFER_LENGTH]); TermBuffers[i] = AtomicBuffers[i]; AtomicBuffers[i + LogBufferDescriptor.PARTITION_COUNT] = new UnsafeBuffer(new byte[LogBufferDescriptor.TERM_META_DATA_LENGTH]); } AtomicBuffers[LogBufferDescriptor.LOG_META_DATA_SECTION_INDEX] = new UnsafeBuffer(new byte[LogBufferDescriptor.LOG_META_DATA_LENGTH]); A.CallTo(() => LogBuffers.AtomicBuffers()).Returns(AtomicBuffers); A.CallTo(() => LogBuffers.TermLength()).Returns(TERM_BUFFER_LENGTH); }
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase) { ErrorHandler handler = new ErrorHandler(); foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers) { dispatcher.ErrorHandlers.Add(handler); } }
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { IErrorHandler errorHandler = new ErrorHandler(); foreach (ChannelDispatcher channelDispatcher in serviceHostBase.ChannelDispatchers) { channelDispatcher.ErrorHandlers.Add(errorHandler); } }
public MessageProcessor(MessageQueue queue, MessageEventHandler messageHandler, ErrorHandler errorHandler) { this.messageQueue = queue; this.messageHandler = messageHandler; this.errorHandler = errorHandler; }
/** * Creates a network access point. * @param apDescriptor the address and port where to bind. * @param messageQueue the FIFO list where incoming messages should be queued * @param errorHandler the instance to notify when errors occur. */ public NetAccessPoint(NetAccessPointDescriptor apDescriptor, MessageQueue messageQueue, ErrorHandler errorHandler) { this.apDescriptor = apDescriptor; this.messageQueue = messageQueue; this.errorHandler = errorHandler; }
protected Verifier( XmlReader document, ExpBuilder builder, ErrorHandler handler ) { this.document = document; this.handler = handler; this.builder = builder; this.attPruner = new AttPruner(builder); emptyStringToken = new StringToken("",builder,this); }
public override void BeginCheck(string descriptiveName, VCExpr vc, ErrorHandler handler) { LineariserOptions linOptions = new Z3LineariserOptions(false, (Z3InstanceOptions)this.options, new List<VCExprVar>()); Push(); context.AddAxiom(context.Axioms, linOptions); context.AddConjecture(vc, linOptions); outcome = context.Check(out z3LabelModels); Pop(); }
internal Checker(ErrorHandler errorHandler, TypeSystem typeSystem, TrivialHashtable scopeFor, // LJW: added scopeFor TrivialHashtable ambiguousTypes, TrivialHashtable referencedLabels) : base(errorHandler, typeSystem, scopeFor, ambiguousTypes, referencedLabels) { this.validChooses = new Hashtable(); this.validMethodCalls = new Hashtable(); this.validSetOperations = new Hashtable(); this.validSelfAccess = new Hashtable(); }
// Constructor. public Attributes(ErrorHandler error) : base(error) { count = 0; nt = null; nm = null; attributes = new ArrayList(8); names = new Hashtable(new Key(null), new Key(null)); }
protected virtual SocketClient AcceptedSocketClient( SocketServer socketServer, Socket clientSocket, string ipAddress, int port, int sizeOfRawBuffer, object userArg, MessageHandler messageHandler, CloseHandler closeHandler, ErrorHandler errorHandler, ConnectHandler connectHandler) { return new SocketClient( socketServer, clientSocket, ipAddress, port, sizeOfRawBuffer, userArg, messageHandler, closeHandler, errorHandler, connectHandler); }
public void SetUp() { header = new Header(INITIAL_TERM_ID, TERM_BUFFER_CAPACITY); termBuffer = A.Fake<IAtomicBuffer>(); errorHandler = A.Fake<ErrorHandler>(); handler = A.Fake<FragmentHandler>(); A.CallTo(() => termBuffer.Capacity).Returns(TERM_BUFFER_CAPACITY); }
public SocketIO(Socket client, int bufferSize, MessageHandler mh, CloseHandler ch, ErrorHandler eh, string ip, int port) : this(bufferSize, mh, ch, eh) { this.ip = ip; this.port = port; clientSocket = client; ns = tcpClient.GetStream(); Receive(); }
// Constructor. public NodeManager(XmlNameTable nt, ErrorHandler eh) { current = (int)Type.None; attributes = null; error = eh; nodes = new NodeInfo[11]; nodes[current] = new DefaultNodeInfo(); xml = nt.Add("xml"); }
public void HandleErrorShouldCallBasicPublishWithSuppliedArguments() { SetupRabbitMqFactoryDefault(); SetupErrorConfig(true, "errorqueue"); var errorHandler = new ErrorHandler(QueueEndpointProvider, RabbitMqFactory, ChannelConfigurator, RabbitMqLogger.NullLogger); errorHandler.HandleError(_message, "testendpoint"); Model.AssertWasCalled(x => x.BasicPublish(string.Empty, QueueEndpoint.Subscription.ErrorHandling.ErrorQueueName, Properties, MessageData)); }
/// <summary> /// Provides the ability to change run-time property values or insert custom extension objects such as error handlers, /// message or parameter interceptors, security extensions, and other custom extension objects. /// </summary> /// <param name="serviceDescription"> /// The service description. /// </param> /// <param name="serviceHostBase"> /// The host that is currently being built. /// </param> public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { IErrorHandler errorHandler = new ErrorHandler(serviceDescription.ServiceType); foreach (var channelDispatcher in serviceHostBase.ChannelDispatchers.OfType<ChannelDispatcher>()) { channelDispatcher.ErrorHandlers.Add(errorHandler); } }
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { IErrorHandler errHandler = new ErrorHandler(); foreach (ChannelDispatcherBase dispatcherBase in serviceHostBase.ChannelDispatchers) { ChannelDispatcher dispatcher = dispatcherBase as ChannelDispatcher; if (dispatcher == null) continue; dispatcher.ErrorHandlers.Add(errHandler); } }
/// <summary> /// Returns the buffer contents for a moniker. /// </summary> /// <returns>Buffer contents</returns> private string GetBufferContents(string fileName, out IVsTextStream srpStream) { Guid CLSID_VsTextBuffer = new Guid("{8E7B96A8-E33D-11d0-A6D5-00C04FB67F6A}"); string bufferContents = ""; srpStream = null; ThreadHelper.ThrowIfNotOnUIThread(); IVsRunningDocumentTable rdt = this.DocumentTable; if (rdt != null) { IVsHierarchy hier; IVsPersistDocData persistDocData; uint itemid, cookie; bool docInRdt = true; IntPtr docData = IntPtr.Zero; int hr = NativeMethods.E_FAIL; try { //Getting a read lock on the document. Must be released later. hr = rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, fileName, out hier, out itemid, out docData, out cookie); if (ErrorHandler.Failed(hr) || docData == IntPtr.Zero) { Guid iid = VSConstants.IID_IUnknown; cookie = 0; docInRdt = false; ILocalRegistry localReg = ThreadHelper.JoinableTaskFactory.Run(async delegate { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); return((ILocalRegistry)this.ProjectMgr.GetService(typeof(SLocalRegistry))); }); ErrorHandler.ThrowOnFailure(localReg.CreateInstance(CLSID_VsTextBuffer, null, ref iid, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out docData)); } persistDocData = Marshal.GetObjectForIUnknown(docData) as IVsPersistDocData; } finally { if (docData != IntPtr.Zero) { Marshal.Release(docData); } } //Try to get the Text lines IVsTextLines srpTextLines = persistDocData as IVsTextLines; if (srpTextLines == null) { // Try getting a text buffer provider first IVsTextBufferProvider srpTextBufferProvider = persistDocData as IVsTextBufferProvider; if (srpTextBufferProvider != null) { hr = srpTextBufferProvider.GetTextBuffer(out srpTextLines); } } if (ErrorHandler.Succeeded(hr)) { srpStream = srpTextLines as IVsTextStream; if (srpStream != null) { // QI for IVsBatchUpdate and call FlushPendingUpdates if they support it IVsBatchUpdate srpBatchUpdate = srpStream as IVsBatchUpdate; if (srpBatchUpdate != null) { //ErrorHandler.ThrowOnFailure(srpBatchUpdate.FlushPendingUpdates(0)); // we don't want to throw here, this can return E_UNSPECIFIED_ERROR srpBatchUpdate.FlushPendingUpdates(0); } int lBufferSize = 0; hr = srpStream.GetSize(out lBufferSize); if (ErrorHandler.Succeeded(hr)) { IntPtr dest = IntPtr.Zero; try { // Note that GetStream returns Unicode to us so we don't need to do any conversions dest = Marshal.AllocCoTaskMem((lBufferSize + 1) * 2); ErrorHandler.ThrowOnFailure(srpStream.GetStream(0, lBufferSize, dest)); //Get the contents bufferContents = Marshal.PtrToStringUni(dest); } finally { if (dest != IntPtr.Zero) { Marshal.FreeCoTaskMem(dest); } } } } } // Unlock the document in the RDT if necessary if (docInRdt && rdt != null) { ErrorHandler.ThrowOnFailure(rdt.UnlockDocument((uint)(_VSRDTFLAGS.RDT_ReadLock | _VSRDTFLAGS.RDT_Unlock_NoSave), cookie)); } if (ErrorHandler.Failed(hr)) { // If this failed then it's probably not a text file. In that case, // we just read the file as a binary bufferContents = File.ReadAllText(fileName); } } return(bufferContents); }
/// <summary> /// Saves or Save As the file /// </summary> /// <param name="isCalledFromSaveAs">Flag determining which Save method called , the SaveAs or the Save.</param> /// <param name="fileName">The name of the project file.</param> protected virtual void DoSave(bool isCalledFromSaveAs, string fileName) { UIThread.DoOnUIThread(delegate() { if (fileName == null) { throw new ArgumentNullException("fileName"); } if (this.Node == null || this.Node.ProjectManager == null || this.Node.ProjectManager.IsClosed || this.Node.ProjectManager.Site == null) { throw new InvalidOperationException(); } using (AutomationScope scope = new AutomationScope(this.Node.ProjectManager.Site)) { IntPtr docData = IntPtr.Zero; try { IVsRunningDocumentTable rdt = this.Node.ProjectManager.Site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; Debug.Assert(rdt != null, " Could not get running document table from the services exposed by this project"); if (rdt == null) { throw new InvalidOperationException(); } // First we see if someone else has opened the requested view of the file. uint itemid; IVsHierarchy ivsHierarchy; uint docCookie; int canceled; string url = this.Node.Url; ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, url, out ivsHierarchy, out itemid, out docData, out docCookie)); // If an empty file name is passed in for Save then make the file name the project name. if (!isCalledFromSaveAs && fileName.Length == 0) { ErrorHandler.ThrowOnFailure(this.Node.ProjectManager.SaveItem(VSSAVEFLAGS.VSSAVE_SilentSave, url, this.Node.Id, docData, out canceled)); } else { Utilities.ValidateFileName(this.Node.ProjectManager.Site, fileName); // Compute the fullpath from the directory of the existing Url. string fullPath = fileName; if (!Path.IsPathRooted(fileName)) { string directory = Path.GetDirectoryName(url); fullPath = Path.Combine(directory, fileName); } if (!isCalledFromSaveAs) { if (!NativeMethods.IsSamePath(this.Node.Url, fullPath)) { throw new InvalidOperationException(); } ErrorHandler.ThrowOnFailure(this.Node.ProjectManager.SaveItem(VSSAVEFLAGS.VSSAVE_SilentSave, fullPath, this.Node.Id, docData, out canceled)); } else { ErrorHandler.ThrowOnFailure(this.Node.ProjectManager.SaveItem(VSSAVEFLAGS.VSSAVE_SilentSave, fullPath, this.Node.Id, docData, out canceled)); } } if (canceled == 1) { throw new InvalidOperationException(); } } catch (COMException e) { throw new InvalidOperationException(e.Message); } finally { if (docData != IntPtr.Zero) { Marshal.Release(docData); } } } }); }
/// <summary> /// Saves or Save Asthe project. /// </summary> /// <param name="isCalledFromSaveAs">Flag determining which Save method called , the SaveAs or the Save.</param> /// <param name="fileName">The name of the project file.</param> private void DoSave(bool isCalledFromSaveAs, string fileName) { Utilities.ArgumentNotNull("fileName", fileName); CheckProjectIsValid(); using (AutomationScope scope = new AutomationScope(this.project.Site)) { // If an empty file name is passed in for Save then make the file name the project name. if (!isCalledFromSaveAs && string.IsNullOrEmpty(fileName)) { // Use the solution service to save the project file. Note that we have to use the service // so that all the shell's elements are aware that we are inside a save operation and // all the file change listenters registered by the shell are suspended. // Get the cookie of the project file from the RTD. IVsRunningDocumentTable rdt = this.project.Site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; Utilities.CheckNotNull(rdt); IVsHierarchy hier; uint itemid; IntPtr unkData; uint cookie; ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, this.project.Url, out hier, out itemid, out unkData, out cookie)); if (IntPtr.Zero != unkData) { Marshal.Release(unkData); } // Verify that we have a cookie. if (0 == cookie) { // This should never happen because if the project is open, then it must be in the RDT. throw new InvalidOperationException(); } // Get the IVsHierarchy for the project. IVsHierarchy prjHierarchy = project.GetOuterInterface <IVsHierarchy>(); // Now get the soulution. IVsSolution solution = this.project.Site.GetService(typeof(SVsSolution)) as IVsSolution; // Verify that we have both solution and hierarchy. Utilities.CheckNotNull(prjHierarchy); Utilities.CheckNotNull(solution); ErrorHandler.ThrowOnFailure(solution.SaveSolutionElement((uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_SaveIfDirty, prjHierarchy, cookie)); } else { // We need to make some checks before we can call the save method on the project node. // This is mainly because it is now us and not the caller like in case of SaveAs or Save that should validate the file name. // The IPersistFileFormat.Save method only does a validation that is necessary to be performed. Example: in case of Save As the // file name itself is not validated only the whole path. (thus a file name like file\file is accepted, since as a path is valid) // 1. The file name has to be valid. string fullPath = fileName; try { fullPath = CommonUtils.GetAbsoluteFilePath(((ProjectNode)Project).ProjectFolder, fileName); } // We want to be consistent in the error message and exception we throw. fileName could be for example #¤&%"¤&"% and that would trigger an ArgumentException on Path.IsRooted. catch (ArgumentException ex) { throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, fileName), ex); } // It might be redundant but we validate the file and the full path of the file being valid. The SaveAs would also validate the path. // If we decide that this is performance critical then this should be refactored. Utilities.ValidateFileName(this.project.Site, fullPath); if (!isCalledFromSaveAs) { // 2. The file name has to be the same if (!CommonUtils.IsSamePath(fullPath, this.project.Url)) { throw new InvalidOperationException(); } ErrorHandler.ThrowOnFailure(this.project.Save(fullPath, 1, 0)); } else { ErrorHandler.ThrowOnFailure(this.project.Save(fullPath, 0, 0)); } } } }
/// <summary> /// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> method. /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// Writes the event to a remote syslog daemon. /// </para> /// <para> /// The format of the output will depend on the appender's layout. /// </para> /// </remarks> protected override void Append(LoggingEvent loggingEvent) { try { // Priority int priority = GeneratePriority(m_facility, GetSeverity(loggingEvent.Level)); // Identity string identity; if (m_identity != null) { identity = m_identity.Format(loggingEvent); } else { identity = loggingEvent.Domain; } // Message. The message goes after the tag/identity string message = RenderLoggingEvent(loggingEvent); Byte[] buffer; int i = 0; char c; StringBuilder builder = new StringBuilder(); while (i < message.Length) { // Clear StringBuilder builder.Length = 0; // Write priority builder.Append('<'); builder.Append(priority); builder.Append('>'); // Write identity builder.Append(identity); builder.Append(": "); for (; i < message.Length; i++) { c = message[i]; // Accept only visible ASCII characters and space. See RFC 3164 section 4.1.3 if (((int)c >= 32) && ((int)c <= 126)) { builder.Append(c); } // If character is newline, break and send the current line else if ((c == '\r') || (c == '\n')) { // Check the next character to handle \r\n or \n\r if ((message.Length > i + 1) && ((message[i + 1] == '\r') || (message[i + 1] == '\n'))) { i++; } i++; break; } } // Grab as a byte array buffer = this.Encoding.GetBytes(builder.ToString()); this.Client.Send(buffer, buffer.Length, this.RemoteEndPoint); } } catch (Exception e) { ErrorHandler.Error( "Unable to send logging event to remote syslog " + this.RemoteAddress.ToString() + " on port " + this.RemotePort + ".", e, ErrorCode.WriteFailure); } }
public void Start() { Debug.WriteLine("START"); if (IsRunning) { return; } IsRunning = true; try { if (_failedLoad || string.IsNullOrEmpty(VlcHelper.VLCLocation)) { throw new ApplicationException("VLC not found. Set location in settings."); } _quit = false; _commands.Clear(); Task.Run(async() => { while (!_quit) { string cmd; if (_commands.TryDequeue(out cmd)) { switch (cmd) { case "init": try { Init(); } catch (ApplicationException ex) { Logger.LogException(ex, "VLC"); _res = ReasonToFinishPlaying.VideoSourceError; _quit = true; } break; case "stop": if (_mediaPlayer != null && _mediaPlayer.IsPlaying) { _mediaPlayer.Stop(); } else { _quit = true; } break; } } await Task.Delay(500); } Cleanup(); }); _commands.Enqueue("init"); _lastFrame = DateTime.UtcNow; _connecting = true; } catch (Exception ex) { Logger.LogException(ex, "VLCStream"); ErrorHandler?.Invoke("Invalid Source (" + Source + ")"); _connecting = false; IsRunning = false; _quit = false; _res = ReasonToFinishPlaying.VideoSourceError; PlayingFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); AudioFinished?.Invoke(this, new PlayingFinishedEventArgs(_res)); } }
/// <summary> /// Returns this after checking if we need to read the Api xml file for this language /// </summary> public LangDescription ReadApiFileIfNeeded() { var apiFilePath = Path.Combine(Npp.FolderNppAutocompApis, LangName + ".xml"); if (_keywords != null && !Utils.HasFileChanged(apiFilePath) && (!IsUserLang || !Utils.HasFileChanged(Npp.ConfXml.FileNppUserDefinedLang))) { return(this); } _autoCompletionItems = null; _keywords = new List <NppKeyword>(); var uniqueKeywords = new HashSet <string>(StringComparer.CurrentCultureIgnoreCase); // get keywords from plugins/Apis/ or autoCompletion/ // FORMAT : // <AutoComplete language="C++"> // <Environment ignoreCase="no" startFunc="(" stopFunc=")" paramSeparator="," terminal=";" additionalWordChar = "."/> // <KeyWord name="abs" func="yes"> // <Overload retVal="int" descr="Returns absolute value of given integer"> // <Param name="int number" /> // </Overload> // </KeyWord> // </AutoComplete> try { if (File.Exists(apiFilePath)) { var xml = new NanoXmlDocument(Utils.ReadAllText(apiFilePath)); foreach (var keywordElmt in xml.RootNode["AutoComplete"].SubNodes.Where(node => node.Name.Equals("KeyWord"))) { var attr = keywordElmt.GetAttribute("name"); if (attr == null) { continue; } var keyword = attr.Value; if (!uniqueKeywords.Contains(keyword)) { uniqueKeywords.Add(keyword); List <NppKeyword.NppOverload> overloads = null; foreach (var overload in keywordElmt.SubNodes.Where(node => node.Name.Equals("Overload"))) { if (overloads == null) { overloads = new List <NppKeyword.NppOverload>(); } var xAttribute = overload.GetAttribute("retVal"); var retVal = xAttribute != null ? xAttribute.Value : string.Empty; xAttribute = overload.GetAttribute("descr"); var descr = xAttribute != null ? xAttribute.Value : string.Empty; var parameters = new List <string>(); foreach (var para in overload.SubNodes.Where(node => node.Name.Equals("Param"))) { var attrname = para.GetAttribute("name"); if (attrname == null) { continue; } parameters.Add(attrname.Value); } // improve description formatting descr = descr.Replace("\n", "<br>"); overloads.Add(new NppKeyword.NppOverload { ReturnValue = retVal, Description = descr, Params = parameters }); } _keywords.Add(new NppKeywordApis(keyword, this) { Overloads = overloads, Origin = NppKeywordOrigin.Api }); } } // get other info on the language var envElement = xml.RootNode["AutoComplete"]["Environment"]; if (envElement != null) { LoadFromAttributes(this, envElement); if (!string.IsNullOrEmpty(additionalWordChar)) { AdditionalWordChar = additionalWordChar.ToArray(); } } } } catch (Exception e) { ErrorHandler.LogError(e, "Error parsing " + apiFilePath); } // get core keywords from langs.xml or userDefinedLang.xml if (IsUserLang) { try { var langElement = new NanoXmlDocument(Utils.ReadAllText(UserLangFilePath)).RootNode.SubNodes.FirstOrDefault(x => x.GetAttribute("name").Value.EqualsCi(LangName)); if (langElement != null) { // get the list of keywords from userDefinedLang.xml foreach (var descendant in langElement["KeywordLists"].SubNodes) { var xAttribute = descendant.GetAttribute(@"name"); if (xAttribute != null && xAttribute.Value.StartsWith("keywords", StringComparison.CurrentCultureIgnoreCase)) { foreach (var keyword in (WebUtility.HtmlDecode(descendant.Value) ?? "").Replace('\r', ' ').Replace('\n', ' ').Split(' ')) { if (!string.IsNullOrEmpty(keyword) && !uniqueKeywords.Contains(keyword)) { uniqueKeywords.Add(keyword); _keywords.Add(new NppKeywordUserLangs(keyword, this) { Origin = NppKeywordOrigin.UserLangs }); } } } } } } catch (Exception e) { ErrorHandler.LogError(e, "Error parsing " + Npp.ConfXml.FileNppUserDefinedLang); } } else { try { var langElement = new NanoXmlDocument(Utils.ReadAllText(Npp.ConfXml.FileNppLangsXml)).RootNode["Languages"].SubNodes.FirstOrDefault(x => x.GetAttribute("name").Value.EqualsCi(LangName)); if (langElement != null) { // get the list of keywords from langs.xml foreach (var descendant in langElement.SubNodes) { foreach (var keyword in (WebUtility.HtmlDecode(descendant.Value) ?? "").Split(' ')) { if (!string.IsNullOrEmpty(keyword) && !uniqueKeywords.Contains(keyword)) { uniqueKeywords.Add(keyword); _keywords.Add(new NppKeywordLangs(keyword, this) { Origin = NppKeywordOrigin.Langs }); } } } // get other info on the language (comentLine, commentStart, commentEnd) LoadFromAttributes(this, langElement); } } catch (Exception e) { ErrorHandler.LogError(e, "Error parsing " + Npp.ConfXml.FileNppLangsXml); } } return(this); }
/// <summary> /// Checks if the toolbox needs to be initialized, and if so, calls <see cref="ModelingPackage.SetupDynamicToolbox"/>. /// </summary> private void InitializeToolbox() { #if ALWAYS_REFRESH_EXP_TOOLBOX IVsAppCommandLine vsAppCommandLine = (IVsAppCommandLine)base.GetService(typeof(IVsAppCommandLine)); int present; string optionValue; if (vsAppCommandLine == null || ErrorHandler.Failed(vsAppCommandLine.GetOption("RootSuffix", out present, out optionValue)) || !Convert.ToBoolean(present)) { // If we can't obtain the IVsAppCommandLine service, or our call to it fails, or no root suffix was specified, try looking at our registry root. IVsShell vsShell = (IVsShell)base.GetService(typeof(SVsShell)); object registryRootObject; if (vsShell == null || ErrorHandler.Failed(vsShell.GetProperty((int)__VSSPROPID.VSSPROPID_VirtualRegistryRoot, out registryRootObject)) || ((string)registryRootObject).EndsWith("EXP", StringComparison.OrdinalIgnoreCase)) { // If we can't get the registry root, or if it says we are running in the experimental hive, call SetupDynamicToolbox. base.SetupDynamicToolbox(); } else { #endif // ALWAYS_REFRESH_EXP_TOOLBOX RegistryKey userRegistryRoot = null; RegistryKey packageRegistryRoot = null; RegistryKey toolboxRevisionsKey = null; IDictionary <string, ToolboxProviderInfo> providers = GetToolboxProviderInfoMap(); bool refreshRequired = false; try { userRegistryRoot = this.UserRegistryRoot; // Note that we could do this twice, once to verify in read mode and a second time to write the // values back out, but it isn't work the extra hassle to do this twice simply to avoid a write // permission check on a user registry key. packageRegistryRoot = userRegistryRoot.OpenSubKey(REGISTRYROOT_PACKAGE_USER, RegistryKeyPermissionCheck.ReadWriteSubTree); bool hadRegistryRoot = packageRegistryRoot != null; bool hadRevisionsKey = false; // If the toolbox has the correct values for all domain models that provide toolbox items, // then we don't do anything. if (hadRegistryRoot) { // Remove obsolete data packageRegistryRoot.DeleteValue(REGISTRYVALUE_TOOLBOXREVISION_OBSOLETESINGLEVALUE, false); // Get new key information toolboxRevisionsKey = packageRegistryRoot.OpenSubKey(REGISTRYKEY_TOOLBOXREVISIONS, RegistryKeyPermissionCheck.ReadWriteSubTree); hadRevisionsKey = toolboxRevisionsKey != null; } else { packageRegistryRoot = userRegistryRoot.CreateSubKey(REGISTRYROOT_PACKAGE_USER, RegistryKeyPermissionCheck.ReadWriteSubTree); } if (!hadRevisionsKey) { toolboxRevisionsKey = packageRegistryRoot.CreateSubKey(REGISTRYKEY_TOOLBOXREVISIONS, RegistryKeyPermissionCheck.ReadWriteSubTree); } string[] valueNames = hadRevisionsKey ? toolboxRevisionsKey.GetValueNames() : null; int matchIndex; int hitCount = 0; foreach (KeyValuePair <string, ToolboxProviderInfo> providerInfo in providers) { int assemblyRevision = providerInfo.Value.ExpectedRevisionNumber; string typeFullName = providerInfo.Key; if (hadRevisionsKey && -1 != (matchIndex = Array.IndexOf <string>(valueNames, typeFullName))) { string valueName = valueNames[matchIndex]; valueNames[matchIndex] = null; ++hitCount; if (assemblyRevision != 0) { int?revision = toolboxRevisionsKey.GetValue(valueName, null) as int?; if (revision.HasValue) { if (assemblyRevision != revision.Value) { refreshRequired = true; toolboxRevisionsKey.SetValue(valueName, assemblyRevision, RegistryValueKind.DWord); } } else { // Wrong value kind, delete and readd the value refreshRequired = true; toolboxRevisionsKey.DeleteValue(valueName); toolboxRevisionsKey.SetValue(valueName, assemblyRevision, RegistryValueKind.DWord); } } else { refreshRequired = true; toolboxRevisionsKey.DeleteValue(valueName); } } else { refreshRequired = true; if (assemblyRevision != 0) { toolboxRevisionsKey.SetValue(typeFullName, assemblyRevision, RegistryValueKind.DWord); } } } if (hadRevisionsKey && hitCount != valueNames.Length) { refreshRequired = true; for (int i = 0; i < valueNames.Length; ++i) { string removeValue = valueNames[i]; if (removeValue != null) { toolboxRevisionsKey.DeleteValue(removeValue, false); } } } } catch (System.Security.SecurityException ex) { Debug.Fail("A security exception occurred while trying to write the current toolbox format revision number to the user registry. " + "You can safely continue execution of the program.", ex.ToString()); // Swallow the exception, since it won't actually cause a problem. The next time the package is loaded, we'll just initialize the toolbox again. } finally { if (userRegistryRoot != null) { if (packageRegistryRoot != null) { if (toolboxRevisionsKey != null) { toolboxRevisionsKey.Close(); } packageRegistryRoot.Close(); } userRegistryRoot.Close(); } } if (refreshRequired) { // Since the toolbox has either not been set up before, or is from an older or newer revision, call SetupDynamicToolbox. // This might not be necessary if it is from a newer revision, but we do it anyway to be safe. base.SetupDynamicToolbox(); } #if ALWAYS_REFRESH_EXP_TOOLBOX } } else if (!string.IsNullOrEmpty(optionValue)) { // If any non-empty root suffix was specified as a command line parameter, call SetupDynamicToolbox. base.SetupDynamicToolbox(); } #endif // ALWAYS_REFRESH_EXP_TOOLBOX }
/// <inheritdoc/> /// <remarks> /// This operation is implemented by calling <see cref="IVsTextView.RemoveCommandFilter"/>. /// </remarks> protected override void Disconnect() { ErrorHandler.ThrowOnFailure(TextViewAdapter.RemoveCommandFilter(this)); }
public Atomic_conditionContext atomic_condition() { Atomic_conditionContext _localctx = new Atomic_conditionContext(Context, State); EnterRule(_localctx, 16, RULE_atomic_condition); try { State = 189; switch (Interpreter.AdaptivePredict(TokenStream, 6, Context)) { case 1: EnterOuterAlt(_localctx, 1); { } break; case 2: EnterOuterAlt(_localctx, 2); { State = 159; _localctx.left = terms(); State = 160; Match(NEQ); State = 161; _localctx.right = terms(); _localctx.value = PumpingLemma.ComparisonExpression.NotEqual(_localctx.left.value, _localctx.right.value); } break; case 3: EnterOuterAlt(_localctx, 3); { State = 164; _localctx.left = terms(); State = 165; Match(EQ); State = 166; _localctx.right = terms(); _localctx.value = PumpingLemma.ComparisonExpression.Equal(_localctx.left.value, _localctx.right.value); } break; case 4: EnterOuterAlt(_localctx, 4); { State = 169; _localctx.left = terms(); State = 170; Match(LT); State = 171; _localctx.right = terms(); _localctx.value = PumpingLemma.ComparisonExpression.LessThan(_localctx.left.value, _localctx.right.value); } break; case 5: EnterOuterAlt(_localctx, 5); { State = 174; _localctx.left = terms(); State = 175; Match(LEQ); State = 176; _localctx.right = terms(); _localctx.value = PumpingLemma.ComparisonExpression.LessThanOrEqual(_localctx.left.value, _localctx.right.value); } break; case 6: EnterOuterAlt(_localctx, 6); { State = 179; _localctx.left = terms(); State = 180; Match(GT); State = 181; _localctx.right = terms(); _localctx.value = PumpingLemma.ComparisonExpression.GreaterThan(_localctx.left.value, _localctx.right.value); } break; case 7: EnterOuterAlt(_localctx, 7); { State = 184; _localctx.left = terms(); State = 185; Match(GEQ); State = 186; _localctx.right = terms(); _localctx.value = PumpingLemma.ComparisonExpression.GreaterThanOrEqual(_localctx.left.value, _localctx.right.value); } break; } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return(_localctx); }
/// <summary> /// Draws the background gradient image in the control based on the various gradient settings that are set for the control. All drawing will /// be performed in memory-based device context before rendering onto the control to allow for flicker-free drawing. /// </summary> protected virtual void DrawBackGradientImage(Graphics gCtl) { Bitmap bmpGradBackMem = null; Graphics gGradBackMem = null; GraphicsState origGraphState = null; try { // At the beginning of your drawing origGraphState = gCtl.Save(); bmpGradBackMem = new Bitmap(this.Width, this.Height); gGradBackMem = Graphics.FromImage(bmpGradBackMem); CoolGradientType BackGradTypeActive = GetBackGradientType(); Color BackGradColor1Active = GetBackGradientColor(1); Color BackGradColor2Active = GetBackGradientColor(2); float fGradientSpan = GetBackGradientSpan(); Point ptGradOffset = GetBackGradientOffset(); Rectangle rectBounds = new Rectangle(0, 0, this.Width, this.Height); if (BackGradColor1Active != Color.Transparent && BackGradTypeActive != CoolGradientType.None) { CoolDraw.DrawGradientShape(CoolShape.Rectangle, BackGradTypeActive, gGradBackMem, BackGradColor1Active, BackGradColor2Active, rectBounds, Color.Transparent, 0, fGradientSpan, ptGradOffset.X, ptGradOffset.Y); } else { Color?FillColor = null; if (BackGradColor1Active != Color.Transparent) { FillColor = BackGradColor1Active; } CoolDraw.DrawShape(CoolShape.Rectangle, gGradBackMem, rectBounds, Color.Transparent, 0, 0, 0, FillColor); }//end if Rectangle rectDraw = new Rectangle(0, 0, this.Width, this.Height); //gCtl.CompositingMode = CompositingMode.SourceCopy; gCtl.DrawImage(bmpGradBackMem, rectDraw); } catch (Exception err) { ErrorHandler.ShowErrorMessage(err, "Error in DrawBackGradientImage function of DotCoolPanel control."); } finally { if (origGraphState != null) { gCtl.Restore(origGraphState); } if (gGradBackMem != null) { gGradBackMem.Dispose(); } if (bmpGradBackMem != null) { bmpGradBackMem.Dispose(); } } }
protected internal virtual void InvokeGeneratorEx(FileNode fileNode, String document, bool runEvenIfNotDirty) { base.InvokeGenerator(fileNode); Utilities.ArgumentNotNull("fileNode", fileNode); SingleFileGeneratorNodeProperties nodeproperties = fileNode.NodeProperties as SingleFileGeneratorNodeProperties; if (nodeproperties == null) { throw new InvalidOperationException(); } string customToolProgID = nodeproperties.CustomTool; if (string.IsNullOrEmpty(customToolProgID)) { return; } // not sure what to do if BuildAction is set to "MSBuild:Compile". IronPython doesn't handle this correctly either. // This build action is set for .xaml files but doing nothing doesn't seem to cause problems, so for now we ignore this // generator type and do nothing too. If we don't do this, we get lots of message boxes when the clsid of this non-existent // single file generator isn't found. // We should try to find out what the proper action is here. There is no "MSBuild:Compile" entry in the registry // for the C# or VB project system single file generators, so there must be some special handling for this build type // otherwise it would just be blank. Naturally, the IronPython sample isn't any help here. if (customToolProgID.StartsWith("MSBuild:Compile", StringComparison.OrdinalIgnoreCase)) { var project = fileNode.ProjectMgr as XSharpProjectNode; if (project.IsXamlFile(document)) { // need to generate the .g.prg file. project.Build(project.CurrentConfig.ConfigCanonicalName, "BuildGenerateSources"); // BuildGenerateSources } // The C# project system then calls a InvokeMsBuild method with the following contents /* * HRESULT CVsProjBaseFileNode::InvokeMSBuildTarget(_In_z_ LPCWSTR wszMSBuildTarget) * { * HRESULT hr = NOERROR; * * if (wszMSBuildTarget != NULL) * { * CLangBuildMgr *pBuildMgr = GetProject()->GetBuildMgr(); * CComPtr<MSBuildEngine::IProject> srpMSBuildProject = pBuildMgr->GetMSBuildProject(); * * if (CXMakeHelper::DoesTargetExist(srpMSBuildProject, wszMSBuildTarget) && pBuildMgr->HasPassedSecurityChecks()) * { * // Initialize the build engine for this project and configuration. * CSmartMSBuildInitializer smsbi; * CLangProjectConfig *pProjConfig = pBuildMgr->GetConfigs()->GetActiveConfig(); * hr = smsbi.Initialize(pBuildMgr, pProjConfig); * * if (SUCCEEDED(hr)) * { * // Build the specified target in the MSBuild project. * hr = pBuildMgr->BuildTarget(wszMSBuildTarget); * } * * // Don't bother keeping the return value here--we want to * // return failure from Initialize or BuildTarget instead. * smsbi.Restore(pBuildMgr); * } * } * * return hr; * } */ return; } string customToolNamespace = nodeproperties.CustomToolNamespace; ThreadHelper.ThrowIfNotOnUIThread(); try { if (!this.runningGenerator) { //Find if any dependent node exists string dependentNodeName = null; HierarchyNode dependentNode = fileNode.FirstChild; while (dependentNode != null) { string dependentUpon = dependentNode.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon); if (!String.IsNullOrEmpty(dependentUpon)) { if (!Path.IsPathRooted(dependentUpon)) { dependentUpon = Path.Combine(Path.GetDirectoryName(fileNode.Url), dependentUpon); } if (string.Compare(dependentUpon, fileNode.Url, StringComparison.OrdinalIgnoreCase) == 0) { dependentNodeName = ((FileNode)dependentNode).FileName; break; } } dependentNode = dependentNode.NextSibling; } bool outputOutOfDate = dependentNodeName == null; if ((!runEvenIfNotDirty) && !outputOutOfDate) { string generatedFile = Path.Combine(Path.GetDirectoryName(fileNode.GetMkDocument()), dependentNodeName); outputOutOfDate = !File.Exists(generatedFile); if (!outputOutOfDate) { outputOutOfDate = File.GetLastWriteTime(fileNode.GetMkDocument()) > File.GetLastWriteTime(generatedFile); if (!outputOutOfDate) { IVsHierarchy rdtHier; IVsPersistDocData perDocData; uint cookie; outputOutOfDate = this.VerifyFileDirtyInRdt(document, out rdtHier, out perDocData, out cookie); } } } //if (runEvenIfNotDirty || outputOutOfDate) { //Get the buffer contents for the current node string moniker = fileNode.GetMkDocument(); this.runningGenerator = true; anyGeneratorsRunning++; //Get the generator IVsSingleFileGenerator generator; int generateDesignTimeSource; int generateSharedDesignTimeSource; int generateTempPE; SingleFileGeneratorFactory factory = new SingleFileGeneratorFactory(this.ProjectMgr.ProjectGuid, this.ProjectMgr.Site); ErrorHandler.ThrowOnFailure(factory.CreateGeneratorInstance(customToolProgID, out generateDesignTimeSource, out generateSharedDesignTimeSource, out generateTempPE, out generator)); //Check to see if the generator supports siting IObjectWithSite objWithSite = generator as IObjectWithSite; if (objWithSite != null) { objWithSite.SetSite(fileNode.OleServiceProvider); } //Determine the namespace if (string.IsNullOrEmpty(customToolNamespace)) { customToolNamespace = this.ComputeNamespace(moniker); } //Run the generator IntPtr[] output = new IntPtr[1]; output[0] = IntPtr.Zero; uint outPutSize; if (dependentNodeName == null) { string extension = null; try { generator.DefaultExtension(out extension); } catch (Exception e) { if (System.Diagnostics.Debugger.IsAttached) { Debug.WriteLine(e); } } if (!String.IsNullOrEmpty(extension)) { dependentNodeName = Path.GetFileNameWithoutExtension(fileNode.FileName) + extension; } else { dependentNodeName = fileNode.FileName; } } //If you found a dependent node. if (dependentNode != null) { //Then check out the node and dependent node from SCC if (!this.CanEditFile(dependentNode.GetMkDocument())) { throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED); } } else //It is a new node to be added to the project { // Check out the project file if necessary. if (!this.ProjectMgr.QueryEditProjectFile(false)) { throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED); } } IVsTextStream stream; string inputFileContents = this.GetBufferContents(moniker, out stream); var res = generator.Generate(moniker, inputFileContents, customToolNamespace, output, out outPutSize, this); byte[] data = new byte[outPutSize]; if (output[0] != IntPtr.Zero) { Marshal.Copy(output[0], data, 0, (int)outPutSize); Marshal.FreeCoTaskMem(output[0]); } //Todo - Create a file and add it to the Project string fileToAdd = this.UpdateGeneratedCodeFile(fileNode, data, (int)outPutSize, dependentNodeName, dependentNode); } } } finally { this.runningGenerator = false; anyGeneratorsRunning--; } }
protected virtual string UpdateGeneratedCodeFile(FileNode fileNode, byte[] data, int size, string fileName, HierarchyNode dependentNode) { string filePath = Path.Combine(Path.GetDirectoryName(fileNode.GetMkDocument()), fileName); ThreadHelper.ThrowIfNotOnUIThread(); IVsRunningDocumentTable rdt = this.ProjectMgr.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; // (kberes) Shouldn't this be an InvalidOperationException instead with some not to annoying errormessage to the user? if (rdt == null) { ErrorHandler.ThrowOnFailure(VSConstants.E_FAIL); } IVsHierarchy hier; uint cookie; uint itemid; IntPtr docData = IntPtr.Zero; ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)(_VSRDTFLAGS.RDT_NoLock), filePath, out hier, out itemid, out docData, out cookie)); if (docData != IntPtr.Zero) { Marshal.Release(docData); IVsTextStream srpStream; string inputFileContents = this.GetBufferContents(filePath, out srpStream); if (srpStream != null) { int oldLen = 0; int hr = srpStream.GetSize(out oldLen); if (ErrorHandler.Succeeded(hr)) { IntPtr dest = IntPtr.Zero; try { if (data.Length > 2 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF) { // the data is in UTF-8 format and must be converted to Unicode, since the IVsTextStream // buffer is always Unicode // // The ResXCodeGenerator generates UTF-8 code, other SingleFileGenerators might do the same thing, who knows? string txt = new System.Text.UTF8Encoding().GetString(data, 3, data.Length - 3); // skip over encoding preamble UnicodeEncoding enc = new UnicodeEncoding(); int len = enc.GetByteCount(txt); Byte[] unicodeData = new Byte[len]; enc.GetBytes(txt, 0, txt.Length, unicodeData, 0); dest = Marshal.AllocCoTaskMem(len); Marshal.Copy(unicodeData, 0, dest, unicodeData.Length); ErrorHandler.ThrowOnFailure(srpStream.ReplaceStream(0, oldLen, dest, len / 2)); // Note: 4th param is # of chars, not bytes! } // end of changes else { dest = Marshal.AllocCoTaskMem(data.Length); Marshal.Copy(data, 0, dest, data.Length); ErrorHandler.ThrowOnFailure(srpStream.ReplaceStream(0, oldLen, dest, size / 2)); } // for now, always save the generated file. Otherwise we have issues when the source file is dirty and the user // builds the project. The generator runs (because of the overridden SaveItem() in the project node) but the generated // file ends up dirty and when the project is built, everything should be saved. // We could probably force a save on that node, but it seems cleaner to always save the generated file. int canceled; ErrorHandler.ThrowOnFailure(this.ProjectMgr.SaveItem(VSSAVEFLAGS.VSSAVE_SilentSave, filePath, dependentNode.ID, docData, out canceled)); } finally { if (dest != IntPtr.Zero) { Marshal.Release(dest); } } } } } else { using (FileStream generatedFileStream = File.Open(filePath, FileMode.OpenOrCreate)) { generatedFileStream.Write(data, 0, size); // adjust length, in case the file shrinks in size.. generatedFileStream.SetLength(size); } EnvDTE.ProjectItem projectItem = fileNode.GetAutomationObject() as EnvDTE.ProjectItem; if (projectItem != null && (this.ProjectMgr.FindChild(fileNode.FileName) == null)) { projectItem.ProjectItems.AddFromFile(filePath); } } return(filePath); }
public Condition_hContext condition_h() { Condition_hContext _localctx = new Condition_hContext(Context, State); EnterRule(_localctx, 14, RULE_condition_h); try { State = 156; switch (Interpreter.AdaptivePredict(TokenStream, 5, Context)) { case 1: EnterOuterAlt(_localctx, 1); { State = 118; _localctx.atom = atomic_condition(); _localctx.value = _localctx.atom.value; } break; case 2: EnterOuterAlt(_localctx, 2); { State = 121; Match(LPAREN); State = 122; _localctx.sub = condition_h(); State = 123; Match(RPAREN); _localctx.value = _localctx.sub.value; } break; case 3: EnterOuterAlt(_localctx, 3); { State = 126; _localctx.atom = atomic_condition(); State = 127; Match(AND); State = 128; _localctx.sub2 = condition_h(); _localctx.value = PumpingLemma.LogicalExpression.And(_localctx.atom.value, _localctx.sub2.value); } break; case 4: EnterOuterAlt(_localctx, 4); { State = 131; Match(LPAREN); State = 132; _localctx.sub1 = condition_h(); State = 133; Match(RPAREN); State = 134; Match(AND); State = 135; _localctx.sub2 = condition_h(); _localctx.value = PumpingLemma.LogicalExpression.And(_localctx.sub1.value, _localctx.sub2.value); } break; case 5: EnterOuterAlt(_localctx, 5); { State = 138; _localctx.atom = atomic_condition(); State = 139; Match(OR); State = 140; _localctx.sub2 = condition_h(); _localctx.value = PumpingLemma.LogicalExpression.Or(_localctx.atom.value, _localctx.sub2.value); } break; case 6: EnterOuterAlt(_localctx, 6); { State = 143; Match(LPAREN); State = 144; _localctx.sub1 = condition_h(); State = 145; Match(RPAREN); State = 146; Match(OR); State = 147; _localctx.sub2 = condition_h(); _localctx.value = PumpingLemma.LogicalExpression.Or(_localctx.sub1.value, _localctx.sub2.value); } break; case 7: EnterOuterAlt(_localctx, 7); { State = 150; Match(NOT); State = 151; Match(LPAREN); State = 152; _localctx.sub = condition_h(); State = 153; Match(RPAREN); _localctx.value = PumpingLemma.LogicalExpression.Not(_localctx.sub.value); } break; } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return(_localctx); }
public TermContext term() { TermContext _localctx = new TermContext(Context, State); EnterRule(_localctx, 0, RULE_term); try { State = 35; switch (Interpreter.AdaptivePredict(TokenStream, 0, Context)) { case 1: EnterOuterAlt(_localctx, 1); { State = 18; _localctx._INT = Match(INT); _localctx.value = PumpingLemma.LinearIntegerExpression.Constant((_localctx._INT != null?int.Parse(_localctx._INT.Text):0)); } break; case 2: EnterOuterAlt(_localctx, 2); { State = 20; _localctx._IDENT = Match(IDENT); _localctx.value = PumpingLemma.LinearIntegerExpression.Variable((_localctx._IDENT != null?_localctx._IDENT.Text:null)); } break; case 3: EnterOuterAlt(_localctx, 3); { State = 22; _localctx._INT = Match(INT); State = 23; Match(TIMES); State = 24; _localctx._IDENT = Match(IDENT); _localctx.value = PumpingLemma.LinearIntegerExpression.SingleTerm( (_localctx._INT != null?int.Parse(_localctx._INT.Text):0), PumpingLemma.VariableType.Variable((_localctx._IDENT != null?_localctx._IDENT.Text:null)) ); } break; case 4: EnterOuterAlt(_localctx, 4); { State = 26; _localctx._IDENT = Match(IDENT); State = 27; Match(TIMES); State = 28; _localctx._INT = Match(INT); _localctx.value = PumpingLemma.LinearIntegerExpression.SingleTerm( (_localctx._INT != null?int.Parse(_localctx._INT.Text):0), PumpingLemma.VariableType.Variable((_localctx._IDENT != null?_localctx._IDENT.Text:null)) ); } break; case 5: EnterOuterAlt(_localctx, 5); { State = 30; Match(LPAREN); State = 31; _localctx.a = terms(); State = 32; Match(RPAREN); _localctx.value = _localctx.a.value; } break; } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return(_localctx); }
/// <summary> /// Construct a new image over a log to represent a stream of messages from a <seealso cref="Publication"/>. /// </summary> /// <param name="subscription"> to which this <seealso cref="Image"/> belongs. </param> /// <param name="sessionId"> of the stream of messages. </param> /// <param name="subscriberPosition"> for indicating the position of the subscriber in the stream. </param> /// <param name="logBuffers"> containing the stream of messages. </param> /// <param name="errorHandler"> to be called if an error occurs when polling for messages. </param> /// <param name="sourceIdentity"> of the source sending the stream of messages. </param> /// <param name="correlationId"> of the request to the media driver. </param> public Image(Subscription subscription, int sessionId, IPosition subscriberPosition, LogBuffers logBuffers, ErrorHandler errorHandler, string sourceIdentity, long correlationId) { Subscription = subscription; SessionId = sessionId; _subscriberPosition = subscriberPosition; _logBuffers = logBuffers; _errorHandler = errorHandler; SourceIdentity = sourceIdentity; CorrelationId = correlationId; _joinPosition = subscriberPosition.Get(); _termBuffers = logBuffers.DuplicateTermBuffers(); var termLength = logBuffers.TermLength(); _termLengthMask = termLength - 1; _positionBitsToShift = LogBufferDescriptor.PositionBitsToShift(termLength); _initialTermId = LogBufferDescriptor.InitialTermId(logBuffers.MetaDataBuffer()); _header = new Header(LogBufferDescriptor.InitialTermId(logBuffers.MetaDataBuffer()), _positionBitsToShift, this); }
public override void Handle(ErrorHandler erh) { throw this; }
protected void Page_Load(object sender, EventArgs e) { //bool hide = false; if (this.Request.IsAuthenticated) { this.Visible = false; } else { try { // hide = true; var facebookContext = GetFacebookWebContext(); if (facebookContext != null) { appId.Value = PortalSettings.CustomSettings["SITESETTINGS_FACEBOOK_APP_ID"].ToString(); appidfacebook.Value = PortalSettings.CustomSettings["SITESETTINGS_FACEBOOK_APP_ID"].ToString(); // hide = false; if (facebookContext.IsAuthenticated()) { //Here is were i check if the user login via facebook FacebookSignInMethod(); } } else { //TODO: ocultar boton y mostrar warning loginfb_div.Visible = false; ErrorHandler.Publish(LogLevel.Error, "Facebook settings are not correct"); } } catch (FacebookApiException ex) { loginfb_div.Visible = false; ErrorHandler.Publish(LogLevel.Error, Resources.Appleseed.FACEBOOK_ERROR, ex); } try { var TwitterRequestToken = GetTwitterRequestToken(); if (TwitterRequestToken != null) { // hide = false; } else { //TODO: ocultar boton y mostrar warning logintwit_div.Visible = false; ErrorHandler.Publish(LogLevel.Error, "Twitter settings are not correct"); } } catch (TwitterizerException ex) { logintwit_div.Visible = false; ErrorHandler.Publish(LogLevel.Error, Resources.Appleseed.TWITTER_ERROR, ex); } if (this.PortalSettings.CustomSettings.ContainsKey("SITESETTINGS_GOOGLE_LOGIN") && this.PortalSettings.CustomSettings["SITESETTINGS_GOOGLE_LOGIN"].ToString().Length != 0 && !bool.Parse(this.PortalSettings.CustomSettings["SITESETTINGS_GOOGLE_LOGIN"].ToString())) { google_div.Visible = false; } else //hide = false; if ((this.PortalSettings.CustomSettings.ContainsKey("SITESETTINGS_LINKEDIN_APP_ID") && this.PortalSettings.CustomSettings["SITESETTINGS_LINKEDIN_APP_ID"].ToString().Length != 0) && (this.PortalSettings.CustomSettings.ContainsKey("SITESETTINGS_LINKEDIN_APP_SECRET") && this.PortalSettings.CustomSettings["SITESETTINGS_LINKEDIN_APP_SECRET"].ToString().Length != 0)) { // hide = false; Session["LinkedInAppId"] = PortalSettings.CustomSettings["SITESETTINGS_LINKEDIN_APP_ID"].ToString(); Session["LinkedInAppSecret"] = PortalSettings.CustomSettings["SITESETTINGS_LINKEDIN_APP_SECRET"].ToString(); } else { linkedin_div.Visible = false; } } }
public async Task <string> Consume(string json) { try { dynamic jsonObject = JsonConvert.DeserializeObject(json); //1.genaral var msg = new WB.MESSAGE.Message(); msg.ObjectName = jsonObject.ObjectName; msg.MsgAction = jsonObject.MsgAction; try { string modid = jsonObject.ModId; if (!string.IsNullOrEmpty(modid)) { msg.ModId = modid.Trim(); } } catch { } //2. Get body try { List <ModuleFieldInfo> modfld = jsonObject.Body.ToObject <List <ModuleFieldInfo> >(); foreach (ModuleFieldInfo moduleFieldInfo in modfld) { if (!string.IsNullOrEmpty(moduleFieldInfo.Value)) { msg.Body.Add(moduleFieldInfo.FieldName); msg.Body.Add(moduleFieldInfo.Value.TrimEnd(',')); if (msg.ModId == null) { msg.ModId = moduleFieldInfo.ModuleID; } } } } catch { } if (msg.Body == null || msg.Body.Count == 0) { JObject obj = JObject.Parse(json); JArray arrBody = (JArray)obj["Body"]; msg.Body = SysUtils.String2Arrray(arrBody.ToString().Replace("[", "").Replace("]", "").Replace("\r\n", "").Replace("\"", ""), ","); } //3.Process business if (jsonObject.MsgType == Constants.MSG_MNT_TYPE) { MaintenanceFacade maintenanceFacade = new MaintenanceFacade(); maintenanceFacade.Process(ref msg); } else if (jsonObject.MsgType == Constants.MSG_MISC_TYPE) { MiscellaneousFacade miscellaneousFacade = new MiscellaneousFacade(); miscellaneousFacade.Process(ref msg); } //4.Return var order = new { Value = msg.Body }; //json = JsonConvert.SerializeObject(order); json = JsonConvert.SerializeObject(msg.Body); } catch (RequestTimeoutException ex) { ErrorHandler.Process(ex); } catch (ErrorMessage ex) { ErrorHandler.Process(ex); } catch (Exception ex) { ErrorHandler.Process(ex); } return(json); }
/// <summary> /// This function is the callback used to execute a command when the a menu item is clicked. /// See the Initialize method to see how the menu item is associated to this function using /// the OleMenuCommandService service and the MenuCommand class. /// </summary> private void GenerateTestStub(object sender, EventArgs e) { var uiShell = (IVsUIShell)GetService(typeof(SVsUIShell)); var clsid = Guid.Empty; var dte = (DTE)GetGlobalService(typeof(DTE)); var document = dte.ActiveDocument; var sel = (TextSelection)document.Selection; var pnt = sel.ActivePoint; var projectItem = document.ProjectItem; var fileCodeModel = projectItem.FileCodeModel; var cut = (CodeClass)fileCodeModel.CodeElementFromPoint(pnt, vsCMElement.vsCMElementClass); // TODO: stop right here if the class already ends in "Test" CodeFunction mut = null; try { mut = (CodeFunction)fileCodeModel.CodeElementFromPoint(pnt, vsCMElement.vsCMElementFunction); } catch (COMException) { // there may not be any methods, or cursor was not near any method } // TODO: stop right here if the method is not visible to the test class var testClassName = cut.Name + "Test"; var testClassFileName = testClassName + ".cs"; var testClassFile = dte.Solution.FindProjectItem(testClassFileName); if (testClassFile == null) { var put = projectItem.ContainingProject; var putName = put.Name; var candidates = FindTestProject(putName, dte); Project testProject; if (candidates.Count == 0) { int result; ErrorHandler.ThrowOnFailure( uiShell.ShowMessageBox( 0, ref clsid, "Sucks to be you", string.Format(CultureInfo.CurrentCulture, "There exists no test project for the project '{0}'.", putName), string.Empty, 0, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, OLEMSGICON.OLEMSGICON_INFO, 0, // false out result ) ); return; } if (candidates.Count == 1) { testProject = candidates[0]; } else { var sb = new StringBuilder(); var c = 0; foreach (var project in candidates) { sb.Append(c); sb.Append(" = "); sb.AppendLine(project.Name); c = c + 1; } var selectionString = Interaction.InputBox(sb.ToString(), "Which project should the test class be added to?", "0"); var selectedIndex = Convert.ToInt32(selectionString, 10); testProject = candidates[selectedIndex]; } var testProjectRoot = Path.GetDirectoryName(testProject.FullName); var testClassFolder = testProjectRoot; var targetNamespace = testProject.Name; if (cut.Namespace.Name.StartsWith(put.Name + ".")) { var rootOffset = cut.Namespace.Name.Remove(0, put.Name.Length + 1); testClassFolder = Path.Combine(testClassFolder, rootOffset); targetNamespace = targetNamespace + "." + rootOffset; } var absolutePathToTestClass = Path.Combine(testClassFolder, testClassFileName); var testClassContents = new StringBuilder(); testClassContents.AppendLine("using System;"); testClassContents.AppendLine("using Microsoft.VisualStudio.TestTools.UnitTesting;"); testClassContents.AppendFormat("using {0};", cut.Namespace.Name).AppendLine(); testClassContents.AppendLine(); testClassContents.AppendFormat("namespace {0}", targetNamespace).AppendLine(); testClassContents.AppendLine("{"); testClassContents.AppendLine(" /// <summary>"); testClassContents.AppendFormat(@" /// A class to test <see cref=""{0}""/>.", cut.Name).AppendLine(); testClassContents.AppendLine(" /// </summary>"); testClassContents.AppendLine(" [TestClass]"); testClassContents.AppendFormat(" public class {0}", testClassName).AppendLine(); testClassContents.AppendLine(" {"); testClassContents.AppendLine(" }"); testClassContents.AppendLine("}"); File.WriteAllText(absolutePathToTestClass, testClassContents.ToString()); testClassFile = testProject.ProjectItems.AddFromFile(absolutePathToTestClass); } testClassFile.Open(EnvDTE.Constants.vsViewKindCode); testClassFile.Document.Activate(); var testFileElements = testClassFile.FileCodeModel.CodeElements; var testClass = (CodeClass)FindElement(testFileElements, testClassName, vsCMElement.vsCMElementClass); if (mut != null) { var testMethodName = mut.Name + "TODO"; var position = FindInsertionPoint(testFileElements, testMethodName); try { dte.UndoContext.Open("Insert test method"); var testMethod = testClass.AddFunction( testMethodName, vsCMFunction.vsCMFunctionFunction, vsCMTypeRef.vsCMTypeRefVoid, position, vsCMAccess.vsCMAccessPublic); var editPoint = testMethod.StartPoint.CreateEditPoint(); // Adding the "[TestMethod]" attribute this way avoid the DTE adding it as // "[Test()]" when using AddAttribute() editPoint.Insert("[TestMethod]"); editPoint.Insert(CrLf); editPoint.Indent(null, 2); editPoint.LineDown(2); editPoint.StartOfLine(); // TODO: generate local variables to match the parameter names & types //var parameters = mut.Parameters; //foreach (var codeElement2 in parameters) //{ // CodeParameter = codeElement2; // editPoint.Indent(CodeParameter.Name); //} // TODO: check if the methodUnderTest is an instance or a static method // TODO: check if the methodUnderTest returns a value or not // TODO: use editPoint.Insert("Text") instead of the following? editPoint.Indent(null, 3); editPoint.Insert("var actual = " + cut.Name + "." + mut.Name + "();"); editPoint.Insert(CrLf); editPoint.Indent(null, 3); editPoint.Insert("Assert.AreEqual(0, actual);"); // place the cursor at the method call editPoint.LineUp(1); var selection = (TextSelection)testClassFile.Document.Selection; selection.GotoLine(editPoint.Line); selection.EndOfLine(false); selection.CharLeft(false, 2); } finally { dte.UndoContext.Close(); } } }
public TaskDialogButton ShowModal() { var config = new NativeMethods.TASKDIALOGCONFIG(); config.cbSize = (uint)Marshal.SizeOf(typeof(NativeMethods.TASKDIALOGCONFIG)); config.pButtons = IntPtr.Zero; config.pRadioButtons = IntPtr.Zero; var uiShell = (IVsUIShell)_provider.GetService(typeof(SVsUIShell)); if (uiShell == null) { // We are shutting down, so return the default return(SelectedButton); } uiShell.GetDialogOwnerHwnd(out config.hwndParent); uiShell.EnableModeless(0); var customButtons = new List <TaskDialogButton>(); config.dwCommonButtons = 0; foreach (var button in Buttons) { var flag = GetButtonFlag(button); if (flag != 0) { config.dwCommonButtons |= flag; } else { customButtons.Add(button); } } try { if (customButtons.Any()) { config.cButtons = (uint)customButtons.Count; var ptr = config.pButtons = Marshal.AllocHGlobal(customButtons.Count * Marshal.SizeOf(typeof(NativeMethods.TASKDIALOG_BUTTON))); for (int i = 0; i < customButtons.Count; ++i) { NativeMethods.TASKDIALOG_BUTTON data; data.nButtonID = GetButtonId(null, null, i); if (string.IsNullOrEmpty(customButtons[i].Subtext)) { data.pszButtonText = customButtons[i].Text; } else { data.pszButtonText = string.Format("{0}\n{1}", customButtons[i].Text, customButtons[i].Subtext); } Marshal.StructureToPtr(data, ptr + i * Marshal.SizeOf(typeof(NativeMethods.TASKDIALOG_BUTTON)), false); } } else { config.cButtons = 0; config.pButtons = IntPtr.Zero; } if (_buttons.Any() && SelectedButton != null) { config.nDefaultButton = GetButtonId(SelectedButton, customButtons); } else { config.nDefaultButton = 0; } if (_radioButtons.Any()) { config.cRadioButtons = (uint)_radioButtons.Count; var ptr = config.pRadioButtons = Marshal.AllocHGlobal(_radioButtons.Count * Marshal.SizeOf(typeof(NativeMethods.TASKDIALOG_BUTTON))); for (int i = 0; i < _radioButtons.Count; ++i) { NativeMethods.TASKDIALOG_BUTTON data; data.nButtonID = GetRadioId(null, null, i); data.pszButtonText = _radioButtons[i].Text; Marshal.StructureToPtr(data, ptr + i * Marshal.SizeOf(typeof(NativeMethods.TASKDIALOG_BUTTON)), false); } if (SelectedRadioButton != null) { config.nDefaultRadioButton = GetRadioId(SelectedRadioButton, _radioButtons); } else { config.nDefaultRadioButton = 0; } } config.pszWindowTitle = Title; config.pszMainInstruction = MainInstruction; config.pszContent = Content; config.pszExpandedInformation = ExpandedInformation; config.pszExpandedControlText = ExpandedControlText; config.pszCollapsedControlText = CollapsedControlText; config.pszFooter = Footer; config.pszVerificationText = VerificationText; config.pfCallback = Callback; config.hMainIcon = (IntPtr)GetIconResource(MainIcon); config.hFooterIcon = (IntPtr)GetIconResource(FooterIcon); if (Width.HasValue) { config.cxWidth = (uint)Width.Value; } else { config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_SIZE_TO_CONTENT; } if (EnableHyperlinks) { config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_ENABLE_HYPERLINKS; } if (AllowCancellation) { config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_ALLOW_DIALOG_CANCELLATION; } if (UseCommandLinks && config.cButtons > 0) { config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_USE_COMMAND_LINKS; } if (!ShowExpandedInformationInContent) { config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_EXPAND_FOOTER_AREA; } if (ExpandedByDefault) { config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_EXPANDED_BY_DEFAULT; } if (SelectedVerified) { config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_VERIFICATION_FLAG_CHECKED; } if (CanMinimize) { config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_CAN_BE_MINIMIZED; } config.dwFlags |= NativeMethods.TASKDIALOG_FLAGS.TDF_POSITION_RELATIVE_TO_WINDOW; int selectedButton, selectedRadioButton; bool verified; ErrorHandler.ThrowOnFailure(NativeMethods.TaskDialogIndirect( ref config, out selectedButton, out selectedRadioButton, out verified )); SelectedButton = GetButton(selectedButton, customButtons); SelectedRadioButton = GetRadio(selectedRadioButton, _radioButtons); SelectedVerified = verified; } finally { uiShell.EnableModeless(1); if (config.pButtons != IntPtr.Zero) { for (int i = 0; i < customButtons.Count; ++i) { Marshal.DestroyStructure(config.pButtons + i * Marshal.SizeOf(typeof(NativeMethods.TASKDIALOG_BUTTON)), typeof(NativeMethods.TASKDIALOG_BUTTON)); } Marshal.FreeHGlobal(config.pButtons); } if (config.pRadioButtons != IntPtr.Zero) { for (int i = 0; i < _radioButtons.Count; ++i) { Marshal.DestroyStructure(config.pRadioButtons + i * Marshal.SizeOf(typeof(NativeMethods.TASKDIALOG_BUTTON)), typeof(NativeMethods.TASKDIALOG_BUTTON)); } Marshal.FreeHGlobal(config.pRadioButtons); } } return(SelectedButton); }
void IPscxErrorHandler.WriteFileError(string path, Exception exc) { ErrorHandler.HandleFileError(false, path, exc); }
void IPscxErrorHandler.WriteLastWin32Error(string errorId, object target) { ErrorHandler.WriteLastWin32Error(errorId, ErrorCategory.NotSpecified, target); }
public override void Init(GDbTabWrapper <TKey, ReadableTuple <TKey> > tab, DisplayableProperty <TKey, ReadableTuple <TKey> > dp) { _tab = tab; _initSettings(tab, dp); _tab.Settings.NewItemAddedFunction += item => item.SetRawValue(ServerItemGroupAttributes.Table, new Dictionary <int, ReadableTuple <int> >()); GenericDatabase gdb = ((GenericDatabase)_tab.Database); _itemGroupsTable.Commands.PreviewCommandUndo += _previewCommandChanged; _itemGroupsTable.Commands.PreviewCommandRedo += _previewCommandChanged; _itemGroupsTable.Commands.PreviewCommandExecuted += _previewCommandChanged; _itemGroupsTable.Commands.CommandUndo += _commandChanged; _itemGroupsTable.Commands.CommandRedo += _commandChanged; _itemGroupsTable.Commands.CommandExecuted += _commandChanged; gdb.Commands.PreviewCommandUndo += _previewCommandChanged2; gdb.Commands.PreviewCommandRedo += _previewCommandChanged2; gdb.Commands.PreviewCommandExecuted += _previewCommandChanged2; gdb.Commands.CommandUndo += _commandChanged2; gdb.Commands.CommandRedo += _commandChanged2; gdb.Commands.CommandExecuted += _commandChanged2; Grid grid = new Grid(); grid.SetValue(Grid.RowProperty, _row); grid.SetValue(Grid.ColumnProperty, 0); grid.SetValue(Grid.ColumnSpanProperty, 1); grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(-1, GridUnitType.Auto) }); grid.RowDefinitions.Add(new RowDefinition()); grid.ColumnDefinitions.Add(new ColumnDefinition()); Label label = new Label(); label.Content = "Item IDs"; label.FontStyle = FontStyles.Italic; label.Padding = new Thickness(0); label.Margin = new Thickness(3); _lv = new RangeListView(); _lv.SetValue(TextSearch.TextPathProperty, "ID"); _lv.SetValue(WpfUtils.IsGridSortableProperty, true); _lv.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled); _lv.SetValue(Grid.RowProperty, 1); _lv.FocusVisualStyle = null; _lv.Margin = new Thickness(3); _lv.BorderThickness = new Thickness(1); _lv.HorizontalAlignment = HorizontalAlignment.Left; _lv.SelectionChanged += _lv_SelectionChanged; Extensions.GenerateListViewTemplate(_lv, new ListViewDataTemplateHelper.GeneralColumnInfo[] { new ListViewDataTemplateHelper.GeneralColumnInfo { Header = ServerItemAttributes.Id.DisplayName, DisplayExpression = "ID", SearchGetAccessor = "ID", FixedWidth = 60, TextAlignment = TextAlignment.Right, ToolTipBinding = "ID" }, new ListViewDataTemplateHelper.RangeColumnInfo { Header = ServerItemAttributes.Name.DisplayName, DisplayExpression = "Name", SearchGetAccessor = "Name", IsFill = true, ToolTipBinding = "Name", TextWrapping = TextWrapping.Wrap, MinWidth = 70 }, new ListViewDataTemplateHelper.GeneralColumnInfo { Header = "Freq", DisplayExpression = "Drop", SearchGetAccessor = "Rate", ToolTipBinding = "Rate", FixedWidth = 40, TextAlignment = TextAlignment.Right }, new ListViewDataTemplateHelper.GeneralColumnInfo { Header = "Drop %", DisplayExpression = "Chance", SearchGetAccessor = "ChanceInt", ToolTipBinding = "Chance", FixedWidth = 60, TextAlignment = TextAlignment.Right } }, new DefaultListViewComparer <ItemView>(), new string[] { "Added", "Blue", "Modified", "Green", "Normal", "Black" }); _lv.ContextMenu = new ContextMenu(); _lv.MouseDoubleClick += new MouseButtonEventHandler(_lv_MouseDoubleClick); MenuItem miSelect = new MenuItem { Header = "Select", Icon = new Image { Source = (BitmapSource)ApplicationManager.PreloadResourceImage("arrowdown.png") } }; MenuItem miEditDrop = new MenuItem { Header = "Edit", Icon = new Image { Source = (BitmapSource)ApplicationManager.PreloadResourceImage("properties.png") } }; MenuItem miRemoveDrop = new MenuItem { Header = "Remove", Icon = new Image { Source = (BitmapSource)ApplicationManager.PreloadResourceImage("delete.png") } }; MenuItem miAddDrop = new MenuItem { Header = "Add", Icon = new Image { Source = (BitmapSource)ApplicationManager.PreloadResourceImage("add.png") } }; _lv.ContextMenu.Items.Add(miSelect); _lv.ContextMenu.Items.Add(miEditDrop); _lv.ContextMenu.Items.Add(miRemoveDrop); _lv.ContextMenu.Items.Add(miAddDrop); dp.AddResetField(_lv); miSelect.Click += new RoutedEventHandler(_miSelect_Click); miEditDrop.Click += new RoutedEventHandler(_miEditDrop_Click); miRemoveDrop.Click += new RoutedEventHandler(_miRemoveDrop_Click); miAddDrop.Click += new RoutedEventHandler(_miAddDrop_Click); dp.AddUpdateAction(new Action <ReadableTuple <TKey> >(delegate(ReadableTuple <TKey> item) { Dictionary <int, ReadableTuple <int> > groups = (Dictionary <int, ReadableTuple <int> >)item.GetRawValue(1); if (groups == null) { groups = new Dictionary <int, ReadableTuple <int> >(); item.SetRawValue(1, groups); } Table <int, ReadableTuple <int> > btable = ((GenericDatabase)tab.Database).GetMetaTable <int>(ServerDbs.Items); if (groups.Count == 0) { _lv.ItemsSource = new RangeObservableCollection <ItemView>(); return; } List <ItemView> result = new List <ItemView>(); try { int chances = groups.Where(p => p.Key != 0).Sum(p => p.Value.GetValue <int>(ServerItemGroupSubAttributes.Rate)); result.AddRange(groups.Select(keypair => new ItemView(btable, groups, keypair.Key, chances)).OrderBy(p => p, Extensions.BindDefaultSearch <ItemView>(_lv, "ID"))); } catch { } _lv.ItemsSource = new RangeObservableCollection <ItemView>(result); })); _dp = new DisplayableProperty <TKey, ReadableTuple <TKey> >(); int line = 0; Grid subGrid = GTabsMaker.PrintGrid(ref line, 2, 1, 1, new SpecifiedIndexProvider(new int[] { //ServerItemGroupSubAttributes.Id.Index, -1, ServerItemGroupSubAttributes.Rate.Index, -1, ServerItemGroupSubAttributes.Amount.Index, -1, ServerItemGroupSubAttributes.Random.Index, -1, ServerItemGroupSubAttributes.IsAnnounced.Index, -1, ServerItemGroupSubAttributes.Duration.Index, -1, ServerItemGroupSubAttributes.IsNamed.Index, -1, ServerItemGroupSubAttributes.IsBound.Index, -1 }), -1, 0, -1, -1, _dp, ServerItemGroupSubAttributes.AttributeList); subGrid.VerticalAlignment = VerticalAlignment.Top; grid.Children.Add(label); grid.Children.Add(_lv); tab.PropertiesGrid.RowDefinitions.Clear(); tab.PropertiesGrid.RowDefinitions.Add(new RowDefinition()); tab.PropertiesGrid.ColumnDefinitions.Clear(); tab.PropertiesGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(340) }); tab.PropertiesGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(10) }); tab.PropertiesGrid.ColumnDefinitions.Add(new ColumnDefinition()); tab.PropertiesGrid.Children.Add(grid); _dp.Deploy(_tab, null, true); foreach (var update in _dp.Updates) { Tuple <DbAttribute, FrameworkElement> x = update; if (x.Item1.DataType == typeof(int)) { TextBox element = (TextBox)x.Item2; _dp.AddUpdateAction(new Action <ReadableTuple <TKey> >(item => element.Dispatch( delegate { Debug.Ignore(() => element.Text = item.GetValue <int>(x.Item1).ToString(CultureInfo.InvariantCulture)); element.UndoLimit = 0; element.UndoLimit = int.MaxValue; }))); element.TextChanged += delegate { if (tab.ItemsEventsDisabled) { return; } try { if (tab.List.SelectedItem != null && _lv.SelectedItem != null) { _setSelectedItem(x.Item1, element.Text); } } catch (Exception err) { ErrorHandler.HandleException(err); } }; } else if (x.Item1.DataType == typeof(bool)) { CheckBox element = (CheckBox)x.Item2; _dp.AddUpdateAction(new Action <ReadableTuple <TKey> >(item => element.Dispatch(p => Debug.Ignore(() => p.IsChecked = item.GetValue <bool>(x.Item1))))); element.Checked += delegate { if (tab.ItemsEventsDisabled) { return; } try { if (tab.List.SelectedItem != null && _lv.SelectedItem != null) { _setSelectedItem(x.Item1, true); } } catch (Exception err) { ErrorHandler.HandleException(err); } }; element.Unchecked += delegate { if (tab.ItemsEventsDisabled) { return; } try { if (tab.List.SelectedItem != null && _lv.SelectedItem != null) { _setSelectedItem(x.Item1, false); } } catch (Exception err) { ErrorHandler.HandleException(err); } }; } else if (x.Item1.DataType == typeof(string)) { TextBox element = (TextBox)x.Item2; _dp.AddUpdateAction(new Action <ReadableTuple <TKey> >(item => element.Dispatch( delegate { try { string val = item.GetValue <string>(x.Item1); if (val == element.Text) { return; } element.Text = item.GetValue <string>(x.Item1); element.UndoLimit = 0; element.UndoLimit = int.MaxValue; } catch { } }))); element.TextChanged += delegate { if (tab.ItemsEventsDisabled) { return; } _validateUndo(tab, element.Text, x.Item1); if (ReferenceEquals(x.Item1, ServerItemGroupSubAttributes.Rate)) { ((RangeObservableCollection <ItemView>)_lv.ItemsSource).ToList().ForEach(p => p.VisualUpdate()); } }; } } }
private void Save(string path, bool xml) { listMaker1.AlphaSortList(); listMaker1.BeginUpdate(); try { int noA = listMaker1.Count; int roundlimit = Convert.ToInt32(numSplitAmount.Value / 2); if ((noA % numSplitAmount.Value) <= roundlimit) { noA += roundlimit; } int noGroups = Convert.ToInt32(Math.Round(noA / numSplitAmount.Value)); int baseIndex = 0; int splitValue = (int)numSplitAmount.Value; var articles = listMaker1.GetArticleList(); if (xml) { string pathPrefix = path.Replace(".xml", " {0}.xml"); for (int i = 1; i <= noGroups; i++) { _p.List.ArticleList = articles.GetRange(baseIndex, Math.Min(splitValue, articles.Count)); baseIndex += splitValue; UserPrefs.SavePrefs(_p, string.Format(pathPrefix, i)); } MessageBox.Show("Lists Saved to AWB Settings Files"); } else { string pathPrefix = path.Replace(".txt", " {0}.txt"); for (int i = 1; i <= noGroups; i++) { StringBuilder strList = new StringBuilder(); foreach (Article a in articles.GetRange(baseIndex, Math.Min(splitValue, articles.Count))) { strList.AppendLine(a.ToString()); } Tools.WriteTextFileAbsolutePath(strList.ToString().TrimEnd(), string.Format(pathPrefix, i), false); baseIndex += splitValue; } MessageBox.Show("Lists saved to text files"); } listMaker1.Clear(); } catch (IOException ex) { MessageBox.Show(ex.Message, "Save error", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception ex) { ErrorHandler.Handle(ex); } listMaker1.EndUpdate(); }
private void Init() { _mediaPlayer?.Dispose(); _videoFormat = VideoFormat; _lockCB = LockVideo; _unlockCB = UnlockVideo; _displayCB = DisplayVideo; _cleanupVideoCB = CleanupVideo; _audioSetup = AudioSetup; _processAudio = ProcessAudio; _cleanupAudio = CleanupAudio; _pauseAudio = PauseAudio; _resumeAudio = ResumeAudio; _flushAudio = FlushAudio; _drainAudio = DrainAudio; string overrideURL = null; if (_camera != null) { switch (_camera.Camobject.settings.sourceindex) { case 9: var od = _camera.ONVIFDevice; if (od != null) { var ep = od.StreamEndpoint; if (ep != null) { var u = ep.Uri.Uri; overrideURL = u; } } break; } } FromType ftype = FromType.FromLocation; Seekable = false; try { var p = Path.GetFullPath(overrideURL ?? Source); Seekable = !string.IsNullOrEmpty(p); if (Seekable) { ftype = FromType.FromPath; } } catch (Exception) { Seekable = false; } using (var media = new Media(LibVLC, overrideURL ?? Source, ftype)) { Duration = Time = 0; foreach (var opt in _options) { media.AddOption(opt); } _mediaPlayer = new MediaPlayer(media); if (!_isAudio) { _mediaPlayer.SetVideoFormatCallbacks(_videoFormat, _cleanupVideoCB); _mediaPlayer.SetVideoCallbacks(_lockCB, _unlockCB, _displayCB); } if (!_ignoreAudio) { _mediaPlayer.SetAudioFormatCallback(_audioSetup, _cleanupAudio); _mediaPlayer.SetAudioCallbacks(_processAudio, _pauseAudio, _resumeAudio, _flushAudio, _drainAudio); } _mediaPlayer.EncounteredError += (sender, e) => { ErrorHandler?.Invoke("VLC Error"); _res = ReasonToFinishPlaying.DeviceLost; _quit = true; }; _mediaPlayer.EndReached += (sender, e) => { _res = ReasonToFinishPlaying.DeviceLost; _quit = true; }; _mediaPlayer.Stopped += (sender, e) => { _quit = true; }; } _mediaPlayer.Play(); }
/// <summary> /// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> /// method. /// </summary> /// <param name="loggingEvent">the event to log</param> /// <remarks> /// <para>Writes the event to the system event log using the /// <see cref="ApplicationName"/>.</para> /// /// <para>If the event has an <c>EventID</c> property (see <see cref="LoggingEvent.Properties"/>) /// set then this integer will be used as the event log event id.</para> /// /// <para> /// There is a limit of 32K characters for an event log message /// </para> /// </remarks> override protected void Append(LoggingEvent loggingEvent) { // // Write the resulting string to the event log system // int eventID = m_eventId; // Look for the EventID property object eventIDPropertyObj = loggingEvent.LookupProperty("EventID"); if (eventIDPropertyObj != null) { if (eventIDPropertyObj is int) { eventID = (int)eventIDPropertyObj; } else { string eventIDPropertyString = eventIDPropertyObj as string; if (eventIDPropertyString == null) { eventIDPropertyString = eventIDPropertyObj.ToString(); } if (eventIDPropertyString != null && eventIDPropertyString.Length > 0) { // Read the string property into a number int intVal; if (SystemInfo.TryParse(eventIDPropertyString, out intVal)) { eventID = intVal; } else { ErrorHandler.Error("Unable to parse event ID property [" + eventIDPropertyString + "]."); } } } } short category = m_category; // Look for the Category property object categoryPropertyObj = loggingEvent.LookupProperty("Category"); if (categoryPropertyObj != null) { if (categoryPropertyObj is short) { category = (short)categoryPropertyObj; } else { string categoryPropertyString = categoryPropertyObj as string; if (categoryPropertyString == null) { categoryPropertyString = categoryPropertyObj.ToString(); } if (categoryPropertyString != null && categoryPropertyString.Length > 0) { // Read the string property into a number short shortVal; if (SystemInfo.TryParse(categoryPropertyString, out shortVal)) { category = shortVal; } else { ErrorHandler.Error("Unable to parse event category property [" + categoryPropertyString + "]."); } } } } // Write to the event log try { string eventTxt = RenderLoggingEvent(loggingEvent); // There is a limit of about 32K characters for an event log message if (eventTxt.Length > MAX_EVENTLOG_MESSAGE_SIZE) { eventTxt = eventTxt.Substring(0, MAX_EVENTLOG_MESSAGE_SIZE); } EventLogEntryType entryType = GetEntryType(loggingEvent.Level); using (SecurityContext.Impersonate(this)) { EventLog.WriteEntry(m_applicationName, eventTxt, entryType, eventID, category); } } catch (Exception ex) { ErrorHandler.Error("Unable to write to event log [" + m_logName + "] using source [" + m_applicationName + "]", ex); } }
private SimpleExpressionContext simpleExpression(int _p) { ParserRuleContext _parentctx = Context; int _parentState = State; SimpleExpressionContext _localctx = new SimpleExpressionContext(Context, _parentState); SimpleExpressionContext _prevctx = _localctx; int _startState = 4; EnterRecursionRule(_localctx, 4, RULE_simpleExpression, _p); int _la; try { int _alt; EnterOuterAlt(_localctx, 1); { State = 22; ErrorHandler.Sync(this); switch (Interpreter.AdaptivePredict(TokenStream, 1, Context)) { case 1: { State = 20; variableRef(); } break; case 2: { State = 21; functionRef(); } break; } Context.Stop = TokenStream.LT(-1); State = 32; ErrorHandler.Sync(this); _alt = Interpreter.AdaptivePredict(TokenStream, 3, Context); while (_alt != 2 && _alt != global::Antlr4.Runtime.Atn.ATN.INVALID_ALT_NUMBER) { if (_alt == 1) { if (ParseListeners != null) { TriggerExitRuleEvent(); } _prevctx = _localctx; { State = 30; ErrorHandler.Sync(this); switch (Interpreter.AdaptivePredict(TokenStream, 2, Context)) { case 1: { _localctx = new SimpleExpressionContext(_parentctx, _parentState); PushNewRecursionContext(_localctx, _startState, RULE_simpleExpression); State = 24; if (!(Precpred(Context, 4))) { throw new FailedPredicateException(this, "Precpred(Context, 4)"); } State = 25; _la = TokenStream.LA(1); if (!(_la == PLUS || _la == MINUS)) { ErrorHandler.RecoverInline(this); } else { ErrorHandler.ReportMatch(this); Consume(); } State = 26; simpleExpression(5); } break; case 2: { _localctx = new SimpleExpressionContext(_parentctx, _parentState); PushNewRecursionContext(_localctx, _startState, RULE_simpleExpression); State = 27; if (!(Precpred(Context, 3))) { throw new FailedPredicateException(this, "Precpred(Context, 3)"); } State = 28; _la = TokenStream.LA(1); if (!(_la == MULTIPLY || _la == DIVIDE)) { ErrorHandler.RecoverInline(this); } else { ErrorHandler.ReportMatch(this); Consume(); } State = 29; simpleExpression(4); } break; } } } State = 34; ErrorHandler.Sync(this); _alt = Interpreter.AdaptivePredict(TokenStream, 3, Context); } } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { UnrollRecursionContexts(_parentctx); } return(_localctx); }
/// <summary> /// Initialize the appender based on the options set /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// </remarks> override public void ActivateOptions() { try { base.ActivateOptions(); if (m_securityContext == null) { m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); } bool sourceAlreadyExists = false; string currentLogName = null; using (SecurityContext.Impersonate(this)) { sourceAlreadyExists = EventLog.SourceExists(m_applicationName); if (sourceAlreadyExists) { currentLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName); } } if (sourceAlreadyExists && currentLogName != m_logName) { LogLog.Debug(declaringType, "Changing event source [" + m_applicationName + "] from log [" + currentLogName + "] to log [" + m_logName + "]"); } else if (!sourceAlreadyExists) { LogLog.Debug(declaringType, "Creating event source Source [" + m_applicationName + "] in log " + m_logName + "]"); } string registeredLogName = null; using (SecurityContext.Impersonate(this)) { if (sourceAlreadyExists && currentLogName != m_logName) { // // Re-register this to the current application if the user has changed // the application / logfile association // EventLog.DeleteEventSource(m_applicationName, m_machineName); CreateEventSource(m_applicationName, m_logName, m_machineName); registeredLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName); } else if (!sourceAlreadyExists) { CreateEventSource(m_applicationName, m_logName, m_machineName); registeredLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName); } } m_levelMapping.ActivateOptions(); LogLog.Debug(declaringType, "Source [" + m_applicationName + "] is registered to log [" + registeredLogName + "]"); } catch (System.Security.SecurityException ex) { ErrorHandler.Error("Caught a SecurityException trying to access the EventLog. Most likely the event source " + m_applicationName + " doesn't exist and must be created by a local administrator. Will disable EventLogAppender." + " See http://logging.apache.org/log4net/release/faq.html#trouble-EventLog", ex); Threshold = Level.Off; } }
public Symbolic_string_hContext symbolic_string_h() { Symbolic_string_hContext _localctx = new Symbolic_string_hContext(Context, State); EnterRule(_localctx, 10, RULE_symbolic_string_h); try { State = 112; switch (Interpreter.AdaptivePredict(TokenStream, 4, Context)) { case 1: EnterOuterAlt(_localctx, 1); { State = 68; _localctx.w = word(); _localctx.value = _localctx.w.value; } break; case 2: EnterOuterAlt(_localctx, 2); { State = 71; _localctx.w = word(); State = 72; _localctx.ss = symbolic_string_h(); _localctx.value = PumpingLemma.ParserUtils.join(_localctx.w.value, _localctx.ss.value); } break; case 3: EnterOuterAlt(_localctx, 3); { State = 75; _localctx.w = word(); State = 76; Match(REPEAT); State = 77; _localctx.i = integer(); _localctx.value = PumpingLemma.ParserUtils.repeatLast(_localctx.w.value, _localctx.i.value); } break; case 4: EnterOuterAlt(_localctx, 4); { State = 80; _localctx.w = word(); State = 81; Match(REPEAT); State = 82; _localctx.i = integer(); State = 83; _localctx.ss = symbolic_string_h(); _localctx.value = PumpingLemma.ParserUtils.join( PumpingLemma.ParserUtils.repeatLast(_localctx.w.value, _localctx.i.value), _localctx.ss.value); } break; case 5: EnterOuterAlt(_localctx, 5); { State = 86; Match(LPAREN); State = 87; _localctx.ss = symbolic_string_h(); State = 88; Match(RPAREN); _localctx.value = _localctx.ss.value; } break; case 6: EnterOuterAlt(_localctx, 6); { State = 91; Match(LPAREN); State = 92; _localctx.ss = symbolic_string_h(); State = 93; Match(RPAREN); State = 94; _localctx.ssp = symbolic_string_h(); _localctx.value = PumpingLemma.ParserUtils.join(_localctx.ss.value, _localctx.ssp.value); } break; case 7: EnterOuterAlt(_localctx, 7); { State = 97; Match(LPAREN); State = 98; _localctx.ss = symbolic_string_h(); State = 99; Match(RPAREN); State = 100; Match(REPEAT); State = 101; _localctx.i = integer(); _localctx.value = PumpingLemma.ParserUtils.repeat(_localctx.ss.value, _localctx.i.value); } break; case 8: EnterOuterAlt(_localctx, 8); { State = 104; Match(LPAREN); State = 105; _localctx.ss = symbolic_string_h(); State = 106; Match(RPAREN); State = 107; Match(REPEAT); State = 108; _localctx.i = integer(); State = 109; _localctx.ssp = symbolic_string_h(); _localctx.value = PumpingLemma.ParserUtils.join( PumpingLemma.ParserUtils.repeat(_localctx.ss.value, _localctx.i.value), _localctx.ssp.value); } break; } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return(_localctx); }
/// <returns> /// Information about the current selected Azure web site node in Solution Explorer, or <c>null</c> /// if no node is selected, it's not a website node, or the information could not be retrieved. /// </returns> private AzureWebSiteInfo GetSelectedAzureWebSite() { // Get the current selected node in Solution Explorer. var shell = (IVsUIShell)_serviceProvider.GetService(typeof(SVsUIShell)); var serverExplorerToolWindowGuid = new Guid(ToolWindowGuids.ServerExplorer); IVsWindowFrame serverExplorerFrame; if (ErrorHandler.Failed(shell.FindToolWindow(0, ref serverExplorerToolWindowGuid, out serverExplorerFrame)) || serverExplorerFrame == null) { return(null); } object obj; if (ErrorHandler.Failed(serverExplorerFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocView, out obj))) { return(null); } var serverExplorerHierWnd = obj as IVsUIHierarchyWindow; if (serverExplorerHierWnd == null) { return(null); } IntPtr hierPtr; uint itemid; IVsMultiItemSelect mis; if (ErrorHandler.Failed(serverExplorerHierWnd.GetCurrentSelection(out hierPtr, out itemid, out mis)) || hierPtr == IntPtr.Zero) { return(null); } IVsHierarchy hier; try { hier = (IVsHierarchy)Marshal.GetObjectForIUnknown(hierPtr); } finally { Marshal.Release(hierPtr); } // Get the browse object of that node - this is the object that exposes properties to show in the Properties window. if (ErrorHandler.Failed(hier.GetProperty(itemid, (int)__VSHPROPID.VSHPROPID_SelContainer, out obj))) { return(null); } var selCtr = obj as ISelectionContainer; if (selCtr == null) { return(null); } var objs = new object[1]; if (ErrorHandler.Failed(selCtr.GetObjects((uint)Constants.GETOBJS_SELECTED, 1, objs))) { return(null); } obj = objs[0]; if (obj == null) { return(null); } // We need to find out whether this is an Azure Website object. We can't do a type check because the type of the // browse object is private. We can, however, query for properties with specific names, and we can check the types // of those properties. In particular, WebSiteState is a public enum type that is a part of the Azure Explorer contract, // so we can check for it, and we can be reasonably sure that it is only exposed by website nodes. It seems that // the namespace is subject to change, however, as it was marked internal in VS2015. var statusProp = obj.GetType().GetProperty("Status"); if (statusProp == null || (statusProp.PropertyType.FullName != "Microsoft.VisualStudio.Web.WindowsAzure.Contracts.WebSiteState" && statusProp.PropertyType.FullName != "Microsoft.VisualStudio.Web.Internal.Contracts.WebSiteState") ) { return(null); } // Is the web site running? int status = (int)statusProp.GetValue(obj); if (status != 1) { return(null); } // Get the URI var urlProp = obj.GetType().GetProperty("Url"); if (urlProp == null || urlProp.PropertyType != typeof(string)) { return(null); } Uri uri; if (!Uri.TryCreate((string)urlProp.GetValue(obj), UriKind.Absolute, out uri)) { return(null); } // Get Azure subscription ID var subIdProp = obj.GetType().GetProperty("SubscriptionID"); if (subIdProp == null || subIdProp.PropertyType != typeof(string)) { return(null); } string subscriptionId = (string)subIdProp.GetValue(obj); return(new AzureWebSiteInfo(uri, subscriptionId)); }