/// <summary> /// Builds a domain consisting of the Workflow Manager privileges /// </summary> /// <returns>A coded value domain of strings</returns> private IGPDomain BuildPrivilegesDomain() { IGPCodedValueDomain domain = new GPCodedValueDomainClass(); // Sort the types first SortedList <string, string> sortedValues = new SortedList <string, string>(); IJTXPrivilegeSet privileges = this.WmxDatabase.ConfigurationManager.Privileges; for (int i = 0; i < privileges.Count; i++) { IJTXPrivilege2 priv = privileges.get_Item(i) as IJTXPrivilege2; sortedValues.Add(priv.Name, null); } // Add the "all privileges" option to the list sortedValues.Add(C_OPT_ALL_PRIVILEGES, null); // Add the sorted types to the domain foreach (string value in sortedValues.Keys) { IGPValue tempGpVal = new GPStringClass(); tempGpVal.SetAsText(value); domain.AddCode(tempGpVal, value); } return(domain as IGPDomain); }
/// <summary> /// Builds a domain consisting of all the usernames in the system /// </summary> /// <param name="wmxDb">A reference to the active Workflow Manager database</param> /// <param name="extraValues">An array of string values to be added to the list</param> /// <returns>A coded value domain as an IGPDomain</returns> public static IGPDomain BuildUsersDomain(IJTXDatabase3 wmxDb, string[] extraValues) { IGPCodedValueDomain domain = new GPCodedValueDomainClass(); // Sort the types first IJTXUserSet allValues = wmxDb.ConfigurationManager.Users; SortedList <string, string> sortedValues = new SortedList <string, string>(); for (int i = 0; i < allValues.Count; i++) { sortedValues.Add(allValues.get_Item(i).UserName, null); } // Add the extra values, if any if (extraValues != null) { foreach (string s in extraValues) { sortedValues.Add(s, null); } } // Add the sorted types to the domain foreach (string value in sortedValues.Keys) { IGPValue tempGpVal = new GPStringClass(); tempGpVal.SetAsText(value); domain.AddCode(tempGpVal, value); } return(domain as IGPDomain); }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); try { // Ensure that the current user has admin access to the current Workflow Manager DB if (!CurrentUserIsWmxAdministrator()) { throw new WmauException(WmauErrorCodes.C_USER_NOT_ADMIN_ERROR); } // Retrieve the parameter in which the list of MXDs will be stored WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameter3 param = paramMap.GetParam(C_PARAM_MAP_DOCUMENT_LIST); IGPParameterEdit3 paramEdit = paramMap.GetParamEdit(C_PARAM_MAP_DOCUMENT_LIST); // Set up the multi-value objects IGPMultiValue mvValue = new GPMultiValueClass(); mvValue.MemberDataType = param.DataType; // Get the list of MXD names and add them all to the multivalue SortedList <string, string> mapDocuments = this.ListMapDocumentsInDatabase(); foreach (string mapDocName in mapDocuments.Keys) { IGPString strVal = new GPStringClass(); strVal.Value = mapDocName; mvValue.AddValue(strVal as IGPValue); msgs.AddMessage("Map Document: " + mapDocName); } paramEdit.Value = (IGPValue)mvValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { try { WmauError error = new WmauError(WmauErrorCodes.C_UNSPECIFIED_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } catch { // Catch anything else that possibly happens } } }
/// <summary> /// Helper function to set up a GP tool parameter so that the workflow manager /// database can be chosen. /// </summary> /// <returns>A parameter for selecting the target WMX DB</returns> protected IGPParameter3 BuildWmxDbParameter() { IGPParameterEdit paramEdit = null; IGPCodedValueDomain cvDomain = new GPCodedValueDomainClass(); // When we first build out the parameter list, ensure that we indicate // what the current Workflow Manager database is m_wmxDbAlias = string.Empty; IsWorkflowManagerDatabaseSet(); // Parameter allowing specification of the Workflow Manager database IGPString strVal = new GPStringClass(); strVal.Value = m_wmxDbAlias; paramEdit = BuildParameter( esriGPParameterDirection.esriGPParameterDirectionInput, esriGPParameterType.esriGPParameterTypeOptional, Properties.Resources.DESC_COM_WMX_DATABASE, C_PARAM_WMX_DATABASE_ALIAS, (strVal as IGPValue).DataType, strVal as IGPValue); IJTXDatabaseConnectionManager connMgr = new JTXDatabaseConnectionManagerClass(); foreach (string alias in connMgr.DatabaseNames) { cvDomain.AddStringCode(alias, alias); } paramEdit.Domain = cvDomain as IGPDomain; return(paramEdit as IGPParameter3); }
/// <summary> /// Builds a domain of the priority strings in the system /// </summary> /// <param name="wmxDb">A reference to the active Workflow Manager database</param> /// <returns>A coded value domain as an IGPDomain</returns> public static IGPDomain BuildPriorityDomain(IJTXDatabase3 wmxDb) { IGPCodedValueDomain domain = new GPCodedValueDomainClass(); // Sort the types first IJTXPrioritySet allValues = wmxDb.ConfigurationManager.Priorities; SortedList <int, string> sortedValues = new SortedList <int, string>(); for (int i = 0; i < allValues.Count; i++) { IJTXPriority temp = allValues.get_Item(i); sortedValues.Add(temp.Value, temp.Name); } // Since the highest priority elements are those with the largest number, // reverse the order of the list so that these priorities show up first IEnumerable <string> valueList = sortedValues.Values.Reverse(); // Add the sorted types to the domain foreach (string value in valueList) { IGPValue tempGpVal = new GPStringClass(); tempGpVal.SetAsText(value); domain.AddCode(tempGpVal, value); } return(domain as IGPDomain); }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); try { // Ensure that the current user has admin access to the current Workflow Manager DB if (!CurrentUserIsWmxAdministrator()) { throw new WmauException(WmauErrorCodes.C_USER_NOT_ADMIN_ERROR); } // Retrieve the MXD and delete it IJTXConfiguration3 configMgr = WmxDatabase.ConfigurationManager as IJTXConfiguration3; IJTXMap map = configMgr.GetJTXMap(m_mxdName); configMgr.DeleteJTXMap(map.ID); // Update the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParamEdit = paramMap.GetParamEdit(C_PARAM_OUT_MXD_NAME); IGPString outValue = new GPStringClass(); outValue.Value = m_mxdName; outParamEdit.Value = outValue as IGPValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { try { WmauError error = new WmauError(WmauErrorCodes.C_DELETE_MXD_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } catch { // Catch anything else that possibly happens } } finally { // Release any COM objects here! } }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); try { // Retrieve the parameter in which the list of workbook names will be stored WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameter3 param = paramMap.GetParam(C_PARAM_TAM_WORKBOOK_LIST); IGPParameterEdit3 paramEdit = paramMap.GetParamEdit(C_PARAM_TAM_WORKBOOK_LIST); // Set up the multi-value objects IGPMultiValue mvValue = new GPMultiValueClass(); mvValue.MemberDataType = param.DataType; // Get the list of TA workbook names and add them all to the multivalue SortedList <string, string> tamWorkbooks = this.ListTamWorkbooksInDatabase(); foreach (string workbookAlias in tamWorkbooks.Keys) { IGPString strVal = new GPStringClass(); strVal.Value = workbookAlias; mvValue.AddValue(strVal as IGPValue); msgs.AddMessage("Workbook: " + workbookAlias); } paramEdit.Value = (IGPValue)mvValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { try { WmauError error = new WmauError(WmauErrorCodes.C_UNSPECIFIED_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } catch { // Catch anything else that possibly happens } } }
/// <summary> /// Builds a domain of the version names for a workspace /// </summary> /// <param name="wmxDb">A reference to the active Workflow Manager database</param> /// <param name="workspaceName">The human-readable name of the workspace whose versions to look up</param> /// <param name="extraValues">An array of string values to be added to the list</param> /// <returns>A coded value domain of strings</returns> public static IGPDomain BuildVersionsDomain(IJTXDatabase3 wmxDb, string workspaceName, string[] extraValues) { IGPCodedValueDomain domain = new GPCodedValueDomainClass(); try { // Get all of the public versions connected to this workspace string workspaceId = Common.WmauHelperFunctions.LookupWorkspaceId(wmxDb, workspaceName); IWorkspace workspace = wmxDb.GetDataWorkspace(workspaceId, null); IVersionedWorkspace3 versionedWorkspace = workspace as IVersionedWorkspace3; IEnumVersionInfo allValues = versionedWorkspace.Versions; // Sort the types first SortedList <string, string> sortedValues = new SortedList <string, string>(); IVersionInfo version; while ((version = allValues.Next()) != null) { sortedValues.Add(version.VersionName, null); } // Add the extra values, if any if (extraValues != null) { foreach (string s in extraValues) { sortedValues.Add(s, null); } } // Add the sorted types to the domain foreach (string value in sortedValues.Keys) { IGPValue tempGpVal = new GPStringClass(); tempGpVal.SetAsText(value); domain.AddCode(tempGpVal, value); } } catch (System.Runtime.InteropServices.COMException comEx) { // If we run into an exception, send word up the chain throw new WmauException(WmauErrorCodes.C_VERSION_LOOKUP_ERROR, comEx); } return(domain as IGPDomain); }
/// <summary> /// Builds a domain of the data workspace names in the system /// </summary> /// <param name="wmxDb">A reference to the active Workflow Manager database</param> /// <param name="extraValues">An array of string values to be added to the list</param> /// <returns>A coded value domain as an IGPDomain</returns> public static IGPDomain BuildWorkspaceDomain(IJTXDatabase3 wmxDb, string[] extraValues) { IGPCodedValueDomain domain = new GPCodedValueDomainClass(); SortedList <string, string> sortedValues = new SortedList <string, string>(); // Workflow Manager intentionally caches the data workspaces in the system. To ensure // that we have the most current list of data workspaces, invalidate this cache // before attempting to retrieve the list from the system. wmxDb.InvalidateDataWorkspaceNames(); // Sort the types first IJTXDataWorkspaceNameSet allValues = wmxDb.GetDataWorkspaceNames(null); for (int i = 0; i < allValues.Count; i++) { IJTXDataWorkspaceName ws = allValues.get_Item(i); sortedValues.Add(ws.Name, null); } // Add the extra values, if any if (extraValues != null) { foreach (string s in extraValues) { sortedValues.Add(s, null); } } // Add the sorted types to the domain foreach (string value in sortedValues.Keys) { IGPValue tempGpVal = new GPStringClass(); tempGpVal.SetAsText(value); domain.AddCode(tempGpVal, value); } return(domain as IGPDomain); }
/// <summary> /// Builds a domain from the names of the job types in the system /// </summary> /// <param name="wmxDb">A reference to the active Workflow Manager database</param> /// <returns>A coded value domain as an IGPDomain</returns> public static IGPDomain BuildJobTypeDomain(IJTXDatabase3 wmxDb) { IGPCodedValueDomain domain = new GPCodedValueDomainClass(); // Sort the types first IJTXJobTypeSet allValues = wmxDb.ConfigurationManager.JobTypes; SortedList <string, string> sortedValues = new SortedList <string, string>(); for (int i = 0; i < allValues.Count; i++) { sortedValues.Add(allValues.get_Item(i).Name, null); } // Add the sorted types to the domain foreach (string value in sortedValues.Keys) { IGPValue tempGpVal = new GPStringClass(); tempGpVal.SetAsText(value); domain.AddCode(tempGpVal, value); } return(domain as IGPDomain); }
/// <summary> /// Set up a coded value domain containing the names of all the spatial notifications /// (a.k.a. "change rules") currently in the database. /// </summary> /// <param name="wmxDb">A reference to the active Workflow Manager database</param> /// <returns>A coded value domain as an IGPDomain</returns> public static IGPDomain BuildChangeRulesDomain(IJTXDatabase3 wmxDb) { IGPCodedValueDomain domain = new GPCodedValueDomainClass(); SortedList <string, string> sortedValues = new SortedList <string, string>(); IJTXChangeRuleSet allChangeRules = wmxDb.SpatialNotificationManager.ChangeRules; // Sort the types first for (int i = 0; i < allChangeRules.Count; i++) { IJTXChangeRule tempRule = allChangeRules.get_Item(i); sortedValues.Add(tempRule.Name, null); } // Add the sorted types to the domain foreach (string value in sortedValues.Keys) { IGPValue tempGpVal = new GPStringClass(); tempGpVal.SetAsText(value); domain.AddCode(tempGpVal, value); } return(domain as IGPDomain); }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); WorkspaceWorksheetReader reader = null; try { // Ensure that the current user has admin access to the current Workflow Manager DB if (!CurrentUserIsWmxAdministrator()) { throw new WmauException(WmauErrorCodes.C_USER_NOT_ADMIN_ERROR); } reader = new WorkspaceWorksheetReader(this.m_excelFilePath, msgs); // Prepare to set/build the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameter3 outParam = paramMap.GetParam(C_PARAM_OUT_WORKSPACES_CREATED); IGPParameterEdit3 outParamEdit = paramMap.GetParamEdit(C_PARAM_OUT_WORKSPACES_CREATED); IGPMultiValue outMultiValue = new GPMultiValueClass(); outMultiValue.MemberDataType = outParam.DataType; // Load the workspace info from the spreadsheet List <Common.WorkspaceInfo> dataWorkspaces = reader.GetWorkspacesFromSpreadsheet(); // Loop through each of the workspaces IJTXDatabaseConnectionManager dbConnectionManager = new JTXDatabaseConnectionManagerClass(); IJTXDatabaseConnection dbConnection = dbConnectionManager.GetConnection(WmxDatabase.Alias); foreach (Common.WorkspaceInfo wmauWorkspaceInfo in dataWorkspaces) { string workspaceName = wmauWorkspaceInfo.Name; if (Common.WmauHelperFunctions.LookupWorkspaceNameObj(this.WmxDatabase, workspaceName) != null) { msgs.AddWarning("Skipping existing workspace '" + workspaceName + "'"); } else { IJTXWorkspaceConfiguration workspaceInfo = dbConnection.AddDataWorkspace(); this.CopyDataWorkspace(wmauWorkspaceInfo, ref workspaceInfo, msgs); workspaceInfo.Store(); msgs.AddMessage("Added new workspace '" + workspaceName + "'"); IGPString outElement = new GPStringClass(); outElement.Value = workspaceName; outMultiValue.AddValue(outElement as IGPValue); } } // Set the value of the output parameter outParamEdit.Value = outMultiValue as IGPValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } } catch (Exception ex) { try { WmauError error = new WmauError(WmauErrorCodes.C_WORKSPACE_LOAD_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } catch { // Catch anything else that possibly happens } } } finally { if (reader != null) { reader.Close(); } } }
/// <summary> /// Builds a domain containing the usernames of the users to whom a /// user can assign jobs. /// </summary> /// <param name="wmxDb">A reference to the active Workflow Manager database</param> /// <param name="username">The name of the user to be tested</param> /// <param name="extraValues">An array of string values to be added to the list</param> /// <returns>A coded value domain of strings</returns> public static IGPDomain BuildAssignableUsersDomain(IJTXDatabase3 wmxDb, string username, string[] extraValues) { IGPCodedValueDomain domain = null; // Only proceed if the user exists in the Workflow Manager database IJTXUser3 user = wmxDb.ConfigurationManager.GetUser(username) as IJTXUser3; if (user == null) { return(domain as IGPDomain); } // Case 1: If the user can assign the job to anyone, then // just use the "all users" list if (user.HasNamedPrivilege(ESRI.ArcGIS.JTX.Utilities.Constants.PRIV_ASSIGN_ANY_JOB)) { domain = Common.WmauGpDomainBuilder.BuildUsersDomain(wmxDb, extraValues) as IGPCodedValueDomain; } else { domain = new GPCodedValueDomainClass(); string[] eligibleUsers = null; // Case 2: The user can assign jobs to anyone within any of their groups if (user.HasNamedPrivilege(ESRI.ArcGIS.JTX.Utilities.Constants.PRIV_GROUP_JOB_ASSIGN)) { HashSet <string> usernames = new HashSet <string>(); IJTXUserGroupSet groups = user.Groups; for (int i = 0; i < groups.Count; i++) { IJTXUserGroup group = groups.get_Item(i); for (int j = 0; j < group.Users.Count; j++) { usernames.Add(group.Users.get_Item(j).UserName); } } eligibleUsers = usernames.ToArray(); } // Case 3: The user can assign jobs to themselves else if (user.HasNamedPrivilege(ESRI.ArcGIS.JTX.Utilities.Constants.PRIV_INDIVIDUAL_JOB_ASSIGN)) { eligibleUsers = new string[] { username }; } // Case 4: The user can't assign jobs to anyone else { eligibleUsers = new string[0]; } // Sort the types first SortedList <string, string> sortedValues = new SortedList <string, string>(); for (int i = 0; i < eligibleUsers.Length; i++) { sortedValues.Add(eligibleUsers[i], null); } // Add the extra values, if any if (extraValues != null) { foreach (string s in extraValues) { sortedValues.Add(s, null); } } // Add the sorted types to the domain foreach (string value in sortedValues.Keys) { IGPValue tempGpVal = new GPStringClass(); tempGpVal.SetAsText(value); domain.AddCode(tempGpVal, value); } } return(domain as IGPDomain); }
/// <summary> /// Builds a domain consisting of the names of the system groups to which a /// user can assign a job. /// </summary> /// <param name="wmxDb">A reference to the active Workflow Manager database</param> /// <param name="username">The name of the user to be tested</param> /// <param name="extraValues">An array of string values to be added to the list</param> /// <returns>A coded value domain as an IGPDomain</returns> public static IGPDomain BuildAssignableGroupsDomain(IJTXDatabase3 wmxDb, string username, string[] extraValues) { IGPCodedValueDomain domain = new GPCodedValueDomainClass(); string[] eligibleGroups = null; // Only proceed if the user exists in the Workflow Manager database IJTXUser3 user = wmxDb.ConfigurationManager.GetUser(username) as IJTXUser3; if (user == null) { return(domain as IGPDomain); } // The groups to which this user can assign jobs are based on several // different permissions. Check these permissions, in order from least // restrictive to most restrictive. if (user.HasNamedPrivilege(ESRI.ArcGIS.JTX.Utilities.Constants.PRIV_ASSIGN_ANY_JOB)) { int numGroups = wmxDb.ConfigurationManager.UserGroups.Count; eligibleGroups = new string[numGroups]; for (int i = 0; i < numGroups; i++) { eligibleGroups[i] = wmxDb.ConfigurationManager.UserGroups.get_Item(i).Name; } } else if (user.HasNamedPrivilege(ESRI.ArcGIS.JTX.Utilities.Constants.PRIV_GROUP_JOB_ASSIGN)) { eligibleGroups = new string[user.Groups.Count]; for (int i = 0; i < user.Groups.Count; i++) { eligibleGroups[i] = user.Groups.get_Item(i).Name; } } else { eligibleGroups = new string[0]; } // Sort the types first SortedList <string, string> sortedValues = new SortedList <string, string>(); for (int i = 0; i < eligibleGroups.Length; i++) { sortedValues.Add(eligibleGroups[i], null); } // Add the extra values, if any if (extraValues != null) { foreach (string s in extraValues) { sortedValues.Add(s, null); } } // Add the sorted types to the domain foreach (string value in sortedValues.Keys) { IGPValue tempGpVal = new GPStringClass(); tempGpVal.SetAsText(value); domain.AddCode(tempGpVal, value); } return(domain as IGPDomain); }
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { _message = message; // classes to carry out the basic client/server communication HttpWebResponse httpResponse = null; string changeSetID = "-1"; IGPString baseURLGPString = new GPStringClass(); ICursor searchCursor = null; IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter userNameParameter = paramvalues.get_Element(in_userNameNumber) as IGPParameter; IGPString userNameGPValue = gpUtilities3.UnpackGPValue(userNameParameter) as IGPString; IHttpBasicGPValue userCredentialGPValue = new HttpBasicGPValue(); if (userNameGPValue != null) { userCredentialGPValue.UserName = userNameGPValue.Value; } else { return; } IGPParameter passwordParameter = paramvalues.get_Element(in_passwordNumber) as IGPParameter; IGPStringHidden passwordGPValue = gpUtilities3.UnpackGPValue(passwordParameter) as IGPStringHidden; if (passwordGPValue != null) { userCredentialGPValue.PassWord = passwordGPValue.Value; } else { return; } ITable revisionTable = null; int secondsToTimeout = 10; try { UpdateMessages(paramvalues, envMgr, message); if ((message.MaxSeverity == esriGPMessageSeverity.esriGPMessageSeverityAbort) || (message.MaxSeverity == esriGPMessageSeverity.esriGPMessageSeverityError)) { message.AddMessages(message); return; } IGPParameter baseURLParameter = paramvalues.get_Element(in_uploadURLNumber) as IGPParameter; baseURLGPString = gpUtilities3.UnpackGPValue(baseURLParameter) as IGPString; IGPParameter commentParameter = paramvalues.get_Element(in_uploadCommentNumber) as IGPParameter; IGPString uploadCommentGPString = gpUtilities3.UnpackGPValue(commentParameter) as IGPString; ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass() as ISpatialReferenceFactory; m_wgs84 = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984) as ISpatialReference; System.Xml.Serialization.XmlSerializer serializer = null; serializer = new XmlSerializer(typeof(osm)); osm createChangeSetOSM = new osm(); string user_displayname = ""; int userID = -1; // set the "default" value of the OSM server int maxElementsinChangeSet = 50000; HttpWebRequest httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/capabilities") as HttpWebRequest; httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient); SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord); httpClient.Timeout = secondsToTimeout * 1000; createChangeSetOSM.generator = m_Generator; createChangeSetOSM.version = "0.6"; changeset createChangeSet = new changeset(); createChangeSet.id = "0"; createChangeSet.open = changesetOpen.@false; List<tag> changeSetTags = new List<tag>(); tag createdByTag = new tag(); createdByTag.k = "created_by"; createdByTag.v = "ArcGIS Editor for OpenStreetMap"; changeSetTags.Add(createdByTag); tag commentTag = new tag(); commentTag.k = "comment"; commentTag.v = uploadCommentGPString.Value; changeSetTags.Add(commentTag); createChangeSet.tag = changeSetTags.ToArray(); createChangeSetOSM.Items = new object[] { createChangeSet }; api apiCapabilities = null; // retrieve some server settings try { httpResponse = httpClient.GetResponse() as HttpWebResponse; osm osmCapabilities = null; Stream stream = httpResponse.GetResponseStream(); XmlTextReader xmlReader = new XmlTextReader(stream); osmCapabilities = serializer.Deserialize(xmlReader) as osm; xmlReader.Close(); apiCapabilities = osmCapabilities.Items[0] as api; httpResponse.Close(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); message.AddWarning(ex.Message); } if (apiCapabilities != null) { // read the timeout parameter secondsToTimeout = Convert.ToInt32(apiCapabilities.timeout.seconds); httpClient.Timeout = secondsToTimeout * 1000; // update the setting of allowed features per changeset from the actual capabilities response maxElementsinChangeSet = Convert.ToInt32(apiCapabilities.changesets.maximum_elements); } // retrieve some information about the user try { httpClient = null; httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/user/details") as HttpWebRequest; httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient); SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord); httpResponse = httpClient.GetResponse() as HttpWebResponse; osm osmCapabilities = null; Stream stream = httpResponse.GetResponseStream(); XmlTextReader xmlReader = new XmlTextReader(stream); osmCapabilities = serializer.Deserialize(xmlReader) as osm; xmlReader.Close(); user userInformation = osmCapabilities.Items[0] as user; if (userInformation != null) { user_displayname = userInformation.display_name; userID = Convert.ToInt32(userInformation.id); } } catch (ArgumentOutOfRangeException ex) { message.AddError(120044, ex.Message); return; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); message.AddWarning(ex.Message); } IGPParameter revisionTableParameter = paramvalues.get_Element(in_changesTablesNumber) as IGPParameter; int featureUpdateCounter = 0; IQueryFilter revisionTableQueryFilter = null; try { gpUtilities3.DecodeTableView(gpUtilities3.UnpackGPValue(revisionTableParameter), out revisionTable, out revisionTableQueryFilter); } catch { message.AddError(120045,resourceManager.GetString("GPTools_OSMGPUpload_missingRevisionTable")); return; } int revChangeSetIDFieldIndex = revisionTable.Fields.FindField("osmchangeset"); int revActionFieldIndex = revisionTable.Fields.FindField("osmaction"); int revElementTypeFieldIndex = revisionTable.Fields.FindField("osmelementtype"); int revVersionFieldIndex = revisionTable.Fields.FindField("osmversion"); int revFCNameFieldIndex = revisionTable.Fields.FindField("sourcefcname"); int revOldIDFieldIndex = revisionTable.Fields.FindField("osmoldid"); int revNewIDFieldIndex = revisionTable.Fields.FindField("osmnewid"); int revStatusFieldIndex = revisionTable.Fields.FindField("osmstatus"); int revStatusCodeFieldIndex = revisionTable.Fields.FindField("osmstatuscode"); int revErrorMessageFieldIndex = revisionTable.Fields.FindField("osmerrormessage"); int revLongitudeFieldIndex = revisionTable.Fields.FindField("osmlon"); int revLatitudeFieldIndex = revisionTable.Fields.FindField("osmlat"); // let's find all the rows that have a different status than OK - meaning success IQueryFilter queryFilter = new QueryFilterClass(); searchCursor = revisionTable.Search(queryFilter, false); IRow searchRowToUpdate = null; // lookup table to adjust all osm ID references if there are know entities Dictionary<long, long> nodeosmIDLookup = new Dictionary<long, long>(); Dictionary<long, long> wayosmIDLookup = new Dictionary<long, long>(); Dictionary<long, long> relationosmIDLookup = new Dictionary<long, long>(); // let's pre-populate the lookup IDs with already know entities // it is necessary if the revision table is used more than once and in different sessions queryFilter.WhereClause = "NOT " + revisionTable.SqlIdentifier("osmnewid") + " IS NULL"; using (ComReleaser comReleaser = new ComReleaser()) { ICursor searchIDCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchIDCursor); IRow searchRow = searchIDCursor.NextRow(); comReleaser.ManageLifetime(searchRow); while (searchRow != null) { if (revOldIDFieldIndex > -1 && revNewIDFieldIndex > -1) { string elementType = Convert.ToString(searchRow.get_Value(revElementTypeFieldIndex)); switch (elementType) { case "node": if (nodeosmIDLookup.ContainsKey(Convert.ToInt64(searchRow.get_Value(revOldIDFieldIndex))) == false) { nodeosmIDLookup.Add(Convert.ToInt64(searchRow.get_Value(revOldIDFieldIndex)), Convert.ToInt64(searchRow.get_Value(revNewIDFieldIndex))); } break; case "way": if (wayosmIDLookup.ContainsKey(Convert.ToInt64(searchRow.get_Value(revOldIDFieldIndex))) == false) { wayosmIDLookup.Add(Convert.ToInt64(searchRow.get_Value(revOldIDFieldIndex)), Convert.ToInt64(searchRow.get_Value(revNewIDFieldIndex))); } break; case "relation": if (relationosmIDLookup.ContainsKey(Convert.ToInt64(searchRow.get_Value(revOldIDFieldIndex))) == false) { relationosmIDLookup.Add(Convert.ToInt64(searchRow.get_Value(revOldIDFieldIndex)), Convert.ToInt64(searchRow.get_Value(revNewIDFieldIndex))); } break; default: break; } } searchRow = searchIDCursor.NextRow(); } } IFeatureClass pointFeatureClass = null; int pointOSMIDFieldIndex = -1; IFeatureClass lineFeatureClass = null; IFeatureClass polygonFeatureClass = null; ITable relationTable = null; int osmDelimiterPosition = ((IDataset)revisionTable).Name.IndexOf("_osm_"); string osmBaseName = ((IDataset)revisionTable).Name.Substring(0, osmDelimiterPosition); IFeatureWorkspace osmFeatureWorkspace = ((IDataset)revisionTable).Workspace as IFeatureWorkspace; if (osmFeatureWorkspace != null) { pointFeatureClass = osmFeatureWorkspace.OpenFeatureClass(osmBaseName + "_osm_pt"); pointOSMIDFieldIndex = pointFeatureClass.FindField("OSMID"); lineFeatureClass = osmFeatureWorkspace.OpenFeatureClass(osmBaseName + "_osm_ln"); polygonFeatureClass = osmFeatureWorkspace.OpenFeatureClass(osmBaseName + "_osm_ply"); relationTable = osmFeatureWorkspace.OpenTable(osmBaseName + "_osm_relation"); } // determine version of extension int internalExtensionVersion = pointFeatureClass.OSMExtensionVersion(); string sData = OsmRest.SerializeUtils.CreateXmlSerializable(createChangeSetOSM, serializer, Encoding.ASCII, "text/xml"); HttpWebRequest httpClient2 = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/changeset/create") as HttpWebRequest; httpClient2.Method = "PUT"; httpClient2 = OSMGPDownload.AssignProxyandCredentials(httpClient2); SetBasicAuthHeader(httpClient2, userCredentialGPValue.EncodedUserNamePassWord); httpClient2.Timeout = secondsToTimeout * 1000; try { Stream requestStream = httpClient2.GetRequestStream(); StreamWriter mywriter = new StreamWriter(requestStream); mywriter.Write(sData); mywriter.Close(); WebResponse clientResponse = httpClient2.GetResponse(); Stream readStream = clientResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(readStream); changeSetID = streamReader.ReadToEnd(); streamReader.Close(); message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPUpload_openChangeSet"), changeSetID)); } catch (Exception ex) { if (httpResponse != null) { if (httpResponse.StatusCode != System.Net.HttpStatusCode.OK) { foreach (var errorItem in httpResponse.Headers.GetValues("Error")) { message.AddError(120009, errorItem); } message.AddError(120009, httpResponse.StatusCode.ToString()); message.AddError(120009, ex.Message); } } else { message.AddError(120047, ex.Message); } return; } IGPParameter uploadFormatParameter = paramvalues.get_Element(in_uploadFormatNumber) as IGPParameter; IGPBoolean useOSMChangeFormatGPValue = gpUtilities3.UnpackGPValue(uploadFormatParameter) as IGPBoolean; // Al Hack if (useOSMChangeFormatGPValue == null) { useOSMChangeFormatGPValue = new GPBoolean(); useOSMChangeFormatGPValue.Value = false; } SQLFormatter sqlFormatter = new SQLFormatter(revisionTable); if (useOSMChangeFormatGPValue.Value == true) { #region osmchange upload format osmChange osmChangeDocument = new osmChange(); osmChangeDocument.generator = m_Generator; osmChangeDocument.version = "0.6"; // xml elements to describe the changeset create uploadCreates = null; modify uploadModify = null; delete uploadDelete = null; // helper classes to keep track of elements entered into a changeset List<object> listOfCreates = null; List<object> listOfModifies = null; List<object> listOfDeletes = null; List<object> changeSetItems = new List<object>(); #region upload create actions // loop through creates queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'create'"; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); searchRowToUpdate = searchCursor.NextRow(); comReleaser.ManageLifetime(searchRowToUpdate); // if we have at least one entry with a create action, then add the 'create' element to the changeset representation if (searchRowToUpdate != null) { uploadCreates = new create(); listOfCreates = new List<object>(); } while (searchRowToUpdate != null) { try { if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } string action = String.Empty; if (revActionFieldIndex != -1) { action = searchRowToUpdate.get_Value(revActionFieldIndex) as string; } string elementType = String.Empty; if (revElementTypeFieldIndex != -1) { elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string; } string sourceFCName = String.Empty; if (revFCNameFieldIndex != -1) { sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string; } long osmOldID = -1; if (revOldIDFieldIndex != -1) { osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } // if the overall number of uploaded elements is too big for a single changeset we do need to split it up // into multiple sets if (featureUpdateCounter > 0 & (featureUpdateCounter % maxElementsinChangeSet) == 0) { // add any outstanding creations to the changeset items if (listOfCreates != null && uploadCreates != null) { uploadCreates.Items = listOfCreates.ToArray(); // in case there are any creates let's add them to the changeset document changeSetItems.Add(uploadCreates); } // add all the changeset items to the changeset document osmChangeDocument.Items = changeSetItems.ToArray(); // submit changeset try { httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/changeset/" + changeSetID + "/upload") as HttpWebRequest; httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient); httpClient.Method = "POST"; SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord); httpClient.Timeout = secondsToTimeout * 1000; string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(osmChangeDocument, null, Encoding.UTF8, "text/xml"); message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPUpload_featureSubmit"), featureUpdateCounter)); OsmRest.HttpUtils.Post(httpClient, sContent); httpResponse = httpClient.GetResponse() as HttpWebResponse; diffResult diffResultResonse = OsmRest.HttpUtils.GetResponse(httpResponse); // parse changes locally and update local data sources if (diffResultResonse != null) { ParseResultDiff(diffResultResonse, revisionTable, pointFeatureClass, lineFeatureClass, polygonFeatureClass, relationTable, user_displayname, userID, changeSetID, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } } catch (Exception ex) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); message.AddError(120009, ex.Message); if (ex is WebException) { WebException webException = ex as WebException; string serverErrorMessage = webException.Response.Headers["Error"]; if (!String.IsNullOrEmpty(serverErrorMessage)) { message.AddError(120009, serverErrorMessage); } } if (httpResponse != null) { httpResponse.Close(); } return; } finally { // reset the list and containers of modifications for the next batch listOfCreates.Clear(); changeSetItems.Clear(); if (httpResponse != null) { httpResponse.Close(); } } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } switch (elementType) { case "node": node createNode = CreateNodeRepresentation(pointFeatureClass, action, osmOldID, changeSetID, 1, null, internalExtensionVersion); listOfCreates.Add(createNode); break; case "way": way createWay = null; if (sourceFCName.Contains("_osm_ln")) { createWay = CreateWayRepresentation(lineFeatureClass, action, osmOldID, changeSetID, 1, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_ply")) { createWay = CreateWayRepresentation(polygonFeatureClass, action, osmOldID, changeSetID, 1, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } listOfCreates.Add(createWay); break; case "relation": relation createRelation = null; if (sourceFCName.Contains("_osm_ln")) { createRelation = CreateRelationRepresentation((ITable)lineFeatureClass, action, osmOldID, changeSetID, 1, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_ply")) { createRelation = CreateRelationRepresentation((ITable)polygonFeatureClass, action, osmOldID, changeSetID, 1, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_relation")) { createRelation = CreateRelationRepresentation(relationTable, action, osmOldID, changeSetID, 1, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } listOfCreates.Add(createRelation); break; default: break; } // increment the counter keeping track of the submitted changes featureUpdateCounter = featureUpdateCounter + 1; } catch { } searchRowToUpdate = searchCursor.NextRow(); } if (listOfCreates != null && uploadCreates != null) { // sort the list of created elements in the order of nodes, ways, relations listOfCreates.Sort(new OSMElementComparer()); uploadCreates.Items = listOfCreates.ToArray(); // in case there are any creates let's add them to the changeset document changeSetItems.Add(uploadCreates); } } #endregion #region upload modify actions // loop through modifies using (ComReleaser comReleaser = new ComReleaser()) { queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'modify'"; searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); searchRowToUpdate = searchCursor.NextRow(); if (searchRowToUpdate != null) { uploadModify = new modify(); listOfModifies = new List<object>(); } while (searchRowToUpdate != null) { if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } try { string action = String.Empty; if (revActionFieldIndex != -1) { action = searchRowToUpdate.get_Value(revActionFieldIndex) as string; } string elementType = String.Empty; if (revElementTypeFieldIndex != -1) { elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string; } string sourceFCName = String.Empty; if (revFCNameFieldIndex != -1) { sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string; } long osmOldID = -1; if (revOldIDFieldIndex != -1) { osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } // if the overall number of uploaded elements is too big for a single changeset we do need to split it up long modifyID = -1; if (revNewIDFieldIndex != -1) { object osmIDValue = searchRowToUpdate.get_Value(revNewIDFieldIndex); if (osmIDValue == DBNull.Value) { osmIDValue = osmOldID; } try { modifyID = Convert.ToInt64(osmIDValue); } catch { } // modifies should only happen to osm IDs > 0 // if that condition is not met let's skip this feature as something is not right if (modifyID < 0) { searchRowToUpdate = searchCursor.NextRow(); continue; } } int osmVersion = -1; if (revVersionFieldIndex != -1) { osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex)); } // into multiple sets if ((featureUpdateCounter % maxElementsinChangeSet) == 0) { // add any outstanding modifications to the changeset items if (listOfModifies != null && uploadModify != null) { uploadModify.Items = listOfModifies.ToArray(); // in case there are any creates let's add them to the changeset document changeSetItems.Add(uploadModify); } // add all the changeset items to the changeset document osmChangeDocument.Items = changeSetItems.ToArray(); // submit changeset try { httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/changeset/" + changeSetID + "/upload") as HttpWebRequest; httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient); httpClient.Method = "POST"; SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord); httpClient.Timeout = secondsToTimeout * 1000; string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(osmChangeDocument, null, Encoding.UTF8, "text/xml"); OsmRest.HttpUtils.Post(httpClient, sContent); httpResponse = httpClient.GetResponse() as HttpWebResponse; diffResult diffResultResonse = OsmRest.HttpUtils.GetResponse(httpResponse); // parse changes locally and update local data sources if (diffResultResonse != null) { ParseResultDiff(diffResultResonse, revisionTable, pointFeatureClass, lineFeatureClass, polygonFeatureClass, relationTable, user_displayname, userID, changeSetID, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } } catch (Exception ex) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); message.AddError(120009, ex.Message); if (ex is WebException) { WebException webException = ex as WebException; string serverErrorMessage = webException.Response.Headers["Error"]; if (!String.IsNullOrEmpty(serverErrorMessage)) { message.AddError(120009, serverErrorMessage); } if (httpResponse != null) { httpResponse.Close(); } } return; } finally { // reset the list and containers of modifications for the next batch listOfModifies.Clear(); changeSetItems.Clear(); if (httpResponse != null) { httpResponse.Close(); } } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } switch (elementType) { case "node": node updateNode = CreateNodeRepresentation(pointFeatureClass, action, modifyID, changeSetID, osmVersion, null, internalExtensionVersion); listOfModifies.Add(updateNode); break; case "way": way updateWay = null; if (sourceFCName.Contains("_osm_ln")) { updateWay = CreateWayRepresentation(lineFeatureClass, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_ply")) { updateWay = CreateWayRepresentation(polygonFeatureClass, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } listOfModifies.Add(updateWay); break; case "relation": relation updateRelation = null; if (sourceFCName.Contains("_osm_ln")) { updateRelation = CreateRelationRepresentation((ITable)lineFeatureClass, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_ply")) { updateRelation = CreateRelationRepresentation((ITable)polygonFeatureClass, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_relation")) { updateRelation = CreateRelationRepresentation(relationTable, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } listOfModifies.Add(updateRelation); break; default: break; } // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; } catch { } searchRowToUpdate = searchCursor.NextRow(); } if (listOfModifies != null && uploadModify != null) { uploadModify.Items = listOfModifies.ToArray(); // in case there are any creates let's add them to the changeset document changeSetItems.Add(uploadModify); } } #endregion #region upload delete actions // loop through deletes in "reverse" - relation, then way, then node string[] elementTypes = new string[] { "relation", "way", "node" }; foreach (string osmElementType in elementTypes) { using (ComReleaser comReleaser = new ComReleaser()) { queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'delete' AND " + sqlFormatter.SqlIdentifier("osmelementtype") + " = '" + osmElementType + "'"; searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); searchRowToUpdate = searchCursor.NextRow(); if (searchRowToUpdate != null) { if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } if (uploadDelete == null) { uploadDelete = new delete(); listOfDeletes = new List<object>(); } } while (searchRowToUpdate != null) { try { string action = String.Empty; if (revActionFieldIndex != -1) { action = searchRowToUpdate.get_Value(revActionFieldIndex) as string; } string elementType = String.Empty; if (revElementTypeFieldIndex != -1) { elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string; } string sourceFCName = String.Empty; if (revFCNameFieldIndex != -1) { sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string; } long osmOldID = -1; if (revOldIDFieldIndex != -1) { osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } int osmVersion = -1; if (revVersionFieldIndex != -1) { osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex)); } // into multiple sets if ((featureUpdateCounter % maxElementsinChangeSet) == 0) { // add any outstanding creations to the changeset items if (listOfDeletes != null && uploadDelete != null) { uploadDelete.Items = listOfDeletes.ToArray(); // in case there are any creates let's add them to the changeset document changeSetItems.Add(uploadDelete); } // add all the changeset items to the changeset document osmChangeDocument.Items = changeSetItems.ToArray(); // submit changeset try { httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/changeset/" + changeSetID + "/upload") as HttpWebRequest; httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient); httpClient.Method = "POST"; SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord); httpClient.Timeout = secondsToTimeout * 1000; string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(osmChangeDocument, null, Encoding.UTF8, "text/xml"); OsmRest.HttpUtils.Post(httpClient, sContent); httpResponse = httpClient.GetResponse() as HttpWebResponse; diffResult diffResultResonse = OsmRest.HttpUtils.GetResponse(httpResponse); // parse changes locally and update local data sources if (diffResultResonse != null) { ParseResultDiff(diffResultResonse, revisionTable, pointFeatureClass, lineFeatureClass, polygonFeatureClass, relationTable, user_displayname, userID, changeSetID, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } } catch (Exception ex) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); message.AddError(120009, ex.Message); if (ex is WebException) { WebException webException = ex as WebException; string serverErrorMessage = webException.Response.Headers["Error"]; if (!String.IsNullOrEmpty(serverErrorMessage)) { message.AddError(120009, serverErrorMessage); } } if (httpResponse != null) { httpResponse.Close(); } return; } finally { // reset the list and containers of modifications for the next batch listOfDeletes.Clear(); changeSetItems.Clear(); if (httpResponse != null) { httpResponse.Close(); } } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } switch (elementType) { case "node": IPoint deletePoint = null; if (revLongitudeFieldIndex != -1 && revLatitudeFieldIndex != -1) { try { // let's reconstruct the delete point deletePoint = new PointClass(); deletePoint.X = Convert.ToDouble(searchRowToUpdate.get_Value(revLongitudeFieldIndex)); deletePoint.Y = Convert.ToDouble(searchRowToUpdate.get_Value(revLatitudeFieldIndex)); deletePoint.SpatialReference = m_wgs84; } catch (Exception ex) { message.AddWarning(ex.Message); } if (deletePoint == null) { // inform the about the issue - no successful creation of point and continue on to the next delete instruction // in the revision table message.AddWarning(resourceManager.GetString("GPTools_OSMGPUpload_invalidPoint")); searchRowToUpdate = searchCursor.NextRow(); continue; } } node deleteNode = CreateNodeRepresentation(pointFeatureClass, action, osmOldID, changeSetID, osmVersion, deletePoint, internalExtensionVersion); listOfDeletes.Add(deleteNode); break; case "way": way deleteWay = null; if (sourceFCName.Contains("_osm_ln")) { deleteWay = CreateWayRepresentation(lineFeatureClass, action, osmOldID, changeSetID, osmVersion, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_ply")) { deleteWay = CreateWayRepresentation(polygonFeatureClass, action, osmOldID, changeSetID, osmVersion, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } listOfDeletes.Add(deleteWay); break; case "relation": relation deleteRelation = null; if (sourceFCName.Contains("_osm_ln")) { deleteRelation = CreateRelationRepresentation((ITable)lineFeatureClass, action, osmOldID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_ply")) { deleteRelation = CreateRelationRepresentation((ITable)polygonFeatureClass, action, osmOldID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_relation")) { deleteRelation = CreateRelationRepresentation(relationTable, action, osmOldID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } listOfDeletes.Add(deleteRelation); break; default: break; } // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; } catch { } searchRowToUpdate = searchCursor.NextRow(); } } } if (listOfDeletes != null && uploadDelete != null) { uploadDelete.Items = listOfDeletes.ToArray(); // in case there are any creates let's add them to the changeset document changeSetItems.Add(uploadDelete); } #endregion if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } // add all the changeset items to the changeset document osmChangeDocument.Items = changeSetItems.ToArray(); // submit changeset try { httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/changeset/" + changeSetID + "/upload") as HttpWebRequest; httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient); httpClient.Method = "POST"; SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord); httpClient.Timeout = secondsToTimeout * 1000; message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPUpload_featureSubmit"), featureUpdateCounter)); string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(osmChangeDocument, null, Encoding.UTF8, "text/xml"); OsmRest.HttpUtils.Post(httpClient, sContent); httpResponse = httpClient.GetResponse() as HttpWebResponse; //Exception with an error HTTP 400 diffResult diffResultResonse = OsmRest.HttpUtils.GetResponse(httpResponse); message.AddMessage(resourceManager.GetString("GPTools_OSMGPUpload_updatelocalData")); // parse changes locally and update local data sources if (diffResultResonse != null) { ParseResultDiff(diffResultResonse, revisionTable, pointFeatureClass, lineFeatureClass, polygonFeatureClass, relationTable, user_displayname, userID, changeSetID, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } } catch (Exception ex) { message.AddError(120009, ex.Message); try { if (ex is WebException) { WebException webException = ex as WebException; string serverErrorMessage = webException.Response.Headers["Error"]; if (!String.IsNullOrEmpty(serverErrorMessage)) { message.AddError(120009, serverErrorMessage); } } } catch (Exception innerexception) { message.AddError(120009, innerexception.Message); } } finally { if (httpResponse != null) { httpResponse.Close(); } } #endregion } else { #region single upload format #region submit the create nodes first queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'create' AND " + sqlFormatter.SqlIdentifier("osmelementtype") + " = 'node'"; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); while ((searchRowToUpdate = searchCursor.NextRow()) != null) { try { string action = String.Empty; if (revActionFieldIndex != -1) { action = searchRowToUpdate.get_Value(revActionFieldIndex) as string; } string elementType = String.Empty; if (revElementTypeFieldIndex != -1) { elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string; } string sourceFCName = String.Empty; if (revFCNameFieldIndex != -1) { sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string; } long osmOldID = -1; if (revOldIDFieldIndex != -1) { osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } // if the overall number of uploaded elements is too big for a single changeset we do need to split it up // into multiple sets if ((featureUpdateCounter % maxElementsinChangeSet) == 0) { CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } osm createNode = CreateOSMNodeRepresentation(pointFeatureClass, action, osmOldID, changeSetID, -1, null, internalExtensionVersion); httpClient = null; httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/" + elementType + "/create") as HttpWebRequest; httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient); httpClient.Method = "PUT"; SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord); httpClient.Timeout = secondsToTimeout * 1000; httpResponse = null; string nodeContent = OsmRest.SerializeUtils.CreateXmlSerializable(createNode, serializer, Encoding.UTF8, "text/xml"); if (String.IsNullOrEmpty(nodeContent)) { continue; } OsmRest.HttpUtils.Put(httpClient, nodeContent); httpResponse = httpClient.GetResponse() as HttpWebResponse; createNode = null; // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; if (httpResponse != null) { string newIDString = OsmRest.HttpUtils.GetResponseContent(httpResponse); nodeosmIDLookup.Add(osmOldID, Convert.ToInt64(newIDString)); // update the revision table if (revNewIDFieldIndex != -1) { searchRowToUpdate.set_Value(revNewIDFieldIndex, Convert.ToString(newIDString)); } if (revVersionFieldIndex != -1) { searchRowToUpdate.set_Value(revVersionFieldIndex, 1); } if (revStatusFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusFieldIndex, httpResponse.StatusCode.ToString()); } if (revStatusCodeFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode); } if (revChangeSetIDFieldIndex != -1) { searchRowToUpdate.set_Value(revChangeSetIDFieldIndex, Convert.ToString(changeSetID)); } // update the source point feature class as well updateSource((ITable)pointFeatureClass, action, osmOldID, Convert.ToInt64(newIDString), user_displayname, userID, 1, Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup,internalExtensionVersion); } } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } } finally { try { searchRowToUpdate.Store(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } if (httpResponse != null) { httpResponse.Close(); } } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } } } #endregion #region next the create ways queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'create' AND " + sqlFormatter.SqlIdentifier("osmelementtype") + " = 'way'"; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); while ((searchRowToUpdate = searchCursor.NextRow()) != null) { try { string action = String.Empty; if (revActionFieldIndex != -1) { action = searchRowToUpdate.get_Value(revActionFieldIndex) as string; } string elementType = String.Empty; if (revElementTypeFieldIndex != -1) { elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string; } string sourceFCName = String.Empty; if (revFCNameFieldIndex != -1) { sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string; } long osmOldID = -1; if (revOldIDFieldIndex != -1) { osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } bool isPolygon = false; if (sourceFCName.IndexOf("_osm_ply") > -1) { isPolygon = true; } // if the overall number of uploaded elements is too big for a single changeset we do need to split it up // into multiple sets if ((featureUpdateCounter % maxElementsinChangeSet) == 0) { CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } osm createWay = new osm(); if (isPolygon == false) { createWay = CreateOSMWayRepresentation(lineFeatureClass, action, osmOldID, changeSetID, -1, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } else { createWay = CreateOSMWayRepresentation(polygonFeatureClass, action, osmOldID, changeSetID, -1, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } try { HttpWebRequest httpClient3 = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/" + elementType + "/create") as HttpWebRequest; httpClient3 = OSMGPDownload.AssignProxyandCredentials(httpClient3); httpClient3.Method = "PUT"; SetBasicAuthHeader(httpClient3, userCredentialGPValue.EncodedUserNamePassWord); httpClient.Timeout = secondsToTimeout * 1000; string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(createWay, serializer, Encoding.UTF8, "text/xml"); OsmRest.HttpUtils.Put(httpClient3, sContent); createWay = null; httpResponse = null; httpResponse = httpClient3.GetResponse() as HttpWebResponse; // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } } if (httpResponse != null) { string newIDString = OsmRest.HttpUtils.GetResponseContent(httpResponse); wayosmIDLookup.Add(osmOldID, Convert.ToInt64(newIDString)); // update the revision table if (revNewIDFieldIndex != -1) { searchRowToUpdate.set_Value(revNewIDFieldIndex, Convert.ToString(newIDString)); } if (revVersionFieldIndex != -1) { searchRowToUpdate.set_Value(revVersionFieldIndex, 1); } if (revStatusFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusFieldIndex, httpResponse.StatusCode.ToString()); } if (revStatusCodeFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode); } if (revChangeSetIDFieldIndex != -1) { searchRowToUpdate.set_Value(revChangeSetIDFieldIndex, Convert.ToString(changeSetID)); } // update the source line/polygon feature class as well if (isPolygon == false) { updateSource((ITable)lineFeatureClass, action, osmOldID, Convert.ToInt64(newIDString), user_displayname, userID, 1, Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else { updateSource((ITable)polygonFeatureClass, action, osmOldID, Convert.ToInt64(newIDString), user_displayname, userID, 1, Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } } } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } } finally { try { searchRowToUpdate.Store(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } if (httpResponse != null) { httpResponse.Close(); } } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } } } #endregion #region and then create relations queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'create' AND " + sqlFormatter.SqlIdentifier("osmelementtype") + " = 'relation'"; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); while ((searchRowToUpdate = searchCursor.NextRow()) != null) { try { string action = String.Empty; if (revActionFieldIndex != -1) { action = searchRowToUpdate.get_Value(revActionFieldIndex) as string; } string elementType = String.Empty; if (revElementTypeFieldIndex != -1) { elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string; } string sourceFCName = String.Empty; if (revFCNameFieldIndex != -1) { sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string; } long osmOldID = -1; if (revOldIDFieldIndex != -1) { osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } bool isPolygon = false; if (sourceFCName.IndexOf("_osm_ply") > -1) { isPolygon = true; } // if the overall number of uploaded elements is too big for a single changeset we do need to split it up // into multiple sets if ((featureUpdateCounter % maxElementsinChangeSet) == 0) { CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } osm createRelation = null; // the relation is acutally multi-part line if (sourceFCName.Contains("_osm_ln")) { createRelation = CreateOSMRelationRepresentation((ITable)lineFeatureClass, action, osmOldID, changeSetID, -1, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_ply")) { createRelation = CreateOSMRelationRepresentation((ITable)polygonFeatureClass, action, osmOldID, changeSetID, -1, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else { createRelation = CreateOSMRelationRepresentation(relationTable, action, osmOldID, changeSetID, -1, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } try { HttpWebRequest httpClient4 = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/" + elementType + "/create") as HttpWebRequest; httpClient4 = OSMGPDownload.AssignProxyandCredentials(httpClient4); SetBasicAuthHeader(httpClient4, userCredentialGPValue.EncodedUserNamePassWord); httpClient4.Timeout = secondsToTimeout * 1000; string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(createRelation, serializer, Encoding.UTF8, "text/xml"); OsmRest.HttpUtils.Put(httpClient4, sContent); httpResponse = null; httpResponse = httpClient4.GetResponse() as HttpWebResponse; // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } } if (httpResponse != null) { string newIDString = OsmRest.HttpUtils.GetResponseContent(httpResponse); relationosmIDLookup.Add(osmOldID, Convert.ToInt64(newIDString)); // update the revision table if (revNewIDFieldIndex != -1) { searchRowToUpdate.set_Value(revNewIDFieldIndex, Convert.ToString(newIDString)); } if (revVersionFieldIndex != -1) { searchRowToUpdate.set_Value(revVersionFieldIndex, 1); } if (revStatusFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusFieldIndex, httpResponse.StatusCode.ToString()); } if (revStatusCodeFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode); } if (revChangeSetIDFieldIndex != -1) { searchRowToUpdate.set_Value(revChangeSetIDFieldIndex, Convert.ToInt32(changeSetID)); } if (sourceFCName.Contains("_osm_ln")) { updateSource((ITable)lineFeatureClass, action, osmOldID, Convert.ToInt64(newIDString), user_displayname, userID, 1, Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else if (sourceFCName.Contains("_osm_ply")) { updateSource((ITable)polygonFeatureClass, action, osmOldID, Convert.ToInt64(newIDString), user_displayname, userID, 1, Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else { // update the source table holding the relation information class as well updateSource(relationTable, action, osmOldID, Convert.ToInt64(newIDString), user_displayname, userID, 1, Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } } } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } } finally { try { searchRowToUpdate.Store(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } } } #endregion #region after that submit the modify node, way, relation using (ComReleaser comReleaser = new ComReleaser()) { queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'modify'"; searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); while ((searchRowToUpdate = searchCursor.NextRow()) != null) { try { string action = String.Empty; if (revActionFieldIndex != -1) { action = searchRowToUpdate.get_Value(revActionFieldIndex) as string; } string elementType = String.Empty; if (revElementTypeFieldIndex != -1) { elementType = searchRowToUpdate.get_Value(revElementTypeFieldIndex) as string; } string sourceFCName = String.Empty; if (revFCNameFieldIndex != -1) { sourceFCName = searchRowToUpdate.get_Value(revFCNameFieldIndex) as string; } long osmOldID = -1; if (revOldIDFieldIndex != -1) { osmOldID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } // if the overall number of uploaded elements is too big for a single changeset we do need to split it up // into multiple sets if ((featureUpdateCounter % maxElementsinChangeSet) == 0) { CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } switch (elementType) { case "node": #region submit nodes to OSM server switch (action) { case "modify": long modifyID = -1; if (revNewIDFieldIndex != -1) { object osmIDValue = searchRowToUpdate.get_Value(revNewIDFieldIndex); if (osmIDValue == DBNull.Value) { osmIDValue = osmOldID; } try { modifyID = Convert.ToInt64(osmIDValue); } catch { } // modifies should only happen to osm IDs > 0 // if that condition is not met let's skip this feature as something is not right if (modifyID < 0) { continue; } } int osmVersion = -1; if (revVersionFieldIndex != -1) { osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex)); } try { HttpWebRequest httpClient5 = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/" + elementType + "/" + modifyID.ToString()) as HttpWebRequest; httpClient5 = OSMGPDownload.AssignProxyandCredentials(httpClient5); SetBasicAuthHeader(httpClient5, userCredentialGPValue.EncodedUserNamePassWord); osm updateNode = CreateOSMNodeRepresentation(pointFeatureClass, action, modifyID, changeSetID, osmVersion, null, internalExtensionVersion); string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(updateNode, serializer, Encoding.UTF8, "text/xml"); // if the serialized node at this time is a null or an empty string let's continue to the next point if (String.IsNullOrEmpty(sContent)) { continue; } OsmRest.HttpUtils.Put(httpClient5, sContent); httpResponse = httpClient5.GetResponse() as HttpWebResponse; // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; if (httpResponse != null) { string newVersionString = OsmRest.HttpUtils.GetResponseContent(httpResponse); // update the revision table if (revVersionFieldIndex != -1) { searchRowToUpdate.set_Value(revVersionFieldIndex, Convert.ToString(newVersionString)); } if (revStatusFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusFieldIndex, httpResponse.StatusCode.ToString()); } if (revStatusCodeFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode); } if (revChangeSetIDFieldIndex != -1) { searchRowToUpdate.set_Value(revChangeSetIDFieldIndex, Convert.ToInt32(changeSetID)); } // for a modify the old id is still the new id if (revNewIDFieldIndex != -1 && revOldIDFieldIndex != -1) { searchRowToUpdate.set_Value(revNewIDFieldIndex, searchRowToUpdate.get_Value(revOldIDFieldIndex)); } // update the source point feature class as well updateSource((ITable)pointFeatureClass, action, modifyID, modifyID, user_displayname, userID, Convert.ToInt32(newVersionString), Convert.ToInt32(changeSetID), null, null, null, internalExtensionVersion); httpResponse.Close(); } } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } } break; case "delete": // the delete operations are handled separately break; default: break; } break; #endregion case "way": #region submit ways to the OSM server // determine if we have a polygon or a polyline feature class bool isPolygon = false; if (sourceFCName.IndexOf("_osm_ply") > -1) { isPolygon = true; } switch (action) { case "modify": long modifyID = -1; if (revNewIDFieldIndex != -1) { object osmIDValue = searchRowToUpdate.get_Value(revNewIDFieldIndex); if (osmIDValue == DBNull.Value) { osmIDValue = osmOldID; } try { modifyID = Convert.ToInt64(osmIDValue); } catch { } // modifies should only happen to osm IDs > 0 // if that condition is not met let's skip this feature as something is not right if (modifyID < 0) { continue; } } int osmVersion = -1; if (revVersionFieldIndex != -1) { osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex)); } osm updateWay = new osm(); if (isPolygon == false) { updateWay = CreateOSMWayRepresentation(lineFeatureClass, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } else { updateWay = CreateOSMWayRepresentation(polygonFeatureClass, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); } try { string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(updateWay, serializer, Encoding.UTF8, "text/xml"); httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/" + elementType + "/" + modifyID.ToString()) as HttpWebRequest; httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient); SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord); OsmRest.HttpUtils.Put(httpClient, sContent); httpResponse = httpClient.GetResponse() as HttpWebResponse; // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; if (httpResponse != null) { string newVersionString = OsmRest.HttpUtils.GetResponseContent(httpResponse); // update the revision table if (revVersionFieldIndex != -1) { searchRowToUpdate.set_Value(revVersionFieldIndex, Convert.ToString(newVersionString)); } if (revStatusFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusFieldIndex, httpResponse.StatusCode.ToString()); } if (revStatusCodeFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode); } if (revChangeSetIDFieldIndex != -1) { searchRowToUpdate.set_Value(revChangeSetIDFieldIndex, Convert.ToInt32(changeSetID)); } // for a modify the old id is still the new id if (revNewIDFieldIndex != -1 && revOldIDFieldIndex != -1) { searchRowToUpdate.set_Value(revNewIDFieldIndex, searchRowToUpdate.get_Value(revOldIDFieldIndex)); } // update the source line/polygon feature class as well if (isPolygon == false) { updateSource((ITable)lineFeatureClass, action, modifyID, modifyID, user_displayname, userID, Convert.ToInt32(newVersionString), Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } else { updateSource((ITable)polygonFeatureClass, action, modifyID, modifyID, user_displayname, userID, Convert.ToInt32(newVersionString), Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); } httpResponse.Close(); } } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } } break; case "delete": // the delete operations are handled separately break; default: break; } break; #endregion case "relation": #region submit relations to the OSM server switch (action) { case "create": break; case "modify": long modifyID = -1; if (revNewIDFieldIndex != -1) { object osmIDValue = searchRowToUpdate.get_Value(revNewIDFieldIndex); if (osmIDValue == DBNull.Value) { osmIDValue = osmOldID; } try { modifyID = Convert.ToInt64(osmIDValue); } catch { } // modifies should only happen to osm IDs > 0 // if that condition is not met let's skip this feature as something is not right if (modifyID < 0) { continue; } } int osmVersion = -1; if (revVersionFieldIndex != -1) { osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex)); } osm updateRelation = CreateOSMRelationRepresentation(relationTable, action, modifyID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); try { string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(updateRelation, serializer, Encoding.UTF8, "text/xml"); httpClient = HttpWebRequest.Create(baseURLGPString.Value + "/api/0.6/" + elementType + "/" + modifyID.ToString()) as HttpWebRequest; httpClient = OSMGPDownload.AssignProxyandCredentials(httpClient); SetBasicAuthHeader(httpClient, userCredentialGPValue.EncodedUserNamePassWord); OsmRest.HttpUtils.Put(httpClient, sContent); httpResponse = httpClient.GetResponse() as HttpWebResponse; // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; if (httpResponse != null) { string newVersionString = OsmRest.HttpUtils.GetResponseContent(httpResponse); // update the revision table if (revVersionFieldIndex != -1) { searchRowToUpdate.set_Value(revVersionFieldIndex, Convert.ToInt32(newVersionString)); } if (revStatusFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusFieldIndex, httpResponse.StatusCode.ToString()); } if (revStatusCodeFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode); } if (revChangeSetIDFieldIndex != -1) { searchRowToUpdate.set_Value(revChangeSetIDFieldIndex, Convert.ToInt32(changeSetID)); } // for a modify the old id is still the new id if (revNewIDFieldIndex != -1 && revOldIDFieldIndex != -1) { searchRowToUpdate.set_Value(revNewIDFieldIndex, searchRowToUpdate.get_Value(revOldIDFieldIndex)); } // update the source table holding the relation information class as well updateSource(relationTable, action, modifyID, modifyID, user_displayname, userID, Convert.ToInt32(newVersionString), Convert.ToInt32(changeSetID), nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); httpResponse.Close(); } } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } } break; case "delete": // the delete operations are handled separately break; default: break; } break; #endregion default: break; } } catch (Exception ex) { message.AddAbort(ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } } finally { try { searchRowToUpdate.Store(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } if (httpResponse != null) { httpResponse.Close(); } } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } } } #endregion #region now let's handle the delete in the reverse order - relation first, then ways, and then nodes as the last entity #region delete relations // now let's handle the delete in the reverse order - relation first, then ways, and then nodes as the last entity queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'delete' AND " + sqlFormatter.SqlIdentifier("osmelementtype") + " = 'relation'"; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); while ((searchRowToUpdate = searchCursor.NextRow()) != null) { // if the overall number of uploaded elements is too big for a single changeset we do need to split it up // into multiple sets if ((featureUpdateCounter % maxElementsinChangeSet) == 0) { CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } long osmID = -1; if (revOldIDFieldIndex != -1) { osmID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } int osmVersion = -1; if (revVersionFieldIndex != -1) { osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex)); } osm deleteRelation = CreateOSMRelationRepresentation(relationTable, "delete", osmID, changeSetID, osmVersion, nodeosmIDLookup, wayosmIDLookup, relationosmIDLookup, internalExtensionVersion); string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(deleteRelation, serializer, Encoding.UTF8, "text/xml"); string errorMessage = String.Empty; try { httpResponse = OsmRest.HttpUtils.Delete(baseURLGPString.Value + "/api/0.6/relation/" + Convert.ToString(osmID), sContent, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout) as HttpWebResponse; // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; if (revStatusFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusFieldIndex, (int)httpResponse.StatusCode); } if (revStatusCodeFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode); } if (httpResponse != null) { httpResponse.Close(); } } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } if (httpResponse != null) { httpResponse.Close(); } } try { searchRowToUpdate.Store(); } catch { } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } } } #endregion #region handle delete ways queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'delete' AND " + sqlFormatter.SqlIdentifier("osmelementtype") + " = 'way'"; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); while ((searchRowToUpdate = searchCursor.NextRow()) != null) { // if the overall number of uploaded elements is too big for a single changeset we do need to split it up // into multiple sets if ((featureUpdateCounter % maxElementsinChangeSet) == 0) { CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } long osmID = -1; if (revOldIDFieldIndex != -1) { osmID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } int osmVersion = -1; if (revVersionFieldIndex != -1) { osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex)); } osm deleteWay = CreateOSMWayRepresentation(lineFeatureClass, "delete", osmID, changeSetID, osmVersion, wayosmIDLookup, pointFeatureClass, pointOSMIDFieldIndex, internalExtensionVersion); string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(deleteWay, serializer, Encoding.UTF8, "text/xml"); try { httpResponse = null; httpResponse = OsmRest.HttpUtils.Delete(baseURLGPString.Value + "/api/0.6/way/" + Convert.ToString(osmID), sContent, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout) as HttpWebResponse; // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; string errorMessage = String.Empty; // just grab the response and set it on the database if (revStatusFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusFieldIndex, (int)httpResponse.StatusCode); } if (revStatusCodeFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode); } if (httpResponse != null) { httpResponse.Close(); } } catch (Exception ex) { message.AddError(1200009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } if (httpResponse != null) { httpResponse.Close(); } } try { searchRowToUpdate.Store(); } catch { } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } } } #endregion #region handle delete points queryFilter.WhereClause = "(" + sqlFormatter.SqlIdentifier("osmstatuscode") + " <> 200 OR " + sqlFormatter.SqlIdentifier("osmstatus") + " IS NULL) AND " + sqlFormatter.SqlIdentifier("osmaction") + " = 'delete' AND " + sqlFormatter.SqlIdentifier("osmelementtype") + " = 'node'"; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = revisionTable.Search(queryFilter, false); comReleaser.ManageLifetime(searchCursor); while ((searchRowToUpdate = searchCursor.NextRow()) != null) { // if the overall number of uploaded elements is too big for a single changeset we do need to split it up // into multiple sets if ((featureUpdateCounter % maxElementsinChangeSet) == 0) { CreateNextChangeSet(message, createChangeSetOSM, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, ref changeSetID, baseURLGPString, ref featureUpdateCounter); } long osmID = -1; if (revOldIDFieldIndex != -1) { osmID = Convert.ToInt64(searchRowToUpdate.get_Value(revOldIDFieldIndex)); } int osmVersion = -1; if (revVersionFieldIndex != -1) { osmVersion = Convert.ToInt32(searchRowToUpdate.get_Value(revVersionFieldIndex)); } IPoint deletePoint = null; if (revLongitudeFieldIndex != -1 && revLatitudeFieldIndex != -1) { try { // let's reconstruct the delete point deletePoint = new PointClass(); deletePoint.X = Convert.ToDouble(searchRowToUpdate.get_Value(revLongitudeFieldIndex)); deletePoint.Y = Convert.ToDouble(searchRowToUpdate.get_Value(revLatitudeFieldIndex)); deletePoint.SpatialReference = m_wgs84; } catch (Exception ex) { message.AddWarning(ex.Message); } if (deletePoint == null) { // inform the about the issue - no successful creation of point and continue on to the next delete instruction // in the revision table message.AddWarning(resourceManager.GetString("GPTools_OSMGPUpload_invalidPoint")); continue; } } osm deleteNode = CreateOSMNodeRepresentation(pointFeatureClass, "delete", osmID, changeSetID, osmVersion, deletePoint, internalExtensionVersion); string sContent = OsmRest.SerializeUtils.CreateXmlSerializable(deleteNode, serializer, Encoding.UTF8, "text/xml"); if (String.IsNullOrEmpty(sContent)) { continue; } string errorMessage = String.Empty; try { httpResponse = OsmRest.HttpUtils.Delete(baseURLGPString.Value + "/api/0.6/node/" + Convert.ToString(osmID), sContent, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout) as HttpWebResponse; if (revStatusFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusFieldIndex, (int)httpResponse.StatusCode); } if (revStatusCodeFieldIndex != -1) { searchRowToUpdate.set_Value(revStatusCodeFieldIndex, (int)httpResponse.StatusCode); } if (httpResponse != null) { httpResponse.Close(); } } catch (Exception ex) { message.AddError(120009, ex.Message); if (ex is WebException) { updateErrorStatus(message, revStatusFieldIndex, revStatusCodeFieldIndex, revErrorMessageFieldIndex, ref searchRowToUpdate, ex); } if (httpResponse != null) { httpResponse.Close(); } } // track the update/sync requests against the server featureUpdateCounter = featureUpdateCounter + 1; try { searchRowToUpdate.Store(); } catch { } if (TrackCancel.Continue() == false) { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); return; } } } #endregion #endregion #endregion } } catch (Exception ex) { message.AddError(120058, ex.Message); message.AddError(120058, ex.StackTrace); } finally { closeChangeSet(message, userCredentialGPValue.EncodedUserNamePassWord, secondsToTimeout, changeSetID, baseURLGPString); if (revisionTable != null) { try { ISchemaLock tableSchemaLock = revisionTable as ISchemaLock; if (tableSchemaLock != null) { tableSchemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock); } } catch (Exception eLock) { message.AddError(120059, resourceManager.GetString("GPTools_OSMGPUpload_LockErrorTitle") + eLock.Message); } } if (revisionTable != null) { Marshal.FinalReleaseComObject(revisionTable); } // if the searchCursor still has a reference somewhere do release it now - and as a result release any remaining table locks if (searchCursor != null) { Marshal.FinalReleaseComObject(searchCursor); } gpUtilities3.RemoveInternalData(); gpUtilities3.ReleaseInternals(); //Marshal.ReleaseComObject(gpUtilities3); } }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); try { // Ensure that the current user has admin access to the current Workflow Manager DB if (!CurrentUserIsWmxAdministrator()) { throw new WmauException(WmauErrorCodes.C_USER_NOT_ADMIN_ERROR); } IJTXConfigurationEdit2 configEdit = this.WmxDatabase.ConfigurationManager as IJTXConfigurationEdit2; // Look up the appropriate user(s) IJTXUserSet users = null; if (m_userName.Equals(C_OPT_ALL_USERS)) { users = configEdit.Users; } else { users = new JTXUserSetClass(); (users as IJTXUserSetEdit).Add(configEdit.GetUser(m_userName)); } // Grant/revoke admin access to the specified users for (int i = 0; i < users.Count; i++) { IJTXUser3 user = users.get_Item(i) as IJTXUser3; user.IsAdministrator = m_privilegeAction.Equals(C_OPT_GRANT) ? true : false; (user as IJTXUserConfig).Store(); } // If the tool was set to preserve the current user's access and the tool removed it, // re-grant their access string username = ESRI.ArcGIS.JTXUI.ConfigurationCache.GetCurrentSystemUser(ESRI.ArcGIS.JTXUI.ConfigurationCache.UseUserDomain); IJTXUser3 userObj = configEdit.GetUser(username) as IJTXUser3; if (!userObj.IsAdministrator) { if (m_preserveCurrentUser) { userObj.IsAdministrator = true; (userObj as IJTXUserConfig).Store(); msgs.AddMessage("Re-granting admin access for user '" + username + "'"); } else { msgs.AddWarning("User '" + username + "' is no longer an administrator on this Workflow Manager database"); } } // Update the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParam = paramMap.GetParamEdit(C_PARAM_OUT_USER_NAME); IGPString strValue = new GPStringClass(); strValue.Value = m_userName; outParam.Value = strValue as IGPValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { try { WmauError error = new WmauError(WmauErrorCodes.C_UNSPECIFIED_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } catch { // Catch anything else that possibly happens } } finally { // Release any COM objects here! } }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); try { // Ensure that the current user has admin access to the current Workflow Manager DB if (!CurrentUserIsWmxAdministrator()) { throw new WmauException(WmauErrorCodes.C_USER_NOT_ADMIN_ERROR); } IJTXSpatialNotificationManager snManager = this.WmxDatabase.SpatialNotificationManager; IJTXSpatialNotifierNameSet allSnNames = snManager.SpatialNotifiers; IJTXNotificationConfiguration notificationConfig = this.WmxDatabase.ConfigurationManager as IJTXNotificationConfiguration; // Create a new spatial notification IJTXChangeRule2 changeRule = snManager.AddChangeRule() as IJTXChangeRule2; // Set the name changeRule.Name = m_snName; // Set the notifier IJTXNotificationType srcNotifType = notificationConfig.GetNotificationType(m_emailNotifier); // Set the properties of the spatial notification's e-mail notification to match that // of the source e-mail notification (phew!) IJTXEmailSpatialNotifier emailNotifier = this.CreateSpatialNotifierByName(C_TYPE_EMAIL_NOTIFIER) as IJTXEmailSpatialNotifier; emailNotifier.Subject = srcNotifType.SubjectTemplate; emailNotifier.Body = srcNotifType.MessageTemplate; emailNotifier.SenderEmail = srcNotifType.SenderTemplate; emailNotifier.SenderDisplayName = srcNotifType.SenderDisplayNameTemplate; string[] subscribers = srcNotifType.get_Subscribers(); IStringArray subscribersObj = new StrArrayClass(); foreach (string subscriber in subscribers) { subscribersObj.Add(subscriber); } emailNotifier.Subscribers = subscribersObj; changeRule.Notifier = emailNotifier as IJTXSpatialNotifier; // Set the description, if applicable if (!string.IsNullOrEmpty(m_snDescription)) { changeRule.Description = m_snDescription; } // Set the summarization behavior changeRule.SummarizeNotifications = m_summarize; // Store the resulting change rule changeRule.Store(); // Update the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParam = paramMap.GetParamEdit(C_PARAM_OUT_NAME); IGPString strValue = new GPStringClass(); strValue.Value = m_snName; outParam.Value = strValue as IGPValue; msgs.AddWarning("To avoid database corruption, at least one dataset or area evaluator must be added to notification '" + m_snName + "' immediately!"); msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { try { WmauError error = new WmauError(WmauErrorCodes.C_SN_CREATION_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } catch { // Catch anything else that possibly happens } } finally { // Release any COM objects here! } }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); // Set the default properties for the specified job type try { IJTXConfiguration3 configMgr = this.WmxDatabase.ConfigurationManager as IJTXConfiguration3; IJTXConfigurationEdit2 configEdit = this.WmxDatabase.ConfigurationManager as IJTXConfigurationEdit2; IJTXJobTypeEdit3 jobType = configEdit.GetJobType(m_jobTypeName) as IJTXJobTypeEdit3; // Set the default data workspace for the selected job type if (m_dataWorkspaceName.Equals(C_OPT_NONE)) { jobType.DefaultDataWorkspace = null; msgs.AddMessage("Clearing default data workspace for job type '" + m_jobTypeName + "'"); } else { // Translate the workspace name to a DB name object IJTXDataWorkspaceName dwName = Common.WmauHelperFunctions.LookupWorkspaceNameObj(this.WmxDatabase, m_dataWorkspaceName); msgs.AddMessage("Default data workspace for job type '" + m_jobTypeName + "' is now '" + dwName.Name + "'"); jobType.DefaultDataWorkspace = dwName; } // Set the default parent version for the selected job type if (m_parentVersion.Equals(C_OPT_NONE)) { msgs.AddMessage("Clearing default parent version for job type '" + m_jobTypeName + "'"); jobType.DefaultParentVersionName_2 = string.Empty; } else { msgs.AddMessage("Default parent version for job type '" + m_jobTypeName + "' is now '" + m_parentVersion + "'"); jobType.DefaultParentVersionName_2 = m_parentVersion; } // Save the changes to the job type jobType.Store(); // Set the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParamEdit = paramMap.GetParamEdit(C_PARAM_OUT_DATA_WORKSPACE); IGPString outValue = new GPStringClass(); outValue.Value = m_jobTypeName; outParamEdit.Value = outValue as IGPValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { WmauError error = new WmauError(WmauErrorCodes.C_UNSPECIFIED_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); try { // Ensure that the current user has admin access to the current Workflow Manager DB if (!CurrentUserIsWmxAdministrator()) { throw new WmauException(WmauErrorCodes.C_USER_NOT_ADMIN_ERROR); } IJTXConfigurationEdit2 configEdit = this.WmxDatabase.ConfigurationManager as IJTXConfigurationEdit2; // Look up the appropriate privilege(s) and group(s) IJTXPrivilegeSet privileges = null; if (m_privilegeName.Equals(C_OPT_ALL_PRIVILEGES)) { privileges = configEdit.Privileges; } else { privileges = new JTXPrivilegeSetClass(); (privileges as IJTXPrivilegeSetEdit).Add(configEdit.GetPrivilege(m_privilegeName)); } IJTXUserGroupSet groups = null; if (m_groupName.Equals(C_OPT_ALL_GROUPS)) { groups = configEdit.UserGroups; } else { groups = new JTXUserGroupSetClass(); (groups as IJTXUserGroupSetEdit).Add(configEdit.GetUserGroup(m_groupName)); } // Add/remove the privilege(s) to the group(s) for (int i = 0; i < privileges.Count; i++) { IJTXPrivilege2 privilege = privileges.get_Item(i) as IJTXPrivilege2; for (int j = 0; j < groups.Count; j++) { IJTXUserGroupConfig2 targetGroup = groups.get_Item(j) as IJTXUserGroupConfig2; if (m_privilegeAction.Equals(C_OPT_GRANT)) { targetGroup.AssignPrivilegeToGroup2(privilege.UID); } else { targetGroup.RemovePrivilegeFromGroup2(privilege.UID); } targetGroup.Store(); } } // Update the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParam = paramMap.GetParamEdit(C_PARAM_OUT_PRIVILEGE_NAME); IGPString strValue = new GPStringClass(); strValue.Value = m_privilegeName; outParam.Value = strValue as IGPValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { try { WmauError error = new WmauError(WmauErrorCodes.C_UNSPECIFIED_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } catch { // Catch anything else that possibly happens } } finally { // Release any COM objects here! } }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); try { // Ensure that the current user has admin access to the current Workflow Manager DB if (!CurrentUserIsWmxAdministrator()) { throw new WmauException(WmauErrorCodes.C_USER_NOT_ADMIN_ERROR); } // Retrieve the parameter in which the data workspace names will be stored WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameter3 param = paramMap.GetParam(C_PARAM_WORKSPACE_LIST); IGPParameterEdit3 paramEdit = paramMap.GetParamEdit(C_PARAM_WORKSPACE_LIST); // Set up the multi-value objects IGPMultiValue mvValue = new GPMultiValueClass(); mvValue.MemberDataType = param.DataType; // Workflow Manager intentionally caches the data workspaces in the system. To ensure // that we have the most current list of data workspaces, invalidate this cache // before attempting to retrieve the list from the system. this.WmxDatabase.InvalidateDataWorkspaceNames(); // Get the list of names SortedList <string, string> sortedValues = new SortedList <string, string>(); IJTXDataWorkspaceNameSet allValues = this.WmxDatabase.GetDataWorkspaceNames(null); for (int i = 0; i < allValues.Count; i++) { IJTXDataWorkspaceName ws = allValues.get_Item(i); sortedValues.Add(ws.Name, null); } // Add the names to the output parameter foreach (string name in sortedValues.Keys) { IGPString strVal = new GPStringClass(); strVal.Value = name; mvValue.AddValue(strVal as IGPValue); msgs.AddMessage("Workspace: " + name); } paramEdit.Value = (IGPValue)mvValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { try { WmauError error = new WmauError(WmauErrorCodes.C_UNSPECIFIED_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } catch { // Catch anything else that possibly happens } } finally { // Release any COM objects here! } }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { ICursor cursor = null; // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); try { // Ensure that the current user has admin access to the current Workflow Manager DB if (!CurrentUserIsWmxAdministrator()) { throw new WmauException(WmauErrorCodes.C_USER_NOT_ADMIN_ERROR); } IJTXSpatialNotificationManager snManager = this.WmxDatabase.SpatialNotificationManager; // Find the rule that we're modifying IJTXChangeRule2 changeRule = GetChangeRuleByName(m_spatialNotification) as IJTXChangeRule2; // Create and configure the area evaluator IJTXAOIConditionEvaluator areaEvaluator = CreateEvaluator(C_TYPE_AREA_EVALUATOR) as IJTXAOIConditionEvaluator; areaEvaluator.SpatialRel = m_geometricOperations[m_geometricOperation]; areaEvaluator.UseInverse = m_useInverse; areaEvaluator.UseJobAOI = m_useJobAoi; // Set the AOI of the job, if there is one // Ensure that there's nothing wrong with the AOI feature that is selected, if any if (!m_useJobAoi) { if (m_alternateAoi != null) { IFeatureLayer featLayer = m_alternateAoi as IFeatureLayer; IFeatureSelection featSel = m_alternateAoi as IFeatureSelection; ISelectionSet selSet = featSel.SelectionSet as ISelectionSet; if (featLayer.FeatureClass.ShapeType != esriGeometryType.esriGeometryPolygon) { throw new WmauException(new WmauError(WmauErrorCodes.C_AOI_NOT_POLYGON_ERROR)); } else if (selSet.Count != 1) { throw new WmauException(new WmauError(WmauErrorCodes.C_EXPECTED_ONE_SELECTED_FEATURE_ERROR)); } // If we get this far, we know that there's exactly one selected feature, so we // don't have to loop through the selection set selSet.Search(null, true, out cursor); IFeatureCursor featureCursor = cursor as IFeatureCursor; IFeature aoiCandidate = featureCursor.NextFeature(); // We also know that the feature is a polygon, so just make the cast areaEvaluator.AreaOfInterest = aoiCandidate.Shape as IPolygon; } } // Associate the evaluator with the change rule and save the changes changeRule.Evaluators.Add(areaEvaluator as IJTXConditionEvaluator); changeRule.Store(); // Set the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParamEdit = paramMap.GetParamEdit(C_PARAM_OUT_SPATIAL_NOTIFICATION); IGPString outParamStr = new GPStringClass(); outParamStr.Value = m_spatialNotification; outParamEdit.Value = outParamStr as IGPValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { try { WmauError error = new WmauError(WmauErrorCodes.C_ADD_AREA_EVAL_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } catch { // Catch anything else that possibly happens } } finally { // Release any COM objects here! if (cursor != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(cursor); } } }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); try { // Ensure that the current user has admin access to the current Workflow Manager DB if (!CurrentUserIsWmxAdministrator()) { throw new WmauException(WmauErrorCodes.C_USER_NOT_ADMIN_ERROR); } IJTXSpatialNotificationManager snManager = this.WmxDatabase.SpatialNotificationManager; IJTXSpatialNotifierNameSet allSnNames = snManager.SpatialNotifiers; IJTXNotificationConfiguration notificationConfig = this.WmxDatabase.ConfigurationManager as IJTXNotificationConfiguration; // Create a new spatial notification IJTXChangeRule2 changeRule = snManager.AddChangeRule() as IJTXChangeRule2; // Set the name changeRule.Name = m_snName; // Set the properties of the spatial notification's e-mail notification IJTXEmailSpatialNotifier emailNotifier = CreateSpatialNotifierByName(C_TYPE_EMAIL_NOTIFIER) as IJTXEmailSpatialNotifier; emailNotifier.Subject = m_subject; emailNotifier.Body = m_message; // Default the sender's name and e-mail, if none is specified if (string.IsNullOrEmpty(m_senderEmail)) { IJTXConfigurationProperties configProps = this.WmxDatabase.ConfigurationManager as IJTXConfigurationProperties; emailNotifier.SenderEmail = configProps.GetProperty(Constants.JTX_PROPERTY_DEFAULT_SENDER_EMAIL); } else { emailNotifier.SenderEmail = m_senderEmail; } if (string.IsNullOrEmpty(m_senderName)) { IJTXConfigurationProperties configProps = this.WmxDatabase.ConfigurationManager as IJTXConfigurationProperties; emailNotifier.SenderDisplayName = configProps.GetProperty(Constants.JTX_PROPERTY_DEFAULT_SENDER_NAME); } else { emailNotifier.SenderDisplayName = m_senderName; } // Split the subscribers into a list (assume semicolon-deliminted) string[] subscribers = m_subscribers.Split(new char[] { C_DELIM_SUBSCRIBERS }); IStringArray subscribersObj = new StrArrayClass(); foreach (string subscriber in subscribers) { string tempStr = subscriber.Trim(); if (!tempStr.Equals(string.Empty)) { subscribersObj.Add(subscriber.Trim()); } } emailNotifier.Subscribers = subscribersObj; changeRule.Notifier = emailNotifier as IJTXSpatialNotifier; // Set the description, if applicable if (!string.IsNullOrEmpty(m_snDescription)) { changeRule.Description = m_snDescription; } // Set the summarization behavior changeRule.SummarizeNotifications = m_summarize; // Store the resulting change rule changeRule.Store(); // Update the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParam = paramMap.GetParamEdit(C_PARAM_OUT_NAME); IGPString strValue = new GPStringClass(); strValue.Value = m_snName; outParam.Value = strValue as IGPValue; msgs.AddWarning("To avoid database corruption, at least one dataset or area evaluator must be added to notification '" + m_snName + "' immediately!"); msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { try { WmauError error = new WmauError(WmauErrorCodes.C_SN_CREATION_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } catch { // Catch anything else that possibly happens } } finally { // Release any COM objects here! } }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); try { // Ensure that the current user has admin access to the current Workflow Manager DB if (!CurrentUserIsWmxAdministrator()) { throw new WmauException(WmauErrorCodes.C_USER_NOT_ADMIN_ERROR); } IJTXSpatialNotificationManager snManager = this.WmxDatabase.SpatialNotificationManager; // Look up the change rule that we'll be modifying IJTXChangeRule2 changeRule = GetChangeRuleByName(m_spatialNotification) as IJTXChangeRule2; IJTXMultiDatasetConditionEvaluator datasetEvaluator = null; // Try to get an existing dataset evaluator if one exists. if (m_tryExistingEvaluator) { IJTXConditionEvaluatorSet allEvaluators = changeRule.Evaluators; for (int i = 0; i < allEvaluators.Count; i++) { IJTXConditionEvaluator tempEval = allEvaluators.get_Item(i); if (tempEval.Name.Equals(C_TYPE_DATASET_EVALUATOR) && tempEval is IJTXMultiDatasetConditionEvaluator) { datasetEvaluator = tempEval as IJTXMultiDatasetConditionEvaluator; break; } } } // If we don't have an evaluator at this point, then we need to create one if (datasetEvaluator == null) { datasetEvaluator = CreateEvaluator(C_TYPE_DATASET_EVALUATOR) as IJTXMultiDatasetConditionEvaluator; datasetEvaluator.DatasetConfigurations = new JTXDatasetConditionConfigurationSetClass(); changeRule.Evaluators.Add(datasetEvaluator as IJTXConditionEvaluator); } // Create a new dataset configuration IJTXDatasetConditionConfiguration datasetCondition = new JTXDatasetConditionConfigurationClass(); datasetCondition.DatabaseID = m_dataWorkspace; datasetCondition.DatasetName = m_featureClass; datasetCondition.ChangeCondition = m_whenToMonitor; datasetCondition.WhereConditions = m_whereClauses; datasetCondition.ChangeFields = m_monitorAllColumns ? "*" : m_columns.Replace(';', ','); datasetCondition.Name = this.WmxDatabase.GetDataWorkspaceName(m_dataWorkspace).Name + "/" + m_featureClass; // Store the configuration in the dataset evaluator datasetEvaluator.DatasetConfigurations.Add(datasetCondition); changeRule.Store(); // Set the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParamEdit = paramMap.GetParamEdit(C_PARAM_OUT_SPATIAL_NOTIFICATION); IGPString outParamStr = new GPStringClass(); outParamStr.Value = m_spatialNotification; outParamEdit.Value = outParamStr as IGPValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { try { WmauError error = new WmauError(WmauErrorCodes.C_ADD_DATASET_COND_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } catch { // Catch anything else that possibly happens } } finally { // Release any COM objects here! } }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); try { // Ensure that the current user has admin access to the current Workflow Manager DB if (!CurrentUserIsWmxAdministrator()) { throw new WmauException(WmauErrorCodes.C_USER_NOT_ADMIN_ERROR); } // Create the object needed to get at the data workspaces IJTXDatabaseConnectionManager dbConnectionManager = new JTXDatabaseConnectionManagerClass(); IJTXDatabaseConnection dbConnection = dbConnectionManager.GetConnection(this.WmxDatabase.Alias); // Loop through the data workspaces until we find the one we're looking for, then // delete it bool removedWorkspace = false; for (int i = 0; i < dbConnection.DataWorkspaceCount; i++) { IJTXWorkspaceConfiguration workspaceCfg = dbConnection.get_DataWorkspace(i); if (workspaceCfg.Name.Equals(m_dataWorkspace)) { dbConnection.RemoveDataWorkspace(i); removedWorkspace = true; break; } } // Raise an error if we somehow couldn't find it (should never happen with // the domain on the input param) if (!removedWorkspace) { throw new WmauException(WmauErrorCodes.C_WORKSPACE_NOT_FOUND_ERROR); } // Set the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParamEdit = paramMap.GetParamEdit(C_PARAM_OUT_DATA_WORKSPACE); IGPString outParamStr = new GPStringClass(); outParamStr.Value = m_dataWorkspace; outParamEdit.Value = outParamStr as IGPValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { try { WmauError error = new WmauError(WmauErrorCodes.C_UNSPECIFIED_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } catch { // Catch anything else that possibly happens } } finally { // Release any COM objects here! } }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); try { // Ensure that the current user has admin access to the current Workflow Manager DB if (!CurrentUserIsWmxAdministrator()) { throw new WmauException(WmauErrorCodes.C_USER_NOT_ADMIN_ERROR); } // Retrieve the TA workbook IJTXConfiguration3 defaultDbReadonly = WmxDatabase.ConfigurationManager as IJTXConfiguration3; IJTXTaskAssistantWorkflowRecord tamRecord = defaultDbReadonly.GetTaskAssistantWorkflowRecord(this.m_targetName); string styleFileName = this.DetermineStyleFileName(this.m_xmlFilePath); // If we're not allowed to overwrite an existing TA record, then do some error checking if (!this.m_overwriteExisting && tamRecord != null) { msgs.AddWarning("Did not overwrite Task Assistant workbook: " + this.m_targetName); return; } else if (tamRecord != null) { msgs.AddMessage("Replacing Task Assistant workbook '" + m_targetName + "' in database..."); defaultDbReadonly.ReplaceTaskAssistantWorkflowRecord(this.m_targetName, this.m_targetName, this.m_xmlFilePath, styleFileName); } else // tamRecord == null { msgs.AddMessage("Adding Task Assistant workbook '" + m_targetName + "' to database..."); defaultDbReadonly.AddTaskAssistantWorkflowRecord(this.m_targetName, this.m_xmlFilePath, styleFileName); } // Update the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParamEdit = paramMap.GetParamEdit(C_PARAM_OUT_TARGET_NAME); IGPString outValue = new GPStringClass(); outValue.Value = m_targetName; outParamEdit.Value = outValue as IGPValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { try { WmauError error = new WmauError(WmauErrorCodes.C_TAM_UPLOAD_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } catch { // Catch anything else that possibly happens } } }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); try { // Ensure that the current user has admin access to the current Workflow Manager DB if (!CurrentUserIsWmxAdministrator()) { throw new WmauException(WmauErrorCodes.C_USER_NOT_ADMIN_ERROR); } IJTXConfiguration3 configMgr = WmxDatabase.ConfigurationManager as IJTXConfiguration3; IJTXMapEdit wmxMapDoc = configMgr.GetJTXMap(this.m_targetName) as IJTXMapEdit; // If we're not allowed to overwrite an existing map document, then do some error checking if (!this.m_overwriteExisting && wmxMapDoc != null) { msgs.AddWarning("Did not overwrite Map Document: " + this.m_targetName); return; } else if (wmxMapDoc != null) { msgs.AddMessage("Replacing Map Document '" + this.m_targetName + "' in database..."); } else // wmxMapDoc == null { msgs.AddMessage("Adding Map Document '" + this.m_targetName + "' to database..."); wmxMapDoc = configMgr.CreateJTXMap() as IJTXMapEdit; } IMapDocument mapDoc = new MapDocumentClass() as IMapDocument; mapDoc.Open(this.m_mxdFilePath, string.Empty); wmxMapDoc.Name = this.m_targetName; if (!string.IsNullOrEmpty(this.m_targetCategory)) { wmxMapDoc.Category = this.m_targetCategory; } if (!string.IsNullOrEmpty(this.m_description)) { wmxMapDoc.Description = this.m_description; } wmxMapDoc.Directory = string.Empty; wmxMapDoc.FileName = string.Empty; wmxMapDoc.MapDocument = mapDoc; wmxMapDoc.Store(); mapDoc.Close(); // Update the output parameter WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameterEdit3 outParamEdit = paramMap.GetParamEdit(C_PARAM_OUT_TARGET_NAME); IGPString outValue = new GPStringClass(); outValue.Value = m_targetName; outParamEdit.Value = outValue as IGPValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { try { WmauError error = new WmauError(WmauErrorCodes.C_MXD_UPLOAD_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } catch { // Catch anything else that possibly happens } } }
/// <summary> /// Required by IGPFunction2 interface; this function is called when the GP tool is ready to be executed. /// </summary> /// <param name="paramValues"></param> /// <param name="trackCancel"></param> /// <param name="envMgr"></param> /// <param name="msgs"></param> public override void Execute(IArray paramValues, ITrackCancel trackCancel, IGPEnvironmentManager envMgr, IGPMessages msgs) { // Do some common error-checking base.Execute(paramValues, trackCancel, envMgr, msgs); try { // Ensure that the current user has admin access to the current Workflow Manager DB if (!CurrentUserIsWmxAdministrator()) { throw new WmauException(WmauErrorCodes.C_USER_NOT_ADMIN_ERROR); } IJTXConfiguration3 configMgr = this.WmxDatabase.ConfigurationManager as IJTXConfiguration3; // Prep to retrieve the users in the specified groups (if any were specified) string[] userNames = null; if (!string.IsNullOrEmpty(m_groupName)) { msgs.AddMessage("Users in group '" + m_groupName + "':"); string[] groupNameArray = new string[] { m_groupName }; userNames = configMgr.GetUserNamesForGroups(groupNameArray); } else { msgs.AddMessage("All users:"); userNames = new string[configMgr.Users.Count]; for (int i = 0; i < configMgr.Users.Count; i++) { userNames[i] = configMgr.Users.get_Item(i).UserName; } } // Sort the user list SortedList <string, string> sortedNames = new SortedList <string, string>(); foreach (string s in userNames) { sortedNames.Add(s, null); } // Retrieve the parameter in which the list of user names will be stored WmauParameterMap paramMap = new WmauParameterMap(paramValues); IGPParameter3 param = paramMap.GetParam(C_PARAM_USER_LIST); IGPParameterEdit3 paramEdit = paramMap.GetParamEdit(C_PARAM_USER_LIST); // Set up the multi-value objects IGPMultiValue mvValue = new GPMultiValueClass(); mvValue.MemberDataType = param.DataType; // Add the user list to the multivalue param foreach (string user in sortedNames.Keys) { msgs.AddMessage(" " + user); IGPString strVal = new GPStringClass(); strVal.Value = user; mvValue.AddValue(strVal as IGPValue); } paramEdit.Value = (IGPValue)mvValue; msgs.AddMessage(Properties.Resources.MSG_DONE); } catch (WmauException wmEx) { try { msgs.AddError(wmEx.ErrorCodeAsInt, wmEx.Message); } catch { // Catch anything else that possibly happens } } catch (Exception ex) { try { WmauError error = new WmauError(WmauErrorCodes.C_UNSPECIFIED_ERROR); msgs.AddError(error.ErrorCodeAsInt, error.Message + "; " + ex.Message); } catch { // Catch anything else that possibly happens } } finally { // Release any COM objects here! } }