protected override async Task <bool> TryPrepareSchemaCoreAsync()
        {
            if (_path == null)
            {
                _msg.Debug($"{nameof(_path)} is null");
                return(false);
            }

            using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(_path, UriKind.Absolute))))
            {
                if (geodatabase.GetDomains().Any(domain => string.Equals(_domainName, domain.GetName())))
                {
                    _msg.Debug($"Domain {_domainName} already exists in {_path}");
                    return(true);
                }
            }

            // the GP tool is going to fail on creating a domain with the same name
            await Task.WhenAll(
                GeoprocessingUtils.CreateDomainAsync(_path, _domainName, "Correction status for work list"),
                GeoprocessingUtils.AddCodedValueToDomainAsync(_path, _domainName, 100, "Not Corrected"),
                GeoprocessingUtils.AddCodedValueToDomainAsync(_path, _domainName, 200, "Corrected"));

            return(true);
        }
Example #2
0
        public override void Open([NotNull] Uri connectionPath)         // "open workspace"
        {
            Assert.ArgumentNotNull(connectionPath, nameof(connectionPath));

            _msg.Debug($"Try to open {connectionPath}");

            // Empirical: when opening a project (.aprx) with a saved layer
            // using our Plugin Datasource, the connectionPath will be
            // prepended with the project file's directory path and
            // two times URL encoded (e.g., ' ' => %20 => %2520)!

            var path = connectionPath.IsAbsoluteUri
                                           ? connectionPath.LocalPath
                                           : connectionPath.ToString();

            path = HttpUtility.UrlDecode(path);
            path = HttpUtility.UrlDecode(path);

            string name = WorkListUtils.GetName(path);

            _tableNames = new ReadOnlyCollection <string>(
                new List <string>
            {
                FormatTableName(name)
            });
        }
Example #3
0
        public static IEnumerable <X509Certificate2> FindValidCertificates(
            StoreName storeName,
            StoreLocation storeLocation,
            [NotNull] string searchString,
            X509FindType findType = X509FindType.FindBySubjectDistinguishedName)
        {
            X509Certificate2Collection certificates;

            X509Store store = new X509Store(storeName, storeLocation);

            try
            {
                store.Open(OpenFlags.ReadOnly);

                X509Certificate2Collection certCollection = store.Certificates;

                certificates = certCollection.Find(findType, searchString, true);
            }
            catch (Exception e)
            {
                _msg.Debug($"Error finding using {findType} ({searchString})", e);
                yield break;
            }
            finally
            {
                store.Close();
            }

            foreach (X509Certificate2 certificate in certificates)
            {
                yield return(certificate);
            }
        }
Example #4
0
        public async Task CreateWorkListAsync([NotNull] WorkEnvironmentBase environment)
        {
            try
            {
                // is this worklist already loaded?
                if (_registry.Exists(environment.GetWorklistId()))
                {
                    _msg.Debug("Worklist is already loaded");
                    return;
                }

                IWorkList workList = await environment.CreateWorkListAsync(this);

                RegisterObserver(new WorkListObserver());

                // wiring work list events, etc. is done in OnDrawComplete
                // register work list before creating the layer
                _registry.Add(workList);

                foreach (var observer in _observers)
                {
                    observer.WorkListAdded(workList);
                }

                CreateLayer(environment, workList.Name);
            }
            catch (Exception e)
            {
                _msg.Error("Create work list failed", e);
            }
        }
        public static Type LoadType([NotNull] string assemblyName,
                                    [NotNull] string typeName,
                                    IReadOnlyDictionary <string, string> assemblySubstitutes = null)
        {
            Assert.ArgumentNotNullOrEmpty(assemblyName, nameof(assemblyName));
            Assert.ArgumentNotNullOrEmpty(typeName, nameof(typeName));

            var substitutes = assemblySubstitutes ?? _substitutes;

            bool throwOnError =
                !substitutes.TryGetValue(assemblyName, out string subsituteAssembly);

            Assembly assembly = null;

            try
            {
                AssemblyName name = GetAssemblyName(BinDirectory, assemblyName);

                if (string.IsNullOrEmpty(name.CodeBase))
                {
                    _msg.VerboseDebugFormat("Loading type {0} from {1}",
                                            typeName, name);
                }
                else
                {
                    _msg.VerboseDebugFormat("Loading type {0} from {1} (codebase: {2})",
                                            typeName, name, name.CodeBase);
                }

                assembly = Assembly.Load(name);
            }
            catch (Exception e)
            {
                _msg.Debug($"Loading {typeName} failed because assembly {assemblyName} from {BinDirectory} could not be loaded.", e);

                if (throwOnError)
                {
                    throw;
                }

                _msg.DebugFormat("Trying assembly substitute {0}...", subsituteAssembly);

                assembly = Assembly.Load(subsituteAssembly);
            }

            Type type = assembly.GetType(typeName, throwOnError);

            if (type == null)
            {
                string substituteType = typeName.Replace(assemblyName, subsituteAssembly);

                _msg.Debug(
                    $"Failed loading type {typeName} from {assemblyName}, trying {substituteType} from {subsituteAssembly}");

                return(LoadType(Assert.NotNull(subsituteAssembly), substituteType,
                                new Dictionary <string, string>(0)));
            }

            return(type);
        }
        public static async Task <GeometryProcessingClient> StartGeometryProcessingClient(
            [NotNull] string executablePath, string configFilePath)
        {
            ClientChannelConfig clientChannelConfig;

            if (string.IsNullOrEmpty(configFilePath))
            {
                _msg.Debug(
                    "Geometry processing microservice client configuration not found, using default settings...");

                clientChannelConfig = new ClientChannelConfig
                {
                    HostName = "localhost",
                    Port     = 5153
                };
            }
            else
            {
                clientChannelConfig = GetClientChannelConfig(configFilePath);
            }

            var result = new GeometryProcessingClient(clientChannelConfig);

            await result.AllowStartingLocalServerAsync(executablePath).ConfigureAwait(false);

            return(result);
        }
        public void ConfigureMapping(Configuration nhConfiguration)
        {
            if (_assemblyNames != null)
            {
                foreach (string assembly in _assemblyNames)
                {
                    // Consider assemblies with mappings to be optional - if the assembly
                    // cannot be loaded, it will presumably not execute any code either.

                    if (!AssemblyExists(assembly))
                    {
                        _msg.DebugFormat(
                            "Assembly {0} cannot be found and therefore its NHibernate mappings will not be added.",
                            assembly);

                        continue;
                    }

                    _msg.DebugFormat("Trying to add assembly {0}", assembly);

                    try
                    {
                        nhConfiguration.AddAssembly(assembly);
                    }
                    catch (Exception e)
                    {
                        _msg.Debug($"Error loading assembly {assembly}", e);
                        throw;
                    }
                }
            }

            if (!string.IsNullOrEmpty(_assemblyWithEmbeddedFiles))
            {
                Assembly assembly;
                try
                {
                    // If a (single) assembly with embedded files is configured, consider
                    // it mandatory.
                    assembly = Assembly.Load(_assemblyWithEmbeddedFiles);
                }
                catch (Exception e)
                {
                    _msg.Debug($"Error loading assembly {_assemblyWithEmbeddedFiles}", e);
                    throw;
                }

                foreach (string embeddedFile in _embeddedFiles)
                {
                    nhConfiguration.AddInputStream(
                        assembly.GetManifestResourceStream(embeddedFile));
                }
            }
        }
Example #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SessionWrapper"/> class.
        /// </summary>
        /// <param name="inner">The actual nhibernate session</param>
        /// <param name="isOutermost">Whether this is a completely new session or not.
        /// If not, we just piggy-back on top of it.</param>
        public SessionWrapper(ISession inner, bool isOutermost)
        {
            IsOutermost = isOutermost;

            _inner = inner;

            if (isOutermost)
            {
                _transaction = _inner.BeginTransaction();
                _msg.Debug("Started new NH session and transaction");
            }
        }
Example #9
0
        public static ChannelCredentials CreateChannelCredentials(
            bool useTls,
            [CanBeNull] string clientCertificate = null)
        {
            if (!useTls)
            {
                _msg.DebugFormat("Using insecure channel credentials");

                return(ChannelCredentials.Insecure);
            }

            string rootCertificatesAsPem =
                CertificateUtils.GetUserRootCertificatesInPemFormat();

            if (_msg.IsVerboseDebugEnabled)
            {
                _msg.DebugFormat("Trusted root credentials provided: {0}",
                                 rootCertificatesAsPem);
            }

            KeyCertificatePair sslClientCertificate = null;

            if (!string.IsNullOrEmpty(clientCertificate))
            {
                KeyPair keyPair = CertificateUtils.FindKeyCertificatePairFromStore(
                    clientCertificate, new[]
                {
                    X509FindType.FindBySubjectDistinguishedName,
                    X509FindType.FindByThumbprint,
                    X509FindType.FindBySubjectName
                }, StoreName.My, StoreLocation.CurrentUser);

                if (keyPair != null)
                {
                    _msg.Debug("Using client-side certificate");

                    sslClientCertificate =
                        new KeyCertificatePair(keyPair.PublicKey, keyPair.PrivateKey);
                }
                else
                {
                    throw new ArgumentException(
                              $"Could not usable find client certificate {clientCertificate} in certificate store.");
                }
            }

            var result = new SslCredentials(rootCertificatesAsPem, sslClientCertificate);

            return(result);
        }
Example #10
0
        public string ShowWorklist([NotNull] WorkEnvironmentBase environment, [NotNull] string path)
        {
            Assert.ArgumentNotNull(environment, nameof(environment));
            Assert.ArgumentNotNullOrEmpty(path, nameof(path));

            IWorkList worklist;

            string name = WorkListUtils.GetName(path).ToLower();

            if (_registry.Exists(name))
            {
                worklist = _registry.Get(name);
            }
            else
            {
                var factory = new XmlBasedWorkListFactory(path, name);

                if (_registry.TryAdd(factory))
                {
                    _msg.Debug($"Add work list {name} from file {path}");
                }

                worklist = _registry.Get(name);
            }

            Assert.NotNull(worklist);

            if (!_viewsByWorklistName.ContainsKey(worklist.Name))
            {
                var item = ProjectItemUtils.Get <WorklistItem>(Path.GetFileName(path));

                if (item == null)
                {
                    Assert.True(ProjectItemUtils.TryAdd(path, out item), $"Cannot add item {path}");
                    Assert.NotNull(item);
                }

                _viewsByWorklistName.Add(worklist.Name, new WorkListObserver(worklist, item));

                Uri uri = WorkListUtils.GetDatasource(GetProject().HomeFolderPath, name,
                                                      environment.FileSuffix);
                FeatureLayer layer = AddLayer(uri, name, item.Name);

                // use item name as layer name (and as view display name as well)
                LayerUtils.ApplyRenderer(layer, environment.GetLayerDocument());
            }

            return(Assert.NotNullOrEmpty(worklist.Name));
        }
        private static CalculateOverlapsResponse CalculateOverlapsRpc(
            RemoveOverlapsGrpc.RemoveOverlapsGrpcClient rpcClient,
            IList <Feature> selectedFeatures,
            IList <Feature> overlappingFeatures,
            CancellationToken cancellationToken)
        {
            CalculateOverlapsRequest request =
                CreateCalculateOverlapsRequest(selectedFeatures, overlappingFeatures);

            CalculateOverlapsResponse response;

            try
            {
                response = rpcClient.CalculateOverlaps(request, null, null,
                                                       cancellationToken);
            }
            catch (Exception e)
            {
                _msg.Debug($"Error calling remote procedure: {e.Message} ", e);

                throw;
            }

            return(response);
        }
Example #12
0
        private static void ThrowExceptionToClient(Exception exception)
        {
            // This is to avoid a generic exception with little meaning

            // Determine if it is a good idea to use metadata trailers:

            //serverCallContext.ResponseTrailers.Add("ERROR", exception.Message);

            //// This causes a different statuts code / message(probably too long / or illegal characters!)
            //serverCallContext.ResponseTrailers.Add("EXCEPTION",
            //                                       exception.ToString());

            // TODO: Add exception type, error code, etc.

            // TODO: Check if this is still the case:
            // For synchronous calls, there is no result object to extract the trailers from. Simply use the exception

            var rpcException =
                new RpcException(new Status(StatusCode.Unavailable, exception.ToString()),
                                 exception.Message);

            _msg.Debug("Re-throwing exception as RPC Exception", exception);

            throw rpcException;
        }
Example #13
0
        protected GeometryReshaperBase([NotNull] ICollection <IFeature> featuresToReshape)
        {
            Assert.ArgumentNotNull(featuresToReshape, nameof(featuresToReshape));

            RefreshArea = new EnvelopeClass();

            ReshapeGeometryCloneByFeature =
                new Dictionary <IFeature, IGeometry>(featuresToReshape.Count);

            foreach (IFeature feature in featuresToReshape)
            {
                ReshapeGeometryCloneByFeature.Add(feature, feature.ShapeCopy);

                if (XyTolerance == null)
                {
                    XyTolerance = GeometryUtils.GetXyTolerance(feature.Shape);
                }
                else if (!MathUtils.AreEqual(XyTolerance.Value,
                                             GeometryUtils.GetXyTolerance(feature.Shape)))
                {
                    _msg.Debug(
                        "Reshape multiple geometries: Not all features have the same spatial reference (xy tolerance).");
                }
            }
        }
Example #14
0
        protected override async void OnClick()
        {
            await ViewUtils.TryAsync(async() =>
            {
                var window  = FrameworkApplication.ActiveWindow as IProjectWindow;
                string path = window?.SelectedItems.FirstOrDefault()?.Path;

                if (string.IsNullOrEmpty(path))
                {
                    return;
                }

                _msg.Debug($"Open work list from file {path}");

                WorkEnvironmentBase environment = CreateEnvironment(path);

                if (environment == null)
                {
                    return;
                }

                string worklistName = await QueuedTask.Run(() => WorkListsModule.Current.ShowWorklist(environment, path));
                Assert.NotNullOrEmpty(worklistName);

                WorkListsModule.Current.ShowView(worklistName, worklistName);
            }, _msg);
        }
Example #15
0
        public static Type LoadType([NotNull] string assemblyName,
                                    [NotNull] string typeName)
        {
            Assert.ArgumentNotNullOrEmpty(assemblyName, nameof(assemblyName));
            Assert.ArgumentNotNullOrEmpty(typeName, nameof(typeName));

            AssemblyName name = GetAssemblyName(BinDirectory, assemblyName);

            if (string.IsNullOrEmpty(name.CodeBase))
            {
                _msg.VerboseDebugFormat("Loading type {0} from {1}",
                                        typeName, name);
            }
            else
            {
                _msg.VerboseDebugFormat("Loading type {0} from {1} (codebase: {2})",
                                        typeName, name, name.CodeBase);
            }

            Assembly assembly = Assembly.Load(name);

            bool throwOnError =
                !_substitutes.TryGetValue(assemblyName, out string subsituteAssembly);
            Type type = assembly.GetType(typeName, throwOnError);

            if (type == null)
            {
                string substituteType = typeName.Replace(assemblyName, subsituteAssembly);
                _msg.Debug(
                    $"Failed loading type {typeName} from {assemblyName}, trying {substituteType} from {subsituteAssembly}");
                return(LoadType(Assert.NotNull(subsituteAssembly), substituteType));
            }

            return(type);
        }
Example #16
0
        private void LogTransfer([CanBeNull] object sourceValue,
                                 FieldValueTransferLogLevel logLevel)
        {
            string formattedValue = GetFormattedValue(sourceValue);

            string message =
                string.Format("Transferring value from field '{0}' to field '{1}': {2}",
                              SourceFieldName, TargetFieldName, formattedValue);

            switch (logLevel)
            {
            case FieldValueTransferLogLevel.Debug:
                _msg.Debug(message);
                break;

            case FieldValueTransferLogLevel.VerboseDebug:
                _msg.VerboseDebug(message);
                break;

            case FieldValueTransferLogLevel.Info:
                _msg.Info(message);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(logLevel));
            }
        }
        public void Disconnect()
        {
            Channel?.ShutdownAsync();

            try
            {
                if (_startedProcess != null && !_startedProcess.HasExited)
                {
                    _startedProcess?.Kill();
                }
            }
            catch (Exception e)
            {
                _msg.Debug($"Error killing the started microserver process {_startedProcess}", e);
            }
        }
Example #18
0
        private static bool?SubCurveTouchesDifferentParts(IPath subCurve,
                                                          IGeometry cuttingGeometry)
        {
            bool?curveTouchesDifferentParts = null;

            if (((IGeometryCollection)cuttingGeometry).GeometryCount > 1)
            {
                double xyTolerance = GeometryUtils.GetXyTolerance(cuttingGeometry);

                IGeometry fromPointPart = GeometryUtils.GetHitGeometryPart(
                    subCurve.FromPoint, cuttingGeometry, xyTolerance);

                IGeometry toPointPart = GeometryUtils.GetHitGeometryPart(
                    subCurve.ToPoint, cuttingGeometry, xyTolerance);

                if (fromPointPart != toPointPart)
                {
                    _msg.Debug("Line connecting different parts");
                    curveTouchesDifferentParts = true;
                }
                else
                {
                    curveTouchesDifferentParts = false;
                }
            }

            return(curveTouchesDifferentParts);
        }
Example #19
0
        private static void CreateIndex([NotNull] IssueFeatureWriter writer,
                                        [CanBeNull] ITrackCancel trackCancel,
                                        bool ignoreErrors)
        {
            _msg.InfoFormat(writer.WriteCount == 1
                                                ? "Creating spatial index for {0} issue feature in '{1}'"
                                                : "Creating spatial index for {0} issue features in '{1}'",
                            writer.WriteCount, writer.Name);

            try
            {
                writer.CreateSpatialIndex(trackCancel);
            }
            catch (Exception e)
            {
                if (!ignoreErrors)
                {
                    throw;
                }

                _msg.Debug("Error creating spatial index", e);
                _msg.WarnFormat("Error creating spatial index for feature class {0}: {1}",
                                writer.Name, e.Message);
            }
        }
Example #20
0
        public byte[] WriteGeometry([NotNull] IGeometry geometry)
        {
            try
            {
                switch (geometry.GeometryType)
                {
                case esriGeometryType.esriGeometryPoint:
                    return(WritePoint((IPoint)geometry));

                case esriGeometryType.esriGeometryPolyline:
                    return(WritePolyline((IPolyline)geometry));

                case esriGeometryType.esriGeometryPolygon:
                    return(WritePolygon((IPolygon)geometry));

                case esriGeometryType.esriGeometryMultiPatch:
                    return(WriteMultipatch((IMultiPatch)geometry));

                default:
                    throw new NotImplementedException(
                              $"Geometry type {geometry.GeometryType} is not implemented.");
                }
            }
            catch (Exception e)
            {
                _msg.Debug($"Error writing geometry to WKB: {GeometryUtils.ToString(geometry)}",
                           e);
                throw;
            }
        }
Example #21
0
        public void DisposeSurface()
        {
            if (_rasterSurface == null)
            {
                return;
            }

            _msg.Debug("Disposing raster");

            _rasterSurface.Dispose();
            _rasterSurface = null;

            IWorkspace memoryWs = null;

            if (_memoryRasterDataset != null)
            {
                memoryWs = _memoryRasterDataset.Workspace;
                _memoryRasterDataset.Delete();
                ComUtils.ReleaseComObject(_memoryRasterDataset);
                _memoryRasterDataset = null;
            }

            if (memoryWs != null)
            {
                ((IDataset)memoryWs).Delete();
                ComUtils.ReleaseComObject(memoryWs);
            }
        }
Example #22
0
        private void Do([NotNull] Action <ISession> procedure,
                        RequiredContext requiredContext,
                        [CanBeNull] IDetachedState detachedState)
        {
            using (ISession session = OpenSession())
            {
                AssertRequiredContext(session, requiredContext);

                detachedState?.ReattachState(this);

                try
                {
                    procedure(session);
                }
                catch (Exception e)
                {
                    // Roll back, if this is the outermost transaction
                    if (session is SessionWrapper sessionWrapper &&
                        sessionWrapper.IsOutermost)
                    {
                        _msg.Debug("Rolling back nHibernate transaction due to exception.", e);

                        session.Transaction.Rollback();
                    }

                    throw;
                }
            }
        }
Example #23
0
        private static string HandleToStringException(Exception e)
        {
            string msg = string.Format("Error converting to string: {0}",
                                       e.Message);

            _msg.Debug(msg, e);
            return(msg);
        }
Example #24
0
        static void Main(string[] args)
        {
            try
            {
                IServiceHealth   health;
                Grpc.Core.Server server = Run(args, out health);

                _msg.Info("Type Q(uit) to stop the server.");

                while (true)
                {
                    // Avoid mindless spinning
                    Thread.Sleep(100);

                    if (System.Console.KeyAvailable)
                    {
                        if (System.Console.ReadKey(true).Key == ConsoleKey.Q)
                        {
                            _msg.Warn("Shutting down due to user input");
                            break;
                        }
                    }

                    // TODO: Uncomment after next pull
                    //if (health.IsAnyServiceUnhealthy())
                    //{
                    //	_msg.Warn("Shutting down due to service state NOT_SERVING");
                    //	break;
                    //}
                }

                if (server != null)
                {
                    GrpcServerUtils.GracefullyStop(server);
                }
            }
            catch (Exception ex)
            {
                _msg.Error("An error occurred in microservice.", ex);
                Environment.ExitCode = -1;
            }
            finally
            {
                _msg.Debug("License released, shutting down...");
            }
        }
Example #25
0
        private static bool TryGetVersion([CanBeNull] out string version)
        {
            try
            {
                // the following code fails in the 64bit background environment (see COM-221)
                RuntimeInfo runtime = RuntimeManager.ActiveRuntime;

                if (runtime == null)
                {
                    // not bound yet?

                    // There seems to be another scenario where this is null (observed
                    // for background gp on a particular setup, which also includes server).

                    _msg.Debug(
                        "RuntimeInfo not available. Trying to get version from assembly");

                    if (TryGetVersionFromVersionAssembly(out version))
                    {
                        return(true);
                    }

                    _msg.DebugFormat("Unable to get ArcGIS version from assembly");
                    version = null;
                    return(false);
                }

                version = runtime.Version;
                return(true);
            }
            catch (DllNotFoundException e)
            {
                _msg.VerboseDebugFormat(
                    "Error accessing RuntimeManager: {0}; trying to get version from assembly",
                    e.Message);

                if (TryGetVersionFromVersionAssembly(out version))
                {
                    return(true);
                }

                _msg.DebugFormat("Unable to get ArcGIS version from assembly");
                return(false);
            }
        }
Example #26
0
        public bool InitializeApplication(
            [NotNull] esriLicenseProductCode[] productCodes,
            [NotNull] esriLicenseExtensionCode[] extensionLicenseCodes)
        {
            try
            {
                TryBindProduct(productCodes);
            }
            catch (Exception ex)
            {
                _msg.Debug("Exception while binding ArcGIS 10 product.", ex);
            }

            if (_aoInitialize == null)
            {
                try
                {
                    // If the next line fails with error code -2147221164: make sure that exe's are compiled for x86
                    // Otherwise on 64bit systems this error occurs.
                    _aoInitialize = new AoInitializeClass();
                }
                catch (Exception e)
                {
                    _msg.Debug("Error initializing ArcObjects", e);

                    _msg.Warn("Unable to initialize ArcGIS. This application cannot run! " +
                              "Please check that ArcGIS (Desktop, Engine or Server) is installed.");
                    return(false);
                }
            }

            //Initialize the application
            _productsCodes   = productCodes;
            _extensionsCodes = extensionLicenseCodes;

            esriLicenseStatus licenseStatus = CheckOutLicenses();

            if (licenseStatus != esriLicenseStatus.esriLicenseCheckedOut)
            {
                _msg.WarnFormat("ESRI License Initializer: {0}", LicenseMessage(licenseStatus));
                return(false);
            }

            return(true);
        }
        private static void EnsuresZsAreNonNan([NotNull] IGeometry inGeometry,
                                               [NotNull] IGeometry originalGeometry,
                                               [NotNull] IFeature feature)
        {
            bool zSimple = GeometryUtils.TrySimplifyZ(inGeometry);

            if (zSimple)
            {
                return;
            }

            _msg.Debug(
                "Geometry has undefined Zs, even after calculating non-simple Zs.");

            // Remaining NaNs cannot be interpolated -> e.g. because there is only 1 Z value in a part

            // make sure each part has at least some Z values, otherwise CalculateNonSimpleZs fails:
            int geometryCount = ((IGeometryCollection)inGeometry).GeometryCount;

            for (var i = 0; i < geometryCount; i++)
            {
                IGeometry part = ((IGeometryCollection)inGeometry).Geometry[i];

                if (!GeometryUtils.HasUndefinedZValues(part))
                {
                    continue;
                }

                _msg.DebugFormat("Geometry part <index> {0} has no Zs. Extrapolating...",
                                 i);

                IGeometry originalGeoInDataSpatialRef;

                // NOTE: same SR needed because ExtrapolateZs / QueryPointAndDistance does not honor different spatial refs
                if (GeometryUtils.EnsureSpatialReference(originalGeometry, feature,
                                                         out originalGeoInDataSpatialRef))
                {
                    _msg.DebugFormat(
                        "The original shape of {0} was projected from map coordinates back to the feature class' spatial reference.",
                        GdbObjectUtils.ToString(feature));
                }

                IGeometry extrapolatedPart = GeometryUtils.ExtrapolateZ(
                    part, (IPolycurve)originalGeoInDataSpatialRef);

                GeometryUtils.ReplaceGeometryPart(inGeometry, i, extrapolatedPart);

                if (originalGeoInDataSpatialRef != originalGeometry)
                {
                    Marshal.ReleaseComObject(originalGeoInDataSpatialRef);
                }

                _msg.InfoFormat(
                    "Z values for {0} were extrapolated from source geometry.",
                    GdbObjectUtils.ToString(feature));
            }
        }
Example #28
0
        public static Assembly LoadAssembly(
            [NotNull] string assemblyName,
            [CanBeNull] IReadOnlyDictionary <string, string> assemblySubstitutes = null)
        {
            IReadOnlyDictionary <string, string> substitutes = GetSubstitutes(assemblySubstitutes);

            bool throwOnError =
                !substitutes.TryGetValue(assemblyName, out string substituteAssembly);

            Assembly assembly;

            try
            {
                AssemblyName name = GetAssemblyName(BinDirectory, assemblyName);

                if (string.IsNullOrEmpty(name.CodeBase))
                {
                    _msg.VerboseDebugFormat("Loading assembly from {0}", name);
                }
                else
                {
                    _msg.VerboseDebugFormat("Loading assembly from {0} (codebase: {1})",
                                            name, name.CodeBase);
                }

                assembly = Assembly.Load(name);
            }
            catch (Exception e)
            {
                _msg.Debug($"Loading {assemblyName} from {BinDirectory} failed.", e);

                if (throwOnError)
                {
                    throw;
                }

                _msg.DebugFormat("Trying assembly substitute {0}...", substituteAssembly);

                assembly = Assembly.Load(substituteAssembly);
            }

            return(assembly);
        }
Example #29
0
        public static bool EnsureFolderExists([NotNull] string path)
        {
            if (Directory.Exists(path))
            {
                return(true);
            }

            try
            {
                _msg.Debug($"Try to create folder {path}");
                Directory.CreateDirectory(path);

                return(true);
            }
            catch (Exception e)
            {
                _msg.Debug($"Cannot create folder {path}", e);
                return(false);
            }
        }
Example #30
0
        private static bool TryGetVersion([CanBeNull] out string version)
        {
            try
            {
                // the following code fails
                // - in the 64bit background environment (see COM-221): DllNotFound
                // - in specific cross-thread situations: InvalidComObject
                RuntimeInfo runtime = RuntimeManager.ActiveRuntime;

                if (runtime == null)
                {
                    // not bound yet?

                    // There seems to be another scenario where this is null (observed
                    // for background gp on a particular setup, which also includes server).

                    _msg.Debug(
                        "RuntimeInfo not available. Trying to get version from assembly");

                    if (TryGetVersionFromVersionAssembly(out version))
                    {
                        return(true);
                    }

                    _msg.DebugFormat("Unable to get ArcGIS version from assembly");
                    version = null;
                    return(false);
                }

                version = runtime.Version;
                return(true);
            }
            catch (DllNotFoundException e)
            {
                return(HandleErrorAndGetVersionFromAssembly(e, out version));
            }
            catch (InvalidComObjectException e)
            {
                return(HandleErrorAndGetVersionFromAssembly(e, out version));
            }
        }