/// <summary> /// Prova a mettere il task specificato in coda per l'elaborazione associandolo all'identificativo specificato /// e restituisce true se l'inserimento viene completate con successo. In caso contrario, restituisce false ed /// imposta l'errore esplicativo. /// </summary> /// <param name="tm">i metadati relativi al task di cui è stata richiesta l'elaborazione</param> /// <param name="taskRequestId">l'identificativo univoco della richiesta di elaborazione</param> /// <param name="error">l'eventuale errore impostato qualora si dovessero verificare dei problemi</param> /// <returns>true se non si verificano errori durante l'accodamento del task, altrimenti false</returns> /// <remarks> /// Se il task viene accodato con successo, l'oggetto dedicato all'eventuale errore è impostato al valore null, /// altrimenti al suo interno vengono impostati il codice d'errore e un identificativo univoco sul server, /// oltre ad effettuare il logging dell'errore. /// </remarks> public bool TryQueueTask(TaskMetadata tm, string taskRequestId, out ServiceFault error) { bool result; string taskProcId; if (m_TaskScheduler.InsertUserTask(tm, out taskProcId)) { if (TryInsertIdPair(taskRequestId, taskProcId)) { WriteToLog("TryQueueTask: task scheduled with request id = {0}, processing id = {1}.", taskRequestId, taskProcId); error = null; result = true; } else { string errorDetails = "TryQueueTask: unable to insert task identifiers within table: " + string.Format("request id = {0}, processing id = {1}.", taskRequestId, taskProcId); HandleError(errorDetails, ServiceFaultCode.InternalError, out error); result = false; } } else { HandleError("TryQueueTask: unable to queue a new task.", ServiceFaultCode.InternalError, out error); result = false; } return(result); }
/// <summary> /// Verifica che i metadati del task associato all'identificativo specificato siano esistenti ed eventualmente /// li copia in output e restituisce true. In caso contrario restituisce false ed imposta i metadati in output /// al valore null e un errore esplicativo. /// </summary> /// <param name="taskRequestId">l'identificativo univoco della richiesta di elaborazione</param> /// <param name="tm">la copia dei metadati relativi al task di cui è stata richiesta l'elaborazione</param> /// <param name="error">l'eventuale errore impostato qualora si dovessero verificare dei problemi</param> /// <returns>true se non si verificano errori durante il recupero dei metadati, altrimenti false</returns> /// <remarks> /// Se i metadati richiesti vengono trovati, l'oggetto dedicato all'eventuale errore è impostato al valore null, /// altrimenti al suo interno vengono impostati il codice d'errore e un identificativo univoco sul server, oltre /// ad effettuare il logging dell'errore. /// </remarks> public bool TryGetUserTask(string taskRequestId, out TaskMetadata tm, out ServiceFault error) { string taskProcId; if (!TryGetProcessingId(taskRequestId, out taskProcId)) { string errorDetails = string.Format("TryGetUserTask: unable to find processing id for request id = {0}.", taskRequestId); HandleError(errorDetails, ServiceFaultCode.TaskResultsNotFound, out error); tm = null; return(false); } if (!m_TaskScheduler.TryGetUserTask(taskProcId, out tm)) { string errorDetails = "TryGetUserTask: unable to find task for " + string.Format("request id = {0}, processing id = {1}.", taskRequestId, taskProcId); HandleError(errorDetails, ServiceFaultCode.TaskResultsNotFound, out error); tm = null; return(false); } error = null; return(true); }
/// <summary> /// Permette il trasferimento dei risultati relativi ad un task già elaborato e specificato dal proprio /// identificativo, impostando l'oggetto che dovrà contenere queste informazioni. /// </summary> /// <param name="id">l'identificativo precedentemente associato alla richiesta di elaborazione</param> /// <param name="results">i risultati relativi al task di cui è stata completata l'elaborazione</param> public void GetResults(string id, out TaskResults results) { m_Container.WriteToLog("GetResults: task request id = {0}.", id); ServiceFault fault = null; // Ottiene la copia dei metadati relativi al task. TaskMetadata tm; if (!m_Container.TryGetUserTask(id, out tm, out fault)) { throw new FaultException <ServiceFault>(fault); } m_Container.WriteToLog("GetResults: sending results from file {0}.", tm.PathToTargetFile); // Prepara e invia il risultato. try { results = new TaskResults() { ElapsedTime = m_Container.GetProcessingTime(tm), EncounteredErrors = tm.Errors, Contents = File.ReadAllText(tm.PathToTargetFile) }; } catch (Exception e) { m_Container.HandleError(e.ToString(), ServiceFaultCode.SendTaskResultsFailed, out fault); throw new FaultException <ServiceFault>(fault); } }
/// <summary> /// Prova a generare un identificativo di 16 byte sicuro dal punto di vista crittografico, restituendo true /// se la procedura viene completata correttamente. In caso contrario, viene impostato l'errore esplicativo /// e il metodo restituisce false. /// </summary> /// <param name="id">l'identificativo generato in modo sicuro, oppure null in caso di errore</param> /// <param name="error">l'eventuale errore impostato qualora si dovessero verificare dei problemi</param> /// <returns>true se l'identificativo viene generato correttamente, altrimenti false</returns> /// <remarks> /// Se l'identificativo viene generato correttamente, l'oggetto dedicato all'eventuale errore viene impostato /// al valore null, altrimenti al suo interno vengono impostati il codice d'errore e un identificativo che lo /// identifica univocamente sul server, oltre ad effettuare il logging dell'errore. /// </remarks> public bool TryGetRandomId(out string id, out ServiceFault error) { bool result; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); try { byte[] randomBytes = new byte[16]; rng.GetBytes(randomBytes); Guid guid = new Guid(randomBytes); id = guid.ToString(); error = null; result = true; } catch (CryptographicException e) { HandleError(e.ToString(), ServiceFaultCode.TaskGenerateRequestIdFailed, out error); id = null; result = false; } finally { rng.Dispose(); } return(result); }
/// <summary> /// Initializes the message with a service fault. /// </summary> public _NAME_ResponseMessage(ServiceFault ServiceFault) { this._NAME_Response = new _NAME_Response(); if (ServiceFault != null) { this._NAME_Response.ResponseHeader = ServiceFault.ResponseHeader; } }
protected override void InternalProcessRecord() { ITopologyConfigurationSession session = this.CreateSession(); EhfTargetServerConfig config = Utils.CreateEhfTargetConfig(session, this.ConnectorId, this); using (EhfProvisioningService ehfProvisioningService = new EhfProvisioningService(config)) { Exception ex = null; try { this.InvokeWebService(session, config, ehfProvisioningService); } catch (FaultException <ServiceFault> faultException) { ServiceFault detail = faultException.Detail; if (detail.Id == FaultId.UnableToConnectToDatabase) { ex = new InvalidOperationException("ServiceFault: EHF is unable to connect to its database", faultException); } else { ex = faultException; } } catch (MessageSecurityException ex2) { switch (EhfProvisioningService.DecodeMessageSecurityException(ex2)) { case EhfProvisioningService.MessageSecurityExceptionReason.DatabaseFailure: ex = new InvalidOperationException("MessageSecurityException: EHF is unable to connect to its database", ex2.InnerException); goto IL_A4; case EhfProvisioningService.MessageSecurityExceptionReason.InvalidCredentials: ex = new InvalidOperationException("MessageSecurityException: EHF connector contains invalid credentials", ex2.InnerException); goto IL_A4; } ex = ex2; IL_A4 :; } catch (CommunicationException ex3) { ex = ex3; } catch (TimeoutException ex4) { ex = ex4; } catch (EhfProvisioningService.ContractViolationException ex5) { ex = ex5; } if (ex != null) { base.WriteError(ex, ErrorCategory.InvalidOperation, null); } } }
/// <summary> /// Genera un identificativo univoco per l'errore e lo associa ai dati specificati per poterne effettuare /// il logging tramite il logger di questa applicazione ed imposta in uscita l'errore esplicativo. /// </summary> /// <param name="errorDetails">le informazioni che descrivono l'errore verificatosi</param> /// <param name="errorCode">il codice che descrive l'errore verificatosi</param> /// <param name="error">l'errore esplicativo contenente identificativo e codice descrittivo</param> public void HandleError(string errorDetails, ServiceFaultCode errorCode, out ServiceFault error) { string errorId; HandleError(errorDetails, out errorId); error = new ServiceFault() { Id = errorId, Code = errorCode }; }
/// <summary> /// Permette il trasferimento dei dati relativi al task da elaborare ed imposta una stringa contenente /// l'identificativo univoco associato alla richiesta di elaborazione, necessario per ottenere in seguito /// i risultati dell'elaborazione. /// </summary> /// <param name="data">i dati relativi al task di cui si richiede l'elaborazione</param> /// <param name="id">l'identificativo associato alla richiesta di elaborazione</param> public void SubmitData(TaskData data, out string id) { m_Container.WriteToLog("SubmitData: receiving data, name = {0}.", data.Name); ServiceFault fault = null; // Genera un ID univoco da associare alla richiesta. string taskRequestId; if (!m_Container.TryGetRandomId(out taskRequestId, out fault)) { throw new FaultException <ServiceFault>(fault); } m_Container.WriteToLog("SubmitData: task request id = {0}.", taskRequestId); string tdFilePath = m_Container.GetTaskDataFilePath(); // task data file path // Salva i dati ricevuti sul task da elaborare. if (!m_Container.TrySaveDataToFile(data.Contents, tdFilePath, out fault)) { throw new FaultException <ServiceFault>(fault); } m_Container.WriteToLog("SubmitData: task request id = {0}, file saved to {1}.", taskRequestId, tdFilePath); // Verifica che la risorsa sia disponibile. string className, classVersion; if (!m_Container.TrySearchResource(tdFilePath, out className, out classVersion, out fault)) { throw new FaultException <ServiceFault>(fault); } string trFilePath = m_Container.GetTaskResultsFilePath(); // task results file path // Prepara il task da elaborare. TaskMetadata tm = new TaskMetadata(className, classVersion, tdFilePath, trFilePath); tm.UpdateOnReady(DateTime.Now); // Inserisce il task in coda allo scheduler. if (!m_Container.TryQueueTask(tm, taskRequestId, out fault)) { throw new FaultException <ServiceFault>(fault); } m_Container.WriteToLog("SubmitData: task scheduled with request id = {0}, target file = {1}.", taskRequestId, trFilePath); id = taskRequestId; }
/// <summary> /// Creates a fault message. /// </summary> /// <param name="request">The request.</param> /// <param name="exception">The exception.</param> /// <returns>A fault message.</returns> protected static ServiceFault CreateFault(IServiceRequest request, Exception exception) { DiagnosticsMasks diagnosticsMask = DiagnosticsMasks.ServiceNoInnerStatus; ServiceFault fault = new ServiceFault(); if (request != null) { fault.ResponseHeader.Timestamp = DateTime.UtcNow; fault.ResponseHeader.RequestHandle = request.RequestHeader.RequestHandle; if (request.RequestHeader != null) { diagnosticsMask = (DiagnosticsMasks)request.RequestHeader.ReturnDiagnostics; } } ServiceResult result = null; ServiceResultException sre = exception as ServiceResultException; if (sre != null) { result = new ServiceResult(sre); Utils.Trace( Utils.TraceMasks.Service, "Service Fault Occured. Reason={0}", result); } else { result = new ServiceResult(exception, StatusCodes.BadUnexpectedError); Utils.Trace(exception, "SERVER - Unexpected Service Fault: {0}", exception.Message); } fault.ResponseHeader.ServiceResult = result.Code; StringTable stringTable = new StringTable(); fault.ResponseHeader.ServiceDiagnostics = new DiagnosticInfo( result, diagnosticsMask, true, stringTable); fault.ResponseHeader.StringTable = stringTable.ToArray(); return(fault); }
/// <summary> /// Sends a fault response secured with the symmetric keys. /// </summary> protected void SendServiceFault(ChannelToken token, uint requestId, ServiceResult fault) { Utils.Trace("Channel {0} Request {1}: SendServiceFault()", ChannelId, requestId); BufferCollection buffers = null; try { // construct fault. ServiceFault response = new ServiceFault(); response.ResponseHeader.ServiceResult = fault.Code; StringTable stringTable = new StringTable(); response.ResponseHeader.ServiceDiagnostics = new DiagnosticInfo( fault, DiagnosticsMasks.NoInnerStatus, true, stringTable); response.ResponseHeader.StringTable = stringTable.ToArray(); // the limits should never be exceeded when sending a fault. bool limitsExceeded = false; // secure message. buffers = WriteSymmetricMessage( TcpMessageType.Message, requestId, token, response, false, out limitsExceeded); // send message. BeginWriteMessage(buffers, null); buffers = null; } catch (Exception e) { if (buffers != null) { buffers.Release(BufferManager, "SendServiceFault"); } ForceChannelFault(ServiceResult.Create(e, StatusCodes.BadTcpInternalError, "Unexpected error sending a service fault.")); } }
private object CreateFailedServiceReply(Type serviceReplyType, ServiceFault serviceFault) { if (!serviceReplyType.IsGenericType) { return new ServiceReply().Fail(serviceFault); } object instance = Activator.CreateInstance(serviceReplyType); PropertyInfo successPropInfo = instance.GetType().GetProperty("Success"); successPropInfo.GetSetMethod().Invoke(instance, new object[] { false }); PropertyInfo failureMessagePropInfo = instance.GetType().GetProperty("FailureDetails"); failureMessagePropInfo.GetSetMethod().Invoke(instance, new object[] { serviceFault }); return instance; }
/// <summary> /// Sends a fault response secured with the asymmetric keys. /// </summary> protected void SendServiceFault(uint requestId, ServiceResult fault) { Utils.Trace("Channel {0} Request {1}: SendServiceFault()", ChannelId, requestId); BufferCollection chunksToSend = null; try { // construct fault. ServiceFault response = new ServiceFault(); response.ResponseHeader.ServiceResult = fault.Code; StringTable stringTable = new StringTable(); response.ResponseHeader.ServiceDiagnostics = new DiagnosticInfo( fault, DiagnosticsMasks.NoInnerStatus, true, stringTable); response.ResponseHeader.StringTable = stringTable.ToArray(); // serialize fault. byte[] buffer = BinaryEncoder.EncodeMessage(response, Quotas.MessageContext); // secure message. chunksToSend = WriteAsymmetricMessage( TcpMessageType.Open, requestId, ServerCertificate, ClientCertificate, new ArraySegment <byte>(buffer, 0, buffer.Length)); // write the message to the server. BeginWriteMessage(chunksToSend, null); chunksToSend = null; } catch (Exception e) { if (chunksToSend != null) { chunksToSend.Release(BufferManager, "SendServiceFault"); } ForceChannelFault(ServiceResult.Create(e, StatusCodes.BadTcpInternalError, "Unexpected error sending a service fault.")); } }
/** * Metoda dodaje rekord u bazu \n * ime - ime korisnika koji je resavao sudoku */ public void SnimiRekord (String ime) { long vreme = Vreme (); using (DataBase data = new DataBase ()) { try { data.Open (); data.NoviRekord (ime, brojPokusaja, vreme); } catch (Exception ex) { ServiceFault fault = new ServiceFault ("Greska prilikom snimanja rekorda!"); throw new FaultException<ServiceFault> (fault); } } }
/** * Metoda koja vraca zadatu rec (film) kao listu karaktera */ public char[] Resenje () { char[] result; if (status == EStatusIgre.IGRA_AKTIVNA) status = EStatusIgre.IGRA_ZAVRSENA_PORAZ; result = film.Naziv.ToCharArray (); if(result.Length < 1) { ServiceFault fault = new ServiceFault ("Greska prilikom preuzimanja resenja!"); throw new FaultException<ServiceFault> (fault); } return result; }
public bool HandleException(Exception ex) { if (ex is FaultException <ServiceFault> ) { ServiceFault fault = ((FaultException <ServiceFault>)ex).Detail; switch (fault.FaultType) { case FaultType.General: FireEvent(ex.Message, "Error!"); break; case FaultType.Validation: FireEvent(ex.Message, "Validierung auf dem Server fehlgeschlagen!"); break; case FaultType.Concurrency: FireEvent("Eine andere Person hat diese Daten in der Zwischenzeit bearbeitet.", "Es ist ein Optimistic-Concurrency-Fehler aufgetreten!"); break; } } else if (ex is FaultException <ValidationFault> ) { ValidationFault fault = ((FaultException <ValidationFault>)ex).Detail; StringBuilder builder = new StringBuilder(); builder.AppendLine("Validierung auf dem Server fehlgeschlagen!"); foreach (ValidationDetail result in fault.Details) { builder.AppendLine( string.Format(CultureInfo.CurrentCulture, "{0}: {1}", result.Key, result.Message)); } FireEvent(builder.ToString(), "Error!"); } else if (ex is UIException) { // Exception was already handled. } else { FireEvent(ex.Message, "Error!"); } return(true); }
/// <summary> /// To the web fault exception. /// </summary> /// <param name="ex">The ex.</param> /// <returns></returns> public static WebFaultException <ServiceFault> ToWebFaultException(this Exception ex) { ex.Trace(); var statusCode = ex.GetStatusCode(); var errorMessage = "Unknown Error"; if (!string.IsNullOrWhiteSpace(ex.GetErrorCode())) { errorMessage = Msg.FromRes(ex.GetErrorCode()); } var fault = new ServiceFault { Code = ex.GetErrorCode(), Message = errorMessage }; return(new WebFaultException <ServiceFault>(fault, statusCode)); }
/// <summary> /// Creates a fault message. /// </summary> /// <param name="request">The request.</param> /// <param name="exception">The exception.</param> /// <returns>A fault message.</returns> protected static Exception CreateSoapFault(IServiceRequest request, Exception exception) { ServiceFault fault = CreateFault(request, exception); // get the error from the header. ServiceResult error = fault.ResponseHeader.ServiceResult; if (error == null) { error = ServiceResult.Create(StatusCodes.BadUnexpectedError, "An unknown error occurred."); } // construct the fault code and fault reason. string codeName = StatusCodes.GetBrowseName(error.Code); return(new ServiceResultException((uint)error.StatusCode, codeName, exception)); }
/// <summary cref="System.ServiceModel.Channels.RequestContext.Close(TimeSpan)" /> public override void Close(TimeSpan timeout) { lock (m_lock) { if (m_channel != null) { ServiceFault fault = new ServiceFault(); fault.ResponseHeader.Timestamp = DateTime.UtcNow; fault.ResponseHeader.ServiceResult = StatusCodes.BadInternalError; // Utils.Trace("Reply Faulted: ChannelId={0}, RequestId={1}", this.m_channel.Id, m_requestId); m_channel.SendResponse(m_requestId, fault); m_channel = null; } } }
/// <summary> /// Dispatches an incoming binary encoded request. /// </summary> /// <param name="request">Request.</param> /// <returns>Invoke service response message.</returns> public virtual InvokeServiceResponseMessage InvokeService(InvokeServiceMessage request) { IServiceRequest decodedRequest = null; IServiceResponse response = null; // create context for request and reply. ServiceMessageContext context = MessageContext; try { // check for null. if (request == null || request.InvokeServiceRequest == null) { throw new ServiceResultException(StatusCodes.BadDecodingError, Utils.Format("Null message cannot be processed.")); } // decoding incoming message. decodedRequest = BinaryDecoder.DecodeMessage(request.InvokeServiceRequest, null, context) as IServiceRequest; // invoke service. response = ProcessRequest(decodedRequest); // encode response. InvokeServiceResponseMessage outgoing = new InvokeServiceResponseMessage(); outgoing.InvokeServiceResponse = BinaryEncoder.EncodeMessage(response, context); return(outgoing); } catch (Exception e) { // create fault. ServiceFault fault = CreateFault(decodedRequest, e); // encode fault response. if (context == null) { context = new ServiceMessageContext(); } InvokeServiceResponseMessage outgoing = new InvokeServiceResponseMessage(); outgoing.InvokeServiceResponse = BinaryEncoder.EncodeMessage(fault, context); return(outgoing); } }
/// <summary> /// Prova a salvare in locale su file la stringa in formato XML contenente i dati del task e restituisce /// true se la procedura viene completata correttamente. In caso contrario, restituisce false ed imposta /// l'errore esplicativo. /// </summary> /// <param name="contents">stringa in formato XML contenente i dati del task</param> /// <param name="targetFileName">il percorso completo sul server in cui salvare i dati ricevuti</param> /// <param name="error">l'eventuale errore impostato qualora si dovessero verificare dei problemi</param> /// <returns>true se non si verificano errori durante la scrittura del file, altrimenti false</returns> /// <remarks> /// Se la stringa ricevuta viene scritta con successo, l'oggetto dedicato all'eventuale errore è impostato /// al valore null, altrimenti al suo interno vengono impostati il codice d'errore e un identificativo /// univoco sul server, oltre ad effettuare il logging dell'errore. /// </remarks> public bool TrySaveDataToFile(string contents, string targetFileName, out ServiceFault error) { bool result; try { File.WriteAllText(targetFileName, contents); error = null; result = true; } catch (Exception e) { HandleError(e.ToString(), ServiceFaultCode.ReceiveTaskDataFailed, out error); result = false; } return(result); }
/* * Rekordi */ /** * Metoda vraca listu Rekordas \n * prima dva argumenta \n * br (int) - koji predstavlja broj * rekorda koje treba preuzeti, ako je null (default) * vraca sve rekorde \n * tipSortiranja (ETipSortiranja) - enumeracija * predstavlja tip sortiranja (default - NajboljiUkupno) */ public List<Rekord> PreuzmiRekorde (int? br = null, ETipSortiranja tipSortiranja = ETipSortiranja.NajboljiUkupno) { List<Rekord> rekordi; using (DataBase data = new DataBase ()) { try { data.Open (); rekordi = data.PreuzmiRekorde (br, tipSortiranja); } catch (Exception ex) { ServiceFault fault = new ServiceFault ("Greska prilikom preuzimanja rekorda!"); throw new FaultException<ServiceFault> (fault); } } return rekordi; }
/// <summary> /// Dispatches an incoming binary encoded request. /// </summary> /// <param name="ar">The ar.</param> /// <returns></returns> public virtual InvokeServiceResponseMessage EndInvokeService(IAsyncResult ar) { try { // wait for the response. IServiceResponse response = ProcessRequestAsyncResult.WaitForComplete(ar, false); // encode the repsonse. InvokeServiceResponseMessage outgoing = new InvokeServiceResponseMessage(); outgoing.InvokeServiceResponse = BinaryEncoder.EncodeMessage(response, MessageContext); return(outgoing); } catch (Exception e) { // create fault. ServiceFault fault = CreateFault(ProcessRequestAsyncResult.GetRequest(ar), e); // encode the fault as a response. InvokeServiceResponseMessage outgoing = new InvokeServiceResponseMessage(); outgoing.InvokeServiceResponse = BinaryEncoder.EncodeMessage(fault, MessageContext); return(outgoing); } }
/// <summary> /// Creates a fault message. /// </summary> /// <param name="request">The request.</param> /// <param name="exception">The exception.</param> /// <returns>A fault message.</returns> protected static Exception CreateSoapFault(IServiceRequest request, Exception exception) { ServiceFault fault = CreateFault(request, exception); // get the error from the header. ServiceResult error = fault.ResponseHeader.ServiceResult; if (error == null) { error = ServiceResult.Create(StatusCodes.BadUnexpectedError, "An unknown error occurred."); } // construct the fault code and fault reason. string codeName = StatusCodes.GetBrowseName(error.Code); FaultCode code = null; FaultReason reason = null; if (!LocalizedText.IsNullOrEmpty(error.LocalizedText)) { reason = new FaultReason(new FaultReasonText(Utils.Format("{0}", error.LocalizedText), CultureInfo.InvariantCulture)); } else { reason = new FaultReason(new FaultReasonText(codeName, CultureInfo.InvariantCulture)); } if (!String.IsNullOrEmpty(error.SymbolicId)) { FaultCode subcode = new FaultCode(error.SymbolicId, error.NamespaceUri); code = new FaultCode(codeName, Namespaces.OpcUa, subcode); } else { code = new FaultCode(codeName, Namespaces.OpcUa); } // throw the fault. return(new FaultException <ServiceFault>(fault, reason, code)); }
/// <summary> /// Creates a UA fault message from an exception. /// </summary> protected virtual Exception CreateSoapFault(RequestHeader requestHeader, Exception e) { ServiceFault fault = new ServiceFault(); fault.ResponseHeader = CreateResponseHeader(requestHeader); // specify a code. StatusCodeException sce = e as StatusCodeException; if (sce != null) { fault.ResponseHeader.ServiceResult = new StatusCode(sce.Code); } else { fault.ResponseHeader.ServiceResult = new StatusCode(StatusCodes.BadUnexpectedError); } // return the message for the exception (add it to the string table first and store the index in the diagnostics). if ((requestHeader.ReturnDiagnostics & (uint)DiagnosticsMasks.ServiceLocalizedText) != 0) { fault.ResponseHeader.StringTable.Add(e.Message); fault.ResponseHeader.ServiceDiagnostics.LocalizedText = fault.ResponseHeader.StringTable.Count - 1; } // return the stack trace for the exception. // this is really handy for debugging but is a security risk and never should be done in a production system. if ((requestHeader.ReturnDiagnostics & (uint)DiagnosticsMasks.ServiceAdditionalInfo) != 0) { fault.ResponseHeader.ServiceDiagnostics.AdditionalInfo = e.StackTrace; } // construct the fault code and fault reason. FaultCode code = new FaultCode(StatusCodes.GetBrowseName(fault.ResponseHeader.ServiceResult.Code), Namespaces.OpcUa); FaultReason reason = new FaultReason(e.Message);; // return the fault. return(new FaultException <ServiceFault>(fault, reason, code)); }
/* * Igra */ /** * Metoda koja pokrece igru \n * sve setuje na nulu i snima trenutno * vreme * na serveru */ public int[] PokreniIgru () { brojPokusaja = 0; vremeStart = DateTime.Now; status = EStatusIgre.IGRA_AKTIVNA; List<int> result = new List<int> (); using (DataBase data = new DataBase ()) { int brojFilmova; int rbFilma; Random random = new Random (); try { data.Open (); brojFilmova = data.BrojFilmova (); rbFilma = random.Next (brojFilmova); film = data.PreuzmiFilm (rbFilma); nazivFilma = film.Naziv.ToUpper ().ToCharArray (); nazivFilma = ZamenaKraktera (nazivFilma); } catch (Exception ex) { ServiceFault fault = new ServiceFault ("Greska prilikom preuzimanja filma iz baze!"); throw new FaultException<ServiceFault> (fault); } } result.Add (nazivFilma.Length); for (int i = 0; i < nazivFilma.Length; i++) if (nazivFilma [i] == ' ') { result.Add (i); nazivFilma [i] = '\0'; } return result.ToArray (); }
public static void ShowErrorMessageDialogue(Exception ex) { if (ex is UserFacingException) { ShowErrorMessageDialogue((UserFacingException)ex); } else if (ex is FaultException <ValidationFault> ) { ShowErrorMessageDialogue(ErrorCode.ValidationFault); } else if (ex is FaultException <ServiceFault> ) { FaultException <ServiceFault> fex = (FaultException <ServiceFault>)ex; ServiceFault sex = fex.Detail; ShowErrorMessageDialogue(sex.ErrorCode.ToString(), sex.ErrorMessage); } else if (ex is FaultException <VersionFault> ) { ShowErrorMessageDialogue(ErrorCode.VersionIncorrectFaultReasonMessage); } else if (ex is FaultException) { ShowErrorMessageDialogue(ErrorCode.ServiceFault); } else if (ex is CommunicationException) { ShowErrorMessageDialogue(ErrorCode.ServerUnavailableMsg); } else if (ex is TimeoutException) { ShowErrorMessageDialogue(ErrorCode.ServerTimedOutMsg); } else { ShowErrorMessageDialogue(ErrorCode.UnexpectedErrorMsg); } }
void OnServiceFault(ServiceFault message) { _log.ErrorFormat("Fault on {0}: {1}", message.ServiceName, message.ToLogString()); if (message.ServiceName == AppDomain.CurrentDomain.FriendlyName) { // we caught an unhandled exception, so what should we do? How about restarting all the services? if (_stopping == false) { _actorCache.Each((name, x) => x.Send(new RestartService(name))); } } if (_stopping) { if (_actorCache.Has(message.ServiceName)) { _actorCache[message.ServiceName].Send(new UnloadService(message.ServiceName)); } } EventChannel.Send(message); }
/// <summary> /// Carica il file specificato contenente i dati da elaborare e prova ad estrarre le informazioni relative /// alla risorsa richiesta per la loro elaborazione. In caso di successo, verifica se tale risorsa è stata /// attivata su questo server e in caso affermativo restituisce true e imposta il nome e la versione della /// risorsa (il nome completo e la versione della classe che implementa la risorsa di elaborazione ). /// In caso contrario, se si verificano errori durante la lettura dei dati, oppure se la risorsa richiesta /// non è stata abilitata su questo server, il metodo restituisce false ed imposta un errore esplicativo. /// </summary> /// <param name="tdFilePath">il percorso completo del file da cui estrarre le informazioni</param> /// <param name="name">nome completo della classe che implementa la risorsa di elaborazione</param> /// <param name="version">versione della classe che implementa la risorsa di elaborazione</param> /// <param name="error">l'eventuale errore impostato qualora si dovessero verificare dei problemi</param> /// <returns>true se non si verificano errori durante la lettura del file, altrimenti false</returns> /// <remarks> /// Se le informazioni vengono lette correttamente, l'oggetto dedicato all'eventuale errore è impostato /// al valore null, altrimenti al suo interno vengono impostati il codice d'errore e un identificativo /// univoco sul server, oltre ad effettuare il logging dell'errore. /// </remarks> public bool TrySearchResource(string tdFilePath, out string name, out string version, out ServiceFault error) { bool result; try { XmlDocument document = new XmlDocument(); document.Load(tdFilePath); XmlElement root = document.DocumentElement; XmlNodeList nodeList = root.SelectNodes("/task/component[@className and @classVersion]"); XmlNode node = (nodeList.Count == 1 ? nodeList[0] : null); name = (node != null ? node.Attributes["className"].Value : string.Empty); version = (node != null ? node.Attributes["classVersion"].Value : string.Empty); if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(version)) { HandleError("TrySearchResource: unable to find the information about the requested processing resource.", ServiceFaultCode.TaskDataFormatError, out error); name = version = null; result = false; } else if (IsResourceEnabled(name, version)) { error = null; result = true; } else { HandleError("TrySearchResource: the requested processing resource has not been enabled.", ServiceFaultCode.ComponentUnavailable, out error); name = version = null; result = false; } } catch (Exception e) { HandleError(e.ToString(), ServiceFaultCode.InternalError, out error); name = version = null; result = false; } return result; }
/// <summary> /// Initializes the message with a service fault. /// </summary> public ModifySubscriptionResponseMessage(ServiceFault ServiceFault) { this.ModifySubscriptionResponse = new ModifySubscriptionResponse(); if (ServiceFault != null) { this.ModifySubscriptionResponse.ResponseHeader = ServiceFault.ResponseHeader; } }
/// <summary> /// Initializes the message with a service fault. /// </summary> public HistoryUpdateResponseMessage(ServiceFault ServiceFault) { this.HistoryUpdateResponse = new HistoryUpdateResponse(); if (ServiceFault != null) { this.HistoryUpdateResponse.ResponseHeader = ServiceFault.ResponseHeader; } }
/// <summary> /// Initializes the message with a service fault. /// </summary> public TransferSubscriptionsResponseMessage(ServiceFault ServiceFault) { this.TransferSubscriptionsResponse = new TransferSubscriptionsResponse(); if (ServiceFault != null) { this.TransferSubscriptionsResponse.ResponseHeader = ServiceFault.ResponseHeader; } }
private EhfCompanyRecord CreateEhfCompanyRecord(SyncedPerimeterConfig perimeterConfig) { EhfCompanyRecord result = null; Exception ex = null; try { Company company = null; int companyId; if (!this.ehfService.TryGetCompanyByGuid(perimeterConfig.Guid, out company) && int.TryParse(perimeterConfig.PerimeterOrgId, out companyId)) { company = this.ehfService.GetCompany(companyId); } if (company != null) { Domain[] allDomains = this.ehfService.GetAllDomains(company.CompanyId); result = new EhfCompanyRecord(company, allDomains); } } catch (FaultException <ServiceFault> faultException) { ServiceFault detail = faultException.Detail; if (detail.Id == FaultId.UnableToConnectToDatabase) { ex = new InvalidOperationException("ServiceFault: EHF is unable to connect to its database", faultException); } else { if (detail.Id == FaultId.CompanyDoesNotExist) { return(null); } ex = faultException; } } catch (MessageSecurityException ex2) { switch (EhfProvisioningService.DecodeMessageSecurityException(ex2)) { case EhfProvisioningService.MessageSecurityExceptionReason.DatabaseFailure: ex = new InvalidOperationException("MessageSecurityException: EHF is unable to connect to its database", ex2.InnerException); goto IL_E6; case EhfProvisioningService.MessageSecurityExceptionReason.InvalidCredentials: ex = new InvalidOperationException("MessageSecurityException: EHF connector contains invalid credentials", ex2.InnerException); goto IL_E6; } ex = ex2; IL_E6 :; } catch (CommunicationException ex3) { ex = ex3; } catch (TimeoutException ex4) { ex = ex4; } catch (EhfProvisioningService.ContractViolationException ex5) { ex = ex5; } if (ex != null) { base.WriteError(ex, ErrorCategory.InvalidOperation, null); } return(result); }
/// <summary> /// Initializes the message with a service fault. /// </summary> public ModifyMonitoredItemsResponseMessage(ServiceFault ServiceFault) { this.ModifyMonitoredItemsResponse = new ModifyMonitoredItemsResponse(); if (ServiceFault != null) { this.ModifyMonitoredItemsResponse.ResponseHeader = ServiceFault.ResponseHeader; } }
/// <summary> /// Initializes the message with a service fault. /// </summary> public CreateSubscriptionResponseMessage(ServiceFault ServiceFault) { this.CreateSubscriptionResponse = new CreateSubscriptionResponse(); if (ServiceFault != null) { this.CreateSubscriptionResponse.ResponseHeader = ServiceFault.ResponseHeader; } }
/// <summary> /// Initializes the message with a service fault. /// </summary> public DeleteMonitoredItemsResponseMessage(ServiceFault ServiceFault) { this.DeleteMonitoredItemsResponse = new DeleteMonitoredItemsResponse(); if (ServiceFault != null) { this.DeleteMonitoredItemsResponse.ResponseHeader = ServiceFault.ResponseHeader; } }
/// <summary> /// Initializes the message with a service fault. /// </summary> public UnregisterNodesResponseMessage(ServiceFault ServiceFault) { this.UnregisterNodesResponse = new UnregisterNodesResponse(); if (ServiceFault != null) { this.UnregisterNodesResponse.ResponseHeader = ServiceFault.ResponseHeader; } }
/// <summary> /// Carica il file specificato contenente i dati da elaborare e prova ad estrarre le informazioni relative /// alla risorsa richiesta per la loro elaborazione. In caso di successo, verifica se tale risorsa è stata /// attivata su questo server e in caso affermativo restituisce true e imposta il nome e la versione della /// risorsa (il nome completo e la versione della classe che implementa la risorsa di elaborazione ). /// In caso contrario, se si verificano errori durante la lettura dei dati, oppure se la risorsa richiesta /// non è stata abilitata su questo server, il metodo restituisce false ed imposta un errore esplicativo. /// </summary> /// <param name="tdFilePath">il percorso completo del file da cui estrarre le informazioni</param> /// <param name="name">nome completo della classe che implementa la risorsa di elaborazione</param> /// <param name="version">versione della classe che implementa la risorsa di elaborazione</param> /// <param name="error">l'eventuale errore impostato qualora si dovessero verificare dei problemi</param> /// <returns>true se non si verificano errori durante la lettura del file, altrimenti false</returns> /// <remarks> /// Se le informazioni vengono lette correttamente, l'oggetto dedicato all'eventuale errore è impostato /// al valore null, altrimenti al suo interno vengono impostati il codice d'errore e un identificativo /// univoco sul server, oltre ad effettuare il logging dell'errore. /// </remarks> public bool TrySearchResource(string tdFilePath, out string name, out string version, out ServiceFault error) { bool result; try { XmlDocument document = new XmlDocument(); document.Load(tdFilePath); XmlElement root = document.DocumentElement; XmlNodeList nodeList = root.SelectNodes("/task/component[@className and @classVersion]"); XmlNode node = (nodeList.Count == 1 ? nodeList[0] : null); name = (node != null ? node.Attributes["className"].Value : string.Empty); version = (node != null ? node.Attributes["classVersion"].Value : string.Empty); if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(version)) { HandleError("TrySearchResource: unable to find the information about the requested processing resource.", ServiceFaultCode.TaskDataFormatError, out error); name = version = null; result = false; } else if (IsResourceEnabled(name, version)) { error = null; result = true; } else { HandleError("TrySearchResource: the requested processing resource has not been enabled.", ServiceFaultCode.ComponentUnavailable, out error); name = version = null; result = false; } } catch (Exception e) { HandleError(e.ToString(), ServiceFaultCode.InternalError, out error); name = version = null; result = false; } return(result); }
/// <summary> /// Creates a UA fault message from an exception. /// </summary> protected virtual Exception CreateSoapFault(RequestHeader requestHeader, Exception e) { ServiceFault fault = new ServiceFault(); fault.ResponseHeader = CreateResponseHeader(requestHeader); // specify a code. StatusCodeException sce = e as StatusCodeException; if (sce != null) { fault.ResponseHeader.ServiceResult = new StatusCode(sce.Code); } else { fault.ResponseHeader.ServiceResult = new StatusCode(StatusCodes.BadUnexpectedError); } // return the message for the exception (add it to the string table first and store the index in the diagnostics). if ((requestHeader.ReturnDiagnostics & (uint)DiagnosticsMasks.ServiceLocalizedText) != 0) { fault.ResponseHeader.StringTable.Add(e.Message); fault.ResponseHeader.ServiceDiagnostics.LocalizedText = fault.ResponseHeader.StringTable.Count-1; } // return the stack trace for the exception. // this is really handy for debugging but is a security risk and never should be done in a production system. if ((requestHeader.ReturnDiagnostics & (uint)DiagnosticsMasks.ServiceAdditionalInfo) != 0) { fault.ResponseHeader.ServiceDiagnostics.AdditionalInfo = e.StackTrace; } // construct the fault code and fault reason. FaultCode code = new FaultCode(StatusCodes.GetBrowseName(fault.ResponseHeader.ServiceResult.Code), Namespaces.OpcUa); FaultReason reason = new FaultReason(e.Message);; // return the fault. return new FaultException<ServiceFault>(fault, reason, code); }
/// <summary> /// Initializes the message with a service fault. /// </summary> public SetPublishingModeResponseMessage(ServiceFault ServiceFault) { this.SetPublishingModeResponse = new SetPublishingModeResponse(); if (ServiceFault != null) { this.SetPublishingModeResponse.ResponseHeader = ServiceFault.ResponseHeader; } }
/// <summary> /// Sends a fault response secured with the asymmetric keys. /// </summary> private void SendServiceFault(uint requestId, ServiceResult fault) { // Utils.Trace("Channel {0} Request {1}: SendServiceFault()", ChannelId, requestId); BufferCollection chunksToSend = null; try { // construct fault. ServiceFault response = new ServiceFault(); response.ResponseHeader.ServiceResult = fault.Code; StringTable stringTable = new StringTable(); response.ResponseHeader.ServiceDiagnostics = new DiagnosticInfo( fault, DiagnosticsMasks.NoInnerStatus, true, stringTable); response.ResponseHeader.StringTable = stringTable.ToArray(); // serialize fault. byte[] buffer = BinaryEncoder.EncodeMessage(response, Quotas.MessageContext); // secure message. chunksToSend = WriteAsymmetricMessage( TcpMessageType.Open, requestId, ServerCertificate, ClientCertificate, new ArraySegment<byte>(buffer, 0, buffer.Length)); // write the message to the server. BeginWriteMessage(chunksToSend, Int32.MaxValue, null); chunksToSend = null; } catch (Exception e) { if (chunksToSend != null) { chunksToSend.Release(BufferManager, "SendServiceFault"); } ForceChannelFault(ServiceResult.Create(e, StatusCodes.BadTcpInternalError, "Unexpected error sending a service fault.")); } }
/// <summary> /// Initializes the message with a service fault. /// </summary> public QueryNextResponseMessage(ServiceFault ServiceFault) { this.QueryNextResponse = new QueryNextResponse(); if (ServiceFault != null) { this.QueryNextResponse.ResponseHeader = ServiceFault.ResponseHeader; } }
/// <summary> /// Initializes the message with a service fault. /// </summary> public DeleteSubscriptionsResponseMessage(ServiceFault ServiceFault) { this.DeleteSubscriptionsResponse = new DeleteSubscriptionsResponse(); if (ServiceFault != null) { this.DeleteSubscriptionsResponse.ResponseHeader = ServiceFault.ResponseHeader; } }
protected void InvokeProvisioningService(string operationName, EhfSynchronizer.ProvisioningServiceCall serviceCall, int numberOfEntries) { ExEventLog.EventTuple eventTuple = default(ExEventLog.EventTuple); Exception ex = null; EhfProvisioningService.MessageSecurityExceptionReason messageSecurityExceptionReason = EhfProvisioningService.MessageSecurityExceptionReason.Other; this.DiagSession.Tracer.TraceDebug <string>((long)this.DiagSession.GetHashCode(), "Executing EHF provisioning operation {0}", operationName); int transientExceptionRetryCount = this.Config.EhfSyncAppConfig.TransientExceptionRetryCount; bool flag = true; do { if (ex != null) { this.LogAndTraceException(operationName, ex, messageSecurityExceptionReason.ToString(), transientExceptionRetryCount + 1); } try { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); serviceCall(); stopwatch.Stop(); this.ehfConnection.PerfCounterHandler.OnOperationSuccessfullyCompleted(operationName, stopwatch.ElapsedMilliseconds, numberOfEntries); this.DiagSession.LogAndTraceInfo(EdgeSyncLoggingLevel.High, "Successfully executed EHF provisioning operation {0}", new object[] { operationName }); return; } catch (FaultException <ServiceFault> faultException) { ex = faultException; ServiceFault detail = faultException.Detail; if (detail.Id == FaultId.UnableToConnectToDatabase) { eventTuple = EdgeSyncEventLogConstants.Tuple_EhfTransientFailure; this.ehfConnection.PerfCounterHandler.OnOperationTransientFailure(operationName); } else { eventTuple = EdgeSyncEventLogConstants.Tuple_EhfCommunicationFailure; this.ehfConnection.PerfCounterHandler.OnOperationCommunicationFailure(operationName); } } catch (MessageSecurityException ex2) { messageSecurityExceptionReason = EhfProvisioningService.DecodeMessageSecurityException(ex2); switch (messageSecurityExceptionReason) { case EhfProvisioningService.MessageSecurityExceptionReason.DatabaseFailure: ex = ex2.InnerException; eventTuple = EdgeSyncEventLogConstants.Tuple_EhfTransientFailure; this.ehfConnection.PerfCounterHandler.OnOperationTransientFailure(operationName); goto IL_186; case EhfProvisioningService.MessageSecurityExceptionReason.InvalidCredentials: ex = ex2.InnerException; eventTuple = EdgeSyncEventLogConstants.Tuple_EhfInvalidCredentials; this.ehfConnection.PerfCounterHandler.OnOperationInvalidCredentialsFailure(operationName); flag = false; goto IL_186; } ex = ex2; eventTuple = EdgeSyncEventLogConstants.Tuple_EhfCommunicationFailure; this.ehfConnection.PerfCounterHandler.OnOperationCommunicationFailure(operationName); IL_186 :; } catch (CommunicationException ex3) { ex = ex3; eventTuple = EdgeSyncEventLogConstants.Tuple_EhfCommunicationFailure; this.ehfConnection.PerfCounterHandler.OnOperationCommunicationFailure(operationName); } catch (TimeoutException ex4) { ex = ex4; eventTuple = EdgeSyncEventLogConstants.Tuple_EhfOperationTimedOut; this.ehfConnection.PerfCounterHandler.OnOperationTimeoutFailure(operationName); flag = false; } catch (EhfProvisioningService.ContractViolationException ex5) { ex = ex5; eventTuple = EdgeSyncEventLogConstants.Tuple_EhfServiceContractViolation; this.ehfConnection.PerfCounterHandler.OnOperationContractViolationFailure(operationName); flag = false; } }while (flag && transientExceptionRetryCount-- > 0); if (ex != null) { this.EventLogAndTraceException(operationName, eventTuple, ex, messageSecurityExceptionReason.ToString()); this.ehfConnection.AbortSyncCycle(ex); } }
/// <summary> /// Initializes the message with a service fault. /// </summary> public WriteResponseMessage(ServiceFault ServiceFault) { this.WriteResponse = new WriteResponse(); if (ServiceFault != null) { this.WriteResponse.ResponseHeader = ServiceFault.ResponseHeader; } }
/// <summary> /// Initializes the message with a service fault. /// </summary> public GetEndpointsResponseMessage(ServiceFault ServiceFault) { this.GetEndpointsResponse = new GetEndpointsResponse(); if (ServiceFault != null) { this.GetEndpointsResponse.ResponseHeader = ServiceFault.ResponseHeader; } }
/// <summary> /// Prova a generare un identificativo di 16 byte sicuro dal punto di vista crittografico, restituendo true /// se la procedura viene completata correttamente. In caso contrario, viene impostato l'errore esplicativo /// e il metodo restituisce false. /// </summary> /// <param name="id">l'identificativo generato in modo sicuro, oppure null in caso di errore</param> /// <param name="error">l'eventuale errore impostato qualora si dovessero verificare dei problemi</param> /// <returns>true se l'identificativo viene generato correttamente, altrimenti false</returns> /// <remarks> /// Se l'identificativo viene generato correttamente, l'oggetto dedicato all'eventuale errore viene impostato /// al valore null, altrimenti al suo interno vengono impostati il codice d'errore e un identificativo che lo /// identifica univocamente sul server, oltre ad effettuare il logging dell'errore. /// </remarks> public bool TryGetRandomId(out string id, out ServiceFault error) { bool result; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); try { byte[] randomBytes = new byte[16]; rng.GetBytes(randomBytes); Guid guid = new Guid(randomBytes); id = guid.ToString(); error = null; result = true; } catch (CryptographicException e) { HandleError(e.ToString(), ServiceFaultCode.TaskGenerateRequestIdFailed, out error); id = null; result = false; } finally { rng.Dispose(); } return result; }
/// <summary> /// Initializes the message with a service fault. /// </summary> public SetTriggeringResponseMessage(ServiceFault ServiceFault) { this.SetTriggeringResponse = new SetTriggeringResponse(); if (ServiceFault != null) { this.SetTriggeringResponse.ResponseHeader = ServiceFault.ResponseHeader; } }
/// <summary> /// Verifica che i metadati del task associato all'identificativo specificato siano esistenti ed eventualmente /// li copia in output e restituisce true. In caso contrario restituisce false ed imposta i metadati in output /// al valore null e un errore esplicativo. /// </summary> /// <param name="taskRequestId">l'identificativo univoco della richiesta di elaborazione</param> /// <param name="tm">la copia dei metadati relativi al task di cui è stata richiesta l'elaborazione</param> /// <param name="error">l'eventuale errore impostato qualora si dovessero verificare dei problemi</param> /// <returns>true se non si verificano errori durante il recupero dei metadati, altrimenti false</returns> /// <remarks> /// Se i metadati richiesti vengono trovati, l'oggetto dedicato all'eventuale errore è impostato al valore null, /// altrimenti al suo interno vengono impostati il codice d'errore e un identificativo univoco sul server, oltre /// ad effettuare il logging dell'errore. /// </remarks> public bool TryGetUserTask(string taskRequestId, out TaskMetadata tm, out ServiceFault error) { string taskProcId; if (!TryGetProcessingId(taskRequestId, out taskProcId)) { string errorDetails = string.Format("TryGetUserTask: unable to find processing id for request id = {0}.", taskRequestId); HandleError(errorDetails, ServiceFaultCode.TaskResultsNotFound, out error); tm = null; return false; } if (!m_TaskScheduler.TryGetUserTask(taskProcId, out tm)) { string errorDetails = "TryGetUserTask: unable to find task for " + string.Format("request id = {0}, processing id = {1}.", taskRequestId, taskProcId); HandleError(errorDetails, ServiceFaultCode.TaskResultsNotFound, out error); tm = null; return false; } error = null; return true; }
/// <summary cref="IClientMessageInspector.AfterReceiveReply" /> public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState) { // check for fault. if (reply.IsFault) { return; } // parse request parameters. object[] parameters = correlationState as object[]; if (parameters == null || parameters.Length != 3) { throw new InvalidOperationException("Cannot decode request because the IClientMessageInspector not configured properly."); } // extract request parameters. MessageVersion messageVersion = parameters[0] as MessageVersion; string action = parameters[1] as string; IServiceMessage request = parameters[2] as IServiceMessage; object encodeable = null; if (!reply.Properties.TryGetValue(MessageProperties.UnencodedBody, out encodeable)) { // extract binary encoded response from body. XmlDictionaryReader reader = reply.GetReaderAtBodyContents(); reader.MoveToStartElement("InvokeServiceResponse", Namespaces.OpcUaXsd); byte[] response = reader.ReadElementContentAsBase64(); // decode body. try { encodeable = BinaryDecoder.DecodeMessage(response, null, m_messageContext); } catch (Exception e) { ServiceResult error = ServiceResult.Create( e, StatusCodes.BadDecodingError, "Could not decoding incoming response message."); ServiceFault fault = new ServiceFault(); fault.ResponseHeader.RequestHandle = request.GetRequest().RequestHeader.RequestHandle; fault.ResponseHeader.Timestamp = DateTime.UtcNow; fault.ResponseHeader.ServiceResult = error.Code; StringTable stringTable = new StringTable(); fault.ResponseHeader.ServiceDiagnostics = new DiagnosticInfo( error, DiagnosticsMasks.NoInnerStatus, true, stringTable); fault.ResponseHeader.StringTable = stringTable.ToArray(); encodeable = fault; } } object unencodedBody = request.CreateResponse((IServiceResponse)encodeable); // create the unencoded reply message. Message unencodedReply = Message.CreateMessage( messageVersion, action + "Response", unencodedBody); unencodedReply.Headers.MessageId = reply.Headers.MessageId; unencodedReply.Headers.RelatesTo = reply.Headers.RelatesTo; unencodedReply.Properties.Add(MessageProperties.UnencodedBody, unencodedBody); // replace the incoming message. reply = unencodedReply; }
/// <summary> /// Prova a mettere il task specificato in coda per l'elaborazione associandolo all'identificativo specificato /// e restituisce true se l'inserimento viene completate con successo. In caso contrario, restituisce false ed /// imposta l'errore esplicativo. /// </summary> /// <param name="tm">i metadati relativi al task di cui è stata richiesta l'elaborazione</param> /// <param name="taskRequestId">l'identificativo univoco della richiesta di elaborazione</param> /// <param name="error">l'eventuale errore impostato qualora si dovessero verificare dei problemi</param> /// <returns>true se non si verificano errori durante l'accodamento del task, altrimenti false</returns> /// <remarks> /// Se il task viene accodato con successo, l'oggetto dedicato all'eventuale errore è impostato al valore null, /// altrimenti al suo interno vengono impostati il codice d'errore e un identificativo univoco sul server, /// oltre ad effettuare il logging dell'errore. /// </remarks> public bool TryQueueTask(TaskMetadata tm, string taskRequestId, out ServiceFault error) { bool result; string taskProcId; if (m_TaskScheduler.InsertUserTask(tm, out taskProcId)) { if (TryInsertIdPair(taskRequestId, taskProcId)) { WriteToLog("TryQueueTask: task scheduled with request id = {0}, processing id = {1}.", taskRequestId, taskProcId); error = null; result = true; } else { string errorDetails = "TryQueueTask: unable to insert task identifiers within table: " + string.Format("request id = {0}, processing id = {1}.", taskRequestId, taskProcId); HandleError(errorDetails, ServiceFaultCode.InternalError, out error); result = false; } } else { HandleError("TryQueueTask: unable to queue a new task.", ServiceFaultCode.InternalError, out error); result = false; } return result; }
/// <summary> /// Initializes the message with a service fault. /// </summary> public CallResponseMessage(ServiceFault ServiceFault) { this.CallResponse = new CallResponse(); if (ServiceFault != null) { this.CallResponse.ResponseHeader = ServiceFault.ResponseHeader; } }
/// <summary> /// Prova a salvare in locale su file la stringa in formato XML contenente i dati del task e restituisce /// true se la procedura viene completata correttamente. In caso contrario, restituisce false ed imposta /// l'errore esplicativo. /// </summary> /// <param name="contents">stringa in formato XML contenente i dati del task</param> /// <param name="targetFileName">il percorso completo sul server in cui salvare i dati ricevuti</param> /// <param name="error">l'eventuale errore impostato qualora si dovessero verificare dei problemi</param> /// <returns>true se non si verificano errori durante la scrittura del file, altrimenti false</returns> /// <remarks> /// Se la stringa ricevuta viene scritta con successo, l'oggetto dedicato all'eventuale errore è impostato /// al valore null, altrimenti al suo interno vengono impostati il codice d'errore e un identificativo /// univoco sul server, oltre ad effettuare il logging dell'errore. /// </remarks> public bool TrySaveDataToFile(string contents, string targetFileName, out ServiceFault error) { bool result; try { File.WriteAllText(targetFileName, contents); error = null; result = true; } catch (Exception e) { HandleError(e.ToString(), ServiceFaultCode.ReceiveTaskDataFailed, out error); result = false; } return result; }
/// <summary> /// Initializes the message with a service fault. /// </summary> public PublishResponseMessage(ServiceFault ServiceFault) { this.PublishResponse = new PublishResponse(); if (ServiceFault != null) { this.PublishResponse.ResponseHeader = ServiceFault.ResponseHeader; } }
/// <summary> /// Initializes the message with a service fault. /// </summary> public RegisterServer2ResponseMessage(ServiceFault ServiceFault) { this.RegisterServer2Response = new RegisterServer2Response(); if (ServiceFault != null) { this.RegisterServer2Response.ResponseHeader = ServiceFault.ResponseHeader; } }
/// <summary> /// Initializes the message with a service fault. /// </summary> public FindServersOnNetworkResponseMessage(ServiceFault ServiceFault) { this.FindServersOnNetworkResponse = new FindServersOnNetworkResponse(); if (ServiceFault != null) { this.FindServersOnNetworkResponse.ResponseHeader = ServiceFault.ResponseHeader; } }
/// <summary> /// Sends a fault response secured with the symmetric keys. /// </summary> private void SendServiceFault(TcpChannelToken token, uint requestId, ServiceResult fault) { // Utils.Trace("Channel {0} Request {1}: SendServiceFault()", ChannelId, requestId); BufferCollection buffers = null; try { // construct fault. ServiceFault response = new ServiceFault(); response.ResponseHeader.ServiceResult = fault.Code; StringTable stringTable = new StringTable(); response.ResponseHeader.ServiceDiagnostics = new DiagnosticInfo( fault, DiagnosticsMasks.NoInnerStatus, true, stringTable); response.ResponseHeader.StringTable = stringTable.ToArray(); // the limits should never be exceeded when sending a fault. bool limitsExceeded = false; // secure message. buffers = WriteSymmetricMessage( TcpMessageType.Message, requestId, token, response, false, out limitsExceeded); // send message. BeginWriteMessage(buffers, Int32.MaxValue, null); buffers = null; } catch (Exception e) { if (buffers != null) { buffers.Release(BufferManager, "SendServiceFault"); } ForceChannelFault(ServiceResult.Create(e, StatusCodes.BadTcpInternalError, "Unexpected error sending a service fault.")); } }
/// <summary> /// Initializes the message with a service fault. /// </summary> public CloseSecureChannelResponseMessage(ServiceFault ServiceFault) { this.CloseSecureChannelResponse = new CloseSecureChannelResponse(); if (ServiceFault != null) { this.CloseSecureChannelResponse.ResponseHeader = ServiceFault.ResponseHeader; } }
/// <summary> /// Creates a fault message. /// </summary> /// <param name="request">The request.</param> /// <param name="exception">The exception.</param> /// <returns>A fault message.</returns> protected static ServiceFault CreateFault(IServiceRequest request, Exception exception) { DiagnosticsMasks diagnosticsMask = DiagnosticsMasks.ServiceNoInnerStatus; ServiceFault fault = new ServiceFault(); if (request != null) { fault.ResponseHeader.Timestamp = DateTime.UtcNow; fault.ResponseHeader.RequestHandle = request.RequestHeader.RequestHandle; if (request.RequestHeader != null) { diagnosticsMask = (DiagnosticsMasks)request.RequestHeader.ReturnDiagnostics; } } ServiceResult result = null; ServiceResultException sre = exception as ServiceResultException; if (sre != null) { result = new ServiceResult(sre); Utils.Trace( Utils.TraceMasks.Service, "Service Fault Occured. Reason={0}", result); } else { result = new ServiceResult(exception, StatusCodes.BadUnexpectedError); Utils.Trace(exception, "SERVER - Unexpected Service Fault: {0}", exception.Message); } fault.ResponseHeader.ServiceResult = result.Code; StringTable stringTable = new StringTable(); fault.ResponseHeader.ServiceDiagnostics = new DiagnosticInfo( result, diagnosticsMask, true, stringTable); fault.ResponseHeader.StringTable = stringTable.ToArray(); return fault; }
/// <summary> /// Initializes the message with a service fault. /// </summary> public ActivateSessionResponseMessage(ServiceFault ServiceFault) { this.ActivateSessionResponse = new ActivateSessionResponse(); if (ServiceFault != null) { this.ActivateSessionResponse.ResponseHeader = ServiceFault.ResponseHeader; } }