Пример #1
0
 private void DeleteField(DeleteField command)
 {
     Raise(command, new FieldDeleted());
 }
Пример #2
0
        /// <summary>
        /// Adds the attribute columns.
        /// </summary>
        private void AddDynamicControls()
        {
            // Clear the filter controls
            phAttributeFilters.Controls.Clear();

            // Remove attribute columns
            foreach (var column in gWorkflows.Columns.OfType <AttributeField>().ToList())
            {
                gWorkflows.Columns.Remove(column);
            }

            if (AvailableAttributes != null)
            {
                foreach (var attribute in AvailableAttributes)
                {
                    var control = attribute.FieldType.Field.FilterControl(attribute.QualifierValues, "filter_" + attribute.Id.ToString(), false, Rock.Reporting.FilterMode.SimpleFilter);
                    if (control != null)
                    {
                        if (control is IRockControl)
                        {
                            var rockControl = (IRockControl)control;
                            rockControl.Label = attribute.Name;
                            rockControl.Help  = attribute.Description;
                            phAttributeFilters.Controls.Add(control);
                        }
                        else
                        {
                            var wrapper = new RockControlWrapper();
                            wrapper.ID    = control.ID + "_wrapper";
                            wrapper.Label = attribute.Name;
                            wrapper.Controls.Add(control);
                            phAttributeFilters.Controls.Add(wrapper);
                        }
                    }

                    string savedValue = gfWorkflows.GetUserPreference(MakeKeyUniqueToType(attribute.Key));
                    if (!string.IsNullOrWhiteSpace(savedValue))
                    {
                        try
                        {
                            var values = JsonConvert.DeserializeObject <List <string> >(savedValue);
                            attribute.FieldType.Field.SetFilterValues(control, attribute.QualifierValues, values);
                        }
                        catch { }
                    }

                    string dataFieldExpression = attribute.Key;
                    bool   columnExists        = gWorkflows.Columns.OfType <AttributeField>().FirstOrDefault(a => a.DataField.Equals(dataFieldExpression)) != null;
                    if (!columnExists)
                    {
                        AttributeField boundField = new AttributeField();
                        boundField.DataField   = dataFieldExpression;
                        boundField.AttributeId = attribute.Id;
                        boundField.HeaderText  = attribute.Name;
                        boundField.Condensed   = false;

                        var attributeCache = Rock.Web.Cache.AttributeCache.Read(attribute.Id);
                        if (attributeCache != null)
                        {
                            boundField.ItemStyle.HorizontalAlign = attributeCache.FieldType.Field.AlignValue;
                        }

                        gWorkflows.Columns.Add(boundField);
                    }
                }
            }

            var dateField = new DateTimeField();

            gWorkflows.Columns.Add(dateField);
            dateField.DataField           = "CreatedDateTime";
            dateField.SortExpression      = "CreatedDateTime";
            dateField.HeaderText          = "Created";
            dateField.FormatAsElapsedTime = true;

            var statusField = new BoundField();

            gWorkflows.Columns.Add(statusField);
            statusField.DataField        = "Status";
            statusField.SortExpression   = "Status";
            statusField.HeaderText       = "Status";
            statusField.DataFormatString = "<span class='label label-info'>{0}</span>";
            statusField.HtmlEncode       = false;

            var stateField = new CallbackField();

            gWorkflows.Columns.Add(stateField);
            stateField.DataField          = "IsCompleted";
            stateField.SortExpression     = "CompletedDateTime";
            stateField.HeaderText         = "State";
            stateField.HtmlEncode         = false;
            stateField.OnFormatDataValue += (sender, e) =>
            {
                if ((bool)e.DataValue)
                {
                    e.FormattedValue = "<span class='label label-default'>Completed</span>";
                }
                else
                {
                    e.FormattedValue = "<span class='label label-success'>Active</span>";
                }
            };

            if (_canView)
            {
                var manageField = new LinkButtonField();
                gWorkflows.Columns.Add(manageField);
                manageField.CssClass = "btn btn-default btn-sm fa fa-file-text-o";
                manageField.Click   += gWorkflows_Manage;
            }

            if (_canEdit)
            {
                var deleteField = new DeleteField();
                gWorkflows.Columns.Add(deleteField);
                deleteField.Click += gWorkflows_Delete;
            }
        }
Пример #3
0
        public static void CanDelete(DeleteField command, Schema schema)
        {
            Guard.NotNull(command, nameof(command));

            GuardHelper.GetFieldOrThrow(schema, command.FieldId, command.ParentFieldId, false);
        }
        /// <summary>
        /// Set the properties of the main grid.
        /// </summary>
        private void InitializeGrid()
        {
            ListGridControl.DataKeyNames = new string[] { "Id" };

            if (string.IsNullOrWhiteSpace(this.ItemFriendlyName))
            {
                ListGridControl.RowItemText = _entityType.FriendlyName;
            }
            else
            {
                ListGridControl.RowItemText = this.ItemFriendlyName;
            }

            ListGridControl.ExportSource = ExcelExportSource.DataSource;

            ListGridControl.HideDeleteButtonForIsSystem = this.PreventSystemItemDelete;

            ListGridControl.Actions.AddClick += gList_Add;
            ListGridControl.GridRebind       += gList_GridRebind;

            ListGridControl.AllowSorting = !this.ShowItemReorder;

            // Show Reorder handle
            if (this.ShowItemReorder)
            {
                _reorderColumn = new ReorderField();

                ListGridControl.Columns.Insert(0, _reorderColumn);

                ListGridControl.GridReorder += gList_GridReorder;
            }

            // Verify block authorization
            bool canEdit         = IsUserAuthorized(Authorization.EDIT);
            bool canAdministrate = IsUserAuthorized(Authorization.ADMINISTRATE);

            ListGridControl.Actions.ShowAdd = this.ShowItemAdd && canEdit;

            if (canEdit)
            {
                if (this.AllowItemSelect)
                {
                    ListGridControl.RowSelected += gList_RowSelected;
                }
            }

            // Show Security button
            if (this.ShowItemSecurity &&
                canAdministrate)
            {
                _securityColumn = ListGridControl.ColumnsOfType <SecurityField>().FirstOrDefault();

                if (_securityColumn == null)
                {
                    _securityColumn = new SecurityField();

                    ListGridControl.Columns.Add(_securityColumn);
                }

                _securityColumn.EntityTypeId = _entityType.Id;
            }

            // Show Delete button
            ListGridControl.IsDeleteEnabled = this.ShowItemDelete && canEdit;

            if (this.ShowItemDelete &&
                canEdit)
            {
                _deleteColumn = ListGridControl.ColumnsOfType <DeleteField>().FirstOrDefault();

                if (_deleteColumn == null)
                {
                    _deleteColumn = new DeleteField();

                    _deleteColumn.Click += gList_Delete;

                    ListGridControl.Columns.Add(_deleteColumn);
                }
            }

            // Perform additional customisation of the list grid if required.
            OnInitializeListGrid(this.ListGridControl);
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            // set person context
            var contextEntity = this.ContextEntity();

            if (contextEntity != null)
            {
                if (contextEntity is Person)
                {
                    _person = contextEntity as Person;
                }
            }

            // set person if grid should be filtered by the current person
            if (GetAttributeValue("FilterItemsForCurrentUser").AsBoolean())
            {
                _person = CurrentPerson;
            }

            gfFilter.Visible = GetAttributeValue("ShowFilters").AsBoolean();

            _channelId = PageParameter("contentChannelId").AsIntegerOrNull();
            if (_channelId != null)
            {
                string cssIcon        = "fa fa-bullhorn";
                var    contentChannel = new ContentChannelService(new RockContext()).Get(_channelId.Value);
                if (contentChannel != null)
                {
                    string startHeading = contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Active";
                    bool   isRange      = contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange;

                    gItems.Columns[1].HeaderText = startHeading;
                    gItems.Columns[3].HeaderText = startHeading;

                    ddlStatus.Visible = contentChannel.RequiresApproval;

                    if (contentChannel.ContentChannelType.IncludeTime)
                    {
                        gItems.Columns[1].Visible = true;
                        gItems.Columns[2].Visible = isRange;
                        gItems.Columns[3].Visible = false;
                        gItems.Columns[4].Visible = false;
                    }
                    else
                    {
                        gItems.Columns[1].Visible = false;
                        gItems.Columns[2].Visible = false;
                        gItems.Columns[3].Visible = true;
                        gItems.Columns[4].Visible = isRange;
                    }

                    gItems.Columns[5].Visible = !contentChannel.ContentChannelType.DisablePriority;
                    lContentChannel.Text      = contentChannel.Name;
                    _typeId = contentChannel.ContentChannelTypeId;

                    if (!string.IsNullOrWhiteSpace(contentChannel.IconCssClass))
                    {
                        cssIcon = contentChannel.IconCssClass;
                    }
                }

                lIcon.Text = string.Format("<i class='{0}'></i>", cssIcon);

                // Block Security and special attributes (RockPage takes care of View)
                bool canAddEditDelete = IsUserAuthorized(Authorization.EDIT);

                gfFilter.ApplyFilterClick   += gfFilter_ApplyFilterClick;
                gfFilter.DisplayFilterValue += gfFilter_DisplayFilterValue;

                gItems.DataKeyNames      = new string[] { "Id" };
                gItems.Actions.ShowAdd   = canAddEditDelete;
                gItems.IsDeleteEnabled   = canAddEditDelete;
                gItems.Actions.AddClick += gItems_Add;
                gItems.GridRebind       += gItems_GridRebind;

                AddAttributeColumns();

                if (contentChannel != null && contentChannel.RequiresApproval)
                {
                    var statusField = new BoundField();
                    gItems.Columns.Add(statusField);
                    statusField.DataField      = "Status";
                    statusField.HeaderText     = "Status";
                    statusField.SortExpression = "Status";
                    statusField.HtmlEncode     = false;
                }

                var securityField = new SecurityField();
                gItems.Columns.Add(securityField);
                securityField.TitleField   = "Title";
                securityField.EntityTypeId = EntityTypeCache.Read(typeof(Rock.Model.ContentChannelItem)).Id;

                var deleteField = new DeleteField();
                gItems.Columns.Add(deleteField);
                deleteField.Click += gItems_Delete;

                // this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it
                this.BlockUpdated += Block_BlockUpdated;
                this.AddConfigurationUpdateTrigger(upnlContent);
            }
        }
Пример #6
0
 public void DeleteField(DeleteField command)
 {
     RaiseEvent(command, new FieldDeleted());
 }
Пример #7
0
        /// <summary>
        /// Adds the attribute columns.
        /// </summary>
        private void AddDynamicControls()
        {
            // Clear the filter controls
            phAttributeFilters.Controls.Clear();

            // Remove attribute columns
            foreach (var column in gEventCalendarItems.Columns.OfType <AttributeField>().ToList())
            {
                gEventCalendarItems.Columns.Remove(column);
            }

            // Remove status columns
            foreach (var column in gEventCalendarItems.Columns.OfType <BoundField>()
                     .Where(c =>
                            c.DataField == "Instances" ||
                            c.DataField == "Status" ||
                            c.DataField == "ApprovalStatus")
                     .ToList())
            {
                gEventCalendarItems.Columns.Remove(column);
            }

            // Remove Delete column
            foreach (var column in gEventCalendarItems.Columns.OfType <DeleteField>().ToList())
            {
                gEventCalendarItems.Columns.Remove(column);
            }

            if (AvailableAttributes != null)
            {
                foreach (var attribute in AvailableAttributes)
                {
                    var control = attribute.FieldType.Field.FilterControl(attribute.QualifierValues, "filter_" + attribute.Id.ToString(), false, Rock.Reporting.FilterMode.SimpleFilter);
                    if (control != null)
                    {
                        if (control is IRockControl)
                        {
                            var rockControl = (IRockControl)control;
                            rockControl.Label = attribute.Name;
                            rockControl.Help  = attribute.Description;
                            phAttributeFilters.Controls.Add(control);
                        }
                        else
                        {
                            var wrapper = new RockControlWrapper();
                            wrapper.ID    = control.ID + "_wrapper";
                            wrapper.Label = attribute.Name;
                            wrapper.Controls.Add(control);
                            phAttributeFilters.Controls.Add(wrapper);
                        }

                        string savedValue = rFilter.GetUserPreference(MakeKeyUniqueToEventCalendar(attribute.Key));
                        if (!string.IsNullOrWhiteSpace(savedValue))
                        {
                            try
                            {
                                var values = JsonConvert.DeserializeObject <List <string> >(savedValue);
                                attribute.FieldType.Field.SetFilterValues(control, attribute.QualifierValues, values);
                            }
                            catch { }
                        }
                    }

                    string dataFieldExpression = attribute.Key;
                    bool   columnExists        = gEventCalendarItems.Columns.OfType <AttributeField>().FirstOrDefault(a => a.DataField.Equals(dataFieldExpression)) != null;
                    if (!columnExists)
                    {
                        AttributeField boundField = new AttributeField();
                        boundField.DataField      = dataFieldExpression;
                        boundField.HeaderText     = attribute.Name;
                        boundField.SortExpression = string.Empty;

                        var attributeCache = Rock.Web.Cache.AttributeCache.Read(attribute.Id);
                        if (attributeCache != null)
                        {
                            boundField.ItemStyle.HorizontalAlign = attributeCache.FieldType.Field.AlignValue;
                        }

                        gEventCalendarItems.Columns.Add(boundField);
                    }
                }
            }

            // Add occurrences Count column
            var occurrencesField = new BadgeField();

            occurrencesField.ImportantMin = int.MaxValue;
            occurrencesField.WarningMin   = 0;
            occurrencesField.WarningMax   = 0;
            occurrencesField.InfoMin      = 1;
            occurrencesField.InfoMax      = int.MaxValue;
            occurrencesField.DataField    = "Occurrences";
            occurrencesField.HeaderText   = "Occurrences";
            occurrencesField.HtmlEncode   = false;
            gEventCalendarItems.Columns.Add(occurrencesField);

            // Add Status column
            var statusField = new BoundField();

            statusField.DataField      = "Status";
            statusField.SortExpression = "EventItem.IsActive";
            statusField.HeaderText     = "Status";
            statusField.HtmlEncode     = false;
            gEventCalendarItems.Columns.Add(statusField);

            // Add Approval Status column
            var approvalStatusField = new BoundField();

            approvalStatusField.DataField      = "ApprovalStatus";
            approvalStatusField.SortExpression = "EventItem.IsApproved";
            approvalStatusField.HeaderText     = "Approval Status";
            approvalStatusField.HtmlEncode     = false;
            gEventCalendarItems.Columns.Add(approvalStatusField);

            // Add delete column
            if (_canEdit)
            {
                var deleteField = new DeleteField();
                gEventCalendarItems.Columns.Add(deleteField);
                deleteField.Click += DeleteEventCalendarItem_Click;
            }
        }
        private void CreateGrids(RockContext rockContext)
        {
            if (ContentChannels.Any())
            {
                this.Visible = true;

                phContentChannelGrids.Controls.Clear();

                foreach (var contentChannel in ContentChannels)
                {
                    bool canEdit = UserCanEdit || contentChannel.IsAuthorized(Authorization.EDIT, CurrentPerson);

                    string iconClass = "fa fa-bullhorn";
                    if (!string.IsNullOrWhiteSpace(contentChannel.IconCssClass))
                    {
                        iconClass = contentChannel.IconCssClass;
                    }

                    var pwItems = new PanelWidget();
                    phContentChannelGrids.Controls.Add(pwItems);
                    pwItems.ID       = string.Format("pwItems_{0}", contentChannel.Id);
                    pwItems.Title    = string.Format("<i class='{0}'></i> {1}", iconClass, contentChannel.Name);
                    pwItems.Expanded = ExpandedPanels.Contains(contentChannel.Id);

                    var divItems = new HtmlGenericControl("div");
                    pwItems.Controls.Add(divItems);
                    divItems.ID = string.Format("divItems_{0}", contentChannel.Id);
                    divItems.AddCssClass("grid");
                    divItems.AddCssClass("grid-panel");

                    Grid gItems = new Grid();
                    divItems.Controls.Add(gItems);
                    gItems.ID                = string.Format("gItems_{0}", contentChannel.Id);
                    gItems.DataKeyNames      = new string[] { "Id" };
                    gItems.EmptyDataText     = "No Items Found";
                    gItems.RowItemText       = "Item";
                    gItems.AllowSorting      = true;
                    gItems.Actions.ShowAdd   = canEdit;
                    gItems.IsDeleteEnabled   = canEdit;
                    gItems.Actions.AddClick += gItems_Add;
                    gItems.RowSelected      += gItems_Edit;
                    gItems.GridRebind       += gItems_GridRebind;

                    //
                    // Add the "Link Existing Item" button.
                    //
                    if (OccurrenceId.HasValue)
                    {
                        var lbtnLinkExisting = new LinkButton();
                        lbtnLinkExisting.Attributes.Add("title", "Link Existing Item");
                        lbtnLinkExisting.CommandArgument = contentChannel.Id.ToString();
                        lbtnLinkExisting.CssClass        = "btn btn-default btn-sm";
                        lbtnLinkExisting.Click          += lbtnLinkExisting_Click;
                        lbtnLinkExisting.Text            = "<i class='fa fa-link'></i>";

                        gItems.Actions.AddCustomActionControl(lbtnLinkExisting);
                    }

                    gItems.Columns.Add(new RockBoundField
                    {
                        DataField      = "Title",
                        HeaderText     = "Title",
                        SortExpression = "Title"
                    });

                    if (contentChannel.ContentChannelType.DateRangeType != ContentChannelDateType.NoDates)
                    {
                        RockBoundField startDateTimeField;
                        RockBoundField expireDateTimeField;
                        if (contentChannel.ContentChannelType.IncludeTime)
                        {
                            startDateTimeField  = new DateTimeField();
                            expireDateTimeField = new DateTimeField();
                        }
                        else
                        {
                            startDateTimeField  = new DateField();
                            expireDateTimeField = new DateField();
                        }

                        startDateTimeField.DataField      = "StartDateTime";
                        startDateTimeField.HeaderText     = contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Active";
                        startDateTimeField.SortExpression = "StartDateTime";
                        gItems.Columns.Add(startDateTimeField);

                        expireDateTimeField.DataField      = "ExpireDateTime";
                        expireDateTimeField.HeaderText     = "Expire";
                        expireDateTimeField.SortExpression = "ExpireDateTime";
                        if (contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange)
                        {
                            gItems.Columns.Add(expireDateTimeField);
                        }
                    }

                    if (!contentChannel.ContentChannelType.DisablePriority)
                    {
                        var priorityField = new RockBoundField
                        {
                            DataField        = "Priority",
                            HeaderText       = "Priority",
                            SortExpression   = "Priority",
                            DataFormatString = "{0:N0}",
                        };
                        priorityField.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                        gItems.Columns.Add(priorityField);
                    }

                    // Add attribute columns
                    int    entityTypeId = EntityTypeCache.Get(typeof(Rock.Model.ContentChannelItem)).Id;
                    string qualifier    = contentChannel.ContentChannelTypeId.ToString();
                    foreach (var attributeCache in new AttributeService(rockContext).GetByEntityTypeQualifier(entityTypeId, "ContentChannelTypeId", qualifier, false)
                             .Where(a => a.IsGridColumn)
                             .OrderBy(a => a.Order)
                             .ThenBy(a => a.Name).ToCacheAttributeList())
                    {
                        string dataFieldExpression = attributeCache.Key;
                        bool   columnExists        = gItems.Columns.OfType <AttributeField>().FirstOrDefault(a => a.DataField.Equals(dataFieldExpression)) != null;
                        if (!columnExists)
                        {
                            AttributeField boundField = new AttributeField();
                            boundField.DataField   = dataFieldExpression;
                            boundField.AttributeId = attributeCache.Id;
                            boundField.HeaderText  = attributeCache.Name;

                            if (attributeCache != null)
                            {
                                boundField.ItemStyle.HorizontalAlign = attributeCache.FieldType.Field.AlignValue;
                            }

                            gItems.Columns.Add(boundField);
                        }
                    }

                    if (contentChannel.RequiresApproval && !contentChannel.ContentChannelType.DisableStatus)
                    {
                        var statusField = new BoundField();
                        gItems.Columns.Add(statusField);
                        statusField.DataField      = "Status";
                        statusField.HeaderText     = "Status";
                        statusField.SortExpression = "Status";
                        statusField.HtmlEncode     = false;
                    }

                    var deleteField = new DeleteField();
                    gItems.Columns.Add(deleteField);
                    deleteField.Click += gItems_Delete;
                }
            }
            else
            {
                this.Visible = false;
            }
        }
Пример #9
0
        /// <summary>
        /// Add all of the columns to the Registrations grid after the Registrants column.
        /// The Column.Insert method does not play well with buttons.
        /// </summary>
        private void RegistrationsTabAddDynamicControls()
        {
            var registrantsField      = gRegistrations.ColumnsOfType <RockTemplateField>().FirstOrDefault(a => a.HeaderText == "Registrants");
            int registrantsFieldIndex = gRegistrations.Columns.IndexOf(registrantsField);

            // Remove all columns to the right of Registrants
            for (int i = registrantsFieldIndex + 2; i < gRegistrations.Columns.Count; i++)
            {
                gRegistrations.Columns.RemoveAt(i);
            }

            // Add Attribute columns if necessary
            if (AvailableRegistrationAttributeIdsForGrid != null)
            {
                foreach (var attributeCache in AvailableRegistrationAttributeIdsForGrid.Select(a => AttributeCache.Get(a)))
                {
                    bool columnExists = gRegistrations.Columns.OfType <AttributeField>().FirstOrDefault(a => a.AttributeId == attributeCache.Id) != null;
                    if (!columnExists)
                    {
                        AttributeField boundField = new AttributeField();
                        boundField.DataField   = attributeCache.Key;
                        boundField.AttributeId = attributeCache.Id;
                        boundField.HeaderText  = attributeCache.Name;
                        boundField.ItemStyle.HorizontalAlign = attributeCache.FieldType.Field.AlignValue;
                        gRegistrations.Columns.Add(boundField);
                    }
                }
            }

            // Add the rest of the columns
            var dtWhen = new DateTimeField {
                DataField = "CreatedDateTime", HeaderText = "When", SortExpression = "CreatedDateTime"
            };

            dtWhen.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
            dtWhen.ItemStyle.HorizontalAlign   = HorizontalAlign.Left;
            gRegistrations.Columns.Add(dtWhen);

            var lDiscount = new RockLiteralField {
                ID = "lDiscount", HeaderText = "Discount Code", SortExpression = "DiscountCode", Visible = false
            };

            lDiscount.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
            lDiscount.ItemStyle.HorizontalAlign   = HorizontalAlign.Left;
            gRegistrations.Columns.Add(lDiscount);

            var lRegistrationCost = new RockLiteralField {
                ID = "lRegistrationCost", HeaderText = "Total Cost", SortExpression = "TotalCost"
            };

            lRegistrationCost.HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
            lRegistrationCost.ItemStyle.HorizontalAlign   = HorizontalAlign.Right;
            gRegistrations.Columns.Add(lRegistrationCost);

            var lBalance = new RockLiteralField {
                ID = "lBalance", HeaderText = "Balance Due", SortExpression = "BalanceDue"
            };

            lBalance.HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
            lBalance.ItemStyle.HorizontalAlign   = HorizontalAlign.Right;
            gRegistrations.Columns.Add(lBalance);

            DeleteField deleteField = new DeleteField();

            deleteField.Click += gRegistrations_Delete;
            gRegistrations.Columns.Add(deleteField);
        }
        public void Execute(IArray paramvalues, ITrackCancel trackcancel,
                            IGPEnvironmentManager envMgr, IGPMessages messages)
        {
            // Remember the original GP environment settings and temporarily override these settings

            var gpSettings = envMgr as IGeoProcessorSettings;
            bool origAddOutputsToMapSetting = gpSettings.AddOutputsToMap;
            bool origLogHistorySetting = gpSettings.LogHistory;
            gpSettings.AddOutputsToMap = false;
            gpSettings.LogHistory = false;

            // Create the Geoprocessor

            Geoprocessor gp = new Geoprocessor();

            try
            {
                // Validate our values

                IGPMessages validateMessages = ((IGPFunction2)this).Validate(paramvalues, false, envMgr);
                if ((validateMessages as IGPMessage).IsError())
                {
                    messages.AddError(1, "Validate failed");
                    return;
                }

                // Unpack values

                IGPParameter gpParam = paramvalues.get_Element(InputStreetsFeatureClass) as IGPParameter;
                IGPValue inputStreetsFeatureClassValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputAltStreetsFeatureClass) as IGPParameter;
                IGPValue inputAltStreetsFeatureClassValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputZLevelsFeatureClass) as IGPParameter;
                IGPValue inputZLevelsFeatureClassValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputCdmsTable) as IGPParameter;
                IGPValue inputCdmsTableValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputRdmsTable) as IGPParameter;
                IGPValue inputRdmsTableValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputSignsTable) as IGPParameter;
                IGPValue inputSignsTableValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(OutputFileGDB) as IGPParameter;
                IGPValue outputFileGDBValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(OutputFileGDBVersion) as IGPParameter;
                IGPValue outputFileGDBVersionValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputFeatureDatasetName) as IGPParameter;
                IGPValue inputFeatureDatasetNameValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputNetworkDatasetName) as IGPParameter;
                IGPValue inputNetworkDatasetNameValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputCreateNetworkAttributesInMetric) as IGPParameter;
                IGPValue inputCreateNetworkAttributeInMetricValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputCreateArcGISOnlineNetworkAttributes) as IGPParameter;
                IGPValue inputCreateArcGISOnlineNetworkAttributesValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputTimeZoneIDBaseFieldName) as IGPParameter;
                IGPValue inputTimeZoneIDBaseFieldNameValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputTimeZoneTable) as IGPParameter;
                IGPValue inputTimeZoneTableValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputCommonTimeZoneForTheEntireDataset) as IGPParameter;
                IGPValue inputCommonTimeZoneForTheEntireDatasetValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputTrafficTable) as IGPParameter;
                IGPValue inputTrafficTableValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputLinkReferenceFileFC14) as IGPParameter;
                IGPValue inputLinkReferenceFileFC14Value = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputLinkReferenceFileFC5) as IGPParameter;
                IGPValue inputLinkReferenceFileFC5Value = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputTMCReferenceFile) as IGPParameter;
                IGPValue inputTMCReferenceFileValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputSPDFile) as IGPParameter;
                IGPValue inputSPDFileValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputLiveTrafficFeedFolder) as IGPParameter;
                IGPValue inputLiveTrafficFeedFolderValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputLiveTrafficFeedArcGISServerConnection) as IGPParameter;
                IGPValue inputLiveTrafficFeedArcGISServerConnectionValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputLiveTrafficFeedGeoprocessingServiceName) as IGPParameter;
                IGPValue inputLiveTrafficFeedGeoprocessingServiceNameValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputLiveTrafficFeedGeoprocessingTaskName) as IGPParameter;
                IGPValue inputLiveTrafficFeedGeoprocessingTaskNameValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputUSCndModTable) as IGPParameter;
                IGPValue inputUSCndModTableValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputNonUSCndModTable) as IGPParameter;
                IGPValue inputNonUSCndModTableValue = m_gpUtils.UnpackGPValue(gpParam);

                double fgdbVersion = 0.0;
                if (!(outputFileGDBVersionValue.IsEmpty()))
                    fgdbVersion = Convert.ToDouble(outputFileGDBVersionValue.GetAsText(), System.Globalization.CultureInfo.InvariantCulture);

                bool createNetworkAttributesInMetric = false;
                if (!(inputCreateNetworkAttributeInMetricValue.IsEmpty()))
                    createNetworkAttributesInMetric = ((inputCreateNetworkAttributeInMetricValue.GetAsText()).ToUpper() == "TRUE");

                bool createArcGISOnlineNetworkAttributes = false;
                if (!(inputCreateArcGISOnlineNetworkAttributesValue.IsEmpty()))
                    createArcGISOnlineNetworkAttributes = ((inputCreateArcGISOnlineNetworkAttributesValue.GetAsText()).ToUpper() == "TRUE");

                if (inputTimeZoneIDBaseFieldNameValue.IsEmpty() ^ inputTimeZoneTableValue.IsEmpty())
                {
                    messages.AddError(1, "The Time Zone ID Base Field Name and the Time Zone Table must be specified together.");
                    return;
                }

                string timeZoneIDBaseFieldName = "";
                bool directedTimeZoneIDFields = false;
                if (!(inputTimeZoneIDBaseFieldNameValue.IsEmpty()))
                {
                    timeZoneIDBaseFieldName = inputTimeZoneIDBaseFieldNameValue.GetAsText();
                    IDETable inputTable = m_gpUtils.DecodeDETable(inputStreetsFeatureClassValue);
                    if (inputTable.Fields.FindField(timeZoneIDBaseFieldName) == -1)
                    {
                        directedTimeZoneIDFields = true;
                        if (((inputTable.Fields.FindField("FT_" + timeZoneIDBaseFieldName) == -1) || (inputTable.Fields.FindField("TF_" + timeZoneIDBaseFieldName) == -1)))
                        {
                            messages.AddError(1, "Field named " + timeZoneIDBaseFieldName + " does not exist, nor the pair of fields with FT_ and TF_ prefixing " + timeZoneIDBaseFieldName + " does not exist.");
                            return;
                        }
                    }
                }

                string commonTimeZone = "";
                if (!(inputCommonTimeZoneForTheEntireDatasetValue.IsEmpty()))
                    commonTimeZone = inputCommonTimeZoneForTheEntireDatasetValue.GetAsText();

                if (inputLinkReferenceFileFC14Value.IsEmpty() ^ inputLinkReferenceFileFC5Value.IsEmpty())
                {
                    messages.AddError(1, "Both Traffic Patterns Link Reference .csv files must be specified together.");
                    return;
                }

                bool usesHistoricalTraffic = !(inputSPDFileValue.IsEmpty());
                bool usesNTPFullCoverage = !(inputLinkReferenceFileFC5Value.IsEmpty());
                if ((inputTMCReferenceFileValue.IsEmpty() & !usesNTPFullCoverage) ^ inputSPDFileValue.IsEmpty())
                {
                    messages.AddError(1, "The Traffic Patterns SPD .csv file must be specified with the Traffic Patterns Link/TMC Reference .csv file(s).");
                    return;
                }

                if (inputTrafficTableValue.IsEmpty() & !inputTMCReferenceFileValue.IsEmpty())
                {
                    messages.AddError(1, "If the TMC Reference .csv file is specified, then the Traffic table must also be specified.");
                    return;
                }

                bool agsConnectionIsEmpty = inputLiveTrafficFeedArcGISServerConnectionValue.IsEmpty();
                bool gpServiceNameIsEmpty = inputLiveTrafficFeedGeoprocessingServiceNameValue.IsEmpty();
                bool gpTaskNameIsEmpty = inputLiveTrafficFeedGeoprocessingTaskNameValue.IsEmpty();
                if ((agsConnectionIsEmpty | gpServiceNameIsEmpty | gpTaskNameIsEmpty) ^
                    (agsConnectionIsEmpty & gpServiceNameIsEmpty & gpTaskNameIsEmpty))
                {
                    messages.AddError(1, "The ArcGIS Server Connection, Geoprocessing Service Name, and Geoprocessing Task Name must all be specified together.");
                    return;
                }

                bool feedFolderIsEmpty = inputLiveTrafficFeedFolderValue.IsEmpty();
                if (!(feedFolderIsEmpty | agsConnectionIsEmpty))
                {
                    messages.AddError(1, "The live traffic feed folder and live traffic feed connection cannot be specified together.");
                    return;
                }

                if (inputTrafficTableValue.IsEmpty() & !(feedFolderIsEmpty & agsConnectionIsEmpty))
                {
                    messages.AddError(1, "The Traffic table must be specified to use Live Traffic.");
                    return;
                }

                bool usesTransport = true;
                if (inputUSCndModTableValue.IsEmpty() && inputNonUSCndModTableValue.IsEmpty())
                    usesTransport = false;

                ITrafficFeedLocation trafficFeedLocation = null;
                if (!agsConnectionIsEmpty)
                {
                    // We're using an ArcGIS Server Connection and Geoprocessing Service/Task

                    ITrafficFeedGPService tfgps = new TrafficFeedGPServiceClass();
                    IName trafficFeedGPServiceName = m_gpUtils.GetNameObject(inputLiveTrafficFeedArcGISServerConnectionValue as IDataElement);
                    tfgps.ConnectionProperties = ((IAGSServerConnectionName)trafficFeedGPServiceName).ConnectionProperties;
                    tfgps.ServiceName = inputLiveTrafficFeedGeoprocessingServiceNameValue.GetAsText();
                    tfgps.TaskName = inputLiveTrafficFeedGeoprocessingTaskNameValue.GetAsText();
                    trafficFeedLocation = tfgps as ITrafficFeedLocation;
                }
                else if (!feedFolderIsEmpty)
                {
                    // We're using a Traffic Feed Folder

                    ITrafficFeedDirectory tfd = new TrafficFeedDirectoryClass();
                    tfd.TrafficDirectory = inputLiveTrafficFeedFolderValue.GetAsText();
                    trafficFeedLocation = tfd as ITrafficFeedLocation;
                }

                // Get the path to the output file GDB, and feature dataset and network dataset names

                string outputFileGdbPath = outputFileGDBValue.GetAsText();
                string fdsName = inputFeatureDatasetNameValue.GetAsText();
                string ndsName = inputNetworkDatasetNameValue.GetAsText();

                // Create the new file geodatabase and feature dataset

                AddMessage("Creating the file geodatabase and feature dataset...", messages, trackcancel);

                int lastBackslash = outputFileGdbPath.LastIndexOf("\\");
                CreateFileGDB createFGDBTool = new CreateFileGDB();
                createFGDBTool.out_folder_path = outputFileGdbPath.Remove(lastBackslash);
                createFGDBTool.out_name = outputFileGdbPath.Substring(lastBackslash + 1);
                createFGDBTool.out_version = "9.3";
                gp.Execute(createFGDBTool, trackcancel);

                CreateFeatureDataset createFDSTool = new CreateFeatureDataset();
                createFDSTool.out_dataset_path = outputFileGdbPath;
                createFDSTool.out_name = fdsName;
                createFDSTool.spatial_reference = inputStreetsFeatureClassValue.GetAsText();
                gp.Execute(createFDSTool, trackcancel);

                // Import the Streets feature class to the file geodatabase
                // If we're using ArcInfo, also sort the feature class

                string pathToFds = outputFileGdbPath + "\\" + fdsName;
                string streetsFeatureClassPath = pathToFds + "\\" + StreetsFCName;

                IAoInitialize aoi = new AoInitializeClass();
                if (aoi.InitializedProduct() == esriLicenseProductCode.esriLicenseProductCodeAdvanced)
                {
                    AddMessage("Importing and spatially sorting the Streets feature class...", messages, trackcancel);

                    Sort sortTool = new Sort();
                    sortTool.in_dataset = inputStreetsFeatureClassValue.GetAsText();
                    sortTool.out_dataset = streetsFeatureClassPath;
                    sortTool.sort_field = "Shape";
                    sortTool.spatial_sort_method = "PEANO";
                    gp.Execute(sortTool, trackcancel);
                }
                else
                {
                    AddMessage("Importing the Streets feature class...", messages, trackcancel);

                    FeatureClassToFeatureClass importFCTool = new FeatureClassToFeatureClass();
                    importFCTool.in_features = inputStreetsFeatureClassValue.GetAsText();
                    importFCTool.out_path = pathToFds;
                    importFCTool.out_name = StreetsFCName;
                    gp.Execute(importFCTool, trackcancel);
                }

                // Add an index to the Streets feature class's LINK_ID field

                AddMessage("Indexing the LINK_ID field...", messages, trackcancel);

                AddIndex addIndexTool = new AddIndex();
                addIndexTool.in_table = streetsFeatureClassPath;
                addIndexTool.fields = "LINK_ID";
                addIndexTool.index_name = "LINK_ID";
                gp.Execute(addIndexTool, trackcancel);

                // Add the alternate street name fields to the Streets feature class

                AddMessage("Creating fields on the Streets feature class for the alternate street names...", messages, trackcancel);

                AddField addFieldTool = new AddField();
                addFieldTool.in_table = streetsFeatureClassPath;

                addFieldTool.field_type = "TEXT";
                addFieldTool.field_length = 240;
                addFieldTool.field_name = "ST_NAME_Alt";
                gp.Execute(addFieldTool, trackcancel);
                addFieldTool.field_length = 3;
                addFieldTool.field_name = "ST_LANGCD_Alt";
                gp.Execute(addFieldTool, trackcancel);
                addFieldTool.field_length = 6;
                addFieldTool.field_name = "ST_NM_PREF_Alt";
                gp.Execute(addFieldTool, trackcancel);
                addFieldTool.field_length = 90;
                addFieldTool.field_name = "ST_TYP_BEF_Alt";
                gp.Execute(addFieldTool, trackcancel);
                addFieldTool.field_length = 105;
                addFieldTool.field_name = "ST_NM_BASE_Alt";
                gp.Execute(addFieldTool, trackcancel);
                addFieldTool.field_length = 6;
                addFieldTool.field_name = "ST_NM_SUFF_Alt";
                gp.Execute(addFieldTool, trackcancel);
                addFieldTool.field_length = 90;
                addFieldTool.field_name = "ST_TYP_AFT_Alt";
                gp.Execute(addFieldTool, trackcancel);
                addFieldTool.field_length = 1;
                addFieldTool.field_name = "DIRONSIGN_Alt";
                gp.Execute(addFieldTool, trackcancel);

                // Extract the explicatable street names

                string ExplicatblTablePath = outputFileGdbPath + "\\Explicatbl";

                AddMessage("Extracting the explicatable street names...", messages, trackcancel);

                TableSelect tableSelectTool = new TableSelect();
                tableSelectTool.in_table = inputAltStreetsFeatureClassValue.GetAsText();
                tableSelectTool.out_table = ExplicatblTablePath;
                tableSelectTool.where_clause = "EXPLICATBL = 'Y'";
                gp.Execute(tableSelectTool, trackcancel);

                // Determine which explicatable names are alternate names and extract them

                MakeTableView makeTableViewTool = new MakeTableView();
                makeTableViewTool.in_table = ExplicatblTablePath;
                makeTableViewTool.out_view = "Explicatbl_View";
                gp.Execute(makeTableViewTool, trackcancel);

                AddJoin addJoinTool = new AddJoin();
                addJoinTool.in_layer_or_view = "Explicatbl_View";
                addJoinTool.in_field = "LINK_ID";
                addJoinTool.join_table = streetsFeatureClassPath;
                addJoinTool.join_field = "LINK_ID";
                gp.Execute(addJoinTool, trackcancel);

                AddMessage("Extracting the alternate street names...", messages, trackcancel);

                TableToTable importTableTool = new TableToTable();
                importTableTool.in_rows = "Explicatbl_View";
                importTableTool.out_path = outputFileGdbPath;
                importTableTool.out_name = "AltNames";
                importTableTool.where_clause = "Explicatbl.ST_TYP_BEF <> " + StreetsFCName + ".ST_TYP_BEF OR " +
                                               "Explicatbl.ST_NM_BASE <> " + StreetsFCName + ".ST_NM_BASE OR " +
                                               "Explicatbl.ST_TYP_AFT <> " + StreetsFCName + ".ST_TYP_AFT";
                importTableTool.field_mapping = "LINK_ID \"LINK_ID\" true true false 4 Long 0 0 ,First,#," + ExplicatblTablePath + ",Explicatbl.LINK_ID,-1,-1;" +
                                                "ST_NAME \"ST_NAME\" true true false 240 Text 0 0 ,First,#," + ExplicatblTablePath + ",Explicatbl.ST_NAME,-1,-1;" +
                                                "ST_LANGCD \"ST_LANGCD\" true true false 3 Text 0 0 ,First,#," + ExplicatblTablePath + ",Explicatbl.ST_LANGCD,-1,-1;" +
                                                "ST_NM_PREF \"ST_NM_PREF\" true true false 6 Text 0 0 ,First,#," + ExplicatblTablePath + ",Explicatbl.ST_NM_PREF,-1,-1;" +
                                                "ST_TYP_BEF \"ST_TYP_BEF\" true true false 90 Text 0 0 ,First,#," + ExplicatblTablePath + ",Explicatbl.ST_TYP_BEF,-1,-1;" +
                                                "ST_NM_BASE \"ST_NM_BASE\" true true false 105 Text 0 0 ,First,#," + ExplicatblTablePath + ",Explicatbl.ST_NM_BASE,-1,-1;" +
                                                "ST_NM_SUFF \"ST_NM_SUFF\" true true false 6 Text 0 0 ,First,#," + ExplicatblTablePath + ",Explicatbl.ST_NM_SUFF,-1,-1;" +
                                                "ST_TYP_AFT \"ST_TYP_AFT\" true true false 90 Text 0 0 ,First,#," + ExplicatblTablePath + ",Explicatbl.ST_TYP_AFT,-1,-1;" +
                                                "DIRONSIGN \"DIRONSIGN\" true true false 1 Text 0 0 ,First,#," + ExplicatblTablePath + ",Explicatbl.DIRONSIGN,-1,-1";
                gp.Execute(importTableTool, trackcancel);

                RemoveJoin removeJoinTool = new RemoveJoin();
                removeJoinTool.in_layer_or_view = "Explicatbl_View";
                removeJoinTool.join_name = StreetsFCName;
                gp.Execute(removeJoinTool, trackcancel);

                Delete deleteTool = new Delete();
                deleteTool.in_data = "Explicatbl_View";
                gp.Execute(deleteTool, trackcancel);
                deleteTool.in_data = ExplicatblTablePath;
                gp.Execute(deleteTool, trackcancel);

                string AltNamesTablePath = outputFileGdbPath + "\\AltNames";

                addIndexTool = new AddIndex();
                addIndexTool.in_table = AltNamesTablePath;
                addIndexTool.fields = "LINK_ID";
                addIndexTool.index_name = "LINK_ID";
                gp.Execute(addIndexTool, trackcancel);

                // Calculate the alternate street name fields

                MakeFeatureLayer makeFeatureLayerTool = new MakeFeatureLayer();
                makeFeatureLayerTool.in_features = streetsFeatureClassPath;
                makeFeatureLayerTool.out_layer = "Streets_Layer";
                gp.Execute(makeFeatureLayerTool, trackcancel);

                addJoinTool = new AddJoin();
                addJoinTool.in_layer_or_view = "Streets_Layer";
                addJoinTool.in_field = "LINK_ID";
                addJoinTool.join_table = AltNamesTablePath;
                addJoinTool.join_field = "LINK_ID";
                gp.Execute(addJoinTool, trackcancel);

                AddMessage("Copying over the alternate ST_NAME values...", messages, trackcancel);

                CalculateField calcFieldTool = new CalculateField();
                calcFieldTool.in_table = "Streets_Layer";
                calcFieldTool.expression_type = "VB";
                calcFieldTool.field = StreetsFCName + ".ST_NAME_Alt";
                calcFieldTool.expression = "[AltNames.ST_NAME]";
                gp.Execute(calcFieldTool, trackcancel);

                AddMessage("Copying over the alternate ST_LANGCD values...", messages, trackcancel);

                calcFieldTool.field = StreetsFCName + ".ST_LANGCD_Alt";
                calcFieldTool.expression = "[AltNames.ST_LANGCD]";
                gp.Execute(calcFieldTool, trackcancel);

                AddMessage("Copying over the alternate ST_NM_PREF values...", messages, trackcancel);

                calcFieldTool.field = StreetsFCName + ".ST_NM_PREF_Alt";
                calcFieldTool.expression = "[AltNames.ST_NM_PREF]";
                gp.Execute(calcFieldTool, trackcancel);

                AddMessage("Copying over the alternate ST_TYP_BEF values...", messages, trackcancel);

                calcFieldTool.field = StreetsFCName + ".ST_TYP_BEF_Alt";
                calcFieldTool.expression = "[AltNames.ST_TYP_BEF]";
                gp.Execute(calcFieldTool, trackcancel);

                AddMessage("Copying over the alternate ST_NM_BASE values...", messages, trackcancel);

                calcFieldTool.field = StreetsFCName + ".ST_NM_BASE_Alt";
                calcFieldTool.expression = "[AltNames.ST_NM_BASE]";
                gp.Execute(calcFieldTool, trackcancel);

                AddMessage("Copying over the alternate ST_NM_SUFF values...", messages, trackcancel);

                calcFieldTool.field = StreetsFCName + ".ST_NM_SUFF_Alt";
                calcFieldTool.expression = "[AltNames.ST_NM_SUFF]";
                gp.Execute(calcFieldTool, trackcancel);

                AddMessage("Copying over the alternate ST_TYP_AFT values...", messages, trackcancel);

                calcFieldTool.field = StreetsFCName + ".ST_TYP_AFT_Alt";
                calcFieldTool.expression = "[AltNames.ST_TYP_AFT]";
                gp.Execute(calcFieldTool, trackcancel);

                AddMessage("Copying over the alternate DIRONSIGN values...", messages, trackcancel);

                calcFieldTool.field = StreetsFCName + ".DIRONSIGN_Alt";
                calcFieldTool.expression = "[AltNames.DIRONSIGN]";
                gp.Execute(calcFieldTool, trackcancel);

                removeJoinTool = new RemoveJoin();
                removeJoinTool.in_layer_or_view = "Streets_Layer";
                removeJoinTool.join_name = "AltNames";
                gp.Execute(removeJoinTool, trackcancel);

                deleteTool = new Delete();
                deleteTool.in_data = "Streets_Layer";
                gp.Execute(deleteTool, trackcancel);
                deleteTool.in_data = AltNamesTablePath;
                gp.Execute(deleteTool, trackcancel);

                // Add fields for the Z-Level values to the Streets feature class

                AddMessage("Creating fields on the Streets feature class for the Z-Level values...", messages, trackcancel);

                addFieldTool = new AddField();
                addFieldTool.in_table = streetsFeatureClassPath;

                addFieldTool.field_type = "SHORT";
                addFieldTool.field_name = "F_ZLEV";
                gp.Execute(addFieldTool, trackcancel);
                addFieldTool.field_name = "T_ZLEV";
                gp.Execute(addFieldTool, trackcancel);

                // Separate out the From and To Z-Level values into separate tables and index the LINK_ID fields

                string FromZsTablePath = outputFileGdbPath + "\\FromZs";
                string ToZsTablePath = outputFileGdbPath + "\\ToZs";

                AddMessage("Extracting the From Z-Level information...", messages, trackcancel);

                tableSelectTool = new TableSelect();
                tableSelectTool.in_table = inputZLevelsFeatureClassValue.GetAsText();
                tableSelectTool.out_table = FromZsTablePath;
                tableSelectTool.where_clause = "INTRSECT = 'Y' AND POINT_NUM = 1";
                gp.Execute(tableSelectTool, trackcancel);

                AddMessage("Extracting the To Z-Level information...", messages, trackcancel);

                tableSelectTool.out_table = ToZsTablePath;
                tableSelectTool.where_clause = "INTRSECT = 'Y' AND POINT_NUM > 1";
                gp.Execute(tableSelectTool, trackcancel);

                AddMessage("Analyzing the Z-Level information...", messages, trackcancel);

                addIndexTool = new AddIndex();
                addIndexTool.in_table = FromZsTablePath;
                addIndexTool.fields = "LINK_ID";
                addIndexTool.index_name = "LINK_ID";
                gp.Execute(addIndexTool, trackcancel);
                addIndexTool.in_table = ToZsTablePath;
                gp.Execute(addIndexTool, trackcancel);

                // Calculate the Z-Level fields

                makeFeatureLayerTool = new MakeFeatureLayer();
                makeFeatureLayerTool.in_features = streetsFeatureClassPath;
                makeFeatureLayerTool.out_layer = "Streets_Layer";
                gp.Execute(makeFeatureLayerTool, trackcancel);

                addJoinTool = new AddJoin();
                addJoinTool.in_layer_or_view = "Streets_Layer";
                addJoinTool.in_field = "LINK_ID";
                addJoinTool.join_table = FromZsTablePath;
                addJoinTool.join_field = "LINK_ID";
                gp.Execute(addJoinTool, trackcancel);

                AddMessage("Copying over the F_ZLEV values...", messages, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = "Streets_Layer";
                calcFieldTool.field = StreetsFCName + ".F_ZLEV";
                calcFieldTool.expression = "[FromZs.Z_LEVEL]";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                removeJoinTool = new RemoveJoin();
                removeJoinTool.in_layer_or_view = "Streets_Layer";
                removeJoinTool.join_name = "FromZs";
                gp.Execute(removeJoinTool, trackcancel);

                addJoinTool = new AddJoin();
                addJoinTool.in_layer_or_view = "Streets_Layer";
                addJoinTool.in_field = "LINK_ID";
                addJoinTool.join_table = ToZsTablePath;
                addJoinTool.join_field = "LINK_ID";
                gp.Execute(addJoinTool, trackcancel);

                AddMessage("Copying over the T_ZLEV values...", messages, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = "Streets_Layer";
                calcFieldTool.field = StreetsFCName + ".T_ZLEV";
                calcFieldTool.expression = "[ToZs.Z_LEVEL]";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                removeJoinTool = new RemoveJoin();
                removeJoinTool.in_layer_or_view = "Streets_Layer";
                removeJoinTool.join_name = "ToZs";
                gp.Execute(removeJoinTool, trackcancel);

                deleteTool = new Delete();
                deleteTool.in_data = "Streets_Layer";
                gp.Execute(deleteTool, trackcancel);

                deleteTool.in_data = FromZsTablePath;
                gp.Execute(deleteTool, trackcancel);
                deleteTool.in_data = ToZsTablePath;
                gp.Execute(deleteTool, trackcancel);

                // Add fields for the distance (Meters), language, and speed (KPH) values to the Streets feature class

                AddMessage("Creating fields on the Streets feature class for distance, speed, and language...", messages, trackcancel);

                addFieldTool = new AddField();
                addFieldTool.in_table = streetsFeatureClassPath;

                addFieldTool.field_type = "DOUBLE";
                addFieldTool.field_name = "Meters";
                gp.Execute(addFieldTool, trackcancel);
                addFieldTool.field_type = "FLOAT";
                addFieldTool.field_name = "KPH";
                gp.Execute(addFieldTool, trackcancel);
                addFieldTool.field_type = "TEXT";
                addFieldTool.field_name = "Language";
                addFieldTool.field_length = 2;
                gp.Execute(addFieldTool, trackcancel);
                addFieldTool.field_type = "TEXT";
                addFieldTool.field_name = "Language_Alt";
                addFieldTool.field_length = 2;
                gp.Execute(addFieldTool, trackcancel);

                // Calculate the distance (Meters), language, and speed (KPH) fields

                AddMessage("Calculating the distance, speed, and language fields...", messages, trackcancel);

                CalculateMetersKPHAndLanguageFields(outputFileGdbPath);

                if (createArcGISOnlineNetworkAttributes)
                {
                    CreateAndPopulateDirectionalVehicleAccessFields("AR_AUTO", streetsFeatureClassPath, gp, messages, trackcancel);
                    CreateAndPopulateDirectionalVehicleAccessFields("AR_BUS", streetsFeatureClassPath, gp, messages, trackcancel);
                    CreateAndPopulateDirectionalVehicleAccessFields("AR_TAXIS", streetsFeatureClassPath, gp, messages, trackcancel);
                    CreateAndPopulateDirectionalVehicleAccessFields("AR_TRUCKS", streetsFeatureClassPath, gp, messages, trackcancel);
                    CreateAndPopulateDirectionalVehicleAccessFields("AR_DELIV", streetsFeatureClassPath, gp, messages, trackcancel);
                    CreateAndPopulateDirectionalVehicleAccessFields("AR_EMERVEH", streetsFeatureClassPath, gp, messages, trackcancel);
                    CreateAndPopulateDirectionalVehicleAccessFields("AR_MOTOR", streetsFeatureClassPath, gp, messages, trackcancel);
                }

                // Add a field to the Streets feature class indicating roads closed for construction

                AddMessage("Creating the ClosedForConstruction field on the Streets feature class...", messages, trackcancel);

                addFieldTool = new AddField();
                addFieldTool.in_table = streetsFeatureClassPath;
                addFieldTool.field_type = "TEXT";
                addFieldTool.field_name = "ClosedForConstruction";
                addFieldTool.field_length = 1;
                gp.Execute(addFieldTool, trackcancel);

                // Create a table for looking up roads closed for construction

                AddMessage("Creating and indexing the table containing roads closed for construction...", messages, trackcancel);

                string closedForConstructionTablePath = outputFileGdbPath + "\\ClosedForConstruction";

                tableSelectTool = new TableSelect();
                tableSelectTool.in_table = inputCdmsTableValue.GetAsText();
                tableSelectTool.out_table = closedForConstructionTablePath;
                tableSelectTool.where_clause = "COND_TYPE = 3";
                gp.Execute(tableSelectTool, trackcancel);

                addIndexTool = new AddIndex();
                addIndexTool.in_table = closedForConstructionTablePath;
                addIndexTool.fields = "LINK_ID";
                addIndexTool.index_name = "LINK_ID";
                gp.Execute(addIndexTool, trackcancel);

                makeFeatureLayerTool = new MakeFeatureLayer();
                makeFeatureLayerTool.in_features = streetsFeatureClassPath;
                makeFeatureLayerTool.out_layer = "Streets_Layer";
                gp.Execute(makeFeatureLayerTool, trackcancel);

                addJoinTool = new AddJoin();
                addJoinTool.in_layer_or_view = "Streets_Layer";
                addJoinTool.in_field = "LINK_ID";
                addJoinTool.join_table = closedForConstructionTablePath;
                addJoinTool.join_field = "LINK_ID";
                addJoinTool.join_type = "KEEP_COMMON";
                gp.Execute(addJoinTool, trackcancel);

                AddMessage("Calculating the ClosedForConstruction field...", messages, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = "Streets_Layer";
                calcFieldTool.field = "Streets.ClosedForConstruction";
                calcFieldTool.expression = "\"Y\"";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                removeJoinTool = new RemoveJoin();
                removeJoinTool.in_layer_or_view = "Streets_Layer";
                removeJoinTool.join_name = "ClosedForConstruction";
                gp.Execute(removeJoinTool, trackcancel);

                deleteTool = new Delete();
                deleteTool.in_data = "Streets_Layer";
                gp.Execute(deleteTool, trackcancel);
                deleteTool.in_data = closedForConstructionTablePath;
                gp.Execute(deleteTool, trackcancel);

                // Add fields to the Streets feature class indicating roads with usage fees

                string[] arFieldSuffixes = new string[] { "AUTO", "BUS", "TAXIS", "CARPOOL", "PEDSTRN",
                                                          "TRUCKS", "THRUTR", "DELIVER", "EMERVEH", "MOTOR" };

                AddMessage("Creating the UFR fields on the Streets feature class...", messages, trackcancel);

                foreach (string arFieldSuffix in arFieldSuffixes)
                {
                    addFieldTool = new AddField();
                    addFieldTool.in_table = streetsFeatureClassPath;
                    addFieldTool.field_name = "UFR_" + arFieldSuffix;
                    addFieldTool.field_type = "TEXT";
                    addFieldTool.field_length = 1;
                    gp.Execute(addFieldTool, trackcancel);
                }

                // Create a table for looking up roads with usage fees

                AddMessage("Creating and indexing the table containing roads with usage fees...", messages, trackcancel);

                string usageFeeRequiredTablePath = outputFileGdbPath + "\\UsageFeeRequired";

                tableSelectTool = new TableSelect();
                tableSelectTool.in_table = inputCdmsTableValue.GetAsText();
                tableSelectTool.out_table = usageFeeRequiredTablePath;
                tableSelectTool.where_clause = "COND_TYPE = 12";
                gp.Execute(tableSelectTool, trackcancel);

                addIndexTool = new AddIndex();
                addIndexTool.in_table = usageFeeRequiredTablePath;
                addIndexTool.fields = "LINK_ID";
                addIndexTool.index_name = "LINK_ID";
                gp.Execute(addIndexTool, trackcancel);

                makeFeatureLayerTool = new MakeFeatureLayer();
                makeFeatureLayerTool.in_features = streetsFeatureClassPath;
                makeFeatureLayerTool.out_layer = "Streets_Layer";
                gp.Execute(makeFeatureLayerTool, trackcancel);

                addJoinTool = new AddJoin();
                addJoinTool.in_layer_or_view = "Streets_Layer";
                addJoinTool.in_field = "LINK_ID";
                addJoinTool.join_table = usageFeeRequiredTablePath;
                addJoinTool.join_field = "LINK_ID";
                addJoinTool.join_type = "KEEP_COMMON";
                gp.Execute(addJoinTool, trackcancel);

                AddMessage("Calculating the ClosedForConstruction field...", messages, trackcancel);

                foreach (string arFieldSuffix in arFieldSuffixes)
                {
                    AddMessage("Calculating the UFR_" + arFieldSuffix + " field on the Streets feature class...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "Streets_Layer";
                    calcFieldTool.field = "Streets.UFR_" + arFieldSuffix;
                    calcFieldTool.expression = "[UsageFeeRequired.AR_" + arFieldSuffix + "]";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);
                }

                removeJoinTool = new RemoveJoin();
                removeJoinTool.in_layer_or_view = "Streets_Layer";
                removeJoinTool.join_name = "UsageFeeRequired";
                gp.Execute(removeJoinTool, trackcancel);

                deleteTool = new Delete();
                deleteTool.in_data = "Streets_Layer";
                gp.Execute(deleteTool, trackcancel);
                deleteTool.in_data = usageFeeRequiredTablePath;
                gp.Execute(deleteTool, trackcancel);

                // Copy the time zones table to the file geodatabase

                if (timeZoneIDBaseFieldName != "")
                {
                    AddMessage("Copying the TimeZones table...", messages, trackcancel);

                    importTableTool = new TableToTable();
                    importTableTool.in_rows = inputTimeZoneTableValue.GetAsText();
                    importTableTool.out_path = outputFileGdbPath;
                    importTableTool.out_name = "TimeZones";
                    gp.Execute(importTableTool, trackcancel);
                }

                #region Process Historical Traffic Tables

                if (usesHistoricalTraffic)
                {
                    // Create the Patterns table and index its PatternID field

                    AddMessage("Creating the Patterns table...", messages, trackcancel);

                    string listOfConstantPatterns = CreatePatternsTable(inputSPDFileValue.GetAsText(), outputFileGdbPath, fgdbVersion);

                    string patternsTablePath = outputFileGdbPath + "\\" + ProfilesTableName;

                    addIndexTool = new AddIndex();
                    addIndexTool.in_table = patternsTablePath;
                    addIndexTool.fields = "PatternID";
                    addIndexTool.index_name = "PatternID";
                    gp.Execute(addIndexTool, trackcancel);

                    string histTrafficJoinTablePath = outputFileGdbPath + "\\" + HistTrafficJoinTableName;

                    // Add fields for the average speeds to the Streets feature class

                    AddMessage("Creating fields for the average speeds and travel times...", messages, trackcancel);

                    addFieldTool = new AddField();
                    addFieldTool.in_table = streetsFeatureClassPath;

                    addFieldTool.field_type = "FLOAT";
                    addFieldTool.field_name = "FT_AverageSpeed";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "TF_AverageSpeed";
                    gp.Execute(addFieldTool, trackcancel);

                    if (usesNTPFullCoverage)
                    {
                        // Convert the Link Reference files to a FileGDB table

                        AddMessage("Converting the Link Reference files to a table...", messages, trackcancel);

                        ConvertLinkReferenceFilesToFGDBTable(inputLinkReferenceFileFC14Value.GetAsText(),
                                                             inputLinkReferenceFileFC5Value.GetAsText(),
                                                             outputFileGdbPath);

                        string referenceTablePath = outputFileGdbPath + "\\TempRefTable";

                        // Extract out the rows we want in our historical traffic table

                        AddMessage("Creating the historical traffic join table...", messages, trackcancel);

                        if (listOfConstantPatterns == "")
                        {
                            Rename renameTool = new Rename();
                            renameTool.in_data = referenceTablePath;
                            renameTool.out_data = histTrafficJoinTablePath;
                            gp.Execute(renameTool, trackcancel);
                        }
                        else
                        {
                            tableSelectTool = new TableSelect();
                            tableSelectTool.in_table = referenceTablePath;
                            tableSelectTool.out_table = histTrafficJoinTablePath;
                            tableSelectTool.where_clause = "NOT ( IS_FC5 = 'Y' AND U IN (" + listOfConstantPatterns +
                                                           ") AND U = M AND M = T AND T = W AND W = R AND R = F AND F = S )";
                            gp.Execute(tableSelectTool, trackcancel);

                            deleteTool = new Delete();
                            deleteTool.in_data = referenceTablePath;
                            gp.Execute(deleteTool, trackcancel);
                        }
                    }
                    else
                    {
                        // Convert the TMC Reference file to a FileGDB table and index its TMC field

                        AddMessage("Converting the TMC Reference file to a table...", messages, trackcancel);

                        ConvertTMCReferenceFileToFGDBTable(inputTMCReferenceFileValue.GetAsText(), outputFileGdbPath);

                        string referenceTablePath = outputFileGdbPath + "\\TempRefTable";

                        addIndexTool = new AddIndex();
                        addIndexTool.in_table = referenceTablePath;
                        addIndexTool.fields = "TMC";
                        addIndexTool.index_name = "TMC";
                        gp.Execute(addIndexTool, trackcancel);

                        // Copy over the Traffic table to the file geodatabase

                        AddMessage("Copying Traffic table to the file geodatabase...", messages, trackcancel);

                        importTableTool = new TableToTable();
                        importTableTool.in_rows = inputTrafficTableValue.GetAsText();
                        importTableTool.out_path = outputFileGdbPath;
                        importTableTool.out_name = "Street";
                        gp.Execute(importTableTool, trackcancel);

                        string trafficTablePath = outputFileGdbPath + "\\Street";

                        // Add the TMC field and calculate it

                        AddMessage("Calculating TMC values for historical traffic...", messages, trackcancel);

                        addFieldTool = new AddField();
                        addFieldTool.in_table = trafficTablePath;
                        addFieldTool.field_type = "TEXT";
                        addFieldTool.field_length = 9;
                        addFieldTool.field_name = "TMC";
                        gp.Execute(addFieldTool, trackcancel);

                        calcFieldTool = new CalculateField();
                        calcFieldTool.in_table = trafficTablePath;
                        calcFieldTool.field = "TMC";
                        calcFieldTool.expression = "Replace(Replace(Right([TRAFFIC_CD], 9), \"+\", \"P\"), \"-\", \"N\")";
                        calcFieldTool.expression_type = "VB";
                        gp.Execute(calcFieldTool, trackcancel);

                        AddMessage("Creating the historical traffic join table...", messages, trackcancel);

                        // Join the Traffic table to the Reference table...

                        makeTableViewTool = new MakeTableView();
                        makeTableViewTool.in_table = trafficTablePath;
                        makeTableViewTool.out_view = "Traffic_View";
                        gp.Execute(makeTableViewTool, trackcancel);

                        addJoinTool = new AddJoin();
                        addJoinTool.in_layer_or_view = "Traffic_View";
                        addJoinTool.in_field = "TMC";
                        addJoinTool.join_table = referenceTablePath;
                        addJoinTool.join_field = "TMC";
                        addJoinTool.join_type = "KEEP_COMMON";
                        gp.Execute(addJoinTool, trackcancel);

                        // ...then create the Streets_Patterns table by copying out the joined rows

                        importTableTool = new TableToTable();
                        importTableTool.in_rows = "Traffic_View";
                        importTableTool.out_path = outputFileGdbPath;
                        importTableTool.out_name = HistTrafficJoinTableName;
                        importTableTool.field_mapping = "LINK_ID \"LINK_ID\" true true false 4 Long 0 0 ,First,#," + trafficTablePath + ",Street.LINK_ID,-1,-1;" +
                                                        "TRAFFIC_CD \"TRAFFIC_CD\" true true false 10 Text 0 0 ,First,#," + trafficTablePath + ",Street.TRAFFIC_CD,-1,-1;" +
                                                        "TMC \"TMC\" true true false 9 Text 0 0 ,First,#," + trafficTablePath + ",Street.TMC,-1,-1;" +
                                                        "U \"U\" true true false 2 Short 0 0 ,First,#," + trafficTablePath + ",TempRefTable.U,-1,-1;" +
                                                        "M \"M\" true true false 2 Short 0 0 ,First,#," + trafficTablePath + ",TempRefTable.M,-1,-1;" +
                                                        "T \"T\" true true false 2 Short 0 0 ,First,#," + trafficTablePath + ",TempRefTable.T,-1,-1;" +
                                                        "W \"W\" true true false 2 Short 0 0 ,First,#," + trafficTablePath + ",TempRefTable.W,-1,-1;" +
                                                        "R \"R\" true true false 2 Short 0 0 ,First,#," + trafficTablePath + ",TempRefTable.R,-1,-1;" +
                                                        "F \"F\" true true false 2 Short 0 0 ,First,#," + trafficTablePath + ",TempRefTable.F,-1,-1;" +
                                                        "S \"S\" true true false 2 Short 0 0 ,First,#," + trafficTablePath + ",TempRefTable.S,-1,-1";
                        gp.Execute(importTableTool, trackcancel);

                        // Delete the join, view, and temporary tables

                        removeJoinTool = new RemoveJoin();
                        removeJoinTool.in_layer_or_view = "Traffic_View";
                        removeJoinTool.join_name = "TempRefTable";
                        gp.Execute(removeJoinTool, trackcancel);

                        deleteTool = new Delete();
                        deleteTool.in_data = "Traffic_View";
                        gp.Execute(deleteTool, trackcancel);

                        deleteTool = new Delete();
                        deleteTool.in_data = referenceTablePath;
                        gp.Execute(deleteTool, trackcancel);

                        deleteTool = new Delete();
                        deleteTool.in_data = trafficTablePath;
                        gp.Execute(deleteTool, trackcancel);
                    }

                    AddMessage("Creating fields on the historical traffic join table...", messages, trackcancel);

                    addFieldTool = new AddField();
                    addFieldTool.in_table = histTrafficJoinTablePath;

                    // Add FCID, FID, position, AverageSpeed[_X], and BaseSpeed[_X] fields to the Streets_Patterns table

                    addFieldTool.field_type = "LONG";
                    addFieldTool.field_name = "EdgeFCID";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "EdgeFID";
                    gp.Execute(addFieldTool, trackcancel);

                    addFieldTool.field_type = "DOUBLE";
                    addFieldTool.field_name = "EdgeFrmPos";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "EdgeToPos";
                    gp.Execute(addFieldTool, trackcancel);

                    addFieldTool.field_type = "FLOAT";
                    addFieldTool.field_name = "AverageSpeed";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "AverageSpeed_U";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "AverageSpeed_M";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "AverageSpeed_T";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "AverageSpeed_W";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "AverageSpeed_R";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "AverageSpeed_F";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "AverageSpeed_S";
                    gp.Execute(addFieldTool, trackcancel);

                    addFieldTool.field_type = "FLOAT";
                    addFieldTool.field_name = "BaseSpeed";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "BaseSpeed_U";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "BaseSpeed_M";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "BaseSpeed_T";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "BaseSpeed_W";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "BaseSpeed_R";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "BaseSpeed_F";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "BaseSpeed_S";
                    gp.Execute(addFieldTool, trackcancel);

                    // If we're creating 10.0, then we also need to create the BaseMinutes field

                    if (fgdbVersion == 10.0)
                    {
                        addFieldTool.field_type = "DOUBLE";
                        addFieldTool.field_name = "BaseMinutes";
                        gp.Execute(addFieldTool, trackcancel);
                    }

                    // Populate the AverageSpeed_X and BaseSpeed_X fields

                    makeTableViewTool = new MakeTableView();
                    makeTableViewTool.in_table = histTrafficJoinTablePath;
                    makeTableViewTool.out_view = "Streets_Patterns_View";
                    gp.Execute(makeTableViewTool, trackcancel);

                    PopulateAverageSpeedAndBaseSpeedFields(patternsTablePath, "U", gp, messages, trackcancel);
                    PopulateAverageSpeedAndBaseSpeedFields(patternsTablePath, "M", gp, messages, trackcancel);
                    PopulateAverageSpeedAndBaseSpeedFields(patternsTablePath, "T", gp, messages, trackcancel);
                    PopulateAverageSpeedAndBaseSpeedFields(patternsTablePath, "W", gp, messages, trackcancel);
                    PopulateAverageSpeedAndBaseSpeedFields(patternsTablePath, "R", gp, messages, trackcancel);
                    PopulateAverageSpeedAndBaseSpeedFields(patternsTablePath, "F", gp, messages, trackcancel);
                    PopulateAverageSpeedAndBaseSpeedFields(patternsTablePath, "S", gp, messages, trackcancel);

                    deleteTool = new Delete();
                    deleteTool.in_data = "Streets_Patterns_View";
                    gp.Execute(deleteTool, trackcancel);

                    // Calculate the AverageSpeed and BaseSpeed fields

                    AddMessage("Calculating the AverageSpeed field...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = histTrafficJoinTablePath;
                    calcFieldTool.field = "AverageSpeed";
                    calcFieldTool.expression = "( (1/[AverageSpeed_U]) + (1/[AverageSpeed_M]) + (1/[AverageSpeed_T]) + (1/[AverageSpeed_W]) + (1/[AverageSpeed_R]) + (1/[AverageSpeed_F]) + (1/[AverageSpeed_S]) ) / " +
                                               "( (1/[AverageSpeed_U]/[AverageSpeed_U]) + (1/[AverageSpeed_M]/[AverageSpeed_M]) + (1/[AverageSpeed_T]/[AverageSpeed_T]) + (1/[AverageSpeed_W]/[AverageSpeed_W]) + (1/[AverageSpeed_R]/[AverageSpeed_R]) + (1/[AverageSpeed_F]/[AverageSpeed_F]) + (1/[AverageSpeed_S]/[AverageSpeed_S]) )";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    AddMessage("Calculating the BaseSpeed field...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = histTrafficJoinTablePath;
                    calcFieldTool.field = "BaseSpeed";
                    calcFieldTool.expression = "( (1/[BaseSpeed_U]) + (1/[BaseSpeed_M]) + (1/[BaseSpeed_T]) + (1/[BaseSpeed_W]) + (1/[BaseSpeed_R]) + (1/[BaseSpeed_F]) + (1/[BaseSpeed_S]) ) / " +
                                               "( (1/[BaseSpeed_U]/[BaseSpeed_U]) + (1/[BaseSpeed_M]/[BaseSpeed_M]) + (1/[BaseSpeed_T]/[BaseSpeed_T]) + (1/[BaseSpeed_W]/[BaseSpeed_W]) + (1/[BaseSpeed_R]/[BaseSpeed_R]) + (1/[BaseSpeed_F]/[BaseSpeed_F]) + (1/[BaseSpeed_S]/[BaseSpeed_S]) )";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    DeleteField deleteFieldTool = new DeleteField();
                    deleteFieldTool.in_table = histTrafficJoinTablePath;
                    deleteFieldTool.drop_field = "AverageSpeed_U;AverageSpeed_M;AverageSpeed_T;AverageSpeed_W;AverageSpeed_R;AverageSpeed_F;AverageSpeed_S;BaseSpeed_U;BaseSpeed_M;BaseSpeed_T;BaseSpeed_W;BaseSpeed_R;BaseSpeed_F;BaseSpeed_S";
                    gp.Execute(deleteFieldTool, trackcancel);

                    makeTableViewTool = new MakeTableView();
                    makeTableViewTool.in_table = histTrafficJoinTablePath;
                    makeTableViewTool.out_view = "Streets_Patterns_View";
                    gp.Execute(makeTableViewTool, trackcancel);

                    addJoinTool = new AddJoin();
                    addJoinTool.in_layer_or_view = "Streets_Patterns_View";
                    addJoinTool.in_field = (usesNTPFullCoverage ? "LINK_PVID" : "LINK_ID");
                    addJoinTool.join_table = streetsFeatureClassPath;
                    addJoinTool.join_field = "LINK_ID";
                    gp.Execute(addJoinTool, trackcancel);

                    // Calculate the BaseMinutes field (if 10.0)

                    if (fgdbVersion == 10.0)
                    {
                        AddMessage("Calculating the BaseMinutes field...", messages, trackcancel);

                        calcFieldTool = new CalculateField();
                        calcFieldTool.in_table = "Streets_Patterns_View";
                        calcFieldTool.field = HistTrafficJoinTableName + ".BaseMinutes";
                        calcFieldTool.expression = "[" + StreetsFCName + ".Meters] * 0.06 / [" + HistTrafficJoinTableName + ".BaseSpeed]";
                        calcFieldTool.expression_type = "VB";
                        gp.Execute(calcFieldTool, trackcancel);
                    }

                    // Calculate the FCID, FID, and position fields

                    AddMessage("Calculating the EdgeFID field for historical traffic...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "Streets_Patterns_View";
                    calcFieldTool.field = HistTrafficJoinTableName + ".EdgeFID";
                    calcFieldTool.expression = "[" + StreetsFCName + ".OBJECTID]";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    removeJoinTool = new RemoveJoin();
                    removeJoinTool.in_layer_or_view = "Streets_Patterns_View";
                    removeJoinTool.join_name = StreetsFCName;
                    gp.Execute(removeJoinTool, trackcancel);

                    deleteTool = new Delete();
                    deleteTool.in_data = "Streets_Patterns_View";
                    gp.Execute(deleteTool, trackcancel);

                    AddMessage("Calculating the EdgeFCID field for historical traffic...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = histTrafficJoinTablePath;
                    calcFieldTool.field = "EdgeFCID";
                    calcFieldTool.expression = "1";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    AddMessage("Calculating the EdgeFrmPos field for historical traffic...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = histTrafficJoinTablePath;

                    calcFieldTool.field = "EdgeFrmPos";
                    calcFieldTool.expression = "x";
                    calcFieldTool.code_block = (usesNTPFullCoverage ? "Select Case [TRAVEL_DIRECTION]\n  Case \"F\": x = 0\n  Case \"T\": x = 1\nEnd Select" :
                                                                      "Select Case Left([TRAFFIC_CD], 1)\n  Case \"+\": x = 0\n  Case \"-\": x = 1\nEnd Select");
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    AddMessage("Calculating the EdgeToPos field for historical traffic...", messages, trackcancel);

                    calcFieldTool.field = "EdgeToPos";
                    calcFieldTool.expression = "x";
                    calcFieldTool.code_block = (usesNTPFullCoverage ? "Select Case [TRAVEL_DIRECTION]\n  Case \"T\": x = 0\n  Case \"F\": x = 1\nEnd Select" :
                                                                      "Select Case Left([TRAFFIC_CD], 1)\n  Case \"-\": x = 0\n  Case \"+\": x = 1\nEnd Select");
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    // Write the average speeds to the streets feature class

                    WriteAverageSpeedsToStreets(outputFileGdbPath, streetsFeatureClassPath, usesNTPFullCoverage, gp, messages, trackcancel);

                    // Add fields for the average travel times to the Streets feature class

                    AddMessage("Creating fields for the average travel times...", messages, trackcancel);

                    addFieldTool = new AddField();
                    addFieldTool.in_table = streetsFeatureClassPath;

                    addFieldTool.field_type = "FLOAT";
                    addFieldTool.field_name = "FT_Minutes";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "TF_Minutes";
                    gp.Execute(addFieldTool, trackcancel);

                    // Calculate the average travel time fields

                    AddMessage("Calculating the FT travel times...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = streetsFeatureClassPath;

                    calcFieldTool.field = "FT_Minutes";
                    calcFieldTool.expression = "[Meters] * 0.06 / s";
                    calcFieldTool.code_block = "s = [FT_AverageSpeed]\nIf IsNull(s) Then s = [KPH]";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    AddMessage("Calculating the TF travel times...", messages, trackcancel);

                    calcFieldTool.field = "TF_Minutes";
                    calcFieldTool.expression = "[Meters] * 0.06 / s";
                    calcFieldTool.code_block = "s = [TF_AverageSpeed]\nIf IsNull(s) Then s = [KPH]";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    // Offset the daily pattern fields (U,M,T,W,R,F,S) on the historical traffic join table

                    OffsetDailyPatternFields(histTrafficJoinTablePath, patternsTablePath);

                    // Add an index to the Streets feature class's FUNC_CLASS field

                    AddMessage("Indexing the FUNC_CLASS field...", messages, trackcancel);

                    addIndexTool = new AddIndex();
                    addIndexTool.in_table = streetsFeatureClassPath;
                    addIndexTool.fields = "FUNC_CLASS";
                    addIndexTool.index_name = "FUNC_CLASS";
                    gp.Execute(addIndexTool, trackcancel);
                }
                else
                {
                    // Create and calculate the generic Minutes field from speed categories

                    addFieldTool = new AddField();
                    addFieldTool.in_table = streetsFeatureClassPath;
                    addFieldTool.field_type = "FLOAT";
                    addFieldTool.field_name = "Minutes";
                    gp.Execute(addFieldTool, trackcancel);

                    AddMessage("Calculating the Minutes field...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = streetsFeatureClassPath;
                    calcFieldTool.field = "Minutes";
                    calcFieldTool.expression = "[Meters] * 0.06 / [KPH]";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);
                }
                #endregion

                #region Process Live Traffic Table

                // Create the live traffic table (for 10.1 or later)

                if (fgdbVersion >= 10.1 && !inputTrafficTableValue.IsEmpty())
                {
                    // Copy over the Traffic table to the file geodatabase

                    AddMessage("Copying Traffic table to the file geodatabase...", messages, trackcancel);

                    importTableTool = new TableToTable();
                    importTableTool.in_rows = inputTrafficTableValue.GetAsText();
                    importTableTool.out_path = outputFileGdbPath;
                    importTableTool.out_name = TMCJoinTableName;
                    gp.Execute(importTableTool, trackcancel);

                    string TMCJoinTablePath = outputFileGdbPath + "\\" + TMCJoinTableName;

                    // Add the TMC field and calculate it

                    AddMessage("Calculating TMC values for live traffic...", messages, trackcancel);

                    addFieldTool = new AddField();
                    addFieldTool.in_table = TMCJoinTablePath;
                    addFieldTool.field_type = "TEXT";
                    addFieldTool.field_length = 9;
                    addFieldTool.field_name = "TMC";
                    gp.Execute(addFieldTool, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = TMCJoinTablePath;
                    calcFieldTool.field = "TMC";
                    calcFieldTool.expression = "Right([TRAFFIC_CD], 9)";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    AddMessage("Creating the live traffic join table...", messages, trackcancel);

                    // Add FCID, FID, and position fields to the Streets_TMC table

                    AddMessage("Creating fields on the live traffic join table...", messages, trackcancel);

                    addFieldTool = new AddField();
                    addFieldTool.in_table = TMCJoinTablePath;

                    addFieldTool.field_type = "LONG";
                    addFieldTool.field_name = "EdgeFCID";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "EdgeFID";
                    gp.Execute(addFieldTool, trackcancel);

                    addFieldTool.field_type = "DOUBLE";
                    addFieldTool.field_name = "EdgeFrmPos";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "EdgeToPos";
                    gp.Execute(addFieldTool, trackcancel);

                    // Calculate the fields

                    AddMessage("Calculating the EdgeFrmPos field for live traffic...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = TMCJoinTablePath;

                    calcFieldTool.field = "EdgeFrmPos";
                    calcFieldTool.expression = "x";
                    calcFieldTool.code_block = "Select Case Left([TRAFFIC_CD], 1)\n  Case \"+\": x = 0\n  Case \"-\": x = 1\nEnd Select";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    AddMessage("Calculating the EdgeToPos field for live traffic...", messages, trackcancel);

                    calcFieldTool.field = "EdgeToPos";
                    calcFieldTool.expression = "x";
                    calcFieldTool.code_block = "Select Case Left([TRAFFIC_CD], 1)\n  Case \"-\": x = 0\n  Case \"+\": x = 1\nEnd Select";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    AddMessage("Calculating the EdgeFCID field for live traffic...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = TMCJoinTablePath;
                    calcFieldTool.field = "EdgeFCID";
                    calcFieldTool.expression = "1";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    AddMessage("Calculating the EdgeFID field for live traffic...", messages, trackcancel);

                    makeTableViewTool = new MakeTableView();
                    makeTableViewTool.in_table = TMCJoinTablePath;
                    makeTableViewTool.out_view = "Streets_TMC_View";
                    gp.Execute(makeTableViewTool, trackcancel);

                    addJoinTool = new AddJoin();
                    addJoinTool.in_layer_or_view = "Streets_TMC_View";
                    addJoinTool.in_field = "LINK_ID";
                    addJoinTool.join_table = streetsFeatureClassPath;
                    addJoinTool.join_field = "LINK_ID";
                    gp.Execute(addJoinTool, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "Streets_TMC_View";
                    calcFieldTool.field = TMCJoinTableName + ".EdgeFID";
                    calcFieldTool.expression = "[" + StreetsFCName + ".OBJECTID]";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    removeJoinTool = new RemoveJoin();
                    removeJoinTool.in_layer_or_view = "Streets_TMC_View";
                    removeJoinTool.join_name = StreetsFCName;
                    gp.Execute(removeJoinTool, trackcancel);

                    deleteTool = new Delete();
                    deleteTool.in_data = "Streets_TMC_View";
                    gp.Execute(deleteTool, trackcancel);

                    // If Historical Traffic is not being used, then we need to create placeholder historical traffic tables

                    if (!usesHistoricalTraffic)
                    {
                        // Create the Streets_Patterns table by starting with a copy of the Streets_TMC table

                        AddMessage("Creating the historical traffic join table...", messages, trackcancel);

                        importTableTool = new TableToTable();
                        importTableTool.in_rows = TMCJoinTablePath;
                        importTableTool.out_path = outputFileGdbPath;
                        importTableTool.out_name = HistTrafficJoinTableName;
                        gp.Execute(importTableTool, trackcancel);

                        string histTrafficJoinTablePath = outputFileGdbPath + "\\" + HistTrafficJoinTableName;

                        AddMessage("Creating and calculating the KPH field on the historical traffic join table...", messages, trackcancel);

                        addFieldTool = new AddField();
                        addFieldTool.in_table = histTrafficJoinTablePath;
                        addFieldTool.field_type = "FLOAT";
                        addFieldTool.field_name = "KPH";
                        gp.Execute(addFieldTool, trackcancel);

                        makeTableViewTool = new MakeTableView();
                        makeTableViewTool.in_table = histTrafficJoinTablePath;
                        makeTableViewTool.out_view = "Streets_Patterns_View";
                        gp.Execute(makeTableViewTool, trackcancel);

                        addJoinTool = new AddJoin();
                        addJoinTool.in_layer_or_view = "Streets_Patterns_View";
                        addJoinTool.in_field = "EdgeFID";
                        addJoinTool.join_table = streetsFeatureClassPath;
                        addJoinTool.join_field = "OBJECTID";
                        gp.Execute(addJoinTool, trackcancel);

                        calcFieldTool = new CalculateField();
                        calcFieldTool.in_table = "Streets_Patterns_View";
                        calcFieldTool.field = HistTrafficJoinTableName + ".KPH";
                        calcFieldTool.expression = "[" + StreetsFCName + ".KPH]";
                        calcFieldTool.expression_type = "VB";
                        gp.Execute(calcFieldTool, trackcancel);

                        removeJoinTool = new RemoveJoin();
                        removeJoinTool.in_layer_or_view = "Streets_Patterns_View";
                        removeJoinTool.join_name = StreetsFCName;
                        gp.Execute(removeJoinTool, trackcancel);

                        deleteTool = new Delete();
                        deleteTool.in_data = "Streets_Patterns_View";
                        gp.Execute(deleteTool, trackcancel);

                        AddMessage("Creating and calculating the daily patterns fields on the historical traffic join table...", messages, trackcancel);

                        string[] fieldNames = new string[] { "S", "M", "T", "W", "R", "F", "S" };
                        foreach (string f in fieldNames)
                        {
                            addFieldTool = new AddField();
                            addFieldTool.in_table = histTrafficJoinTablePath;
                            addFieldTool.field_type = "SHORT";
                            addFieldTool.field_name = f;
                            gp.Execute(addFieldTool, trackcancel);

                            calcFieldTool = new CalculateField();
                            calcFieldTool.in_table = histTrafficJoinTablePath;
                            calcFieldTool.field = f;
                            calcFieldTool.expression = "1";
                            calcFieldTool.expression_type = "VB";
                            gp.Execute(calcFieldTool, trackcancel);
                        }

                        // Create the Patterns table

                        CreateNonHistoricalPatternsTable(outputFileGdbPath);
                    }
                }
                #endregion

                // Copy the Cdms table to the file geodatabase

                AddMessage("Copying the Condition/Driving Manoeuvres (CDMS) table and indexing...", messages, trackcancel);

                importTableTool = new TableToTable();
                importTableTool.in_rows = inputCdmsTableValue.GetAsText();
                importTableTool.out_path = outputFileGdbPath;
                importTableTool.out_name = "Cdms";
                gp.Execute(importTableTool, trackcancel);

                string cdmsTablePath = outputFileGdbPath + "\\Cdms";

                addIndexTool = new AddIndex();
                addIndexTool.in_table = cdmsTablePath;
                addIndexTool.fields = "COND_ID";
                addIndexTool.index_name = "COND_ID";
                gp.Execute(addIndexTool, trackcancel);

                // Copy the Rdms table to the file geodatabase

                AddMessage("Copying the Restricted Driving Manoeuvres (RDMS) table...", messages, trackcancel);

                importTableTool = new TableToTable();
                importTableTool.in_rows = inputRdmsTableValue.GetAsText();
                importTableTool.out_path = outputFileGdbPath;
                importTableTool.out_name = "Rdms";
                gp.Execute(importTableTool, trackcancel);

                string rdmsTablePath = outputFileGdbPath + "\\Rdms";

                // Add and calculate the end of link and condition type fields to the Rdms table

                AddMessage("Creating and calculating fields for the manoeuvre types and ends of link...", messages, trackcancel);

                addFieldTool = new AddField();
                addFieldTool.in_table = rdmsTablePath;
                addFieldTool.field_name = "COND_TYPE";
                addFieldTool.field_type = "LONG";
                gp.Execute(addFieldTool, trackcancel);

                addFieldTool.field_name = "END_OF_LK";
                addFieldTool.field_type = "TEXT";
                addFieldTool.field_length = 1;
                gp.Execute(addFieldTool, trackcancel);

                makeTableViewTool = new MakeTableView();
                makeTableViewTool.in_table = rdmsTablePath;
                makeTableViewTool.out_view = "Rdms_View";
                gp.Execute(makeTableViewTool, trackcancel);

                addJoinTool = new AddJoin();
                addJoinTool.in_layer_or_view = "Rdms_View";
                addJoinTool.in_field = "COND_ID";
                addJoinTool.join_table = cdmsTablePath;
                addJoinTool.join_field = "COND_ID";
                gp.Execute(addJoinTool, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = "Rdms_View";
                calcFieldTool.field = "Rdms.COND_TYPE";
                calcFieldTool.expression = "[Cdms.COND_TYPE]";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                calcFieldTool.field = "Rdms.END_OF_LK";
                calcFieldTool.expression = "[Cdms.END_OF_LK]";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                removeJoinTool = new RemoveJoin();
                removeJoinTool.in_layer_or_view = "Rdms_View";
                removeJoinTool.join_name = "Cdms";
                gp.Execute(removeJoinTool, trackcancel);

                deleteTool = new Delete();
                deleteTool.in_data = "Rdms_View";
                gp.Execute(deleteTool, trackcancel);

                // Extract only the gates (condition type 4) and prohibitied manoeuvres (condition type 7)
                // If using Transport, also extract the Transport manoeuvres (condition type 26)

                AddMessage("Extracting restricted driving manoeuvres...", messages, trackcancel);

                string prohibRdmsWEndOfLkTablePath = outputFileGdbPath + "\\ProhibRdmsWEndOfLk";

                tableSelectTool = new TableSelect();
                tableSelectTool.in_table = rdmsTablePath;
                tableSelectTool.out_table = prohibRdmsWEndOfLkTablePath;
                if (usesTransport)
                    tableSelectTool.where_clause = "COND_TYPE IN (4, 7, 26)";
                else
                    tableSelectTool.where_clause = "COND_TYPE IN (4, 7)";
                gp.Execute(tableSelectTool, trackcancel);

                AddMessage("Creating turn feature class...", messages, trackcancel);

                // Create the turn feature class

                string tempStatsTablePath = outputFileGdbPath + "\\tempStatsTable";

                Statistics statsTool = new Statistics();
                statsTool.in_table = prohibRdmsWEndOfLkTablePath;
                statsTool.out_table = tempStatsTablePath;
                statsTool.statistics_fields = "SEQ_NUMBER MAX";
                gp.Execute(statsTool, null);

                CreateAndPopulateTurnFeatureClass(outputFileGdbPath, fdsName, "ProhibRdmsWEndOfLk", "tempStatsTable",
                                                  messages, trackcancel);

                deleteTool = new Delete();
                deleteTool.in_data = tempStatsTablePath;
                gp.Execute(deleteTool, trackcancel);

                string pathToTurnFC = pathToFds + "\\" + TurnFCName;

                // Create and calculate condition type and access restriction fields on the turn feature class

                addFieldTool = new AddField();
                addFieldTool.in_table = pathToTurnFC;
                addFieldTool.field_name = "COND_TYPE";
                addFieldTool.field_type = "LONG";
                gp.Execute(addFieldTool, trackcancel);

                AddMessage("Creating access restriction fields on the turn feature class...", messages, trackcancel);

                foreach (string arFieldSuffix in arFieldSuffixes)
                {
                    addFieldTool = new AddField();
                    addFieldTool.in_table = pathToTurnFC;
                    addFieldTool.field_name = "AR_" + arFieldSuffix;
                    addFieldTool.field_type = "TEXT";
                    addFieldTool.field_length = 1;
                    gp.Execute(addFieldTool, trackcancel);
                }

                makeFeatureLayerTool = new MakeFeatureLayer();
                makeFeatureLayerTool.in_features = pathToTurnFC;
                makeFeatureLayerTool.out_layer = "Turn_Layer";
                gp.Execute(makeFeatureLayerTool, trackcancel);

                addJoinTool = new AddJoin();
                addJoinTool.in_layer_or_view = "Turn_Layer";
                addJoinTool.in_field = "COND_ID";
                addJoinTool.join_table = cdmsTablePath;
                addJoinTool.join_field = "COND_ID";
                gp.Execute(addJoinTool, trackcancel);

                AddMessage("Calculating the COND_TYPE field on the turn feature class...", messages, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = "Turn_Layer";
                calcFieldTool.field = TurnFCName + ".COND_TYPE";
                calcFieldTool.expression = "[Cdms.COND_TYPE]";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                foreach (string arFieldSuffix in arFieldSuffixes)
                {
                    AddMessage("Calculating the AR_" + arFieldSuffix + " field on the turn feature class...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "Turn_Layer";
                    calcFieldTool.field = TurnFCName + ".AR_" + arFieldSuffix;
                    calcFieldTool.expression = "[Cdms.AR_" + arFieldSuffix + "]";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);
                }

                removeJoinTool = new RemoveJoin();
                removeJoinTool.in_layer_or_view = "Turn_Layer";
                removeJoinTool.join_name = "Cdms";
                gp.Execute(removeJoinTool, trackcancel);

                deleteTool = new Delete();
                deleteTool.in_data = "Turn_Layer";
                gp.Execute(deleteTool, trackcancel);

                deleteTool.in_data = cdmsTablePath;
                gp.Execute(deleteTool, trackcancel);

                deleteTool.in_data = prohibRdmsWEndOfLkTablePath;
                gp.Execute(deleteTool, trackcancel);

                GC.Collect();

                #region Process Transport Tables

                if (usesTransport)
                {
                    string nonDimensionalCndModTablePath = outputFileGdbPath + "\\nonDimensionalCndMod";
                    string dimensionalCndModTablePath = outputFileGdbPath + "\\dimensionalCndMod";

                    if (!(inputUSCndModTableValue.IsEmpty()))
                    {
                        // Extract the Transport information for the US

                        AddMessage("Extracting the US non-dimensional conditions...", messages, trackcancel);

                        tableSelectTool = new TableSelect();
                        tableSelectTool.in_table = inputUSCndModTableValue.GetAsText();
                        tableSelectTool.out_table = nonDimensionalCndModTablePath;
                        tableSelectTool.where_clause = "MOD_TYPE IN (38, 39, 46, 49, 60, 75)";
                        gp.Execute(tableSelectTool, trackcancel);

                        AddMessage("Extracting the US dimensional conditions...", messages, trackcancel);

                        tableSelectTool.out_table = dimensionalCndModTablePath;
                        tableSelectTool.where_clause = "MOD_TYPE IN (41, 42, 43, 44, 45, 48, 81)";
                        gp.Execute(tableSelectTool, trackcancel);

                        // Create a new field to hold the dimension in a common unit (m or kg or KPH)

                        addFieldTool = new AddField();
                        addFieldTool.in_table = dimensionalCndModTablePath;
                        addFieldTool.field_name = "MetersOrKilogramsOrKPH";
                        addFieldTool.field_type = "DOUBLE";
                        gp.Execute(addFieldTool, trackcancel);

                        AddMessage("Calculating common units of measure...", messages, trackcancel);

                        calcFieldTool = new CalculateField();
                        calcFieldTool.in_table = dimensionalCndModTablePath;
                        calcFieldTool.field = "MetersOrKilogramsOrKPH";
                        calcFieldTool.code_block = "x = CLng([MOD_VAL])\nSelect Case [MOD_TYPE]\n" +
                                                   "  Case 41, 44, 45, 81: x = x * 0.0254\n" +
                                                   "  Case 42, 43: x = x * 0.45359237\n" +
                                                   "  Case 48: x = x * 1.609344\nEnd Select";
                        calcFieldTool.expression = "x";
                        calcFieldTool.expression_type = "VB";
                        gp.Execute(calcFieldTool, trackcancel);

                        if (!(inputNonUSCndModTableValue.IsEmpty()))
                        {
                            string tempNonDimensionalCndModTablePath = outputFileGdbPath + "\\tempNonDimensionalCndMod";
                            string tempDimensionalCndModTablePath = outputFileGdbPath + "\\tempDimensionalCndMod";

                            // Extract the Transport information for outside the US to temporary tables

                            AddMessage("Extracting the non-US non-dimensional conditions...", messages, trackcancel);

                            tableSelectTool = new TableSelect();
                            tableSelectTool.in_table = inputNonUSCndModTableValue.GetAsText();
                            tableSelectTool.out_table = tempNonDimensionalCndModTablePath;
                            tableSelectTool.where_clause = "MOD_TYPE IN (38, 39, 46, 49, 60, 75)";
                            gp.Execute(tableSelectTool, trackcancel);

                            AddMessage("Extracting the non-US dimensional conditions...", messages, trackcancel);

                            tableSelectTool.out_table = tempDimensionalCndModTablePath;
                            tableSelectTool.where_clause = "MOD_TYPE IN (41, 42, 43, 44, 45, 48, 81)";
                            gp.Execute(tableSelectTool, trackcancel);

                            // Create a new field to hold the dimension in a common unit (m or kg)

                            addFieldTool = new AddField();
                            addFieldTool.in_table = tempDimensionalCndModTablePath;
                            addFieldTool.field_name = "MetersOrKilogramsOrKPH";
                            addFieldTool.field_type = "DOUBLE";
                            gp.Execute(addFieldTool, trackcancel);

                            AddMessage("Calculating common units of measure...", messages, trackcancel);

                            calcFieldTool = new CalculateField();
                            calcFieldTool.in_table = dimensionalCndModTablePath;
                            calcFieldTool.field = "MetersOrKilogramsOrKPH";
                            calcFieldTool.code_block = "x = CLng([MOD_VAL])\nSelect Case [MOD_TYPE]\n" +
                                                       "  Case 41, 44, 45, 81: x = x * 0.01\nEnd Select";
                            calcFieldTool.expression = "x";
                            calcFieldTool.expression_type = "VB";
                            gp.Execute(calcFieldTool, trackcancel);

                            // Append the temporary tables to the main table containing US attributes

                            Append appendTool = new Append();
                            appendTool.inputs = tempNonDimensionalCndModTablePath;
                            appendTool.target = nonDimensionalCndModTablePath;
                            gp.Execute(appendTool, trackcancel);

                            appendTool.inputs = tempDimensionalCndModTablePath;
                            appendTool.target = dimensionalCndModTablePath;
                            gp.Execute(appendTool, trackcancel);

                            deleteTool = new Delete();
                            deleteTool.in_data = tempNonDimensionalCndModTablePath;
                            gp.Execute(deleteTool, trackcancel);
                            deleteTool.in_data = tempDimensionalCndModTablePath;
                            gp.Execute(deleteTool, trackcancel);
                        }
                    }
                    else
                    {
                        // Extract the Transport information for outside the US

                        AddMessage("Extracting the non-US non-dimensional conditions...", messages, trackcancel);

                        tableSelectTool = new TableSelect();
                        tableSelectTool.in_table = inputNonUSCndModTableValue.GetAsText();
                        tableSelectTool.out_table = nonDimensionalCndModTablePath;
                        tableSelectTool.where_clause = "MOD_TYPE IN (38, 39, 46, 49, 60, 75)";
                        gp.Execute(tableSelectTool, trackcancel);

                        AddMessage("Extracting the non-US dimensional conditions...", messages, trackcancel);

                        tableSelectTool.out_table = dimensionalCndModTablePath;
                        tableSelectTool.where_clause = "MOD_TYPE IN (41, 42, 43, 44, 45, 48, 81)";
                        gp.Execute(tableSelectTool, trackcancel);

                        // Create a new field to hold the dimension in a common unit (m or kg)

                        addFieldTool = new AddField();
                        addFieldTool.in_table = dimensionalCndModTablePath;
                        addFieldTool.field_name = "MetersOrKilogramsOrKPH";
                        addFieldTool.field_type = "DOUBLE";
                        gp.Execute(addFieldTool, trackcancel);

                        AddMessage("Calculating common units of measure...", messages, trackcancel);

                        calcFieldTool = new CalculateField();
                        calcFieldTool.in_table = dimensionalCndModTablePath;
                        calcFieldTool.field = "MetersOrKilogramsOrKPH";
                        calcFieldTool.code_block = "x = CLng([MOD_VAL])\nSelect Case [MOD_TYPE]\n" +
                                                   "  Case 41, 44, 45, 81: x = x * 0.01\nEnd Select";
                        calcFieldTool.expression = "x";
                        calcFieldTool.expression_type = "VB";
                        gp.Execute(calcFieldTool, trackcancel);
                    }

                    // Create a table for looking up LINK_IDs from COND_IDs

                    AddMessage("Creating and indexing LINK_ID/COND_ID look-up table for preferred roads...", messages, trackcancel);

                    string preferredLinkIDLookupTablePath = outputFileGdbPath + "\\preferredLinkIDLookupTable";

                    tableSelectTool = new TableSelect();
                    tableSelectTool.in_table = inputCdmsTableValue.GetAsText();
                    tableSelectTool.out_table = preferredLinkIDLookupTablePath;
                    tableSelectTool.where_clause = "COND_TYPE = 27";
                    gp.Execute(tableSelectTool, trackcancel);

                    addIndexTool = new AddIndex();
                    addIndexTool.in_table = preferredLinkIDLookupTablePath;
                    addIndexTool.fields = "COND_ID";
                    addIndexTool.index_name = "COND_ID";
                    gp.Execute(addIndexTool, trackcancel);

                    // Create a table for looking up the condition's direction

                    AddMessage("Creating and indexing direction look-up table for preferred roads...", messages, trackcancel);

                    string preferredDirectionLookupTablePath = outputFileGdbPath + "\\preferredDirectionLookupTable";

                    tableSelectTool = new TableSelect();
                    tableSelectTool.in_table = nonDimensionalCndModTablePath;
                    tableSelectTool.out_table = preferredDirectionLookupTablePath;
                    tableSelectTool.where_clause = "MOD_TYPE = 60";
                    gp.Execute(tableSelectTool, trackcancel);

                    addIndexTool = new AddIndex();
                    addIndexTool.in_table = preferredDirectionLookupTablePath;
                    addIndexTool.fields = "COND_ID";
                    addIndexTool.index_name = "COND_ID";
                    gp.Execute(addIndexTool, trackcancel);

                    // Create a table for looking up LINK_IDs from COND_IDs

                    AddMessage("Creating and indexing LINK_ID/COND_ID look-up table for restrictions...", messages, trackcancel);

                    string restrictionLinkIDLookupTablePath = outputFileGdbPath + "\\restrictionLinkIDLookupTable";

                    tableSelectTool = new TableSelect();
                    tableSelectTool.in_table = inputCdmsTableValue.GetAsText();
                    tableSelectTool.out_table = restrictionLinkIDLookupTablePath;
                    tableSelectTool.where_clause = "COND_TYPE = 23";
                    gp.Execute(tableSelectTool, trackcancel);

                    addIndexTool = new AddIndex();
                    addIndexTool.in_table = restrictionLinkIDLookupTablePath;
                    addIndexTool.fields = "COND_ID";
                    addIndexTool.index_name = "COND_ID";
                    gp.Execute(addIndexTool, trackcancel);

                    // Create a table for looking up the condition's direction

                    AddMessage("Creating and indexing direction look-up table for restrictions...", messages, trackcancel);

                    string restrictionDirectionLookupTablePath = outputFileGdbPath + "\\restrictionDirectionLookupTable";

                    tableSelectTool = new TableSelect();
                    tableSelectTool.in_table = nonDimensionalCndModTablePath;
                    tableSelectTool.out_table = restrictionDirectionLookupTablePath;
                    tableSelectTool.where_clause = "MOD_TYPE = 38";
                    gp.Execute(tableSelectTool, trackcancel);

                    addIndexTool = new AddIndex();
                    addIndexTool.in_table = restrictionDirectionLookupTablePath;
                    addIndexTool.fields = "COND_ID";
                    addIndexTool.index_name = "COND_ID";
                    gp.Execute(addIndexTool, trackcancel);

                    makeFeatureLayerTool = new MakeFeatureLayer();
                    makeFeatureLayerTool.in_features = streetsFeatureClassPath;
                    makeFeatureLayerTool.out_layer = "Streets_Layer";
                    gp.Execute(makeFeatureLayerTool, trackcancel);

                    CreateAndPopulateTruckFCOverrideField(outputFileGdbPath, gp, messages, trackcancel);

                    if (fgdbVersion >= 10.1)
                    {
                        // Create and calculate the preferred fields for Streets

                        CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, true, "STAAPreferred",
                                                                  "MOD_TYPE = 49 AND MOD_VAL = '1'", gp, messages, trackcancel);
                        CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, true, "TruckDesignatedPreferred",
                                                                  "MOD_TYPE = 49 AND MOD_VAL = '2'", gp, messages, trackcancel);
                        CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, true, "NRHMPreferred",
                                                                  "MOD_TYPE = 49 AND MOD_VAL = '3'", gp, messages, trackcancel);
                        CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, true, "ExplosivesPreferred",
                                                                  "MOD_TYPE = 49 AND MOD_VAL = '4'", gp, messages, trackcancel);
                        CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, true, "PIHPreferred",
                                                                  "MOD_TYPE = 49 AND MOD_VAL = '5'", gp, messages, trackcancel);
                        CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, true, "MedicalWastePreferred",
                                                                  "MOD_TYPE = 49 AND MOD_VAL = '6'", gp, messages, trackcancel);
                        CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, true, "RadioactivePreferred",
                                                                  "MOD_TYPE = 49 AND MOD_VAL = '7'", gp, messages, trackcancel);
                        CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, true, "HazmatPreferred",
                                                                  "MOD_TYPE = 49 AND MOD_VAL = '8'", gp, messages, trackcancel);
                        CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, true, "LocallyPreferred",
                                                                  "MOD_TYPE = 49 AND MOD_VAL = '9'", gp, messages, trackcancel);

                        if (createArcGISOnlineNetworkAttributes)
                        {
                            CreateAndPopulateAGOLTextTransportFieldsOnStreets(outputFileGdbPath, "PreferredTruckRoute",
                                                                              new string[] { "STAAPreferred", "TruckDesignatedPreferred", "LocallyPreferred" },
                                                                              gp, messages, trackcancel);
                            CreateAndPopulateAGOLTextTransportFieldsOnStreets(outputFileGdbPath, "PreferredHazmatRoute",
                                                                              new string[] { "NRHMPreferred", "ExplosivesPreferred", "PIHPreferred", "MedicalWastePreferred", "RadioactivePreferred", "HazmatPreferred" },
                                                                              gp, messages, trackcancel);
                        }
                    }

                    // Create and calculate the HazMat restriction fields for Streets

                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, false, "ExplosivesProhibited",
                                                              "MOD_TYPE = 39 AND MOD_VAL = '1'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, false, "GasProhibited",
                                                              "MOD_TYPE = 39 AND MOD_VAL = '2'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, false, "FlammableProhibited",
                                                              "MOD_TYPE = 39 AND MOD_VAL = '3'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, false, "CombustibleProhibited",
                                                              "MOD_TYPE = 39 AND MOD_VAL = '4'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, false, "OrganicProhibited",
                                                              "MOD_TYPE = 39 AND MOD_VAL = '5'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, false, "PoisonProhibited",
                                                              "MOD_TYPE = 39 AND MOD_VAL = '6'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, false, "RadioactiveProhibited",
                                                              "MOD_TYPE = 39 AND MOD_VAL = '7'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, false, "CorrosiveProhibited",
                                                              "MOD_TYPE = 39 AND MOD_VAL = '8'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, false, "OtherHazmatProhibited",
                                                              "MOD_TYPE = 39 AND MOD_VAL = '9'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, false, "AnyHazmatProhibited",
                                                              "MOD_TYPE = 39 AND MOD_VAL = '20'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, false, "PIHProhibited",
                                                              "MOD_TYPE = 39 AND MOD_VAL = '21'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, false, "HarmfulToWaterProhibited",
                                                              "MOD_TYPE = 39 AND MOD_VAL = '22'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, false, "ExplosiveAndFlammableProhibited",
                                                              "MOD_TYPE = 39 AND MOD_VAL = '23'", gp, messages, trackcancel);

                    if (createArcGISOnlineNetworkAttributes)
                    {
                        CreateAndPopulateAGOLTextTransportFieldsOnStreets(outputFileGdbPath, "AGOL_AnyHazmatProhibited",
                                                                          new string[] { "ExplosivesProhibited", "GasProhibited", "FlammableProhibited", "CombustibleProhibited", "OrganicProhibited", "PoisonProhibited", "RadioactiveProhibited", "CorrosiveProhibited",
                                                                                         "OtherHazmatProhibited", "AnyHazmatProhibited", "PIHProhibited", "HarmfulToWaterProhibited", "ExplosiveAndFlammableProhibited" },
                                                                          gp, messages, trackcancel);
                    }

                    // Create and calculate the other restriction fields for Streets

                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, true, false, false, "HeightLimit_Meters",
                                                              "MOD_TYPE = 41", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, true, false, false, "WeightLimit_Kilograms",
                                                              "MOD_TYPE = 42", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, true, false, false, "WeightLimitPerAxle_Kilograms",
                                                              "MOD_TYPE = 43", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, true, false, false, "LengthLimit_Meters",
                                                              "MOD_TYPE = 44", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, true, false, false, "WidthLimit_Meters",
                                                              "MOD_TYPE = 45", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, true, false, "MaxTrailersAllowedOnTruck",
                                                              "MOD_TYPE = 46 AND MOD_VAL IN ('1', '2', '3')", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, false, "SemiOrTractorWOneOrMoreTrailersProhibited",
                                                              "MOD_TYPE = 46 AND MOD_VAL = '4'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, true, false, "MaxAxlesAllowed",
                                                              "MOD_TYPE = 75 AND MOD_VAL IN ('1', '2', '3', '4', '5')", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, false, "SingleAxleProhibited",
                                                              "MOD_TYPE = 75 AND MOD_VAL = '6'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, false, false, false, "TandemAxleProhibited",
                                                              "MOD_TYPE = 75 AND MOD_VAL = '7'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, true, false, false, "KingpinToRearAxleLengthLimit_Meters",
                                                              "MOD_TYPE = 81", gp, messages, trackcancel);

                    // Create and calculate the truck speed fields for Streets

                    CreateAndPopulateTransportFieldsOnStreets(outputFileGdbPath, true, false, true, "TruckKPH",
                                                              "MOD_TYPE = 48", gp, messages, trackcancel);

                    deleteTool = new Delete();
                    deleteTool.in_data = "Streets_Layer";
                    gp.Execute(deleteTool, trackcancel);

                    deleteTool.in_data = preferredLinkIDLookupTablePath;
                    gp.Execute(deleteTool, trackcancel);
                    deleteTool.in_data = preferredDirectionLookupTablePath;
                    gp.Execute(deleteTool, trackcancel);

                    deleteTool.in_data = restrictionLinkIDLookupTablePath;
                    gp.Execute(deleteTool, trackcancel);
                    deleteTool.in_data = restrictionDirectionLookupTablePath;
                    gp.Execute(deleteTool, trackcancel);

                    makeFeatureLayerTool = new MakeFeatureLayer();
                    makeFeatureLayerTool.in_features = pathToTurnFC;
                    makeFeatureLayerTool.out_layer = "RestrictedTurns_Layer";
                    gp.Execute(makeFeatureLayerTool, trackcancel);

                    // Create and calculate the HazMat restriction fields for RestrictedTurns

                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, false, false, "ExplosivesProhibited",
                                                           "MOD_TYPE = 39 AND MOD_VAL = '1'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, false, false, "GasProhibited",
                                                           "MOD_TYPE = 39 AND MOD_VAL = '2'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, false, false, "FlammableProhibited",
                                                           "MOD_TYPE = 39 AND MOD_VAL = '3'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, false, false, "CombustibleProhibited",
                                                           "MOD_TYPE = 39 AND MOD_VAL = '4'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, false, false, "OrganicProhibited",
                                                           "MOD_TYPE = 39 AND MOD_VAL = '5'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, false, false, "PoisonProhibited",
                                                           "MOD_TYPE = 39 AND MOD_VAL = '6'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, false, false, "RadioactiveProhibited",
                                                           "MOD_TYPE = 39 AND MOD_VAL = '7'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, false, false, "CorrosiveProhibited",
                                                           "MOD_TYPE = 39 AND MOD_VAL = '8'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, false, false, "OtherHazmatProhibited",
                                                           "MOD_TYPE = 39 AND MOD_VAL = '9'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, false, false, "AnyHazmatProhibited",
                                                           "MOD_TYPE = 39 AND MOD_VAL = '20'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, false, false, "PIHProhibited",
                                                           "MOD_TYPE = 39 AND MOD_VAL = '21'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, false, false, "HarmfulToWaterProhibited",
                                                           "MOD_TYPE = 39 AND MOD_VAL = '22'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, false, false, "ExplosiveAndFlammableProhibited",
                                                           "MOD_TYPE = 39 AND MOD_VAL = '23'", gp, messages, trackcancel);

                    if (createArcGISOnlineNetworkAttributes)
                    {
                        CreateAndPopulateAGOLTextTransportFieldOnTurns(outputFileGdbPath, "AGOL_AnyHazmatProhibited",
                                                                       new string[] { "ExplosivesProhibited", "GasProhibited", "FlammableProhibited", "CombustibleProhibited", "OrganicProhibited", "PoisonProhibited", "RadioactiveProhibited", "CorrosiveProhibited",
                                                                                      "OtherHazmatProhibited", "AnyHazmatProhibited", "PIHProhibited", "HarmfulToWaterProhibited", "ExplosiveAndFlammableProhibited" },
                                                                       gp, messages, trackcancel);
                    }

                    // Create and calculate the other restriction fields for RestrictedTurns

                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, true, false, "HeightLimit_Meters",
                                                           "MOD_TYPE = 41", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, true, false, "WeightLimit_Kilograms",
                                                           "MOD_TYPE = 42", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, true, false, "WeightLimitPerAxle_Kilograms",
                                                           "MOD_TYPE = 43", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, true, false, "LengthLimit_Meters",
                                                           "MOD_TYPE = 44", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, true, false, "WidthLimit_Meters",
                                                           "MOD_TYPE = 45", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, false, true, "MaxTrailersAllowedOnTruck",
                                                           "MOD_TYPE = 46 AND MOD_VAL IN ('1', '2', '3')", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, false, false, "SemiOrTractorWOneOrMoreTrailersProhibited",
                                                           "MOD_TYPE = 46 AND MOD_VAL = '4'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, false, true, "MaxAxlesAllowed",
                                                           "MOD_TYPE = 75 AND MOD_VAL IN ('1', '2', '3', '4', '5')", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, false, false, "SingleAxleProhibited",
                                                           "MOD_TYPE = 75 AND MOD_VAL = '6'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, false, false, "TandemAxleProhibited",
                                                           "MOD_TYPE = 75 AND MOD_VAL = '7'", gp, messages, trackcancel);
                    CreateAndPopulateTransportFieldOnTurns(outputFileGdbPath, true, false, "KingpinToRearAxleLengthLimit_Meters",
                                                           "MOD_TYPE = 81", gp, messages, trackcancel);

                    deleteTool = new Delete();
                    deleteTool.in_data = "RestrictedTurns_Layer";
                    gp.Execute(deleteTool, trackcancel);

                    // Create and calculate the AllTransportProhibited field

                    addFieldTool = new AddField();
                    addFieldTool.in_table = pathToTurnFC;
                    addFieldTool.field_name = "AllTransportProhibited";
                    addFieldTool.field_type = "TEXT";
                    addFieldTool.field_length = 1;
                    gp.Execute(addFieldTool, trackcancel);

                    makeFeatureLayerTool = new MakeFeatureLayer();
                    makeFeatureLayerTool.in_features = pathToTurnFC;
                    makeFeatureLayerTool.out_layer = "RestrictedTurns_Layer";
                    makeFeatureLayerTool.where_clause = "COND_TYPE = 26 AND ExplosivesProhibited IS NULL AND GasProhibited IS NULL AND " +
                                                        "FlammableProhibited IS NULL AND CombustibleProhibited IS NULL AND OrganicProhibited IS NULL AND " +
                                                        "PoisonProhibited IS NULL AND RadioactiveProhibited IS NULL AND CorrosiveProhibited IS NULL AND " +
                                                        "OtherHazmatProhibited IS NULL AND AnyHazmatProhibited IS NULL AND PIHProhibited IS NULL AND " +
                                                        "HarmfulToWaterProhibited IS NULL AND ExplosiveAndFlammableProhibited IS NULL AND " +
                                                        "HeightLimit_Meters IS NULL AND WeightLimit_Kilograms IS NULL AND WeightLimitPerAxle_Kilograms IS NULL AND " +
                                                        "LengthLimit_Meters IS NULL AND WidthLimit_Meters IS NULL AND MaxTrailersAllowedOnTruck IS NULL AND " +
                                                        "SemiOrTractorWOneOrMoreTrailersProhibited IS NULL AND MaxAxlesAllowed IS NULL AND " +
                                                        "SingleAxleProhibited IS NULL AND TandemAxleProhibited IS NULL AND KingpinToRearAxleLengthLimit_Meters IS NULL";
                    gp.Execute(makeFeatureLayerTool, trackcancel);

                    AddMessage("Calculating the AllTransportProhibited field...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "RestrictedTurns_Layer";
                    calcFieldTool.field = "AllTransportProhibited";
                    calcFieldTool.expression = "\"Y\"";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    deleteTool = new Delete();
                    deleteTool.in_data = "RestrictedTurns_Layer";
                    gp.Execute(deleteTool, trackcancel);

                    deleteTool.in_data = nonDimensionalCndModTablePath;
                    gp.Execute(deleteTool, trackcancel);
                    deleteTool.in_data = dimensionalCndModTablePath;
                    gp.Execute(deleteTool, trackcancel);

                    GC.Collect();
                }
                #endregion

                // Extract the special explications (condition type 9) from the Rdms Table and create RoadSplits table

                AddMessage("Creating RoadSplits table...", messages, trackcancel);

                string specialExplicationRdmsWEndOfLkTablePath = outputFileGdbPath + "\\SpecialExplicationRdmsWEndOfLk";

                tableSelectTool = new TableSelect();
                tableSelectTool.in_table = rdmsTablePath;
                tableSelectTool.out_table = specialExplicationRdmsWEndOfLkTablePath;
                tableSelectTool.where_clause = "COND_TYPE = 9";
                gp.Execute(tableSelectTool, trackcancel);

                deleteTool.in_data = rdmsTablePath;
                gp.Execute(deleteTool, trackcancel);

                CreateRoadSplitsTable("SpecialExplicationRdmsWEndOfLk", outputFileGdbPath, messages, trackcancel);

                deleteTool.in_data = specialExplicationRdmsWEndOfLkTablePath;
                gp.Execute(deleteTool, trackcancel);

                // Create Signpost feature class and table

                AddMessage("Creating signpost feature class and table...", messages, trackcancel);

                CreateSignposts(inputSignsTableValue.GetAsText(), outputFileGdbPath, messages, trackcancel);

                AddSpatialIndex addSpatialIndexTool = new AddSpatialIndex();
                addSpatialIndexTool.in_features = pathToFds + "\\" + SignpostFCName;
                gp.Execute(addSpatialIndexTool, trackcancel);

                addIndexTool = new AddIndex();
                addIndexTool.in_table = outputFileGdbPath + "\\" + SignpostJoinTableName;
                addIndexTool.fields = "SignpostID";
                addIndexTool.index_name = "SignpostID";
                gp.Execute(addIndexTool, trackcancel);

                addIndexTool.fields = "Sequence";
                addIndexTool.index_name = "Sequence";
                gp.Execute(addIndexTool, trackcancel);

                addIndexTool.fields = "EdgeFCID";
                addIndexTool.index_name = "EdgeFCID";
                gp.Execute(addIndexTool, trackcancel);

                addIndexTool.fields = "EdgeFID";
                addIndexTool.index_name = "EdgeFID";
                gp.Execute(addIndexTool, trackcancel);

                GC.Collect();

                // Upgrade the geodatabase (if not 9.3)

                if (fgdbVersion > 9.3)
                {
                    UpgradeGDB upgradeGdbTool = new UpgradeGDB();
                    upgradeGdbTool.input_workspace = outputFileGdbPath;
                    gp.Execute(upgradeGdbTool, trackcancel);
                }

                // Create and build the network dataset, then pack it in a GPValue

                AddMessage("Creating and building the network dataset...", messages, trackcancel);

                CreateAndBuildNetworkDataset(outputFileGdbPath, fgdbVersion, fdsName, ndsName, createNetworkAttributesInMetric,
                                             createArcGISOnlineNetworkAttributes, timeZoneIDBaseFieldName, directedTimeZoneIDFields, commonTimeZone,
                                             usesHistoricalTraffic, trafficFeedLocation, usesTransport);

                // Write the build errors to the turn feature class

                TurnGeometryUtilities.WriteBuildErrorsToTurnFC(outputFileGdbPath, fdsName, TurnFCName, messages, trackcancel);

                // Compact the output file geodatabase

                AddMessage("Compacting the output file geodatabase...", messages, trackcancel);

                Compact compactTool = new Compact();
                compactTool.in_workspace = outputFileGdbPath;
                gp.Execute(compactTool, trackcancel);
            }
            catch (Exception e)
            {
                if (gp.MaxSeverity == 2)
                {
                    object missing = System.Type.Missing;
                    messages.AddError(1, gp.GetMessages(ref missing));
                }
                messages.AddError(1, e.Message);
                messages.AddError(1, e.StackTrace);
            }
            finally
            {
                // Restore the original GP environment settings

                gpSettings.AddOutputsToMap = origAddOutputsToMapSetting;
                gpSettings.LogHistory = origLogHistorySetting;
            }
            GC.Collect();
            return;
        }
Пример #11
0
        /// <summary>
        /// Adds the attribute columns.
        /// </summary>
        private void AddDynamicControls()
        {
            // Clear the filter controls
            phAttributeFilters.Controls.Clear();

            // Remove attribute columns
            foreach (var column in gWorkflows.Columns.OfType <AttributeField>().ToList())
            {
                gWorkflows.Columns.Remove(column);
            }

            if (AvailableAttributes != null)
            {
                foreach (var attribute in AvailableAttributes)
                {
                    var control = attribute.FieldType.Field.FilterControl(attribute.QualifierValues, "filter_" + attribute.Id.ToString(), false);
                    if (control is IRockControl)
                    {
                        var rockControl = (IRockControl)control;
                        rockControl.Label = attribute.Name;
                        rockControl.Help  = attribute.Description;
                        phAttributeFilters.Controls.Add(control);
                    }
                    else
                    {
                        var wrapper = new RockControlWrapper();
                        wrapper.ID    = control.ID + "_wrapper";
                        wrapper.Label = attribute.Name;
                        wrapper.Controls.Add(control);
                        phAttributeFilters.Controls.Add(wrapper);
                    }

                    string savedValue = gfWorkflows.GetUserPreference(MakeKeyUniqueToType(attribute.Key));
                    if (!string.IsNullOrWhiteSpace(savedValue))
                    {
                        try
                        {
                            var values = JsonConvert.DeserializeObject <List <string> >(savedValue);
                            attribute.FieldType.Field.SetFilterValues(control, attribute.QualifierValues, values);
                        }
                        catch { }
                    }

                    string dataFieldExpression = attribute.Key;
                    bool   columnExists        = gWorkflows.Columns.OfType <AttributeField>().FirstOrDefault(a => a.DataField.Equals(dataFieldExpression)) != null;
                    if (!columnExists)
                    {
                        AttributeField boundField = new AttributeField();
                        boundField.DataField      = dataFieldExpression;
                        boundField.HeaderText     = attribute.Name;
                        boundField.SortExpression = string.Empty;

                        var attributeCache = Rock.Web.Cache.AttributeCache.Read(attribute.Id);
                        if (attributeCache != null)
                        {
                            boundField.ItemStyle.HorizontalAlign = attributeCache.FieldType.Field.AlignValue;
                        }

                        gWorkflows.Columns.Add(boundField);
                    }
                }
            }

            var dateField = new DateTimeField();

            gWorkflows.Columns.Add(dateField);
            dateField.DataField           = "CreatedDateTime";
            dateField.SortExpression      = "CreatedDateTime";
            dateField.HeaderText          = "Created";
            dateField.FormatAsElapsedTime = true;

            var statusField = new BoundField();

            gWorkflows.Columns.Add(statusField);
            statusField.DataField      = "Status";
            statusField.SortExpression = "Status";
            statusField.HeaderText     = "Status";
            statusField.HtmlEncode     = false;

            var stateField = new BoundField();

            gWorkflows.Columns.Add(stateField);
            stateField.DataField      = "State";
            stateField.SortExpression = "CompletedDateTime";
            stateField.HeaderText     = "State";
            stateField.HtmlEncode     = false;

            var manageField = new EditField();

            gWorkflows.Columns.Add(manageField);
            manageField.IconCssClass = "fa fa-edit";
            manageField.Click       += gWorkflows_Manage;

            var deleteField = new DeleteField();

            gWorkflows.Columns.Add(deleteField);
            deleteField.Click += gWorkflows_Delete;
        }
Пример #12
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            gPledges.DataKeyNames  = new[] { "id" };
            gPledges.RowDataBound += GPledges_RowDataBound;
            if (!string.IsNullOrWhiteSpace(GetAttributeValue("DetailPage")))
            {
                gPledges.Actions.AddClick += gPledges_Add;
                gPledges.RowSelected      += gPledges_Edit;
            }
            gPledges.GridRebind          += gPledges_GridRebind;
            gfPledges.ApplyFilterClick   += gfPledges_ApplyFilterClick;
            gfPledges.DisplayFilterValue += gfPledges_DisplayFilterValue;

            bool canAddEditDelete = IsUserAuthorized(Authorization.EDIT);

            gPledges.Actions.ShowAdd = canAddEditDelete && !string.IsNullOrWhiteSpace(GetAttributeValue("DetailPage"));
            gPledges.IsDeleteEnabled = canAddEditDelete;

            AddAttributeColumns();

            var deleteField = new DeleteField();

            gPledges.Columns.Add(deleteField);
            deleteField.Click += gPledges_Delete;

            if (GetAttributeValue("LimitPledgesToCurrentPerson").AsBoolean())
            {
                TargetPerson = this.CurrentPerson;
            }
            else
            {
                TargetPerson = ContextEntity <Person>();
            }

            // hide the person column and filter if a person context exists
            if (TargetPerson != null)
            {
                var personField = gPledges.ColumnsOfType <RockBoundField>().FirstOrDefault(a => a.HeaderText == "Person");
                if (personField != null)
                {
                    personField.Visible = false;
                }
                gfPledges.Visible = false;
            }

            var forField = gPledges.ColumnsOfType <RockBoundField>().FirstOrDefault(a => a.HeaderText == "For");

            if (forField != null)
            {
                // show/hide the group column
                forField.Visible = GetAttributeValue("ShowGroupColumn").AsBoolean();
            }

            var accountField = gPledges.ColumnsOfType <RockBoundField>().FirstOrDefault(a => a.HeaderText == "Account");

            if (accountField != null)
            {
                // show/hide the account column
                accountField.Visible = GetAttributeValue("ShowAccountColumn").AsBoolean();
            }

            var modifiedDateField = gPledges.ColumnsOfType <DateField>().FirstOrDefault(a => a.DataField == "ModifiedDateTime");

            if (modifiedDateField != null)
            {
                // show/hide the last modified date column
                modifiedDateField.Visible = GetAttributeValue("ShowLastModifiedDateColumn").AsBoolean();
            }
        }
        public void Execute(IArray paramvalues, ITrackCancel trackcancel,
                            IGPEnvironmentManager envMgr, IGPMessages messages)
        {
            // Remember the original GP environment settings and temporarily override these settings

            var gpSettings = envMgr as IGeoProcessorSettings;
            bool origAddOutputsToMapSetting = gpSettings.AddOutputsToMap;
            bool origLogHistorySetting = gpSettings.LogHistory;
            gpSettings.AddOutputsToMap = false;
            gpSettings.LogHistory = false;

            // Create the Geoprocessor

            Geoprocessor gp = new Geoprocessor();

            try
            {
                // Validate our values

                IGPMessages validateMessages = ((IGPFunction2)this).Validate(paramvalues, false, envMgr);
                if ((validateMessages as IGPMessage).IsError())
                {
                    messages.AddError(1, "Validate failed");
                    return;
                }

                // Unpack values

                IGPParameter gpParam = paramvalues.get_Element(InputAETable) as IGPParameter;
                IGPValue inputAETableValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputAdminAreaFeatureClasses) as IGPParameter;
                var inputAdminAreaFeatureClassesMultiValue = m_gpUtils.UnpackGPValue(gpParam) as IGPMultiValue;
                gpParam = paramvalues.get_Element(OutputFileGDB) as IGPParameter;
                IGPValue outputFileGDBValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputTATable) as IGPParameter;
                IGPValue inputTATableValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputNWFeatureClass) as IGPParameter;
                IGPValue inputNWFeatureClassValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputTimeZoneIDBaseFieldName) as IGPParameter;
                IGPValue inputTimeZoneIDBaseFieldNameValue = m_gpUtils.UnpackGPValue(gpParam);

                if (inputTATableValue.IsEmpty() ^ inputNWFeatureClassValue.IsEmpty())
                {
                    messages.AddError(1, "The TA table and NW feature class must be specified together.");
                    return;
                }

                bool processStreetsFC = (!(inputNWFeatureClassValue.IsEmpty()));
                string timeZoneIDBaseFieldName = "";
                if (!(inputTimeZoneIDBaseFieldNameValue.IsEmpty()))
                    timeZoneIDBaseFieldName = inputTimeZoneIDBaseFieldNameValue.GetAsText();

                // Get the path to the output file GDB

                string outputFileGdbPath = outputFileGDBValue.GetAsText();

                // Create the new file geodatabase

                AddMessage("Creating the file geodatabase...", messages, trackcancel);

                int lastBackslash = outputFileGdbPath.LastIndexOf("\\");
                CreateFileGDB createFGDBTool = new CreateFileGDB();
                createFGDBTool.out_folder_path = outputFileGdbPath.Remove(lastBackslash);
                createFGDBTool.out_name = outputFileGdbPath.Substring(lastBackslash + 1);
                gp.Execute(createFGDBTool, trackcancel);

                // Copy the admin area feature classes

                int numAdminAreaFCs = inputAdminAreaFeatureClassesMultiValue.Count;
                string mergeToolInputs = "";
                for (int i = 0; i < numAdminAreaFCs; i++)
                {
                    AddMessage("Copying the Administrative Area feature classes (" + Convert.ToString(i+1) + " of " + Convert.ToString(numAdminAreaFCs) + ")...", messages, trackcancel);

                    string origAdminFCPath = inputAdminAreaFeatureClassesMultiValue.get_Value(i).GetAsText();
                    FeatureClassToFeatureClass importFCTool = new FeatureClassToFeatureClass();
                    importFCTool.in_features = origAdminFCPath;
                    importFCTool.out_path = outputFileGdbPath;
                    importFCTool.out_name = "Admin" + Convert.ToString(i, System.Globalization.CultureInfo.InvariantCulture);
                    importFCTool.field_mapping = "ID \"ID\" true true false 8 Double 0 0 ,First,#," + origAdminFCPath + ",ID,-1,-1;" +
                                                 "FEATTYP \"FEATTYP\" true true false 2 Short 0 0 ,First,#," + origAdminFCPath + ",FEATTYP,-1,-1;" +
                                                 "ORDER00 \"ORDER00\" true true false 3 Text 0 0 ,First,#," + origAdminFCPath + ",ORDER00,-1,-1;" +
                                                 "NAME \"NAME\" true true false 100 Text 0 0 ,First,#," + origAdminFCPath + ",NAME,-1,-1;" +
                                                 "NAMELC \"NAMELC\" true true false 3 Text 0 0 ,First,#," + origAdminFCPath + ",NAMELC,-1,-1";
                    gp.Execute(importFCTool, trackcancel);

                    mergeToolInputs = mergeToolInputs + outputFileGdbPath + "\\Admin" + Convert.ToString(i, System.Globalization.CultureInfo.InvariantCulture) + ";";
                }
                mergeToolInputs = mergeToolInputs.Remove(mergeToolInputs.Length - 1);

                // Merge the admin area feature classes together into one feature class

                AddMessage("Merging the Administrative Area feature classes...", messages, trackcancel);

                string adminFCPath = outputFileGdbPath + "\\AdminFC";

                Merge mergeTool = new Merge();
                mergeTool.inputs = mergeToolInputs;
                mergeTool.output = adminFCPath;
                gp.Execute(mergeTool, trackcancel);

                Delete deleteTool = null;
                for (int i = 0; i < numAdminAreaFCs; i++)
                {
                    deleteTool = new Delete();
                    deleteTool.in_data = outputFileGdbPath + "\\Admin" + Convert.ToString(i, System.Globalization.CultureInfo.InvariantCulture);
                    gp.Execute(deleteTool, trackcancel);
                }

                // Extract the time zone information and index it

                AddMessage("Extracting the time zone information...", messages, trackcancel);

                string tzTablePath = outputFileGdbPath + "\\TZ";
                TableSelect tableSelectTool = new TableSelect();
                tableSelectTool.in_table = inputAETableValue.GetAsText();
                tableSelectTool.out_table = tzTablePath;
                tableSelectTool.where_clause = "ATTTYP = 'TZ'";
                gp.Execute(tableSelectTool, trackcancel);

                AddIndex addIndexTool = new AddIndex();
                addIndexTool.in_table = tzTablePath;
                addIndexTool.fields = "ID";
                addIndexTool.index_name = "ID";
                gp.Execute(addIndexTool, trackcancel);

                // Add the UTCOffset field and calculate it

                AddField addFieldTool = new AddField();
                addFieldTool.in_table = adminFCPath;
                addFieldTool.field_name = "UTCOffset";
                addFieldTool.field_type = "SHORT";
                gp.Execute(addFieldTool, trackcancel);

                MakeFeatureLayer makeFeatureLayerTool = new MakeFeatureLayer();
                makeFeatureLayerTool.in_features = adminFCPath;
                makeFeatureLayerTool.out_layer = "AdminFC_Layer";
                gp.Execute(makeFeatureLayerTool, trackcancel);

                AddJoin addJoinTool = new AddJoin();
                addJoinTool.in_layer_or_view = "AdminFC_Layer";
                addJoinTool.in_field = "ID";
                addJoinTool.join_table = tzTablePath;
                addJoinTool.join_field = "ID";
                addJoinTool.join_type = "KEEP_COMMON";
                gp.Execute(addJoinTool, trackcancel);

                AddMessage("Calculating the UTCOffset information on the Administrative Area feature class...", messages, trackcancel);

                CalculateField calcFieldTool = new CalculateField();
                calcFieldTool.in_table = "AdminFC_Layer";
                calcFieldTool.field = "AdminFC.UTCOffset";
                calcFieldTool.code_block = "u = Null\ns = Trim([TZ.ATTVALUE])\nIf Not IsNull(s) Then\n" +
                                           "  sign = 1\n  If Left(s, 1) = \"-\" Then sign = -1\n" +
                                           "  u = sign * ( (60 * Abs(CInt(Mid(s, 1, Len(s) - 3)))) + CInt(Right(s, 2)) )\n" +
                                           "End If";
                calcFieldTool.expression = "u";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                RemoveJoin removeJoinTool = new RemoveJoin();
                removeJoinTool.in_layer_or_view = "AdminFC_Layer";
                removeJoinTool.join_name = "TZ";
                gp.Execute(removeJoinTool, trackcancel);

                deleteTool = new Delete();
                deleteTool.in_data = "AdminFC_Layer";
                gp.Execute(deleteTool, trackcancel);
                deleteTool = new Delete();
                deleteTool.in_data = tzTablePath;
                gp.Execute(deleteTool, trackcancel);

                // Extract out only the admin areas that have time zone information

                AddMessage("Extracting Administrative Areas with time zone information...", messages, trackcancel);

                string adminTZFCPath = outputFileGdbPath + "\\AdminFCwTZ";
                Select selectTool = new Select();
                selectTool.in_features = adminFCPath;
                selectTool.out_feature_class = adminTZFCPath;
                selectTool.where_clause = "NOT UTCOffset IS NULL";
                gp.Execute(selectTool, trackcancel);

                // Extract the daylight saving time information and index it

                AddMessage("Extracting the daylight saving time information...", messages, trackcancel);

                string suTablePath = outputFileGdbPath + "\\SU";
                tableSelectTool = new TableSelect();
                tableSelectTool.in_table = inputAETableValue.GetAsText();
                tableSelectTool.out_table = suTablePath;
                tableSelectTool.where_clause = "ATTTYP = 'SU'";
                gp.Execute(tableSelectTool, trackcancel);

                addIndexTool = new AddIndex();
                addIndexTool.in_table = suTablePath;
                addIndexTool.fields = "ID";
                addIndexTool.index_name = "ID";
                gp.Execute(addIndexTool, trackcancel);

                // Add the daylight saving field and calculate it

                addFieldTool = new AddField();
                addFieldTool.in_table = adminTZFCPath;
                addFieldTool.field_name = "DST";
                addFieldTool.field_type = "SHORT";
                gp.Execute(addFieldTool, trackcancel);

                makeFeatureLayerTool = new MakeFeatureLayer();
                makeFeatureLayerTool.in_features = adminTZFCPath;
                makeFeatureLayerTool.out_layer = "AdminFCwTZ_Layer";
                gp.Execute(makeFeatureLayerTool, trackcancel);

                addJoinTool = new AddJoin();
                addJoinTool.in_layer_or_view = "AdminFCwTZ_Layer";
                addJoinTool.in_field = "ID";
                addJoinTool.join_table = suTablePath;
                addJoinTool.join_field = "ID";
                addJoinTool.join_type = "KEEP_ALL";
                gp.Execute(addJoinTool, trackcancel);

                AddMessage("Copying the DST information to the Administrative Area feature class...", messages, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = "AdminFCwTZ_Layer";
                calcFieldTool.field = "AdminFCwTZ.DST";
                calcFieldTool.code_block = "s = 0\nIf Not IsNull( [SU.ATTVALUE] ) Then s = CInt( [SU.ATTVALUE] )";
                calcFieldTool.expression = "s";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                removeJoinTool = new RemoveJoin();
                removeJoinTool.in_layer_or_view = "AdminFCwTZ_Layer";
                removeJoinTool.join_name = "SU";
                gp.Execute(removeJoinTool, trackcancel);

                deleteTool = new Delete();
                deleteTool.in_data = "AdminFCwTZ_Layer";
                gp.Execute(deleteTool, trackcancel);
                deleteTool = new Delete();
                deleteTool.in_data = suTablePath;
                gp.Execute(deleteTool, trackcancel);

                // Create and calculate the sortable MSTIMEZONE field

                addFieldTool = new AddField();
                addFieldTool.in_table = adminTZFCPath;
                addFieldTool.field_name = "SortableMSTIMEZONE";
                addFieldTool.field_type = "TEXT";
                addFieldTool.field_length = 60;
                gp.Execute(addFieldTool, trackcancel);

                AddMessage("Calculating the time zones...", messages, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = adminTZFCPath;
                calcFieldTool.field = "SortableMSTIMEZONE";
                calcFieldTool.code_block = TimeZoneUtilities.MakeSortableMSTIMEZONECode("ORDER00");
                calcFieldTool.expression = "z";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                Rename renameTool = new Rename();
                renameTool.in_data = adminTZFCPath;
                renameTool.out_data = adminTZFCPath + "wNulls";
                gp.Execute(renameTool, trackcancel);

                selectTool = new Select();
                selectTool.in_features = adminTZFCPath + "wNulls";
                selectTool.out_feature_class = adminTZFCPath;
                selectTool.where_clause = "NOT SortableMSTIMEZONE IS NULL";
                gp.Execute(selectTool, trackcancel);

                deleteTool = new Delete();
                deleteTool.in_data = adminTZFCPath + "wNulls";
                gp.Execute(deleteTool, trackcancel);

                // Dissolve the time zone polygons together

                AddMessage("Dissolving the time zones...", messages, trackcancel);

                string timeZoneFCPath = outputFileGdbPath + "\\" + TimeZoneFCName;
                Dissolve dissolveTool = new Dissolve();
                dissolveTool.in_features = adminTZFCPath;
                dissolveTool.out_feature_class = timeZoneFCPath;
                dissolveTool.dissolve_field = "SortableMSTIMEZONE";
                dissolveTool.multi_part = "MULTI_PART";
                gp.Execute(dissolveTool, trackcancel);

                // Create and calculate the MSTIMEZONE field

                addFieldTool = new AddField();
                addFieldTool.in_table = timeZoneFCPath;
                addFieldTool.field_name = "MSTIMEZONE";
                addFieldTool.field_type = "TEXT";
                addFieldTool.field_length = 50;
                gp.Execute(addFieldTool, trackcancel);

                AddMessage("Calculating the time zones...", messages, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = timeZoneFCPath;
                calcFieldTool.field = "MSTIMEZONE";
                calcFieldTool.expression = "Mid([SortableMSTIMEZONE], 7)";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                // Delete the old sortable MSTIMEZONE field

                DeleteField deleteFieldTool = new DeleteField();
                deleteFieldTool.in_table = timeZoneFCPath;
                deleteFieldTool.drop_field = "SortableMSTIMEZONE";
                gp.Execute(deleteFieldTool, trackcancel);

                if (processStreetsFC)
                {
                    // Create the network dataset time zone table

                    AddMessage("Creating the time zones table...", messages, trackcancel);

                    TableToTable importTableTool = new TableToTable();
                    importTableTool.in_rows = timeZoneFCPath;
                    importTableTool.out_path = outputFileGdbPath;
                    importTableTool.out_name = TimeZonesTableName;
                    importTableTool.field_mapping = "MSTIMEZONE \"MSTIMEZONE\" true true false 50 Text 0 0 ,First,#," +
                                                    timeZoneFCPath + ",MSTIMEZONE,-1,-1";
                    gp.Execute(importTableTool, trackcancel);

                    // Import the NW feature class to the file geodatabase

                    AddMessage("Copying the NW feature class to the geodatabase...", messages, trackcancel);

                    FeatureClassToFeatureClass importFCTool = new FeatureClassToFeatureClass();
                    importFCTool.in_features = inputNWFeatureClassValue.GetAsText();
                    importFCTool.out_path = outputFileGdbPath;
                    importFCTool.out_name = "nw";
                    gp.Execute(importFCTool, trackcancel);

                    string pathToLocalNW = outputFileGdbPath + "\\nw";

                    // Create Join polygon feature class

                    AddMessage("Creating the join polygon feature class...", messages, trackcancel);

                    string joinPolygonFCPath = outputFileGdbPath + "\\JoinPolygonFC";

                    MultipartToSinglepart multipartToSinglepartTool = new MultipartToSinglepart();
                    multipartToSinglepartTool.in_features = timeZoneFCPath;
                    multipartToSinglepartTool.out_feature_class = joinPolygonFCPath;
                    gp.Execute(multipartToSinglepartTool, trackcancel);

                    // Add and calculate the time zone ID fields to the join polygons

                    addFieldTool = new AddField();
                    addFieldTool.in_table = joinPolygonFCPath;
                    addFieldTool.field_type = "SHORT";
                    addFieldTool.field_name = "FT_" + timeZoneIDBaseFieldName;
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "TF_" + timeZoneIDBaseFieldName;
                    gp.Execute(addFieldTool, trackcancel);

                    AddMessage("Calculating the FT_" + timeZoneIDBaseFieldName + " field...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = joinPolygonFCPath;
                    calcFieldTool.field = "FT_" + timeZoneIDBaseFieldName;
                    calcFieldTool.expression = "[ORIG_FID]";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    AddMessage("Calculating the TF_" + timeZoneIDBaseFieldName + " field...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = joinPolygonFCPath;
                    calcFieldTool.field = "TF_" + timeZoneIDBaseFieldName;
                    calcFieldTool.expression = "[ORIG_FID]";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    // Delete the MSTIMEZONE and ORIG_FID fields from the join polygon FC

                    deleteFieldTool = new DeleteField();
                    deleteFieldTool.in_table = joinPolygonFCPath;
                    deleteFieldTool.drop_field = "MSTIMEZONE;ORIG_FID";
                    gp.Execute(deleteFieldTool, trackcancel);

                    // Perform a spatial join between the Streets and the join polygons

                    AddMessage("Creating Streets feature class with time zone ID fields...", messages, trackcancel);

                    string outputStreetsFCPath = outputFileGdbPath + "\\" + StreetsFCName;
                    SpatialJoin spatialJoinTool = new SpatialJoin();
                    spatialJoinTool.target_features = pathToLocalNW;
                    spatialJoinTool.join_features = joinPolygonFCPath;
                    spatialJoinTool.out_feature_class = outputStreetsFCPath;
                    spatialJoinTool.match_option = "IS_WITHIN";
                    gp.Execute(spatialJoinTool, trackcancel);

                    // Delete the extraneous fields

                    deleteFieldTool = new DeleteField();
                    deleteFieldTool.in_table = outputStreetsFCPath;
                    deleteFieldTool.drop_field = "Join_Count;TARGET_FID;Shape_Length_1";
                    gp.Execute(deleteFieldTool, trackcancel);

                    // Delete the temporary NW and Join feature classes

                    deleteTool = new Delete();
                    deleteTool.in_data = pathToLocalNW;
                    gp.Execute(deleteTool, trackcancel);
                    deleteTool = new Delete();
                    deleteTool.in_data = joinPolygonFCPath;
                    gp.Execute(deleteTool, trackcancel);

                    // Extract the drive side information and index it

                    AddMessage("Extracting the drive side information...", messages, trackcancel);

                    string driveSideTablePath = outputFileGdbPath + "\\DriveSide";
                    tableSelectTool = new TableSelect();
                    tableSelectTool.in_table = inputAETableValue.GetAsText();
                    tableSelectTool.out_table = driveSideTablePath;
                    tableSelectTool.where_clause = "ATTTYP = '3D'";
                    gp.Execute(tableSelectTool, trackcancel);

                    addIndexTool = new AddIndex();
                    addIndexTool.in_table = driveSideTablePath;
                    addIndexTool.fields = "ID";
                    addIndexTool.index_name = "ID";
                    gp.Execute(addIndexTool, trackcancel);

                    // Add the DriveSide field and calculate it

                    addFieldTool = new AddField();
                    addFieldTool.in_table = adminFCPath;
                    addFieldTool.field_name = "DriveSide";
                    addFieldTool.field_type = "SHORT";
                    gp.Execute(addFieldTool, trackcancel);

                    makeFeatureLayerTool = new MakeFeatureLayer();
                    makeFeatureLayerTool.in_features = adminFCPath;
                    makeFeatureLayerTool.out_layer = "AdminFC_Layer";
                    gp.Execute(makeFeatureLayerTool, trackcancel);

                    addJoinTool = new AddJoin();
                    addJoinTool.in_layer_or_view = "AdminFC_Layer";
                    addJoinTool.in_field = "ID";
                    addJoinTool.join_table = driveSideTablePath;
                    addJoinTool.join_field = "ID";
                    addJoinTool.join_type = "KEEP_COMMON";
                    gp.Execute(addJoinTool, trackcancel);

                    AddMessage("Copying the drive side information to the Administrative Area feature class...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "AdminFC_Layer";
                    calcFieldTool.field = "AdminFC.DriveSide";
                    calcFieldTool.expression = "CInt( [DriveSide.ATTVALUE] )";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    removeJoinTool = new RemoveJoin();
                    removeJoinTool.in_layer_or_view = "AdminFC_Layer";
                    removeJoinTool.join_name = "DriveSide";
                    gp.Execute(removeJoinTool, trackcancel);

                    deleteTool = new Delete();
                    deleteTool.in_data = "AdminFC_Layer";
                    gp.Execute(deleteTool, trackcancel);
                    deleteTool = new Delete();
                    deleteTool.in_data = driveSideTablePath;
                    gp.Execute(deleteTool, trackcancel);

                    // Extract out only the admin areas that have drive side information and index the ORDER00 field

                    AddMessage("Extracting Administrative Areas with drive side information...", messages, trackcancel);

                    string adminFCwDriveSidePath = outputFileGdbPath + "\\AdminFCwDriveSide";
                    selectTool = new Select();
                    selectTool.in_features = adminFCPath;
                    selectTool.out_feature_class = adminFCwDriveSidePath;
                    selectTool.where_clause = "NOT DriveSide IS NULL";
                    gp.Execute(selectTool, trackcancel);

                    addIndexTool = new AddIndex();
                    addIndexTool.in_table = adminFCwDriveSidePath;
                    addIndexTool.fields = "ORDER00";
                    addIndexTool.index_name = "ORDER00";
                    gp.Execute(addIndexTool, trackcancel);

                    // Add the DriveSide field to the AdminFCwTZ feature class and calculate it.

                    addFieldTool = new AddField();
                    addFieldTool.in_table = adminTZFCPath;
                    addFieldTool.field_name = "DriveSide";
                    addFieldTool.field_type = "SHORT";
                    gp.Execute(addFieldTool, trackcancel);

                    makeFeatureLayerTool = new MakeFeatureLayer();
                    makeFeatureLayerTool.in_features = adminTZFCPath;
                    makeFeatureLayerTool.out_layer = "AdminFCwTZ_Layer";
                    gp.Execute(makeFeatureLayerTool, trackcancel);

                    addJoinTool = new AddJoin();
                    addJoinTool.in_layer_or_view = "AdminFCwTZ_Layer";
                    addJoinTool.in_field = "ORDER00";
                    addJoinTool.join_table = adminFCwDriveSidePath;
                    addJoinTool.join_field = "ORDER00";
                    addJoinTool.join_type = "KEEP_COMMON";
                    gp.Execute(addJoinTool, trackcancel);

                    AddMessage("Calculating the DriveSide field on the AdminFCwTZ feature class...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "AdminFCwTZ_Layer";
                    calcFieldTool.field = "AdminFCwTZ.DriveSide";
                    calcFieldTool.expression = "[AdminFCwDriveSide.DriveSide]";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    removeJoinTool = new RemoveJoin();
                    removeJoinTool.in_layer_or_view = "AdminFCwTZ_Layer";
                    removeJoinTool.join_name = "AdminFCwDriveSide";
                    gp.Execute(removeJoinTool, trackcancel);

                    deleteTool = new Delete();
                    deleteTool.in_data = "AdminFCwTZ_Layer";
                    gp.Execute(deleteTool, trackcancel);

                    deleteTool = new Delete();
                    deleteTool.in_data = adminFCwDriveSidePath;
                    gp.Execute(deleteTool, trackcancel);

                    // Extract the information for boundary roads

                    AddMessage("Extracting the information for boundary roads...", messages, trackcancel);

                    string taTablePath = outputFileGdbPath + "\\TA";
                    tableSelectTool = new TableSelect();
                    tableSelectTool.in_table = inputTATableValue.GetAsText();
                    tableSelectTool.out_table = taTablePath;
                    tableSelectTool.where_clause = "ARETYP <= 1120 AND SOL > 0";
                    gp.Execute(tableSelectTool, trackcancel);

                    // Join the boundary road information with the AdminFCwTZ feature class to
                    // create the FT_BoundaryTimeZones and TF_BoundaryTimeZones join tables

                    addIndexTool = new AddIndex();
                    addIndexTool.in_table = adminTZFCPath;
                    addIndexTool.fields = "ID";
                    addIndexTool.index_name = "ID";
                    gp.Execute(addIndexTool, trackcancel);

                    MakeTableView makeTableViewTool = new MakeTableView();
                    makeTableViewTool.in_table = taTablePath;
                    makeTableViewTool.out_view = "TA_View";
                    gp.Execute(makeTableViewTool, trackcancel);

                    addJoinTool = new AddJoin();
                    addJoinTool.in_layer_or_view = "TA_View";
                    addJoinTool.in_field = "AREID";
                    addJoinTool.join_table = adminTZFCPath;
                    addJoinTool.join_field = "ID";
                    addJoinTool.join_type = "KEEP_COMMON";
                    gp.Execute(addJoinTool, trackcancel);

                    AddMessage("Extracting the boundary FT time zones...", messages, trackcancel);

                    importTableTool = new TableToTable();
                    importTableTool.in_rows = "TA_View";
                    importTableTool.out_path = outputFileGdbPath;
                    importTableTool.out_name = "FT_BoundaryTimeZones";
                    importTableTool.where_clause = "TA.SOL = AdminFCwTZ.DriveSide";
                    importTableTool.field_mapping = "ID \"ID\" true true false 8 Double 0 0 ,First,#," + taTablePath + ",TA.ID,-1,-1;" +
                                                    "SortableMSTIMEZONE \"SortableMSTIMEZONE\" true true false 60 Text 0 0 ,First,#," +
                                                    adminTZFCPath + ",AdminFCwTZ.SortableMSTIMEZONE,-1,-1";
                    gp.Execute(importTableTool, trackcancel);

                    string ftBoundaryTimeZonesPath = outputFileGdbPath + "\\FT_BoundaryTimeZones";

                    addIndexTool = new AddIndex();
                    addIndexTool.in_table = ftBoundaryTimeZonesPath;
                    addIndexTool.fields = "ID";
                    addIndexTool.index_name = "ID";
                    gp.Execute(addIndexTool, trackcancel);

                    AddMessage("Extracting the boundary TF time zones...", messages, trackcancel);

                    importTableTool = new TableToTable();
                    importTableTool.in_rows = "TA_View";
                    importTableTool.out_path = outputFileGdbPath;
                    importTableTool.out_name = "TF_BoundaryTimeZones";
                    importTableTool.where_clause = "TA.SOL <> AdminFCwTZ.DriveSide";
                    importTableTool.field_mapping = "ID \"ID\" true true false 8 Double 0 0 ,First,#," + taTablePath + ",TA.ID,-1,-1;" +
                                                    "SortableMSTIMEZONE \"SortableMSTIMEZONE\" true true false 60 Text 0 0 ,First,#," +
                                                    adminTZFCPath + ",AdminFCwTZ.SortableMSTIMEZONE,-1,-1";
                    gp.Execute(importTableTool, trackcancel);

                    string tfBoundaryTimeZonesPath = outputFileGdbPath + "\\TF_BoundaryTimeZones";

                    addIndexTool = new AddIndex();
                    addIndexTool.in_table = tfBoundaryTimeZonesPath;
                    addIndexTool.fields = "ID";
                    addIndexTool.index_name = "ID";
                    gp.Execute(addIndexTool, trackcancel);

                    removeJoinTool = new RemoveJoin();
                    removeJoinTool.in_layer_or_view = "TA_View";
                    removeJoinTool.join_name = "AdminFCwTZ";
                    gp.Execute(removeJoinTool, trackcancel);

                    deleteTool = new Delete();
                    deleteTool.in_data = "TA_View";
                    gp.Execute(deleteTool, trackcancel);
                    deleteTool.in_data = taTablePath;
                    gp.Execute(deleteTool, trackcancel);

                    // Calculate the boundary time zone ID values

                    makeFeatureLayerTool = new MakeFeatureLayer();
                    makeFeatureLayerTool.in_features = outputStreetsFCPath;
                    makeFeatureLayerTool.out_layer = "Streets_Layer";
                    gp.Execute(makeFeatureLayerTool, trackcancel);

                    addJoinTool = new AddJoin();
                    addJoinTool.in_layer_or_view = "Streets_Layer";
                    addJoinTool.in_field = "ID";
                    addJoinTool.join_table = ftBoundaryTimeZonesPath;
                    addJoinTool.join_field = "ID";
                    addJoinTool.join_type = "KEEP_COMMON";
                    gp.Execute(addJoinTool, trackcancel);

                    AddMessage("Calculating the boundary FT time zones...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "Streets_Layer";
                    calcFieldTool.field = StreetsFCName + ".FT_" + timeZoneIDBaseFieldName;
                    calcFieldTool.code_block = TimeZoneUtilities.MakeTimeZoneIDCode(outputFileGdbPath, TimeZonesTableName, "FT_BoundaryTimeZones.SortableMSTIMEZONE");
                    calcFieldTool.expression = "tzID";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    removeJoinTool = new RemoveJoin();
                    removeJoinTool.in_layer_or_view = "Streets_Layer";
                    removeJoinTool.join_name = "FT_BoundaryTimeZones";
                    gp.Execute(removeJoinTool, trackcancel);

                    addJoinTool = new AddJoin();
                    addJoinTool.in_layer_or_view = "Streets_Layer";
                    addJoinTool.in_field = "ID";
                    addJoinTool.join_table = tfBoundaryTimeZonesPath;
                    addJoinTool.join_field = "ID";
                    addJoinTool.join_type = "KEEP_COMMON";
                    gp.Execute(addJoinTool, trackcancel);

                    AddMessage("Calculating the boundary TF time zones...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "Streets_Layer";
                    calcFieldTool.field = StreetsFCName + ".TF_" + timeZoneIDBaseFieldName;
                    calcFieldTool.code_block = TimeZoneUtilities.MakeTimeZoneIDCode(outputFileGdbPath, TimeZonesTableName, "TF_BoundaryTimeZones.SortableMSTIMEZONE");
                    calcFieldTool.expression = "tzID";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    removeJoinTool = new RemoveJoin();
                    removeJoinTool.in_layer_or_view = "Streets_Layer";
                    removeJoinTool.join_name = "TF_BoundaryTimeZones";
                    gp.Execute(removeJoinTool, trackcancel);

                    deleteTool = new Delete();
                    deleteTool.in_data = "Streets_Layer";
                    gp.Execute(deleteTool, trackcancel);

                    deleteTool = new Delete();
                    deleteTool.in_data = ftBoundaryTimeZonesPath;
                    gp.Execute(deleteTool, trackcancel);
                    deleteTool.in_data = tfBoundaryTimeZonesPath;
                    gp.Execute(deleteTool, trackcancel);
                }
                else
                {
                    // Create a dummy TimeZones table and a dummy Streets feature class

                    CreateTable createTableTool = new CreateTable();
                    createTableTool.out_path = outputFileGdbPath;
                    createTableTool.out_name = TimeZonesTableName;
                    gp.Execute(createTableTool, trackcancel);

                    CreateFeatureclass createFCTool = new CreateFeatureclass();
                    createFCTool.out_path = outputFileGdbPath;
                    createFCTool.out_name = StreetsFCName;
                    createFCTool.geometry_type = "POLYLINE";
                    gp.Execute(createFCTool, trackcancel);
                }

                deleteTool = new Delete();
                deleteTool.in_data = adminFCPath;
                gp.Execute(deleteTool, trackcancel);

                deleteTool = new Delete();
                deleteTool.in_data = adminTZFCPath;
                gp.Execute(deleteTool, trackcancel);

                // Compact the output file geodatabase

                AddMessage("Compacting the output file geodatabase...", messages, trackcancel);

                Compact compactTool = new Compact();
                compactTool.in_workspace = outputFileGdbPath;
                gp.Execute(compactTool, trackcancel);
            }
            catch (Exception e)
            {
                if (gp.MaxSeverity == 2)
                {
                    object missing = System.Type.Missing;
                    messages.AddError(1, gp.GetMessages(ref missing));
                }
                messages.AddError(1, e.Message);
                messages.AddError(1, e.StackTrace);
            }
            finally
            {
                // Restore the original GP environment settings

                gpSettings.AddOutputsToMap = origAddOutputsToMapSetting;
                gpSettings.LogHistory = origLogHistorySetting;
            }
            GC.Collect();
            return;
        }
Пример #14
0
        /// <summary>
        /// Adds the attribute columns.
        /// </summary>
        private void AddDynamicControls()
        {
            // remove Family Campus columns
            foreach (var column in pnlGroupMembers.Columns
                     .OfType <RockLiteralField>()
                     .ToList())
            {
                pnlGroupMembers.Columns.Remove(column);
            }

            // remove Group member attribute columns
            foreach (var column in pnlGroupMembers.Columns
                     .OfType <AttributeField>().ToList())
            {
                pnlGroupMembers.Columns.Remove(column);
            }

            // remove Group member assignment columns
            foreach (var column in pnlGroupMembers.Columns
                     .OfType <LinkButtonField>().ToList())
            {
                pnlGroupMembers.Columns.Remove(column);
            }

            // remove the edit field
            foreach (var column in pnlGroupMembers.Columns
                     .OfType <EditField>().ToList())
            {
                pnlGroupMembers.Columns.Remove(column);
            }

            // Remove the delete field
            foreach (var column in pnlGroupMembers.Columns
                     .OfType <DeleteField>()
                     .ToList())
            {
                pnlGroupMembers.Columns.Remove(column);
            }

            // Set up group member attribute columns
            var rockContext           = new RockContext();
            var attributeValueService = new AttributeValueService(rockContext);

            foreach (var attribute in GetGroupAttributes())
            {
                // add the attribute data column
                var attributeColumn = pnlGroupMembers.Columns.OfType <AttributeField>().FirstOrDefault(a => a.AttributeId == attribute.Id);
                if (attributeColumn == null)
                {
                    var boundField = new AttributeField
                    {
                        DataField      = attribute.Id + attribute.Key,
                        AttributeId    = attribute.Id,
                        HeaderText     = attribute.Name,
                        SortExpression = string.Format("attribute:{0}", attribute.Id),
                    };

                    boundField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;

                    decimal needsFilled = 0;
                    if (attribute.FieldType != null)
                    {
                        var groupMemberIds  = _group.Members.Select(m => m.Id).ToList();
                        var attributeValues = attributeValueService.GetByAttributeId(attribute.Id)
                                              .Where(v => groupMemberIds.Contains((int)v.EntityId) && !(v.Value == null || v.Value.Trim() == string.Empty))
                                              .Select(v => v.Value).ToList();

                        // if the values are numeric, sum a number value
                        if (attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.INTEGER.AsGuid()) || attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.DECIMAL.AsGuid()))
                        {
                            needsFilled = attributeValues.Sum(v => v.AsDecimal());
                        }
                        else if (attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.MULTI_SELECT.AsGuid()))
                        {
                            // handles checkboxes and non-empty strings
                            needsFilled = attributeValues.Count(v => !string.IsNullOrWhiteSpace(v));
                        }
                        else
                        {
                            // handles single select and boolean
                            needsFilled = attributeValues.Count(v => v.AsBoolean());
                        }
                    }

                    if (needsFilled > 0)
                    {
                        pnlGroupMembers.ShowFooter = true;
                        boundField.FooterText      = needsFilled.ToString();
                    }

                    pnlGroupMembers.Columns.Add(boundField);
                }

                if (pnlGroupMembers.ShowFooter)
                {
                    pnlGroupMembers.Columns[1].FooterText = "Total";
                    pnlGroupMembers.Columns[1].FooterStyle.HorizontalAlign = HorizontalAlign.Left;
                }
            }

            // Add dynamic assignment columns for volunteer groups
            if (_resources != null && _group.GroupType.GroupTypePurposeValue != null && _group.GroupType.GroupTypePurposeValue.Value == "Serving Area")
            {
                foreach (var groupType in _resourceTypes.Where(gt => gt.GetAttributeValue("AllowVolunteerAssignment").AsBoolean(true)))
                {
                    if (_resources.ContainsKey(groupType.Name))
                    {
                        var resourceGroupGuid = _resources[groupType.Name];
                        if (resourceGroupGuid != null && !string.IsNullOrWhiteSpace(resourceGroupGuid.Value))
                        {
                            var parentGroup = new GroupService(rockContext).Get(resourceGroupGuid.Value.AsGuid());
                            if (parentGroup != null && parentGroup.GroupTypeId != _group.GroupTypeId)
                            {
                                var groupAssignment = new LinkButtonField();
                                groupAssignment.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                                groupAssignment.ExcelExportBehavior       = ExcelExportBehavior.NeverInclude;
                                groupAssignment.HeaderText           = parentGroup.Name;
                                groupAssignment.HeaderStyle.CssClass = "";
                                pnlGroupMembers.Columns.Add(groupAssignment);

                                var assignmentExport = new RockLiteralField();
                                assignmentExport.ID = string.Format("lAssignments_{0}", groupType.Id);
                                assignmentExport.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                                assignmentExport.ExcelExportBehavior       = ExcelExportBehavior.AlwaysInclude;
                                assignmentExport.HeaderStyle.CssClass      = "";
                                assignmentExport.HeaderText = parentGroup.Name;
                                assignmentExport.Visible    = false;
                                pnlGroupMembers.Columns.Add(assignmentExport);
                            }
                        }
                    }
                }
            }

            // Add edit column
            var editField = new EditField();

            pnlGroupMembers.Columns.Add(editField);
            editField.Click += pnlGroupMembers_EditClick;

            // Add delete column
            var deleteField = new DeleteField();

            pnlGroupMembers.Columns.Add(deleteField);
            deleteField.Click += pnlGroupMembers_DeleteClick;
        }
Пример #15
0
        protected void AddDynamicControls(ContentChannel channel)
        {
            // Remove all columns
            gContentChannelItems.Columns.Clear();
            phAttributeFilters.Controls.Clear();

            if (channel != null)
            {
                // Add Reorder column
                var reorderField = new ReorderField();
                gContentChannelItems.Columns.Add(reorderField);

                // Add Title column
                var titleField = new BoundField();
                titleField.DataField      = "Title";
                titleField.HeaderText     = "Title";
                titleField.SortExpression = "Title";
                gContentChannelItems.Columns.Add(titleField);

                // Add Attribute columns
                int    entityTypeId  = EntityTypeCache.Get(typeof(Rock.Model.ContentChannelItem)).Id;
                string channelId     = channel.Id.ToString();
                string channelTypeId = channel.ContentChannelTypeId.ToString();
                foreach (var attribute in AvailableAttributes)
                {
                    var control = attribute.FieldType.Field.FilterControl(attribute.QualifierValues, "filter_" + attribute.Id.ToString(), false, Rock.Reporting.FilterMode.SimpleFilter);
                    if (control != null)
                    {
                        if (control is IRockControl)
                        {
                            var rockControl = (IRockControl)control;
                            rockControl.Label = attribute.Name;
                            rockControl.Help  = attribute.Description;
                            phAttributeFilters.Controls.Add(control);
                        }
                        else
                        {
                            var wrapper = new RockControlWrapper();
                            wrapper.ID    = control.ID + "_wrapper";
                            wrapper.Label = attribute.Name;
                            wrapper.Controls.Add(control);
                            phAttributeFilters.Controls.Add(wrapper);
                        }

                        string savedValue = gfFilter.GetUserPreference(MakeKeyUniqueToChannel(channel.Id, attribute.Key));
                        if (!string.IsNullOrWhiteSpace(savedValue))
                        {
                            try
                            {
                                var values = JsonConvert.DeserializeObject <List <string> >(savedValue);
                                attribute.FieldType.Field.SetFilterValues(control, attribute.QualifierValues, values);
                            }
                            catch
                            {
                                // intentionally ignore
                            }
                        }
                    }

                    string dataFieldExpression = attribute.Key;
                    bool   columnExists        = gContentChannelItems.Columns.OfType <AttributeField>().FirstOrDefault(a => a.DataField.Equals(dataFieldExpression)) != null;
                    if (!columnExists)
                    {
                        AttributeField boundField = new AttributeField();
                        boundField.DataField   = dataFieldExpression;
                        boundField.AttributeId = attribute.Id;
                        boundField.HeaderText  = attribute.Name;
                        boundField.ItemStyle.HorizontalAlign = attribute.FieldType.Field.AlignValue;
                        gContentChannelItems.Columns.Add(boundField);
                    }
                }

                if (channel.ContentChannelType.DateRangeType != ContentChannelDateType.NoDates)
                {
                    RockBoundField startDateTimeField;
                    RockBoundField expireDateTimeField;
                    if (channel.ContentChannelType.IncludeTime)
                    {
                        startDateTimeField  = new DateTimeField();
                        expireDateTimeField = new DateTimeField();
                    }
                    else
                    {
                        startDateTimeField  = new DateField();
                        expireDateTimeField = new DateField();
                    }

                    startDateTimeField.DataField      = "StartDateTime";
                    startDateTimeField.HeaderText     = channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Date";
                    startDateTimeField.SortExpression = "StartDateTime";
                    gContentChannelItems.Columns.Add(startDateTimeField);

                    expireDateTimeField.DataField      = "ExpireDateTime";
                    expireDateTimeField.HeaderText     = "Expire";
                    expireDateTimeField.SortExpression = "ExpireDateTime";
                    if (channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange)
                    {
                        gContentChannelItems.Columns.Add(expireDateTimeField);
                    }
                }

                if (!channel.ContentChannelType.DisablePriority)
                {
                    // Priority column
                    var priorityField = new BoundField();
                    priorityField.DataField                 = "Priority";
                    priorityField.HeaderText                = "Priority";
                    priorityField.SortExpression            = "Priority";
                    priorityField.DataFormatString          = "{0:N0}";
                    priorityField.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                    gContentChannelItems.Columns.Add(priorityField);
                }

                // Status column
                if (channel.RequiresApproval)
                {
                    var statusField = new BoundField();
                    gContentChannelItems.Columns.Add(statusField);
                    statusField.DataField      = "Status";
                    statusField.HeaderText     = "Status";
                    statusField.SortExpression = "Status";
                    statusField.HtmlEncode     = false;
                }

                // Add occurrences Count column
                var occurrencesField = new BoolField();
                occurrencesField.DataField  = "Occurrences";
                occurrencesField.HeaderText = "Event Occurrences";
                gContentChannelItems.Columns.Add(occurrencesField);

                // Add Created By column
                var createdByPersonNameField = new BoundField();
                createdByPersonNameField.DataField  = "CreatedByPersonName";
                createdByPersonNameField.HeaderText = "Created By";
                createdByPersonNameField.HtmlEncode = false;
                gContentChannelItems.Columns.Add(createdByPersonNameField);

                // Add Tag Field
                if (channel.IsTaggingEnabled)
                {
                    var tagField = new BoundField();
                    gContentChannelItems.Columns.Add(tagField);
                    tagField.DataField          = "Tags";
                    tagField.HeaderText         = "Tags";
                    tagField.ItemStyle.CssClass = "taglist";
                    tagField.HtmlEncode         = false;
                }

                bool canEditChannel = channel.IsAuthorized(Rock.Security.Authorization.EDIT, CurrentPerson);
                gContentChannelItems.Actions.ShowAdd = canEditChannel;
                gContentChannelItems.IsDeleteEnabled = canEditChannel;
                if (canEditChannel)
                {
                    var deleteField = new DeleteField();
                    gContentChannelItems.Columns.Add(deleteField);
                    deleteField.Click += gContentChannelItems_Delete;
                }
            }
        }
Пример #16
0
        /// <summary>
        /// Adds the attribute columns.
        /// </summary>
        private void AddDynamicControls()
        {
            // Clear the filter controls
            phAttributeFilters.Controls.Clear();

            var deleteCol = gConnectionOpportunities.Columns.OfType <DeleteField>().FirstOrDefault();

            if (deleteCol != null)
            {
                gConnectionOpportunities.Columns.Remove(deleteCol);
            }

            var securityCol = gConnectionOpportunities.Columns.OfType <SecurityField>().FirstOrDefault();

            if (securityCol != null)
            {
                gConnectionOpportunities.Columns.Remove(securityCol);
            }

            // Remove attribute columns
            foreach (var column in gConnectionOpportunities.Columns.OfType <AttributeField>().ToList())
            {
                gConnectionOpportunities.Columns.Remove(column);
            }

            if (AvailableAttributes != null)
            {
                foreach (var attribute in AvailableAttributes)
                {
                    var control = attribute.FieldType.Field.FilterControl(attribute.QualifierValues, "filter_" + attribute.Id.ToString(), false, Rock.Reporting.FilterMode.SimpleFilter);
                    if (control != null)
                    {
                        if (control is IRockControl)
                        {
                            var rockControl = (IRockControl)control;
                            rockControl.Label = attribute.Name;
                            rockControl.Help  = attribute.Description;
                            phAttributeFilters.Controls.Add(control);
                        }
                        else
                        {
                            var wrapper = new RockControlWrapper();
                            wrapper.ID    = control.ID + "_wrapper";
                            wrapper.Label = attribute.Name;
                            wrapper.Controls.Add(control);
                            phAttributeFilters.Controls.Add(wrapper);
                        }

                        string savedValue = rFilter.GetUserPreference(MakeKeyUniqueToConnectionType(attribute.Key));
                        if (!string.IsNullOrWhiteSpace(savedValue))
                        {
                            try
                            {
                                var values = JsonConvert.DeserializeObject <List <string> >(savedValue);
                                attribute.FieldType.Field.SetFilterValues(control, attribute.QualifierValues, values);
                            }
                            catch { }
                        }
                    }

                    string dataFieldExpression = attribute.Key;
                    bool   columnExists        = gConnectionOpportunities.Columns.OfType <AttributeField>().FirstOrDefault(a => a.DataField.Equals(dataFieldExpression)) != null;
                    if (!columnExists)
                    {
                        AttributeField boundField = new AttributeField();
                        boundField.DataField   = dataFieldExpression;
                        boundField.AttributeId = attribute.Id;
                        boundField.HeaderText  = attribute.Name;

                        var attributeCache = Rock.Web.Cache.AttributeCache.Read(attribute.Id);
                        if (attributeCache != null)
                        {
                            boundField.ItemStyle.HorizontalAlign = attributeCache.FieldType.Field.AlignValue;
                        }

                        gConnectionOpportunities.Columns.Add(boundField);
                    }
                }
            }

            securityCol              = new SecurityField();
            securityCol.TitleField   = "Name";
            securityCol.EntityTypeId = EntityTypeCache.Read(typeof(Rock.Model.ConnectionOpportunity)).Id;
            gConnectionOpportunities.Columns.Add(securityCol);

            deleteCol = new DeleteField();
            gConnectionOpportunities.Columns.Add(deleteCol);
            deleteCol.Click += DeleteConnectionOpportunity_Click;
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            // set person context
            var contextEntity = this.ContextEntity();

            if (contextEntity != null)
            {
                if (contextEntity is Person)
                {
                    _person = contextEntity as Person;
                }
            }

            // set person if grid should be filtered by the current person
            if (GetAttributeValue("FilterItemsForCurrentUser").AsBoolean())
            {
                _person = CurrentPerson;
            }

            gfFilter.Visible = GetAttributeValue("ShowFilters").AsBoolean();

            if (string.IsNullOrWhiteSpace(GetAttributeValue("ContentChannel")))
            {
                _channelId = PageParameter("contentChannelId").AsIntegerOrNull();
            }
            else
            {
                _channelId = new ContentChannelService(new RockContext()).Get(GetAttributeValue("ContentChannel").AsGuid()).Id;
            }

            if (_channelId != null)
            {
                upnlContent.Visible = true;

                string cssIcon        = "fa fa-bullhorn";
                var    contentChannel = new ContentChannelService(new RockContext()).Get(_channelId.Value);
                if (contentChannel != null)
                {
                    string startHeading = contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Active";

                    _manuallyOrdered = contentChannel.ItemsManuallyOrdered;

                    var startDateTimeColumn  = gItems.ColumnsWithDataField("StartDateTime").OfType <DateTimeField>().FirstOrDefault();
                    var expireDateTimeColumn = gItems.ColumnsWithDataField("ExpireDateTime").OfType <DateTimeField>().FirstOrDefault();
                    var startDateColumn      = gItems.ColumnsWithDataField("StartDateTime").OfType <DateField>().FirstOrDefault();
                    var expireDateColumn     = gItems.ColumnsWithDataField("ExpireDateTime").OfType <DateField>().FirstOrDefault();
                    var priorityColumn       = gItems.ColumnsWithDataField("Priority").FirstOrDefault();

                    //// NOTE: The EventOccurrences Column's visibility is set in GridBind()

                    startDateTimeColumn.HeaderText = startHeading;
                    startDateColumn.HeaderText     = startHeading;

                    ddlStatus.Visible = contentChannel.RequiresApproval && !contentChannel.ContentChannelType.DisableStatus;

                    if (contentChannel.ContentChannelType.IncludeTime)
                    {
                        startDateTimeColumn.Visible  = contentChannel.ContentChannelType.DateRangeType != ContentChannelDateType.NoDates;
                        expireDateTimeColumn.Visible = contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange && GetAttributeValue("ShowExpireColumn").AsBoolean();
                        startDateColumn.Visible      = false;
                        expireDateColumn.Visible     = false;
                    }
                    else
                    {
                        startDateTimeColumn.Visible  = false;
                        expireDateTimeColumn.Visible = false;
                        startDateColumn.Visible      = contentChannel.ContentChannelType.DateRangeType != ContentChannelDateType.NoDates;
                        expireDateColumn.Visible     = contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange && GetAttributeValue("ShowExpireColumn").AsBoolean();
                    }

                    priorityColumn.Visible = !contentChannel.ContentChannelType.DisablePriority && GetAttributeValue("ShowPriorityColumn").AsBoolean();

                    var securityColumn = gItems.Columns.OfType <SecurityField>().FirstOrDefault();
                    if (securityColumn != null)
                    {
                        securityColumn.Visible = GetAttributeValue("ShowSecurityColumn").AsBoolean();
                    }

                    lContentChannel.Text = contentChannel.Name;
                    _typeId = contentChannel.ContentChannelTypeId;

                    if (!string.IsNullOrWhiteSpace(contentChannel.IconCssClass))
                    {
                        cssIcon = contentChannel.IconCssClass;
                    }
                }

                lIcon.Text = string.Format("<i class='{0}'></i>", cssIcon);

                // Block Security and special attributes (RockPage takes care of View)
                bool canAddEditDelete = IsUserAuthorized(Authorization.EDIT);

                gfFilter.ApplyFilterClick   += gfFilter_ApplyFilterClick;
                gfFilter.DisplayFilterValue += gfFilter_DisplayFilterValue;

                gItems.DataKeyNames      = new string[] { "Id" };
                gItems.AllowSorting      = !_manuallyOrdered;
                gItems.Actions.ShowAdd   = canAddEditDelete;
                gItems.IsDeleteEnabled   = canAddEditDelete;
                gItems.Actions.AddClick += gItems_Add;
                gItems.GridRebind       += gItems_GridRebind;
                gItems.GridReorder      += GItems_GridReorder;
                gItems.EntityTypeId      = EntityTypeCache.Read <ContentChannelItem>().Id;

                AddAttributeColumns();

                if (contentChannel != null && contentChannel.RequiresApproval && !contentChannel.ContentChannelType.DisableStatus)
                {
                    var statusField = new BoundField();
                    gItems.Columns.Add(statusField);
                    statusField.DataField      = "Status";
                    statusField.HeaderText     = "Status";
                    statusField.SortExpression = "Status";
                    statusField.HtmlEncode     = false;
                }

                var securityField = new SecurityField();
                gItems.Columns.Add(securityField);
                securityField.TitleField   = "Title";
                securityField.EntityTypeId = EntityTypeCache.Read(typeof(Rock.Model.ContentChannelItem)).Id;

                var deleteField = new DeleteField();
                gItems.Columns.Add(deleteField);
                deleteField.Click += gItems_Delete;

                // this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it
                this.BlockUpdated += Block_BlockUpdated;
                this.AddConfigurationUpdateTrigger(upnlContent);
            }
            else
            {
                upnlContent.Visible = false;
            }
        }
Пример #18
0
 protected Task On(DeleteField command, CommandContext context)
 {
     return(handler.UpdateAsync <SchemaDomainObject>(context, s => s.DeleteField(command)));
 }
Пример #19
0
        private void AddDynamicControls()
        {
            if (AvailableAttributes != null)
            {
                foreach (var attribute in AvailableAttributes)
                {
                    var control = attribute.FieldType.Field.FilterControl(attribute.QualifierValues, "filter_" + attribute.Id.ToString(), false, Rock.Reporting.FilterMode.SimpleFilter);
                    if (control != null)
                    {
                        if (control is IRockControl)
                        {
                            var rockControl = ( IRockControl )control;
                            rockControl.Label = attribute.Name;
                            rockControl.Help  = attribute.Description;
                            phAttributeFilters.Controls.Add(control);
                        }
                        else
                        {
                            var wrapper = new RockControlWrapper();
                            wrapper.ID    = control.ID + "_wrapper";
                            wrapper.Label = attribute.Name;
                            wrapper.Controls.Add(control);
                            phAttributeFilters.Controls.Add(wrapper);
                        }

                        string savedValue = rFilter.GetUserPreference(attribute.Key);
                        if (!string.IsNullOrWhiteSpace(savedValue))
                        {
                            try
                            {
                                var values = JsonConvert.DeserializeObject <List <string> >(savedValue);
                                attribute.FieldType.Field.SetFilterValues(control, attribute.QualifierValues, values);
                            }
                            catch
                            {
                                // intentionally ignore
                            }
                        }
                    }

                    bool columnExists = gList.Columns.OfType <AttributeField>().FirstOrDefault(a => a.AttributeId == attribute.Id) != null;
                    if (!columnExists)
                    {
                        AttributeField boundField = new AttributeField();
                        boundField.DataField   = attribute.Key;
                        boundField.AttributeId = attribute.Id;
                        boundField.HeaderText  = attribute.Name;

                        var attributeCache = Rock.Web.Cache.AttributeCache.Get(attribute.Id);
                        if (attributeCache != null)
                        {
                            boundField.ItemStyle.HorizontalAlign = attributeCache.FieldType.Field.AlignValue;
                        }

                        gList.Columns.Add(boundField);
                    }
                }
            }

            // Add delete column
            var deleteField = new DeleteField();

            gList.Columns.Add(deleteField);
            deleteField.Click += gList_Delete;
        }
Пример #20
0
        /// <summary>
        /// Adds the attribute columns.
        /// </summary>
        private void AddDynamicControls()
        {
            // Clear the filter controls
            phAttributeFilters.Controls.Clear();

            // Remove attribute columns
            foreach (var column in gGroupMembers.Columns.OfType <AttributeField>().ToList())
            {
                gGroupMembers.Columns.Remove(column);
            }

            if (AvailableAttributes != null)
            {
                foreach (var attribute in AvailableAttributes)
                {
                    var control = attribute.FieldType.Field.FilterControl(attribute.QualifierValues, "filter_" + attribute.Id.ToString(), false);
                    if (control != null)
                    {
                        if (control is IRockControl)
                        {
                            var rockControl = (IRockControl)control;
                            rockControl.Label = attribute.Name;
                            rockControl.Help  = attribute.Description;
                            phAttributeFilters.Controls.Add(control);
                        }
                        else
                        {
                            var wrapper = new RockControlWrapper();
                            wrapper.ID    = control.ID + "_wrapper";
                            wrapper.Label = attribute.Name;
                            wrapper.Controls.Add(control);
                            phAttributeFilters.Controls.Add(wrapper);
                        }

                        string savedValue = rFilter.GetUserPreference(MakeKeyUniqueToGroup(attribute.Key));
                        if (!string.IsNullOrWhiteSpace(savedValue))
                        {
                            try
                            {
                                var values = JsonConvert.DeserializeObject <List <string> >(savedValue);
                                attribute.FieldType.Field.SetFilterValues(control, attribute.QualifierValues, values);
                            }
                            catch { }
                        }
                    }

                    string dataFieldExpression = attribute.Key;
                    bool   columnExists        = gGroupMembers.Columns.OfType <AttributeField>().FirstOrDefault(a => a.DataField.Equals(dataFieldExpression)) != null;
                    if (!columnExists)
                    {
                        AttributeField boundField = new AttributeField();
                        boundField.DataField      = dataFieldExpression;
                        boundField.HeaderText     = attribute.Name;
                        boundField.SortExpression = string.Empty;

                        var attributeCache = Rock.Web.Cache.AttributeCache.Read(attribute.Id);
                        if (attributeCache != null)
                        {
                            boundField.ItemStyle.HorizontalAlign = attributeCache.FieldType.Field.AlignValue;
                        }

                        gGroupMembers.Columns.Add(boundField);
                    }
                }
            }

            // Add Link to Profile Page Column
            if (!string.IsNullOrEmpty(GetAttributeValue("PersonProfilePage")))
            {
                AddPersonProfileLinkColumn();
            }

            // Add delete column
            var deleteField = new DeleteField();

            gGroupMembers.Columns.Add(deleteField);
            deleteField.Click += DeleteGroupMember_Click;
        }
        public void Execute(IArray paramvalues, ITrackCancel trackcancel,
                            IGPEnvironmentManager envMgr, IGPMessages messages)
        {
            // Remember the original GP environment settings and temporarily override these settings

            var gpSettings = envMgr as IGeoProcessorSettings;
            bool origAddOutputsToMapSetting = gpSettings.AddOutputsToMap;
            bool origLogHistorySetting = gpSettings.LogHistory;
            gpSettings.AddOutputsToMap = false;
            gpSettings.LogHistory = false;

            // Create the Geoprocessor

            Geoprocessor gp = new Geoprocessor();

            try
            {
                // Validate our values

                IGPMessages validateMessages = ((IGPFunction2)this).Validate(paramvalues, false, envMgr);
                if ((validateMessages as IGPMessage).IsError())
                {
                    messages.AddError(1, "Validate failed");
                    return;
                }

                // Unpack values

                IGPParameter gpParam = paramvalues.get_Element(InputMtdDSTTable) as IGPParameter;
                IGPValue inputMtdDSTTableValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputMtdCntryRefTable) as IGPParameter;
                IGPValue inputMtdCntryRefTableValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputMtdAreaTable) as IGPParameter;
                IGPValue inputMtdAreaTableValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputAdminBndyFeatureClasses) as IGPParameter;
                var inputAdminBndyFeatureClassesMultiValue = m_gpUtils.UnpackGPValue(gpParam) as IGPMultiValue;
                gpParam = paramvalues.get_Element(OutputFileGDB) as IGPParameter;
                IGPValue outputFileGDBValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputStreetsFeatureClass) as IGPParameter;
                IGPValue inputStreetsFeatureClassValue = m_gpUtils.UnpackGPValue(gpParam);
                gpParam = paramvalues.get_Element(InputTimeZoneIDBaseFieldName) as IGPParameter;
                IGPValue inputTimeZoneIDBaseFieldNameValue = m_gpUtils.UnpackGPValue(gpParam);

                bool processStreetsFC = (!(inputStreetsFeatureClassValue.IsEmpty()));
                string timeZoneIDBaseFieldName = "";
                if (!(inputTimeZoneIDBaseFieldNameValue.IsEmpty()))
                    timeZoneIDBaseFieldName = inputTimeZoneIDBaseFieldNameValue.GetAsText();

                // Get the path to the output file GDB

                string outputFileGdbPath = outputFileGDBValue.GetAsText();

                // Create the new file geodatabase

                AddMessage("Creating the file geodatabase...", messages, trackcancel);

                int lastBackslash = outputFileGdbPath.LastIndexOf("\\");
                CreateFileGDB createFGDBTool = new CreateFileGDB();
                createFGDBTool.out_folder_path = outputFileGdbPath.Remove(lastBackslash);
                createFGDBTool.out_name = outputFileGdbPath.Substring(lastBackslash + 1);
                gp.Execute(createFGDBTool, trackcancel);

                // Copy the MtdDST table to the file geodatabase and add the ADMIN_LVL and AREACODE fields to it

                AddMessage("Copying the MtdDST table to the file geodatabase...", messages, trackcancel);

                TableToTable importTableTool = new TableToTable();
                string inputMtdDSTTablePath = inputMtdDSTTableValue.GetAsText();
                importTableTool.in_rows = inputMtdDSTTablePath;
                importTableTool.out_path = outputFileGdbPath;
                importTableTool.out_name = "MtdDST";
                importTableTool.field_mapping = "AREA_ID \"AREA_ID\" true true false 4 Long 0 0 ,First,#," + inputMtdDSTTablePath + ",AREA_ID,-1,-1;" +
                                                "TIME_ZONE \"TIME_ZONE\" true true false 4 Text 0 0 ,First,#," + inputMtdDSTTablePath + ",TIME_ZONE,-1,-1;" +
                                                "DST_EXIST \"DST_EXIST\" true true false 1 Text 0 0 ,First,#," + inputMtdDSTTablePath + ",DST_EXIST,-1,-1";
                gp.Execute(importTableTool, trackcancel);

                string mtdDSTTablePath = outputFileGdbPath + "\\MtdDST";

                AddField addFieldTool = new AddField();
                addFieldTool.in_table = mtdDSTTablePath;
                addFieldTool.field_name = "ADMIN_LVL";
                addFieldTool.field_type = "SHORT";
                gp.Execute(addFieldTool, trackcancel);

                addFieldTool = new AddField();
                addFieldTool.in_table = mtdDSTTablePath;
                addFieldTool.field_name = "AREACODE";
                addFieldTool.field_type = "TEXT";
                addFieldTool.field_length = 76;
                gp.Execute(addFieldTool, trackcancel);

                // Copy the MtdArea table to the file geodatabase and index the AREA_ID field

                AddMessage("Copying the MtdArea table to the file geodatabase...", messages, trackcancel);

                importTableTool = new TableToTable();
                importTableTool.in_rows = inputMtdAreaTableValue.GetAsText();
                importTableTool.out_path = outputFileGdbPath;
                importTableTool.out_name = "MtdArea";
                gp.Execute(importTableTool, trackcancel);

                string mtdAreaTablePath = outputFileGdbPath + "\\MtdArea";

                AddIndex addIndexTool = new AddIndex();
                addIndexTool.in_table = mtdAreaTablePath;
                addIndexTool.fields = "AREA_ID";
                addIndexTool.index_name = "AREA_ID";
                gp.Execute(addIndexTool, trackcancel);

                // Calculate the ADMIN_LVL and AREACODE fields on the MtdDST table

                MakeTableView makeTableViewTool = new MakeTableView();
                makeTableViewTool.in_table = mtdDSTTablePath;
                makeTableViewTool.out_view = "MtdDST_Layer";
                gp.Execute(makeTableViewTool, trackcancel);

                AddJoin addJoinTool = new AddJoin();
                addJoinTool.in_layer_or_view = "MtdDST_Layer";
                addJoinTool.in_field = "AREA_ID";
                addJoinTool.join_table = mtdAreaTablePath;
                addJoinTool.join_field = "AREA_ID";
                addJoinTool.join_type = "KEEP_COMMON";
                gp.Execute(addJoinTool, trackcancel);

                AddMessage("Calculating the ADMIN_LVL field...", messages, trackcancel);

                CalculateField calcFieldTool = new CalculateField();
                calcFieldTool.in_table = "MtdDST_Layer";
                calcFieldTool.field = "MtdDST.ADMIN_LVL";
                calcFieldTool.expression = "[MtdArea.ADMIN_LVL]";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                AddMessage("Calculating the AREACODE field...", messages, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = "MtdDST_Layer";
                calcFieldTool.field = "MtdDST.AREACODE";
                calcFieldTool.code_block = "lvl = [MtdArea.ADMIN_LVL]\n" +
                                           "s = CStr([MtdArea.AREACODE_1])\n" +
                                           "If lvl >= 2 Then s = s & \".\" & CStr([MtdArea.AREACODE_2])\n" +
                                           "If lvl >= 3 Then s = s & \".\" & CStr([MtdArea.AREACODE_3])\n" +
                                           "If lvl >= 4 Then s = s & \".\" & CStr([MtdArea.AREACODE_4])\n" +
                                           "If lvl >= 5 Then s = s & \".\" & CStr([MtdArea.AREACODE_5])\n" +
                                           "If lvl >= 6 Then s = s & \".\" & CStr([MtdArea.AREACODE_6])\n" +
                                           "If lvl >= 7 Then s = s & \".\" & CStr([MtdArea.AREACODE_7])";
                calcFieldTool.expression = "s";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                RemoveJoin removeJoinTool = new RemoveJoin();
                removeJoinTool.in_layer_or_view = "MtdDST_Layer";
                removeJoinTool.join_name = "MtdArea";
                gp.Execute(removeJoinTool, trackcancel);

                Delete deleteTool = new Delete();
                deleteTool.in_data = "MtdDST_Layer";
                gp.Execute(deleteTool, trackcancel);

                // Create the MtdDST# tables by admin levels and index the AREACODE field

                TableSelect tableSelectTool = null;
                for (int i = 1; i <= 7; i++)
                {
                    string iAsString = Convert.ToString(i, System.Globalization.CultureInfo.InvariantCulture);

                    AddMessage("Extracting level " + iAsString + " MtdDST rows...", messages, trackcancel);

                    tableSelectTool = new TableSelect();
                    tableSelectTool.in_table = mtdDSTTablePath;
                    tableSelectTool.out_table = mtdDSTTablePath + iAsString;
                    tableSelectTool.where_clause = "ADMIN_LVL = " + iAsString;
                    gp.Execute(tableSelectTool, trackcancel);

                    addIndexTool = new AddIndex();
                    addIndexTool.in_table = mtdDSTTablePath + iAsString;
                    addIndexTool.fields = "AREACODE";
                    addIndexTool.index_name = "AREACODE";
                    gp.Execute(addIndexTool, trackcancel);
                }

                deleteTool = new Delete();
                deleteTool.in_data = mtdDSTTablePath;
                gp.Execute(deleteTool, trackcancel);

                // Copy the MtdCntryRef table to the file geodatabase (use Statistics tool to remove duplicate rows)

                AddMessage("Copying the MtdCntryRef table to the file geodatabase...", messages, trackcancel);

                string inputMtdCntryRefTablePath = inputMtdCntryRefTableValue.GetAsText();
                string mtdCntryRefTablePath = outputFileGdbPath + "\\MtdCntryRef";
                Statistics statsTool = new Statistics();
                statsTool.in_table = inputMtdCntryRefTablePath;
                statsTool.out_table = mtdCntryRefTablePath;
                statsTool.statistics_fields = "ISO_CODE COUNT";
                statsTool.case_field = "GOVT_CODE;ISO_CODE;DRIVING_SD;ADMINLEVEL";
                gp.Execute(statsTool, trackcancel);

                DeleteField deleteFieldTool = new DeleteField();
                deleteFieldTool.in_table = mtdCntryRefTablePath;
                deleteFieldTool.drop_field = "FREQUENCY;COUNT_ISO_CODE";
                gp.Execute(deleteFieldTool, trackcancel);

                // Index the GOVT_CODE field

                addIndexTool = new AddIndex();
                addIndexTool.in_table = mtdCntryRefTablePath;
                addIndexTool.fields = "GOVT_CODE";
                addIndexTool.index_name = "GOVT_CODE";
                gp.Execute(addIndexTool, trackcancel);

                // Extract the top level (country) records from the MtdArea table and index the AREACODE_1 field

                AddMessage("Extracting the top-level rows from the MtdArea table...", messages, trackcancel);

                string mtdTopAreaTablePath = outputFileGdbPath + "\\TopArea";

                tableSelectTool = new TableSelect();
                tableSelectTool.in_table = mtdAreaTablePath;
                tableSelectTool.out_table = mtdTopAreaTablePath;
                tableSelectTool.where_clause = "AREACODE_2 = 0 AND AREA_TYPE = 'B'";
                gp.Execute(tableSelectTool, trackcancel);

                addIndexTool = new AddIndex();
                addIndexTool.in_table = mtdTopAreaTablePath;
                addIndexTool.fields = "AREACODE_1";
                addIndexTool.index_name = "AREACODE_1";
                gp.Execute(addIndexTool, trackcancel);

                // Create and calculate the TOP_GOVT_CODE field on the MtdArea table

                addFieldTool = new AddField();
                addFieldTool.in_table = mtdAreaTablePath;
                addFieldTool.field_name = "TOP_GOVT_CODE";
                addFieldTool.field_type = "LONG";
                gp.Execute(addFieldTool, trackcancel);

                makeTableViewTool = new MakeTableView();
                makeTableViewTool.in_table = mtdAreaTablePath;
                makeTableViewTool.out_view = "MtdArea_Layer";
                gp.Execute(makeTableViewTool, trackcancel);

                addJoinTool = new AddJoin();
                addJoinTool.in_layer_or_view = "MtdArea_Layer";
                addJoinTool.in_field = "AREACODE_1";
                addJoinTool.join_table = mtdTopAreaTablePath;
                addJoinTool.join_field = "AREACODE_1";
                addJoinTool.join_type = "KEEP_COMMON";
                gp.Execute(addJoinTool, trackcancel);

                AddMessage("Calculating the TOP_GOVT_CODE field...", messages, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = "MtdArea_Layer";
                calcFieldTool.field = "MtdArea.TOP_GOVT_CODE";
                calcFieldTool.expression = "[TopArea.GOVT_CODE]";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                removeJoinTool = new RemoveJoin();
                removeJoinTool.in_layer_or_view = "MtdArea_Layer";
                removeJoinTool.join_name = "TopArea";
                gp.Execute(removeJoinTool, trackcancel);

                deleteTool = new Delete();
                deleteTool.in_data = mtdTopAreaTablePath;
                gp.Execute(deleteTool, trackcancel);

                // Create and calculate the ISO_CODE and DRIVING_SD string fields

                addFieldTool = new AddField();
                addFieldTool.in_table = mtdAreaTablePath;
                addFieldTool.field_name = "ISO_CODE";
                addFieldTool.field_type = "TEXT";
                addFieldTool.field_length = 3;
                gp.Execute(addFieldTool, trackcancel);

                addFieldTool = new AddField();
                addFieldTool.in_table = mtdAreaTablePath;
                addFieldTool.field_name = "DRIVING_SD";
                addFieldTool.field_type = "TEXT";
                addFieldTool.field_length = 1;
                gp.Execute(addFieldTool, trackcancel);

                addJoinTool = new AddJoin();
                addJoinTool.in_layer_or_view = "MtdArea_Layer";
                addJoinTool.in_field = "TOP_GOVT_CODE";
                addJoinTool.join_table = mtdCntryRefTablePath;
                addJoinTool.join_field = "GOVT_CODE";
                addJoinTool.join_type = "KEEP_COMMON";
                gp.Execute(addJoinTool, trackcancel);

                AddMessage("Calculating the ISO_CODE field...", messages, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = "MtdArea_Layer";
                calcFieldTool.field = "MtdArea.ISO_CODE";
                calcFieldTool.expression = "[MtdCntryRef.ISO_CODE]";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                AddMessage("Calculating the DRIVING_SD field...", messages, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = "MtdArea_Layer";
                calcFieldTool.field = "MtdArea.DRIVING_SD";
                calcFieldTool.expression = "[MtdCntryRef.DRIVING_SD]";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                removeJoinTool = new RemoveJoin();
                removeJoinTool.in_layer_or_view = "MtdArea_Layer";
                removeJoinTool.join_name = "MtdCntryRef";
                gp.Execute(removeJoinTool, trackcancel);

                // Create and calculate the FullAREACODE# string fields and the UTCOffset and DST fields

                addFieldTool = new AddField();
                addFieldTool.in_table = mtdAreaTablePath;
                addFieldTool.field_type = "SHORT";
                addFieldTool.field_name = "UTCOffset";
                gp.Execute(addFieldTool, trackcancel);
                addFieldTool.field_name = "DST";
                gp.Execute(addFieldTool, trackcancel);

                string codeBlock = "lvl = [ADMIN_LVL]\ns = CStr([AREACODE_1])";
                for (int i = 1; i <= 7; i++)
                {
                    string iAsString = Convert.ToString(i, System.Globalization.CultureInfo.InvariantCulture);
                    string iPlusOne = Convert.ToString(i+1, System.Globalization.CultureInfo.InvariantCulture);
                    string fullAreaCodeFieldName = "FullAREACODE" + iAsString;
                    addFieldTool = new AddField();
                    addFieldTool.in_table = mtdAreaTablePath;
                    addFieldTool.field_name = fullAreaCodeFieldName;
                    addFieldTool.field_type = "TEXT";
                    addFieldTool.field_length = 76;
                    gp.Execute(addFieldTool, trackcancel);

                    AddMessage("Calculating the FullAREACODE" + iAsString + " field...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = mtdAreaTablePath;
                    calcFieldTool.field = fullAreaCodeFieldName;
                    calcFieldTool.code_block = codeBlock;
                    calcFieldTool.expression = "s";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);
                    codeBlock = codeBlock + "\nIf lvl >= " + iPlusOne + " Then s = s & \".\" & CStr([AREACODE_" + iPlusOne + "])";

                    string dstJoinTableName = "MtdDST" + iAsString;
                    string dstJoinTablePath = outputFileGdbPath + "\\" + dstJoinTableName;

                    addJoinTool = new AddJoin();
                    addJoinTool.in_layer_or_view = "MtdArea_Layer";
                    addJoinTool.in_field = fullAreaCodeFieldName;
                    addJoinTool.join_table = dstJoinTablePath;
                    addJoinTool.join_field = "AREACODE";
                    addJoinTool.join_type = "KEEP_COMMON";
                    gp.Execute(addJoinTool, trackcancel);

                    AddMessage("Calculating the UTCOffset field (" + iAsString + " of 7)...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "MtdArea_Layer";
                    calcFieldTool.field = "MtdArea.UTCOffset";
                    calcFieldTool.code_block = "s = [MtdArea.UTCOffset]\n" +
                                               "joinValue = [" + dstJoinTableName + ".TIME_ZONE]\n" +
                                               "If Not IsNull(joinValue) Then\n" +
                                               "  If Trim(joinValue) <> \"\" Then s = CInt(joinValue) * 6\n" +
                                               "End If";
                    calcFieldTool.expression = "s";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    AddMessage("Calculating the DST field (" + iAsString + " of 7)...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "MtdArea_Layer";
                    calcFieldTool.field = "MtdArea.DST";
                    calcFieldTool.code_block = "s = [MtdArea.DST]\n" +
                                               "joinValue = [" + dstJoinTableName + ".DST_EXIST]\n" +
                                               "If Not IsNull(joinValue) Then\n" +
                                               "  Select Case Trim(joinValue)\n" +
                                               "    Case \"Y\": s = 1\n    Case \"N\": s = 0\n" +
                                               "  End Select\n" +
                                               "End If";
                    calcFieldTool.expression = "s";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    removeJoinTool = new RemoveJoin();
                    removeJoinTool.in_layer_or_view = "MtdArea_Layer";
                    removeJoinTool.join_name = dstJoinTableName;
                    gp.Execute(removeJoinTool, trackcancel);

                    deleteTool = new Delete();
                    deleteTool.in_data = dstJoinTablePath;
                    gp.Execute(deleteTool, trackcancel);
                }

                deleteTool = new Delete();
                deleteTool.in_data = "MtdArea_Layer";
                gp.Execute(deleteTool, trackcancel);

                // Create and calculate the sortable MSTIMEZONE field on the MtdArea table

                addFieldTool = new AddField();
                addFieldTool.in_table = mtdAreaTablePath;
                addFieldTool.field_name = "SortableMSTIMEZONE";
                addFieldTool.field_type = "TEXT";
                addFieldTool.field_length = 60;
                gp.Execute(addFieldTool, trackcancel);

                AddMessage("Calculating the time zones...", messages, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = mtdAreaTablePath;
                calcFieldTool.field = "SortableMSTIMEZONE";
                calcFieldTool.code_block = TimeZoneUtilities.MakeSortableMSTIMEZONECode("ISO_CODE");
                calcFieldTool.expression = "z";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                // Extract the MtdArea rows to be used for generating the time zone polygons and index the AREA_ID field

                string mtdAreaForTZPolysTablePath = outputFileGdbPath + "\\MtdAreaForTZPolys";
                tableSelectTool = new TableSelect();
                tableSelectTool.in_table = mtdAreaTablePath;
                tableSelectTool.out_table = mtdAreaForTZPolysTablePath;
                tableSelectTool.where_clause = CreateWhereClauseForAdminLvlByCountry(outputFileGdbPath, "MtdCntryRef");
                gp.Execute(tableSelectTool, trackcancel);

                addIndexTool = new AddIndex();
                addIndexTool.in_table = mtdAreaForTZPolysTablePath;
                addIndexTool.fields = "AREA_ID";
                addIndexTool.index_name = "AREA_ID";
                gp.Execute(addIndexTool, trackcancel);

                // We no longer need the MtdCntryRef table anymore

                deleteTool = new Delete();
                deleteTool.in_data = mtdCntryRefTablePath;
                gp.Execute(deleteTool, trackcancel);

                // Merge the AdminBndy feature classes together into one feature class

                int numAdminBndyFCs = inputAdminBndyFeatureClassesMultiValue.Count;
                string mergeToolInputs = "";
                for (int i = 0; i < numAdminBndyFCs; i++)
                {
                    mergeToolInputs = mergeToolInputs + inputAdminBndyFeatureClassesMultiValue.get_Value(i).GetAsText() + ";";
                }
                mergeToolInputs = mergeToolInputs.Remove(mergeToolInputs.Length - 1);
                string adminBndyFCPath = outputFileGdbPath + "\\AdminBndy";

                AddMessage("Merging the Administrative Boundary feature classes...", messages, trackcancel);

                Merge mergeTool = new Merge();
                mergeTool.inputs = mergeToolInputs;
                mergeTool.output = adminBndyFCPath;
                gp.Execute(mergeTool, trackcancel);

                // Join the AdminBndy polygons to the MtdArea rows to be used for generating the time zone polygons

                MakeFeatureLayer makeFeatureLayerTool = new MakeFeatureLayer();
                makeFeatureLayerTool.in_features = adminBndyFCPath;
                makeFeatureLayerTool.out_layer = "AdminBndy_Layer";
                gp.Execute(makeFeatureLayerTool, trackcancel);

                addJoinTool = new AddJoin();
                addJoinTool.in_layer_or_view = "AdminBndy_Layer";
                addJoinTool.in_field = "AREA_ID";
                addJoinTool.join_table = mtdAreaForTZPolysTablePath;
                addJoinTool.join_field = "AREA_ID";
                addJoinTool.join_type = "KEEP_COMMON";
                gp.Execute(addJoinTool, trackcancel);

                FeatureClassToFeatureClass importFCTool = new FeatureClassToFeatureClass();
                importFCTool.in_features = "AdminBndy_Layer";
                importFCTool.out_path = outputFileGdbPath;
                importFCTool.out_name = "UndissolvedTZPolys";
                importFCTool.field_mapping = "SortableMSTIMEZONE \"SortableMSTIMEZONE\" true true false 60 Text 0 0 ,First,#," +
                                             mtdAreaForTZPolysTablePath + ",MtdAreaForTZPolys.SortableMSTIMEZONE,-1,-1";
                gp.Execute(importFCTool, trackcancel);
                string undissolvedTZPolysFCPath = outputFileGdbPath + "\\UndissolvedTZPolys";

                removeJoinTool = new RemoveJoin();
                removeJoinTool.in_layer_or_view = "AdminBndy_Layer";
                removeJoinTool.join_name = "MtdAreaForTZPolys";
                gp.Execute(removeJoinTool, trackcancel);

                deleteTool = new Delete();
                deleteTool.in_data = "AdminBndy_Layer";
                gp.Execute(deleteTool, trackcancel);

                deleteTool = new Delete();
                deleteTool.in_data = adminBndyFCPath;
                gp.Execute(deleteTool, trackcancel);
                deleteTool.in_data = mtdAreaForTZPolysTablePath;
                gp.Execute(deleteTool, trackcancel);

                // Dissolve the time zone polygons together

                AddMessage("Dissolving the time zones...", messages, trackcancel);

                string timeZoneFCPath = outputFileGdbPath + "\\" + TimeZoneFCName;
                Dissolve dissolveTool = new Dissolve();
                dissolveTool.in_features = undissolvedTZPolysFCPath;
                dissolveTool.out_feature_class = timeZoneFCPath;
                dissolveTool.dissolve_field = "SortableMSTIMEZONE";
                dissolveTool.multi_part = "MULTI_PART";
                gp.Execute(dissolveTool, trackcancel);

                deleteTool = new Delete();
                deleteTool.in_data = undissolvedTZPolysFCPath;
                gp.Execute(deleteTool, trackcancel);

                // Create and calculate the MSTIMEZONE field

                addFieldTool = new AddField();
                addFieldTool.in_table = timeZoneFCPath;
                addFieldTool.field_name = "MSTIMEZONE";
                addFieldTool.field_type = "TEXT";
                addFieldTool.field_length = 50;
                gp.Execute(addFieldTool, trackcancel);

                AddMessage("Calculating the time zones...", messages, trackcancel);

                calcFieldTool = new CalculateField();
                calcFieldTool.in_table = timeZoneFCPath;
                calcFieldTool.field = "MSTIMEZONE";
                calcFieldTool.expression = "Mid([SortableMSTIMEZONE], 7)";
                calcFieldTool.expression_type = "VB";
                gp.Execute(calcFieldTool, trackcancel);

                // Delete the old sortable MSTIMEZONE field

                deleteFieldTool = new DeleteField();
                deleteFieldTool.in_table = timeZoneFCPath;
                deleteFieldTool.drop_field = "SortableMSTIMEZONE";
                gp.Execute(deleteFieldTool, trackcancel);

                if (processStreetsFC)
                {
                    // Create the network dataset time zone table

                    AddMessage("Creating the time zones table...", messages, trackcancel);

                    importTableTool = new TableToTable();
                    importTableTool.in_rows = timeZoneFCPath;
                    importTableTool.out_path = outputFileGdbPath;
                    importTableTool.out_name = TimeZonesTableName;
                    importTableTool.field_mapping = "MSTIMEZONE \"MSTIMEZONE\" true true false 50 Text 0 0 ,First,#," +
                                                    timeZoneFCPath + ",MSTIMEZONE,-1,-1";
                    gp.Execute(importTableTool, trackcancel);

                    // Separate the MtdArea table by driving side and index the AREA_ID field on each

                    AddMessage("Extracting rows for the left-side driving areas...", messages, trackcancel);

                    string drivingLTablePath = mtdAreaTablePath + "DrivingL";
                    string drivingRTablePath = mtdAreaTablePath + "DrivingR";

                    tableSelectTool = new TableSelect();
                    tableSelectTool.in_table = mtdAreaTablePath;
                    tableSelectTool.out_table = drivingLTablePath;
                    tableSelectTool.where_clause = "DRIVING_SD = 'L'";
                    gp.Execute(tableSelectTool, trackcancel);

                    addIndexTool = new AddIndex();
                    addIndexTool.in_table = drivingLTablePath;
                    addIndexTool.fields = "AREA_ID";
                    addIndexTool.index_name = "AREA_ID";
                    gp.Execute(addIndexTool, trackcancel);

                    AddMessage("Extracting rows for the right-side driving areas...", messages, trackcancel);

                    tableSelectTool = new TableSelect();
                    tableSelectTool.in_table = mtdAreaTablePath;
                    tableSelectTool.out_table = drivingRTablePath;
                    tableSelectTool.where_clause = "DRIVING_SD = 'R'";
                    gp.Execute(tableSelectTool, trackcancel);

                    addIndexTool = new AddIndex();
                    addIndexTool.in_table = drivingRTablePath;
                    addIndexTool.fields = "AREA_ID";
                    addIndexTool.index_name = "AREA_ID";
                    gp.Execute(addIndexTool, trackcancel);

                    // Import the Streets feature class to the file geodatabase and
                    // add the FT_TimeZoneID and TF_TimeZoneID fields

                    AddMessage("Copying the Streets feature class to the geodatabase...", messages, trackcancel);

                    importFCTool = new FeatureClassToFeatureClass();
                    importFCTool.in_features = inputStreetsFeatureClassValue.GetAsText();
                    importFCTool.out_path = outputFileGdbPath;
                    importFCTool.out_name = StreetsFCName;
                    gp.Execute(importFCTool, trackcancel);

                    string pathToStreetsFC = outputFileGdbPath + "\\" + StreetsFCName;

                    addFieldTool = new AddField();
                    addFieldTool.in_table = pathToStreetsFC;
                    addFieldTool.field_name = "FT_" + timeZoneIDBaseFieldName;
                    addFieldTool.field_type = "SHORT";
                    gp.Execute(addFieldTool, trackcancel);
                    addFieldTool.field_name = "TF_" + timeZoneIDBaseFieldName;
                    addFieldTool.field_type = "SHORT";
                    gp.Execute(addFieldTool, trackcancel);

                    // Calculate the TimeZoneID fields

                    makeFeatureLayerTool = new MakeFeatureLayer();
                    makeFeatureLayerTool.in_features = pathToStreetsFC;
                    makeFeatureLayerTool.out_layer = "Streets_Layer";
                    gp.Execute(makeFeatureLayerTool, trackcancel);

                    addJoinTool = new AddJoin();
                    addJoinTool.in_layer_or_view = "Streets_Layer";
                    addJoinTool.in_field = "R_AREA_ID";
                    addJoinTool.join_table = drivingLTablePath;
                    addJoinTool.join_field = "AREA_ID";
                    addJoinTool.join_type = "KEEP_COMMON";
                    gp.Execute(addJoinTool, trackcancel);

                    AddMessage("Calculating the FT_" + timeZoneIDBaseFieldName + " field for left driving side roads...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "Streets_Layer";
                    calcFieldTool.field = StreetsFCName + ".FT_" + timeZoneIDBaseFieldName;
                    calcFieldTool.code_block = TimeZoneUtilities.MakeTimeZoneIDCode(outputFileGdbPath, TimeZonesTableName, "MtdAreaDrivingL.SortableMSTIMEZONE");
                    calcFieldTool.expression = "tzID";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    removeJoinTool = new RemoveJoin();
                    removeJoinTool.in_layer_or_view = "Streets_Layer";
                    removeJoinTool.join_name = "MtdAreaDrivingL";
                    gp.Execute(removeJoinTool, trackcancel);

                    addJoinTool = new AddJoin();
                    addJoinTool.in_layer_or_view = "Streets_Layer";
                    addJoinTool.in_field = "L_AREA_ID";
                    addJoinTool.join_table = drivingRTablePath;
                    addJoinTool.join_field = "AREA_ID";
                    addJoinTool.join_type = "KEEP_COMMON";
                    gp.Execute(addJoinTool, trackcancel);

                    AddMessage("Calculating the FT_" + timeZoneIDBaseFieldName + " field for right driving side roads...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "Streets_Layer";
                    calcFieldTool.field = StreetsFCName + ".FT_" + timeZoneIDBaseFieldName;
                    calcFieldTool.code_block = TimeZoneUtilities.MakeTimeZoneIDCode(outputFileGdbPath, TimeZonesTableName, "MtdAreaDrivingR.SortableMSTIMEZONE");
                    calcFieldTool.expression = "tzID";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    removeJoinTool = new RemoveJoin();
                    removeJoinTool.in_layer_or_view = "Streets_Layer";
                    removeJoinTool.join_name = "MtdAreaDrivingR";
                    gp.Execute(removeJoinTool, trackcancel);

                    addJoinTool = new AddJoin();
                    addJoinTool.in_layer_or_view = "Streets_Layer";
                    addJoinTool.in_field = "L_AREA_ID";
                    addJoinTool.join_table = drivingLTablePath;
                    addJoinTool.join_field = "AREA_ID";
                    addJoinTool.join_type = "KEEP_COMMON";
                    gp.Execute(addJoinTool, trackcancel);

                    AddMessage("Calculating the TF_" + timeZoneIDBaseFieldName + " field for left driving side roads...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "Streets_Layer";
                    calcFieldTool.field = StreetsFCName + ".TF_" + timeZoneIDBaseFieldName;
                    calcFieldTool.code_block = TimeZoneUtilities.MakeTimeZoneIDCode(outputFileGdbPath, TimeZonesTableName, "MtdAreaDrivingL.SortableMSTIMEZONE");
                    calcFieldTool.expression = "tzID";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    removeJoinTool = new RemoveJoin();
                    removeJoinTool.in_layer_or_view = "Streets_Layer";
                    removeJoinTool.join_name = "MtdAreaDrivingL";
                    gp.Execute(removeJoinTool, trackcancel);

                    addJoinTool = new AddJoin();
                    addJoinTool.in_layer_or_view = "Streets_Layer";
                    addJoinTool.in_field = "R_AREA_ID";
                    addJoinTool.join_table = drivingRTablePath;
                    addJoinTool.join_field = "AREA_ID";
                    addJoinTool.join_type = "KEEP_COMMON";
                    gp.Execute(addJoinTool, trackcancel);

                    AddMessage("Calculating the TF_" + timeZoneIDBaseFieldName + " field for right driving side roads...", messages, trackcancel);

                    calcFieldTool = new CalculateField();
                    calcFieldTool.in_table = "Streets_Layer";
                    calcFieldTool.field = StreetsFCName + ".TF_" + timeZoneIDBaseFieldName;
                    calcFieldTool.code_block = TimeZoneUtilities.MakeTimeZoneIDCode(outputFileGdbPath, TimeZonesTableName, "MtdAreaDrivingR.SortableMSTIMEZONE");
                    calcFieldTool.expression = "tzID";
                    calcFieldTool.expression_type = "VB";
                    gp.Execute(calcFieldTool, trackcancel);

                    removeJoinTool = new RemoveJoin();
                    removeJoinTool.in_layer_or_view = "Streets_Layer";
                    removeJoinTool.join_name = "MtdAreaDrivingR";
                    gp.Execute(removeJoinTool, trackcancel);

                    deleteTool = new Delete();
                    deleteTool.in_data = "Streets_Layer";
                    gp.Execute(deleteTool, trackcancel);

                    deleteTool = new Delete();
                    deleteTool.in_data = drivingLTablePath;
                    gp.Execute(deleteTool, trackcancel);
                    deleteTool.in_data = drivingRTablePath;
                    gp.Execute(deleteTool, trackcancel);
                }
                else
                {
                    // Create a dummy TimeZones table and a dummy Streets feature class

                    CreateTable createTableTool = new CreateTable();
                    createTableTool.out_path = outputFileGdbPath;
                    createTableTool.out_name = TimeZonesTableName;
                    gp.Execute(createTableTool, trackcancel);

                    CreateFeatureclass createFCTool = new CreateFeatureclass();
                    createFCTool.out_path = outputFileGdbPath;
                    createFCTool.out_name = StreetsFCName;
                    createFCTool.geometry_type = "POLYLINE";
                    gp.Execute(createFCTool, trackcancel);
                }

                deleteTool = new Delete();
                deleteTool.in_data = mtdAreaTablePath;
                gp.Execute(deleteTool, trackcancel);

                // Compact the output file geodatabase

                AddMessage("Compacting the output file geodatabase...", messages, trackcancel);

                Compact compactTool = new Compact();
                compactTool.in_workspace = outputFileGdbPath;
                gp.Execute(compactTool, trackcancel);
            }
            catch (Exception e)
            {
                if (gp.MaxSeverity == 2)
                {
                    object missing = System.Type.Missing;
                    messages.AddError(1, gp.GetMessages(ref missing));
                }
                messages.AddError(1, e.Message);
                messages.AddError(1, e.StackTrace);
            }
            finally
            {
                // Restore the original GP environment settings

                gpSettings.AddOutputsToMap = origAddOutputsToMapSetting;
                gpSettings.LogHistory = origLogHistorySetting;
            }
            GC.Collect();
            return;
        }
        private void CreateGrids(RockContext rockContext)
        {
            if (ContentChannels.Any())
            {
                this.Visible = true;

                // TODO: security
                bool canEdit = true;

                phContentChannelGrids.Controls.Clear();

                foreach (var contentChannel in ContentChannels)
                {
                    var pwItems = new PanelWidget();
                    phContentChannelGrids.Controls.Add(pwItems);
                    pwItems.ID       = string.Format("pwItems_{0}", contentChannel.Id);
                    pwItems.Title    = contentChannel.Name;
                    pwItems.Expanded = ExpandedPanels.Contains(contentChannel.Id);

                    var divItems = new HtmlGenericControl("div");
                    pwItems.Controls.Add(divItems);
                    divItems.ID = string.Format("divItems_{0}", contentChannel.Id);
                    divItems.AddCssClass("grid");
                    divItems.AddCssClass("grid-panel");

                    Grid gItems = new Grid();
                    divItems.Controls.Add(gItems);
                    gItems.ID                = string.Format("gItems_{0}", contentChannel.Id);
                    gItems.DataKeyNames      = new string[] { "Id" };
                    gItems.EmptyDataText     = "No Items Found";
                    gItems.RowItemText       = "Item";
                    gItems.AllowSorting      = true;
                    gItems.Actions.ShowAdd   = canEdit;
                    gItems.IsDeleteEnabled   = canEdit;
                    gItems.Actions.AddClick += gItems_Add;
                    gItems.RowSelected      += gItems_Edit;
                    gItems.GridRebind       += gItems_GridRebind;

                    gItems.Columns.Add(new RockBoundField
                    {
                        DataField      = "Title",
                        HeaderText     = "Title",
                        SortExpression = "Title"
                    });

                    if (contentChannel.ContentChannelType.IncludeTime)
                    {
                        gItems.Columns.Add(new DateTimeField
                        {
                            DataField      = "StartDateTime",
                            HeaderText     = contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Active",
                            SortExpression = "StartDateTime"
                        });

                        if (contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange)
                        {
                            gItems.Columns.Add(new DateTimeField
                            {
                                DataField      = "ExpireDateTime",
                                HeaderText     = "Expire",
                                SortExpression = "ExpireDateTime"
                            });
                        }
                    }
                    else
                    {
                        gItems.Columns.Add(new DateField
                        {
                            DataField      = "StartDateTime",
                            HeaderText     = contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Active",
                            SortExpression = "StartDateTime"
                        });

                        if (contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange)
                        {
                            gItems.Columns.Add(new DateField
                            {
                                DataField      = "ExpireDateTime",
                                HeaderText     = "Expire",
                                SortExpression = "ExpireDateTime"
                            });
                        }
                    }

                    if (!contentChannel.ContentChannelType.DisablePriority)
                    {
                        var priorityField = new RockBoundField
                        {
                            DataField        = "Priority",
                            HeaderText       = "Priority",
                            SortExpression   = "Priority",
                            DataFormatString = "{0:N0}",
                        };
                        priorityField.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                        gItems.Columns.Add(priorityField);
                    }

                    // Add attribute columns
                    int    entityTypeId = EntityTypeCache.Read(typeof(Rock.Model.ContentChannelItem)).Id;
                    string qualifier    = contentChannel.ContentChannelTypeId.ToString();
                    foreach (var attribute in new AttributeService(rockContext).Queryable()
                             .Where(a =>
                                    a.EntityTypeId == entityTypeId &&
                                    a.IsGridColumn &&
                                    a.EntityTypeQualifierColumn.Equals("ContentChannelTypeId", StringComparison.OrdinalIgnoreCase) &&
                                    a.EntityTypeQualifierValue.Equals(qualifier))
                             .OrderBy(a => a.Order)
                             .ThenBy(a => a.Name))
                    {
                        string dataFieldExpression = attribute.Key;
                        bool   columnExists        = gItems.Columns.OfType <AttributeField>().FirstOrDefault(a => a.DataField.Equals(dataFieldExpression)) != null;
                        if (!columnExists)
                        {
                            AttributeField boundField = new AttributeField();
                            boundField.DataField      = dataFieldExpression;
                            boundField.HeaderText     = attribute.Name;
                            boundField.SortExpression = string.Empty;

                            var attributeCache = Rock.Web.Cache.AttributeCache.Read(attribute.Id);
                            if (attributeCache != null)
                            {
                                boundField.ItemStyle.HorizontalAlign = attributeCache.FieldType.Field.AlignValue;
                            }

                            gItems.Columns.Add(boundField);
                        }
                    }

                    if (contentChannel.RequiresApproval)
                    {
                        var statusField = new BoundField();
                        gItems.Columns.Add(statusField);
                        statusField.DataField      = "Status";
                        statusField.HeaderText     = "Status";
                        statusField.SortExpression = "Status";
                        statusField.HtmlEncode     = false;
                    }

                    var deleteField = new DeleteField();
                    gItems.Columns.Add(deleteField);
                    deleteField.Click += gItems_Delete;
                }
            }
            else
            {
                this.Visible = false;
            }
        }