Ejemplo n.º 1
0
		/// <summary>
		/// Sends verification request to specified Remote Dicom Host (synchronously).
		/// </summary>
		/// <param name="clientAETitle"></param>
		/// <param name="remoteAE"></param>
		/// <param name="remoteHost"></param>
		/// <param name="remotePort"></param>
		/// <returns></returns>
		public VerificationResult Verify(string clientAETitle, string remoteAE, string remoteHost, int remotePort)
		{
			Platform.Log(LogLevel.Info, "Preparing to connect to AE {0} on host {1} on port {2} for verification.", remoteAE, remoteHost, remotePort);
			try
			{
				base.ClientAETitle = clientAETitle;
				base.RemoteAE = remoteAE;
				base.RemoteHost = remoteHost;
				base.RemotePort = remotePort;
				_verificationResult = VerificationResult.Failed;
				base.Connect();
			}
			catch (Exception e)
			{
				Platform.Log(LogLevel.Error, e, "Unexpected exception trying to connect to Remote AE {0} on host {1} on port {2}", remoteAE, remoteHost, remotePort);
			}
			if (base.Status == ScuOperationStatus.Canceled)
				return VerificationResult.Canceled;
			else if (base.Status == ScuOperationStatus.TimeoutExpired)
				return VerificationResult.TimeoutExpired;
            else if (Status == ScuOperationStatus.AssociationRejected)
                return VerificationResult.AssociationRejected;
			else
				return _verificationResult;
		}
Ejemplo n.º 2
0
        public VerificationResult SendVerification(IVerification verification)
        {
            Dictionary<string, string> parameters = _requestBuilderHelper.BuildDictionaryForVerification(verification);

            VerificationResult verificationResult = new VerificationResult();
            XDocument resultDocument = GetResultDocument(parameters, Method.Verify, verificationResult);
            return verificationResult;
        }
Ejemplo n.º 3
0
 internal static void SetColorByVerification(this DataGridViewCell cell, VerificationResult result)
 {
     switch (result)
     {
         case VerificationResult.Error:
             cell.Style.BackColor = CellsPalette.Error;
             break;
         case VerificationResult.Warning:
             cell.Style.BackColor = CellsPalette.Warning;
             break;
     }
 }
Ejemplo n.º 4
0
 public void OnDimseTimeout(DicomClient client, ClientAssociationParameters association)
 {
     Logger.LogInfo("Timeout waiting for response message, continuing.");
     _verificationResult = VerificationResult.TimeoutExpired;
     ProgressEvent.Set();
 }
Ejemplo n.º 5
0
 public void OnReceiveResponseMessage(DicomClient client, ClientAssociationParameters association, byte presentationID, DicomMessage message)
 {
     if (message.Status.Status != DicomState.Success)
     {
         Logger.LogError("Failure status received in sending verification: {0}", message.Status.Description);
         _verificationResult = VerificationResult.Failed;
     }
     else if (_verificationResult == VerificationResult.Canceled)
     {
         Logger.LogInfo("Verification was canceled");
     }
     else
     {
         Logger.LogInfo("Success status received in sending verification!");
         _verificationResult = VerificationResult.Success;
     }
     client.SendReleaseRequest();
     ProgressEvent.Set();
 }
Ejemplo n.º 6
0
 public void OnNetworkError(DicomClient client, ClientAssociationParameters association, Exception e)
 {
     if (_verificationResult != VerificationResult.Canceled)
     {
         Logger.LogErrorException(e, "Unexpected network error");
         _verificationResult = VerificationResult.Failed;
     }
     ProgressEvent.Set();
 }
Ejemplo n.º 7
0
 public void Cancel()
 {
     if (_verificationResult != VerificationResult.Canceled)
     {
         Logger.LogInfo("Canceling verify...");
         _verificationResult = VerificationResult.Canceled;
         if (_dicomClient != null)
             _dicomClient.Abort();
         ProgressEvent.Set();
     }
 }
Ejemplo n.º 8
0
 public void OnReceiveAssociateReject(DicomClient client, ClientAssociationParameters association, DicomRejectResult result, DicomRejectSource source, DicomRejectReason reason)
 {
     Logger.LogInfo("Association Rejection when {0} connected to remote AE {1}", association.CallingAE, association.CalledAE);
     _verificationResult = VerificationResult.Failed;
     ProgressEvent.Set();
 }
Ejemplo n.º 9
0
 private void VerifyComplete(IAsyncResult ar)
 {
     //VerificationScu verificationScu = (VerificationScu)ar.AsyncState;
     _verificationResult = _verificationScu.EndVerify(ar);
     m_WaitHandle.Set();
 }
 /// <summary>
 ///     Create new KSI signature invalid content exception
 /// </summary>
 /// <param name="message">Exception message</param>
 /// <param name="innerException">Inner exception</param>
 /// <param name="signature">The signature the exception is associated with</param>
 /// <param name="verificationResult">Verificiation result</param>
 public KsiSignatureInvalidContentException(string message, Exception innerException, IKsiSignature signature, VerificationResult verificationResult)
     : base(message, innerException)
 {
     Signature          = signature;
     VerificationResult = verificationResult;
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Sends verification request to specified Remote Dicom Host.
        /// </summary>
        /// <param name="clientAETitle"></param>
        /// <param name="remoteAE"></param>
        /// <param name="remoteHost"></param>
        /// <param name="remotePort"></param>
        /// <returns></returns>
        public VerificationResult Verify(string clientAETitle, string remoteAE, string remoteHost, int remotePort)
        {
            if (_dicomClient == null)
            {
                // TODO: Dispose...
                _dicomClient = null;
            }

            Logger.LogInfo("Preparing to connect to AE {0} on host {1} on port {2} for verification.", remoteAE, remoteHost, remotePort);
            try
            {
                IPAddress addr = null;
                foreach (IPAddress dnsAddr in Dns.GetHostAddresses(remoteHost))
                    if (dnsAddr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        addr = dnsAddr;
                        break;
                    }
                if (addr == null)
                {
                    Logger.LogError("No Valid IP addresses for host {0}", remoteHost);
                    _verificationResult = VerificationResult.Failed;
                }
                else
                {
                    _assocParams = new ClientAssociationParameters(clientAETitle, remoteAE, new IPEndPoint(addr, remotePort));

                    SetPresentationContexts();

                    _verificationResult = VerificationResult.Failed;
                    _dicomClient = DicomClient.Connect(_assocParams, this);
                    ProgressEvent.WaitOne();
                }
            }
            catch (Exception e)
            {
                Logger.LogErrorException(e, "Unexpected exception trying to connect to Remote AE {0} on host {1} on port {2}", remoteAE, remoteHost, remotePort);
            }
            return _verificationResult;
        }
        public void CanVerifyReceviedResultsString()
        {
            var id = "testid";
            var testResult = new VerificationResult<string>() { TestId = id };

            var resultSet = new Dictionary<string, VerificationResult<string>> { { id, testResult } };
            var isResultExist = new VerificationSpecsBaseDerived().CheckReceviedResults(resultSet, id);

            Assert.IsTrue(isResultExist);
        }
Ejemplo n.º 13
0
        public void Execute(MySqlConnection connection, MySqlTransaction transaction)
        {
            List<VersionPoint> versions = new List<VersionPoint>();

            SelectBuilder builder = new SelectBuilder();
            builder.Table = "schema_version";
            using (MySqlCommand command = new MySqlCommand(builder.ToString(), connection, transaction))
            {
                using (MySqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        uint version = (uint)reader["version"];
                        bool breaking = false;
                        if (reader.ColumnExists("breaking"))
                            breaking = (bool)reader["breaking"];
                        versions.Add(new VersionPoint(version, breaking));
                    }
                }
            }
            versions.Sort((x, y) => x.Version.CompareTo(y.Version));
            mResult = DoVerify(versions);
        }
Ejemplo n.º 14
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="VerificationFailedException" /> class with a verification result.
 /// </summary>
 /// <param name="verificationResult">The verification result.</param>
 public VerificationFailedException(VerificationResult verificationResult) : base("Verification failed.")
 {
     VerificationResult = verificationResult;
 }
Ejemplo n.º 15
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="VerificationFailedException" /> class with serialized data.
 /// </summary>
 /// <param name="info">
 ///     The <see cref="SerializationInfo" /> that holds the serialized object data about the exception being
 ///     thrown.
 /// </param>
 /// <param name="context">
 ///     The <see cref="StreamingContext" /> that contains contextual information about the source or
 ///     destination.
 /// </param>
 protected VerificationFailedException(SerializationInfo info, StreamingContext context) : base(info, context)
 {
     VerificationResult = (VerificationResult)info.GetValue(nameof(VerificationResult), typeof(VerificationResult));
 }
Ejemplo n.º 16
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="VerificationFailedException" /> class with a verification result, a
 ///     message,
 ///     and a reference to the inner exception that is the cause of this exception.
 /// </summary>
 /// <param name="verificationResult">The verification result.</param>
 /// <param name="message">The message.</param>
 /// <param name="innerException">The inner exception.</param>
 public VerificationFailedException(VerificationResult verificationResult, string message, Exception innerException) : base(message,
                                                                                                                            innerException)
 {
     VerificationResult = verificationResult;
 }
Ejemplo n.º 17
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="VerificationFailedException" /> class with a verification result and
 ///     message.
 /// </summary>
 /// <param name="verificationResult">The verification result.</param>
 /// <param name="message">The message.</param>
 public VerificationFailedException(VerificationResult verificationResult, string message) : base(message)
 {
     VerificationResult = verificationResult;
 }
        public void CanVerifyReceviedResultsGuid()
        {
            var guid = Guid.NewGuid();
            var testResult = new VerificationResult<Guid>() { TestId = guid };

            var resultSet = new Dictionary<Guid, VerificationResult<Guid>> { { guid, testResult } };
            var isResultExist = new VerificationSpecsBaseDerived().CheckReceviedResults(resultSet, guid);

            Assert.IsTrue(isResultExist);
        }
Ejemplo n.º 19
0
        private static void GenerateProxyTypeForList(
            Type sourceElementType,
            Type targetElementType,
            Type proxyType,
            VerificationResult verificationResult)
        {
            var baseType = typeof(ProxyList<,>).MakeGenericType(sourceElementType, targetElementType);
            var baseConstructor = baseType.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)[0];

            var typeBuilder = ProxyAssembly.DefineType(
                string.Format("Proxy_From_IList<{0}>_To_IReadOnlyList<{1}>", sourceElementType.Name, targetElementType.Name),
                TypeAttributes.Class,
                baseType,
                new Type[] { typeof(IReadOnlyList<>).MakeGenericType(targetElementType) });

            var constructorBuilder = typeBuilder.DefineConstructor(
                MethodAttributes.Public,
                CallingConventions.Standard,
                new Type[] { typeof(IList<>).MakeGenericType(sourceElementType) });

            var il = constructorBuilder.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldtoken, proxyType);
            il.Emit(OpCodes.Call, baseConstructor);
            il.Emit(OpCodes.Ret);

            verificationResult.Constructor = constructorBuilder;
            verificationResult.TypeBuilder = typeBuilder;
        }
Ejemplo n.º 20
0
        private static void GenerateProxyTypeFromProperties(Type sourceType, Type targetType, VerificationResult verificationResult)
        {
            var baseType = typeof(ProxyBase<>).MakeGenericType(sourceType);
            var typeBuilder = ProxyAssembly.DefineType(
                string.Format("Proxy_From_{0}_To_{1}", sourceType.Name, targetType.Name),
                TypeAttributes.Class,
                baseType,
                new Type[] { targetType });

            var constructorBuilder = typeBuilder.DefineConstructor(
                MethodAttributes.Public,
                CallingConventions.Standard,
                new Type[] { sourceType });

            var il = constructorBuilder.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Castclass, sourceType);
            il.Emit(OpCodes.Call, baseType.GetConstructor(new Type[] { sourceType }));
            il.Emit(OpCodes.Ret);

            verificationResult.Constructor = constructorBuilder;
            verificationResult.TypeBuilder = typeBuilder;
        }
Ejemplo n.º 21
0
        private static bool VerifyProxySupport(ProxyBuilderContext context, Tuple<Type, Type> key)
        {
            var sourceType = key.Item1;
            var targetType = key.Item2;

            if (context.Visited.ContainsKey(key))
            {
                // We've already seen this combination and so far so good.
                return true;
            }

            ProxyTypeCacheResult cacheResult;
            if (context.Cache.TryGetValue(key, out cacheResult))
            {
                // If we get here we've got a published conversion or error, so we can stop searching.
                return !cacheResult.IsError;
            }

            if (targetType == sourceType || targetType.IsAssignableFrom(sourceType))
            {
                // If we find a trivial conversion, then that will work.
                return true;
            }

            if (!targetType.GetTypeInfo().IsInterface)
            {
                var message = Resources.FormatConverter_TypeMustBeInterface(targetType.FullName, sourceType.FullName);
                context.Cache[key] = ProxyTypeCacheResult.FromError(key, message);

                return false;
            }

            // This is a combination we haven't seen before, and it *might* support proxy generation, so let's
            // start trying.
            var verificationResult = new VerificationResult();
            context.Visited.Add(key, verificationResult);

            // We support conversions from IList<T> -> IReadOnlyList<U> and IReadOnlyList<T> -> IReadOnlyList<U>
            if (targetType.GetTypeInfo().IsGenericType &&
                targetType.GetTypeInfo().GetGenericTypeDefinition() == typeof(IReadOnlyList<>))
            {
                var sourceInterfaceType = GetGenericImplementation(sourceType, typeof(IList<>));
                if (sourceInterfaceType != null)
                {
                    var targetElementType = targetType.GetGenericArguments()[0];
                    var sourceElementType = sourceInterfaceType.GetGenericArguments()[0];

                    var elementKey = new Tuple<Type, Type>(sourceElementType, targetElementType);
                    if (!VerifyProxySupport(context, elementKey))
                    {
                        var error = context.Cache[elementKey];
                        Debug.Assert(error != null && error.IsError);
                        context.Cache[key] = error;
                        return false;
                    }

                    VerificationResult elementResult;
                    context.Visited.TryGetValue(elementKey, out elementResult);

                    var proxyType = elementResult?.Type?.GetTypeInfo() ?? (TypeInfo)elementResult?.TypeBuilder;
                    if (proxyType == null)
                    {
                        // No proxy needed for elements.
                        verificationResult.Type = typeof(ProxyList<,>).MakeGenericType(elementKey.Item1, elementKey.Item2);
                        verificationResult.Constructor = verificationResult.Type.GetConstructors()[0];
                    }
                    else
                    {
                        // We need to proxy each of the elements. Let's generate a type.
                        GenerateProxyTypeForList(elementKey.Item1, elementKey.Item2, proxyType.AsType(), verificationResult);
                    }

                    return true;
                }
            }

            // This doesn't match any of our interface conversions, so we'll codegen a proxy.
            var propertyMappings = new List<KeyValuePair<PropertyInfo, PropertyInfo>>();

            var sourceProperties = sourceType.GetRuntimeProperties();
            foreach (var targetProperty in targetType.GetRuntimeProperties())
            {
                if (!targetProperty.CanRead)
                {
                    var message = Resources.FormatConverter_PropertyMustHaveGetter(
                        targetProperty.Name,
                        targetType.FullName);
                    context.Cache[key] = ProxyTypeCacheResult.FromError(key, message);

                    return false;
                }

                if (targetProperty.CanWrite)
                {
                    var message = Resources.FormatConverter_PropertyMustNotHaveSetter(
                        targetProperty.Name,
                        targetType.FullName);
                    context.Cache[key] = ProxyTypeCacheResult.FromError(key, message);

                    return false;
                }

                if (targetProperty.GetIndexParameters()?.Length > 0)
                {
                    var message = Resources.FormatConverter_PropertyMustNotHaveIndexParameters(
                        targetProperty.Name,
                        targetType.FullName);
                    context.Cache[key] = ProxyTypeCacheResult.FromError(key, message);

                    return false;
                }

                // To allow for flexible versioning, we want to allow missing properties in the source.
                //
                // For now we'll just store null, and later generate a stub getter that returns default(T).
                var sourceProperty = sourceProperties.Where(p => p.Name == targetProperty.Name).FirstOrDefault();
                if (sourceProperty != null &&
                    sourceProperty.CanRead &&
                    sourceProperty.GetMethod?.IsPublic == true)
                {
                    var propertyKey = new Tuple<Type, Type>(sourceProperty.PropertyType, targetProperty.PropertyType);
                    if (!VerifyProxySupport(context, propertyKey))
                    {
                        // There's an error here, so bubble it up and cache it.
                        var error = context.Cache[propertyKey];
                        Debug.Assert(error != null && error.IsError);

                        context.Cache[key] = ProxyTypeCacheResult.FromError(key, error.Error);
                        return false;
                    }

                    propertyMappings.Add(new KeyValuePair<PropertyInfo, PropertyInfo>(targetProperty, sourceProperty));
                }
                else
                {
                    propertyMappings.Add(new KeyValuePair<PropertyInfo, PropertyInfo>(targetProperty, null));
                }
            }

            verificationResult.Mappings = propertyMappings;
            GenerateProxyTypeFromProperties(sourceType, targetType, verificationResult);

            return true;
        }
Ejemplo n.º 22
0
		/// <summary>
		/// Called when received response message.  Sets the <see cref="Result"/> property as appropriate.
		/// </summary>
		/// <param name="client">The client.</param>
		/// <param name="association">The association.</param>
		/// <param name="presentationID">The presentation ID.</param>
		/// <param name="message">The message.</param>
		public override void OnReceiveResponseMessage(DicomClient client, ClientAssociationParameters association, byte presentationID, DicomMessage message)
		{
			if (message.Status.Status != DicomState.Success)
			{
				Platform.Log(LogLevel.Error, "Failure status received in sending verification: {0}", message.Status.Description);
				_verificationResult = VerificationResult.Failed;
			}
			else if (_verificationResult == VerificationResult.Canceled)
			{
				Platform.Log(LogLevel.Info, "Verification was canceled");
			}
			else
			{
				Platform.Log(LogLevel.Info, "Success status received in sending verification!");
				_verificationResult = VerificationResult.Success;
			}
			client.SendReleaseRequest();
			StopRunningOperation();
		}
Ejemplo n.º 23
0
        /// <summary>
        /// Standardizes and Geocodes an address using Bing service
        /// </summary>
        /// <param name="location">The location.</param>
        /// <param name="resultMsg">The result MSG.</param>
        /// <returns>
        /// True/False value of whether the verification was successful or not
        /// </returns>
        public override VerificationResult Verify(Rock.Model.Location location, out string resultMsg)
        {
            VerificationResult result = VerificationResult.None;

            resultMsg = string.Empty;

            // Verify that bing transaction count hasn't been exceeded for the day
            DateTime?txnDate       = Rock.Web.SystemSettings.GetValue(TXN_DATE).AsDateTime();
            int?     dailyTxnCount = 0;

            if (txnDate.Equals(RockDateTime.Today))
            {
                dailyTxnCount = Rock.Web.SystemSettings.GetValue(DAILY_TXN_COUNT).AsIntegerOrNull();
            }
            else
            {
                Rock.Web.SystemSettings.SetValue(TXN_DATE, RockDateTime.Today.ToShortDateString());
            }

            int?maxTxnCount = GetAttributeValue("DailyTransactionLimit").AsIntegerOrNull();

            if (!maxTxnCount.HasValue || maxTxnCount.Value == 0 || dailyTxnCount < maxTxnCount.Value)
            {
                dailyTxnCount++;
                Rock.Web.SystemSettings.SetValue(DAILY_TXN_COUNT, dailyTxnCount.ToString());

                string key = GetAttributeValue("BingMapsKey");

                var queryValues = new Dictionary <string, string>();
                queryValues.Add("adminDistrict", location.State);
                queryValues.Add("locality", location.City);
                queryValues.Add("postalCode", location.PostalCode);
                queryValues.Add("addressLine", location.Street1 + " " + location.Street2);
                queryValues.Add("countryRegion", location.Country);

                var queryParams = new List <string>();
                foreach (var queryKeyValue in queryValues)
                {
                    if (!string.IsNullOrWhiteSpace(queryKeyValue.Value))
                    {
                        queryParams.Add(string.Format("{0}={1}", queryKeyValue.Key, HttpUtility.UrlEncode(queryKeyValue.Value.Trim())));
                    }
                }
                Uri geocodeRequest = new Uri(string.Format("http://dev.virtualearth.net/REST/v1/Locations?{0}&key={1}", queryParams.AsDelimited("&"), key));

                WebClient wc     = new WebClient();
                var       stream = wc.OpenRead(geocodeRequest);

                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Response));
                var x = ser.ReadObject(stream) as Response;
                if (x != null)
                {
                    if (x.ResourceSets.Length > 0 &&
                        x.ResourceSets[0].Resources.Length == 1)
                    {
                        var bingLocation = (Location)x.ResourceSets[0].Resources[0];
                        var matchCodes   = bingLocation.MatchCodes.ToList();

                        resultMsg = string.Format("Confidence: {0}; MatchCodes: {1}",
                                                  bingLocation.Confidence, matchCodes.AsDelimited(","));

                        if (bingLocation.Confidence == "High" &&
                            matchCodes.Contains("Good") &&
                            bingLocation.EntityType == "Address")
                        {
                            if (location.SetLocationPointFromLatLong(bingLocation.Point.Coordinates[0], bingLocation.Point.Coordinates[1]))
                            {
                                result = VerificationResult.Geocoded;
                            }

                            var address = bingLocation.Address;
                            if (address != null)
                            {
                                location.Street1 = address.AddressLine;
                                location.County  = address.AdminDistrict2;
                                location.City    = address.Locality;
                                location.State   = address.AdminDistrict;
                                if (!String.IsNullOrWhiteSpace(address.PostalCode) &&
                                    !((location.PostalCode ?? string.Empty).StartsWith(address.PostalCode)))
                                {
                                    location.PostalCode = address.PostalCode;
                                }

                                result = result | VerificationResult.Standardized;
                            }
                        }
                    }
                    else
                    {
                        resultMsg = "Zero or More than 1 result";
                    }
                }
                else
                {
                    result    = VerificationResult.ConnectionError;
                    resultMsg = "Invalid response";
                }
            }
            else
            {
                result    = VerificationResult.ConnectionError;
                resultMsg = "Daily transaction limit exceeded";
            }

            return(result);
        }